Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a76fd8c88 | ||
|
|
3357d4c9c8 | ||
|
|
2d1c33f1e9 | ||
|
|
03358cab4f | ||
|
|
e188828423 | ||
|
|
2ee8c3807b | ||
|
|
88de2148ae | ||
|
|
871a5fe78a | ||
|
|
60a006008a | ||
|
|
df7dcd3a9c | ||
|
|
292e37aaac | ||
|
|
4906f665fd | ||
|
|
68afaf0cb8 | ||
|
|
38c2d1f1b4 | ||
|
|
4ab5722759 | ||
|
|
51ea9c42d3 | ||
|
|
d6e0bbf0e8 | ||
|
|
e80313e459 | ||
|
|
9decc6866f | ||
|
|
e12f182e7f | ||
|
|
b9aaf55193 | ||
|
|
8567948084 | ||
|
|
37f1f4225d | ||
|
|
6dbc643c44 | ||
|
|
d2fc126fed | ||
|
|
ab721873f3 | ||
|
|
2984bd1604 | ||
|
|
e50a683336 | ||
|
|
9c69e35cfa |
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
77
|
||||
83
|
||||
+10
-3
@@ -31,7 +31,7 @@ COPY apps/web/package.json apps/web/package.json
|
||||
|
||||
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
||||
|
||||
FROM gcr.io/distroless/nodejs24-debian13:nonroot AS runtime
|
||||
FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -41,9 +41,16 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
|
||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
||||
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
|
||||
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
||||
|
||||
EXPOSE 10712
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["apps/api/dist/main.js"]
|
||||
ENV NEW_RELIC_HOME=/app/apps/api \
|
||||
NEW_RELIC_APP_NAME=lolympus \
|
||||
NEW_RELIC_AI_MONITORING_ENABLED=true \
|
||||
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000 \
|
||||
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
|
||||
|
||||
CMD ["--import", "/app/apps/api/node_modules/newrelic/esm-loader.mjs", "-r", "/app/apps/api/node_modules/newrelic", "apps/api/dist/main.js"]
|
||||
@@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
|
||||
|
||||
<p align="center">
|
||||
<video
|
||||
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4"
|
||||
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4"
|
||||
poster="docs/screenshots/lolympus-auction.png"
|
||||
width="960"
|
||||
autoplay="autoplay"
|
||||
@@ -13,20 +13,20 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
|
||||
playsinline="playsinline"
|
||||
controls
|
||||
>
|
||||
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
|
||||
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
|
||||
</video>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/77/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
|
||||
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
|
||||
</p>
|
||||
|
||||
## 배포 주소
|
||||
|
||||
| Environment | Version | URL |
|
||||
| ----------- | ------- | -------------------------------------- |
|
||||
| Production | v77 | <https://lolympus.dahyeon.us/> |
|
||||
| Staging | v77 | <https://890c50be.lolympus.pages.dev/> |
|
||||
| Production | v84 | <https://lolympus.dahyeon.us/> |
|
||||
| Staging | v84 | <https://release-84.lolympus.pages.dev/> |
|
||||
|
||||
## 개요
|
||||
|
||||
@@ -48,7 +48,10 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
|
||||
4. **팀별 진행 페이지**
|
||||
각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다.
|
||||
|
||||
5. **결과 수집과 통계**
|
||||
5. **더블 엘리미네이션 운영**
|
||||
4팀/8팀 더블 엘리미네이션 대진표를 생성하고, 시드 교체, 부전승, 제한적 결과 취소, 그랜드 파이널 리셋을 관리합니다.
|
||||
|
||||
6. **결과 수집과 통계**
|
||||
Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다.
|
||||
|
||||
## 스크린샷
|
||||
@@ -78,6 +81,7 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
|
||||
- Riot 계정 기반 참가자 프로필, 티어, 포지션 확인
|
||||
- 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원
|
||||
- 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리
|
||||
- 4팀/8팀 더블 엘리미네이션 대진표, 시드 관리, 부전승, 제한적 취소, 그랜드 파이널 리셋 지원
|
||||
- 경기별 토너먼트 코드 배정과 팀별 복사 UI
|
||||
- 팀별 경기 일정, 상대 팀, 라인업, 결과 확인
|
||||
- Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공
|
||||
@@ -128,6 +132,29 @@ pnpm start:web:dev
|
||||
|
||||
웹 앱은 기본적으로 `apps/web/.env.development` 값을 사용합니다. API 환경값은 `apps/project.env`와 실행 환경의 시크릿 설정을 함께 확인합니다.
|
||||
|
||||
### API New Relic APM
|
||||
|
||||
API 서버는 `newrelic` Node.js agent를 앱 코드보다 먼저 preload합니다. Docker 런타임과 `pnpm start:api:*` 스크립트 모두 `NEW_RELIC_HOME`을 API 패키지로 지정해 `apps/api/newrelic.cjs` 설정을 읽습니다.
|
||||
|
||||
Kubernetes에서는 Infisical이 `NEW_RELIC_LICENSE_KEY`를 프로세스 시작 전에 환경변수로 주입해야 합니다. 저장소에는 라이선스 키를 두지 않습니다.
|
||||
|
||||
비밀이 아닌 기본값은 Dockerfile과 `apps/api/newrelic.cjs`에 정의되어 있으며 필요하면 런타임 환경변수로 덮어쓸 수 있습니다.
|
||||
|
||||
```bash
|
||||
NEW_RELIC_APP_NAME=lolympus
|
||||
NEW_RELIC_AI_MONITORING_ENABLED=true
|
||||
NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED=100000
|
||||
NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
|
||||
```
|
||||
|
||||
New Relic Node agent의 정수 환경변수는 `100k` 같은 축약형 대신 `100000`처럼 숫자 문자열을 사용합니다.
|
||||
|
||||
### API 성능 리포트 운영
|
||||
|
||||
API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABILITY_ENABLED=true`로 켭니다. 전체 API route 목록은 `pnpm --filter api perf:routes`, 성능 리포트는 `pnpm --filter api perf:report`로 생성합니다. New Relic Transaction 실측 duration, New Relic custom event, local NDJSON 파일을 데이터 소스로 사용할 수 있습니다.
|
||||
|
||||
운영 절차와 해석 기준은 `docs/operations/api-performance-runbook.md`를 참고합니다.
|
||||
|
||||
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
|
||||
|
||||
## 커맨드
|
||||
@@ -137,6 +164,8 @@ pnpm start:web:dev
|
||||
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
|
||||
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
|
||||
| `pnpm --filter api test` | API 테스트 실행 |
|
||||
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
|
||||
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
|
||||
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
|
||||
| `pnpm deploy:web:staging` | Cloudflare Pages staging 배포 |
|
||||
| `pnpm deploy:web:prod` | Cloudflare Pages production 배포 |
|
||||
|
||||
@@ -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*',
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -10,12 +10,14 @@
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.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",
|
||||
@@ -38,6 +40,7 @@
|
||||
"jose": "^6.2.2",
|
||||
"mongoose": "^9.4.1",
|
||||
"nats": "^2.29.3",
|
||||
"newrelic": "^14.1.2",
|
||||
"redis": "^5.12.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
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';
|
||||
@@ -39,6 +41,12 @@ import { UserModule } from './modules/user/user.module';
|
||||
DakaoModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
providers: [
|
||||
AppService,
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: ApiPerformanceInterceptor,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -92,7 +92,10 @@ describe('auction durability projection helpers', () => {
|
||||
it.each([
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false },
|
||||
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
|
||||
{
|
||||
current: { auctionLifecycleId: 'new-life', revision: 1 },
|
||||
expected: false,
|
||||
},
|
||||
])('decides whether projection can apply %#', ({ current, expected }) => {
|
||||
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
|
||||
});
|
||||
@@ -100,14 +103,23 @@ describe('auction durability projection helpers', () => {
|
||||
it.each([
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true },
|
||||
{ current: { auctionLifecycleId: 'life-1', revision: 10 }, expected: false },
|
||||
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
|
||||
{
|
||||
current: { auctionLifecycleId: 'life-1', revision: 10 },
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
current: { auctionLifecycleId: 'new-life', revision: 1 },
|
||||
expected: false,
|
||||
},
|
||||
{ current: {}, expected: false },
|
||||
])('decides whether a durability payload can be processed %#', ({ current, expected }) => {
|
||||
])(
|
||||
'decides whether a durability payload can be processed %#',
|
||||
({ current, expected }) => {
|
||||
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('reads due durability payload keys from Redis', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
|
||||
@@ -333,7 +345,10 @@ describe('auction durability projection helpers', () => {
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
@@ -404,7 +419,10 @@ describe('auction durability projection helpers', () => {
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
@@ -428,6 +446,216 @@ describe('auction durability projection helpers', () => {
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('recovers stale append payloads as history-only records', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyFindOne = jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(null),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const historyUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
|
||||
});
|
||||
const auctionUpdateOne = jest.fn();
|
||||
const sideEffectUpdateOne = jest.fn();
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
findOne: historyFindOne,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
|
||||
});
|
||||
|
||||
expect(historyFindOne).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
auctionId: 'auction-1',
|
||||
sequence: { $gt: 4 },
|
||||
}),
|
||||
);
|
||||
expect(historyUpdateOne).toHaveBeenCalledWith(
|
||||
{
|
||||
auctionId: 'auction-1',
|
||||
auctionStateTransitionId: 'transition-1',
|
||||
},
|
||||
expect.objectContaining({
|
||||
$setOnInsert: expect.objectContaining({
|
||||
sequence: 4,
|
||||
}),
|
||||
}),
|
||||
{ session, upsert: true },
|
||||
);
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not resurrect stale append payloads invalidated by later undo', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyFindOne = jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn();
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
findOne: historyFindOne,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(payload);
|
||||
|
||||
expect(historyFindOne).toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears stale append payloads after history-only recovery', async () => {
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(['payload-1'])
|
||||
.mockResolvedValueOnce({
|
||||
committedAtRedisTimestampMS: '1780000000000',
|
||||
payloadJson: JSON.stringify({
|
||||
...payload,
|
||||
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
|
||||
}),
|
||||
})
|
||||
.mockResolvedValueOnce(1)
|
||||
.mockResolvedValueOnce(1);
|
||||
const historyFindOne = jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(null),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const historyUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
|
||||
});
|
||||
const auctionUpdateOne = jest.fn();
|
||||
const sideEffectUpdateOne = jest.fn();
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 10,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(null),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
findOne: historyFindOne,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}),
|
||||
} as never,
|
||||
{
|
||||
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
|
||||
raw: jest.fn().mockReturnValue({ sendCommand }),
|
||||
} as never,
|
||||
);
|
||||
|
||||
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
|
||||
applied: 1,
|
||||
failed: 0,
|
||||
skipped: 0,
|
||||
});
|
||||
|
||||
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sendCommand).toHaveBeenNthCalledWith(3, [
|
||||
'ZREM',
|
||||
'auction:auctionDurabilityRetryQueue',
|
||||
'payload-1',
|
||||
]);
|
||||
expect(sendCommand).toHaveBeenNthCalledWith(4, ['DEL', 'payload-1']);
|
||||
});
|
||||
|
||||
it('processes due payloads and clears successful outbox entries', async () => {
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
@@ -613,7 +841,9 @@ describe('auction durability projection helpers', () => {
|
||||
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
||||
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
|
||||
|
||||
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
||||
await (
|
||||
scheduler as unknown as { safeTick: () => Promise<void> }
|
||||
).safeTick();
|
||||
|
||||
const auctionRedisService = (
|
||||
scheduler as unknown as {
|
||||
@@ -649,7 +879,9 @@ describe('auction durability projection helpers', () => {
|
||||
.spyOn(scheduler, 'processDueDurabilityPayloads')
|
||||
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
|
||||
|
||||
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
|
||||
await (
|
||||
scheduler as unknown as { safeTick: () => Promise<void> }
|
||||
).safeTick();
|
||||
|
||||
const auctionRedisService = (
|
||||
scheduler as unknown as {
|
||||
@@ -747,7 +979,8 @@ describe('auction durability projection helpers', () => {
|
||||
if (name === 'auctionSideEffectApplication') {
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}
|
||||
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
|
||||
if (name === 'match')
|
||||
return { findById: jest.fn().mockReturnValue(match) };
|
||||
return {};
|
||||
}),
|
||||
} as never,
|
||||
@@ -829,26 +1062,18 @@ describe('auction durability projection helpers', () => {
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectStatus: 'completed',
|
||||
});
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'match-1',
|
||||
{
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentServerTimestampMS: 2000,
|
||||
matchSideEffectRevision: 2,
|
||||
matchSideEffectStatus: 'processing',
|
||||
},
|
||||
);
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'match-1',
|
||||
{
|
||||
});
|
||||
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentServerTimestampMS: 3000,
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectStatus: 'completed',
|
||||
},
|
||||
);
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'EVAL',
|
||||
expect.stringContaining("redis.call('EXPIRE'"),
|
||||
@@ -870,6 +1095,101 @@ describe('auction durability projection helpers', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails sync match teams side effect when the completed projection has no teams', async () => {
|
||||
const completePayload = {
|
||||
...payload,
|
||||
afterAuctionMongoProjection: {
|
||||
auctionTeams: [],
|
||||
matchSideEffectRevision: 1,
|
||||
phase: 'complete',
|
||||
revision: 10,
|
||||
},
|
||||
auctionActionType: 'complete',
|
||||
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
|
||||
revision: 10,
|
||||
} as const;
|
||||
const match = {
|
||||
participants: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
status: 'team-built',
|
||||
teamBuiltAt: undefined,
|
||||
teams: [],
|
||||
};
|
||||
const historyUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
|
||||
});
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
||||
});
|
||||
const auctionFindOneAndUpdate = jest
|
||||
.fn()
|
||||
.mockReturnValueOnce({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
matchSideEffectRevision: 2,
|
||||
matchSideEffectStatus: 'processing',
|
||||
}),
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectStatus: 'failed',
|
||||
}),
|
||||
});
|
||||
const sideEffectUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
|
||||
});
|
||||
const reserveForMatch = jest.fn().mockResolvedValue(match);
|
||||
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
|
||||
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
|
||||
const broadcastMatchSideEffect = jest.fn();
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(null),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') return { updateOne: historyUpdateOne };
|
||||
if (name === 'auction') {
|
||||
return {
|
||||
findOneAndUpdate: auctionFindOneAndUpdate,
|
||||
updateOne: auctionUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auctionSideEffectApplication') {
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}
|
||||
if (name === 'match')
|
||||
return { findById: jest.fn().mockReturnValue(match) };
|
||||
return {};
|
||||
}),
|
||||
} as never,
|
||||
{
|
||||
getCurrentRedisTimestampMS: jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(2000)
|
||||
.mockResolvedValueOnce(3000),
|
||||
raw: jest.fn().mockReturnValue({ sendCommand: jest.fn() }),
|
||||
} as never,
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
scheduler.applyDurabilityPayload(completePayload),
|
||||
).rejects.toThrow('produced no match teams');
|
||||
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
expect(reserveForMatch).not.toHaveBeenCalled();
|
||||
expect(scheduleInitialPoll).not.toHaveBeenCalled();
|
||||
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
matchSideEffectStatus: 'failed',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('applies reset match side effect after durable projection', async () => {
|
||||
const resetPayload = {
|
||||
...payload,
|
||||
@@ -943,7 +1263,10 @@ describe('auction durability projection helpers', () => {
|
||||
createSession: jest.fn().mockResolvedValue(null),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return {
|
||||
@@ -955,7 +1278,8 @@ describe('auction durability projection helpers', () => {
|
||||
if (name === 'auctionSideEffectApplication') {
|
||||
return { updateOne: sideEffectUpdateOne };
|
||||
}
|
||||
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
|
||||
if (name === 'match')
|
||||
return { findById: jest.fn().mockReturnValue(match) };
|
||||
return {};
|
||||
}),
|
||||
} as never,
|
||||
@@ -985,7 +1309,10 @@ describe('auction durability projection helpers', () => {
|
||||
teams: [],
|
||||
tournamentCodeIds: [],
|
||||
});
|
||||
expect(match.participants).toEqual([{ excluded: false }, { excluded: false }]);
|
||||
expect(match.participants).toEqual([
|
||||
{ excluded: false },
|
||||
{ excluded: false },
|
||||
]);
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
buildAuctionRedisKeys,
|
||||
} from './redis/auction-redis.keys';
|
||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
||||
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
|
||||
const AUCTION_DURABILITY_TICK_INTERVAL_MS = 1000;
|
||||
const AUCTION_DURABILITY_BATCH_LIMIT = 20;
|
||||
const AUCTION_DURABILITY_RETRY_DELAY_MS = 5000;
|
||||
@@ -128,7 +130,9 @@ export class AuctionDurabilityScheduler
|
||||
currentRedisTimestampMS: number,
|
||||
batchLimit: number,
|
||||
): Promise<string[]> {
|
||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
||||
const reply = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZRANGEBYSCORE',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
'-inf',
|
||||
@@ -165,11 +169,25 @@ export class AuctionDurabilityScheduler
|
||||
}
|
||||
await this.applyDurabilityPayload(payload);
|
||||
applied += 1;
|
||||
// [AUCTION-DEBUG] 제거 대상. 영속 지연(lag): Redis 커밋 → Mongo 영속까지 걸린 시간 + 배치 백로그.
|
||||
// 사용자가 본 "되돌리기/이력이 2~3 뒤처짐"을 수치화한다(지연이 클수록 undo
|
||||
// 패널이 stale 시퀀스를 보여 엉뚱한 스냅샷 복원 가능성↑).
|
||||
recordNewRelicCustomEvent('AuctionServerDurability', {
|
||||
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
|
||||
auctionStateTransitionId: payload.auctionStateTransitionId,
|
||||
auctionActionType: payload.auctionActionType,
|
||||
revision: payload.revision,
|
||||
auctionHistorySequence: payload.auctionHistorySequence,
|
||||
persistLatencyMS:
|
||||
typeof payload.committedAtRedisTimestampMS === 'number'
|
||||
? currentRedisTimestampMS - payload.committedAtRedisTimestampMS
|
||||
: -1,
|
||||
batchBacklog: payloadKeys.length,
|
||||
});
|
||||
await this.clearDurabilityPayload(payloadKey);
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
const failureDisposition =
|
||||
await this.recordDurabilityPayloadFailure(
|
||||
const failureDisposition = await this.recordDurabilityPayloadFailure(
|
||||
payloadKey,
|
||||
currentRedisTimestampMS,
|
||||
error,
|
||||
@@ -195,7 +213,9 @@ export class AuctionDurabilityScheduler
|
||||
const payloadJson = hash.payloadJson;
|
||||
if (!payloadJson) return null;
|
||||
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
|
||||
const committedAtRedisTimestampMS = Number(hash.committedAtRedisTimestampMS);
|
||||
const committedAtRedisTimestampMS = Number(
|
||||
hash.committedAtRedisTimestampMS,
|
||||
);
|
||||
if (Number.isFinite(committedAtRedisTimestampMS)) {
|
||||
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
|
||||
}
|
||||
@@ -222,13 +242,31 @@ export class AuctionDurabilityScheduler
|
||||
|
||||
try {
|
||||
session?.startTransaction();
|
||||
const historyMutation = parseAuctionHistoryMutation(
|
||||
payload.historyMutation,
|
||||
);
|
||||
if (typeof AuctionModel.findById === 'function') {
|
||||
const currentProjection = await readAuctionProjectionIdentityForMutation(
|
||||
const currentProjection =
|
||||
await readAuctionProjectionIdentityForMutation(
|
||||
AuctionModel,
|
||||
payload.auctionId,
|
||||
session,
|
||||
);
|
||||
if (!shouldProcessAuctionDurabilityPayload(currentProjection, payload)) {
|
||||
if (
|
||||
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
|
||||
) {
|
||||
// 뒤 payload가 먼저 projection revision을 올리면 앞 append payload가 stale이 된다.
|
||||
// 이때 projection/side effect는 건드리지 않고 undo용 history만 멱등 복구한다.
|
||||
if (
|
||||
historyMutation.type === 'append' &&
|
||||
currentProjection.auctionLifecycleId === payload.auctionLifecycleId
|
||||
) {
|
||||
await this.applyStaleAppendHistoryRecovery({
|
||||
AuctionHistoryModel,
|
||||
payload,
|
||||
session,
|
||||
});
|
||||
}
|
||||
if (session) await session.commitTransaction();
|
||||
return;
|
||||
}
|
||||
@@ -370,7 +408,8 @@ export class AuctionDurabilityScheduler
|
||||
);
|
||||
if (!hasMatchedDocument(leaseResult)) return;
|
||||
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||
{
|
||||
AuctionModel,
|
||||
currentServerTimestampMS: currentRedisTimestampMS,
|
||||
expectedMatchSideEffectRevision: Number(
|
||||
@@ -378,7 +417,8 @@ export class AuctionDurabilityScheduler
|
||||
),
|
||||
payload,
|
||||
status: 'processing',
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!processingDelta) return;
|
||||
let expectedMatchSideEffectRevision =
|
||||
processingDelta.matchSideEffectRevision;
|
||||
@@ -396,11 +436,36 @@ export class AuctionDurabilityScheduler
|
||||
teamBuiltAt?: Date;
|
||||
teams: ReturnType<typeof buildMatchTeamsFromProjection>;
|
||||
} | null;
|
||||
if (!match) throw new Error(`Match not found: ${String(payload.matchId)}`);
|
||||
match.teams = buildMatchTeamsFromProjection(
|
||||
if (!match)
|
||||
throw new Error(`Match not found: ${String(payload.matchId)}`);
|
||||
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)}.`,
|
||||
);
|
||||
}
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
@@ -466,6 +531,75 @@ export class AuctionDurabilityScheduler
|
||||
}
|
||||
}
|
||||
|
||||
private async applyStaleAppendHistoryRecovery(params: {
|
||||
AuctionHistoryModel: {
|
||||
findOne?: (...args: never[]) => unknown;
|
||||
updateOne: (...args: never[]) => unknown;
|
||||
};
|
||||
payload: AuctionDurabilityPayload;
|
||||
session: mongoose.ClientSession | null | undefined;
|
||||
}): Promise<void> {
|
||||
const invalidated =
|
||||
await this.isAppendHistoryInvalidatedByLaterDestructiveMutation(params);
|
||||
if (invalidated) return;
|
||||
|
||||
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
|
||||
await execMaybe(
|
||||
params.AuctionHistoryModel.updateOne(
|
||||
historyOperation.filter as never,
|
||||
historyOperation.update as never,
|
||||
{
|
||||
session: params.session,
|
||||
upsert: true,
|
||||
} as never,
|
||||
) as Promise<unknown> | { exec(): Promise<unknown> },
|
||||
);
|
||||
}
|
||||
|
||||
private async isAppendHistoryInvalidatedByLaterDestructiveMutation(params: {
|
||||
AuctionHistoryModel: {
|
||||
findOne?: (...args: never[]) => unknown;
|
||||
};
|
||||
payload: AuctionDurabilityPayload;
|
||||
session: mongoose.ClientSession | null | undefined;
|
||||
}): Promise<boolean> {
|
||||
if (!params.AuctionHistoryModel.findOne) return true;
|
||||
|
||||
// 늦게 도착한 append는 history gap을 메울 수 있지만,
|
||||
// 이후 undo/reset이 의도적으로 삭제한 sequence를 되살리면 안 된다.
|
||||
const query = params.AuctionHistoryModel.findOne({
|
||||
auctionId: params.payload.auctionId,
|
||||
sequence: { $gt: params.payload.auctionHistorySequence },
|
||||
$or: [
|
||||
{
|
||||
'historyMutation.targetHistorySequence': {
|
||||
$lt: params.payload.auctionHistorySequence,
|
||||
},
|
||||
'historyMutation.type': 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
{
|
||||
'historyMutation.resetMode': { $ne: 'preserve-audit' },
|
||||
'historyMutation.type': 'reset',
|
||||
},
|
||||
],
|
||||
} as never);
|
||||
const scoped =
|
||||
query && typeof query === 'object' && 'session' in query
|
||||
? (query as { session: (...args: never[]) => unknown }).session(
|
||||
params.session as never,
|
||||
)
|
||||
: query;
|
||||
const leaned =
|
||||
scoped && typeof scoped === 'object' && 'lean' in scoped
|
||||
? (scoped as { lean: () => unknown }).lean()
|
||||
: scoped;
|
||||
const result =
|
||||
leaned && typeof leaned === 'object' && 'exec' in leaned
|
||||
? await (leaned as { exec: () => Promise<unknown> }).exec()
|
||||
: await Promise.resolve(leaned);
|
||||
return Boolean(result);
|
||||
}
|
||||
|
||||
private async applyResetMatchSideEffect(
|
||||
payload: AuctionDurabilityPayload,
|
||||
mutation: ParsedMatchSideEffectMutation,
|
||||
@@ -553,15 +687,18 @@ export class AuctionDurabilityScheduler
|
||||
);
|
||||
if (!hasMatchedDocument(leaseResult)) return;
|
||||
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
|
||||
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
|
||||
{
|
||||
AuctionModel,
|
||||
currentServerTimestampMS: currentRedisTimestampMS,
|
||||
expectedMatchSideEffectRevision: Number(
|
||||
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
|
||||
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ??
|
||||
0,
|
||||
),
|
||||
payload: params.payload,
|
||||
status: 'processing',
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!processingDelta) return;
|
||||
let expectedMatchSideEffectRevision =
|
||||
processingDelta.matchSideEffectRevision;
|
||||
@@ -605,7 +742,8 @@ export class AuctionDurabilityScheduler
|
||||
} catch (error) {
|
||||
const failureTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
await execMaybe(
|
||||
AuctionSideEffectApplicationModel.updateOne(
|
||||
identity as never,
|
||||
@@ -658,7 +796,9 @@ export class AuctionDurabilityScheduler
|
||||
payload: AuctionDurabilityPayload;
|
||||
session: mongoose.ClientSession | null | undefined;
|
||||
}): Promise<void> {
|
||||
const mutation = parseAuctionHistoryMutation(params.payload.historyMutation);
|
||||
const mutation = parseAuctionHistoryMutation(
|
||||
params.payload.historyMutation,
|
||||
);
|
||||
if (isDestructiveHistoryMutation(mutation)) {
|
||||
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
|
||||
if (!params.AuctionHistoryModel.deleteMany) {
|
||||
@@ -689,7 +829,9 @@ export class AuctionDurabilityScheduler
|
||||
}
|
||||
}
|
||||
|
||||
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
|
||||
const historyOperation = buildAuctionHistoryUpsert(
|
||||
params.payload,
|
||||
).updateOne;
|
||||
await execMaybe(
|
||||
params.AuctionHistoryModel.updateOne(
|
||||
historyOperation.filter as never,
|
||||
@@ -731,7 +873,9 @@ export class AuctionDurabilityScheduler
|
||||
: {}),
|
||||
matchSideEffectStatus: params.status,
|
||||
},
|
||||
...(params.errorMessage ? {} : { $unset: { matchSideEffectError: '' } }),
|
||||
...(params.errorMessage
|
||||
? {}
|
||||
: { $unset: { matchSideEffectError: '' } }),
|
||||
} as never,
|
||||
{
|
||||
projection: {
|
||||
@@ -742,13 +886,11 @@ export class AuctionDurabilityScheduler
|
||||
returnDocument: 'after',
|
||||
} as never,
|
||||
),
|
||||
)) as
|
||||
| {
|
||||
)) as {
|
||||
auctionLifecycleId?: string;
|
||||
matchSideEffectRevision?: number;
|
||||
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
|
||||
}
|
||||
| null;
|
||||
} | null;
|
||||
if (!updatedAuction?.auctionLifecycleId) return null;
|
||||
|
||||
const delta = buildMatchSideEffectDelta({
|
||||
@@ -815,7 +957,9 @@ export class AuctionDurabilityScheduler
|
||||
payloadKey: string,
|
||||
retryAtRedisTimestampMS: number,
|
||||
): Promise<void> {
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZADD',
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
String(retryAtRedisTimestampMS),
|
||||
@@ -829,14 +973,13 @@ export class AuctionDurabilityScheduler
|
||||
error: unknown,
|
||||
): Promise<'dead-lettered' | 'requeued'> {
|
||||
const errorMessage = formatErrorMessageForRedis(error);
|
||||
const attemptReply = await this.auctionRedisService.raw().sendCommand([
|
||||
'HINCRBY',
|
||||
payloadKey,
|
||||
'attempts',
|
||||
'1',
|
||||
]);
|
||||
const attemptReply = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand(['HINCRBY', payloadKey, 'attempts', '1']);
|
||||
const attempts = Number(attemptReply);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'HSET',
|
||||
payloadKey,
|
||||
'lastError',
|
||||
@@ -849,18 +992,20 @@ export class AuctionDurabilityScheduler
|
||||
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([
|
||||
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([
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZADD',
|
||||
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
|
||||
String(currentRedisTimestampMS),
|
||||
@@ -881,12 +1026,14 @@ export class AuctionDurabilityScheduler
|
||||
): Promise<void> {
|
||||
const matchId = String(payload.matchId);
|
||||
const keys = buildAuctionRedisKeys(matchId);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'EVAL',
|
||||
[
|
||||
"local expectedAuctionLifecycleId = ARGV[2]",
|
||||
'local expectedAuctionLifecycleId = ARGV[2]',
|
||||
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||
"if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
|
||||
'if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
|
||||
' return 0',
|
||||
'end',
|
||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||
@@ -961,7 +1108,9 @@ export function parseAuctionHistoryMutation(
|
||||
}
|
||||
if (record.type === 'reset') {
|
||||
const resetMode =
|
||||
record.resetMode === 'preserve-audit' ? 'preserve-audit' : 'clear-history';
|
||||
record.resetMode === 'preserve-audit'
|
||||
? 'preserve-audit'
|
||||
: 'clear-history';
|
||||
return { resetMode, type: 'reset' };
|
||||
}
|
||||
return { type: 'append' };
|
||||
@@ -1055,7 +1204,10 @@ export function buildSideEffectApplicationUpsert(
|
||||
payload: AuctionDurabilityPayload,
|
||||
mutation: ParsedMatchSideEffectMutation,
|
||||
) {
|
||||
const identity = buildSideEffectApplicationIdentityFromPayload(payload, mutation);
|
||||
const identity = buildSideEffectApplicationIdentityFromPayload(
|
||||
payload,
|
||||
mutation,
|
||||
);
|
||||
return {
|
||||
filter: identity,
|
||||
update: {
|
||||
@@ -1100,7 +1252,12 @@ function buildSideEffectApplicationIdentityFromPayload(
|
||||
|
||||
function hashStableJson(value: unknown): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort()))
|
||||
.update(
|
||||
JSON.stringify(
|
||||
value,
|
||||
Object.keys(value as Record<string, unknown>).sort(),
|
||||
),
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
@@ -1140,13 +1297,16 @@ function buildMatchTeamsFromProjection(
|
||||
const members: MatchTeamMember[] = [
|
||||
{
|
||||
assignedPosition:
|
||||
(captain?.preferredPositions?.[0]?.position as Position | undefined) ??
|
||||
'MID',
|
||||
(captain?.preferredPositions?.[0]?.position as
|
||||
| Position
|
||||
| undefined) ?? 'MID',
|
||||
cost: 0,
|
||||
userId: captainUserId,
|
||||
},
|
||||
...rawMembers
|
||||
.filter((member) => member.userId?.toString() !== captainUserId.toString())
|
||||
.filter(
|
||||
(member) => member.userId?.toString() !== captainUserId.toString(),
|
||||
)
|
||||
.map((member) => ({
|
||||
assignedPosition: (member.assignedPosition ?? 'MID') as Position,
|
||||
cost: Number(member.memberAcquisitionBidPointAmount ?? 0),
|
||||
@@ -1198,7 +1358,9 @@ function calculateDurabilityRetryDelayMS(attempts: number): number {
|
||||
);
|
||||
}
|
||||
|
||||
async function execMaybe<T>(queryOrPromise: Promise<T> | { exec(): Promise<T> }) {
|
||||
async function execMaybe<T>(
|
||||
queryOrPromise: Promise<T> | { exec(): Promise<T> },
|
||||
) {
|
||||
if (
|
||||
queryOrPromise &&
|
||||
typeof (queryOrPromise as { exec?: unknown }).exec === 'function'
|
||||
|
||||
@@ -158,7 +158,8 @@ describe('AuctionService', () => {
|
||||
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const auctionFindOne = jest.fn();
|
||||
const { service, auctionRedisCommandService, auctionRedisService } = createService({
|
||||
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||
createService({
|
||||
auction: {
|
||||
findOne: auctionFindOne,
|
||||
},
|
||||
@@ -182,6 +183,77 @@ describe('AuctionService', () => {
|
||||
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists auction history with a summary projection and short local cache', async () => {
|
||||
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
communityId: {
|
||||
equals: jest.fn((value) => value.toString() === communityId.toString()),
|
||||
},
|
||||
};
|
||||
const historyRows = [
|
||||
{
|
||||
action: 'sold',
|
||||
sequence: 4,
|
||||
takenAt: new Date('2026-06-26T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
action: 'open-bidding',
|
||||
sequence: 3,
|
||||
takenAt: new Date('2026-06-26T00:00:01.000Z'),
|
||||
},
|
||||
];
|
||||
const historyExec = jest.fn().mockResolvedValue(historyRows);
|
||||
const historyLean = jest.fn().mockReturnValue({ exec: historyExec });
|
||||
const historyLimit = jest.fn().mockReturnValue({ lean: historyLean });
|
||||
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
|
||||
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
|
||||
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
|
||||
const { service } = createService({
|
||||
auctionHistory: {
|
||||
find: historyFind,
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
service.listHistory({ matchId, communityId }),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
action: 'sold',
|
||||
actionLabel: '낙찰 처리',
|
||||
sequence: 4,
|
||||
takenAt: historyRows[0].takenAt,
|
||||
},
|
||||
{
|
||||
action: 'open-bidding',
|
||||
actionLabel: '입찰 열기',
|
||||
sequence: 3,
|
||||
takenAt: historyRows[1].takenAt,
|
||||
},
|
||||
]);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
|
||||
expect(historyFind).toHaveBeenCalledTimes(1);
|
||||
expect(historySelect).toHaveBeenCalledWith({
|
||||
_id: 0,
|
||||
action: 1,
|
||||
sequence: 1,
|
||||
takenAt: 1,
|
||||
});
|
||||
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
|
||||
expect(historyLimit).toHaveBeenCalledWith(100);
|
||||
|
||||
nowSpy.mockReturnValue(3101);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
@@ -266,7 +338,7 @@ describe('AuctionService', () => {
|
||||
});
|
||||
|
||||
expect(match.status).toBe('team-built');
|
||||
expect(match.teamBuiltAt).toBeInstanceOf(Date);
|
||||
expect(match.teamBuiltAt).toBeUndefined();
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
||||
@@ -542,7 +614,8 @@ describe('AuctionService', () => {
|
||||
}));
|
||||
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
|
||||
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
||||
const { service, auctionRedisCommandService, auctionRedisService } = createService({
|
||||
const { service, auctionRedisCommandService, auctionRedisService } =
|
||||
createService({
|
||||
match: {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
@@ -800,7 +873,9 @@ describe('AuctionService', () => {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(null);
|
||||
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
|
||||
null,
|
||||
);
|
||||
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
||||
redisState,
|
||||
);
|
||||
@@ -870,8 +945,11 @@ describe('AuctionService', () => {
|
||||
phase: 'bidding',
|
||||
revision: 2,
|
||||
};
|
||||
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
|
||||
createService({
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
@@ -973,8 +1051,11 @@ describe('AuctionService', () => {
|
||||
currentHighestBidPointAmount: 120,
|
||||
revision: 3,
|
||||
};
|
||||
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
|
||||
createService({
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
@@ -1007,6 +1088,115 @@ describe('AuctionService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps Redis sold snapshotBefore isolated from the sold structure mutation', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
const playerUserId = new mongoose.Types.ObjectId();
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
auctionEngineVersion: 'redis-v1',
|
||||
matchId,
|
||||
matchSideEffectRevision: 0,
|
||||
};
|
||||
const biddingState = {
|
||||
auctionBidHistory: [],
|
||||
auctionLifecycleId: 'life-1',
|
||||
auctionPlayerOrder: [
|
||||
{
|
||||
userId: playerUserId.toString(),
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
},
|
||||
],
|
||||
auctionTeams: [
|
||||
{
|
||||
captainUserId: captainUserId.toString(),
|
||||
members: [],
|
||||
remainingBidPointAmount: 1000,
|
||||
teamIndex: 1,
|
||||
},
|
||||
],
|
||||
bidRoundExtensionSeconds: 5,
|
||||
currentAuctionHistorySequence: 3,
|
||||
currentAuctionPlayerOrderIndex: 0,
|
||||
currentAuctionRound: 1,
|
||||
currentBidRoundPlayerUserId: playerUserId.toString(),
|
||||
currentHighestBidPointAmount: 120,
|
||||
currentHighestBidderTeamIndex: 1,
|
||||
initialTeamBidPointAmount: 1000,
|
||||
maximumBidRoundDurationSeconds: 30,
|
||||
passedAuctionPlayerQueue: [],
|
||||
phase: 'bidding',
|
||||
revision: 4,
|
||||
topTierAuctionPriorityThreshold: 'NONE',
|
||||
};
|
||||
const soldState = {
|
||||
...biddingState,
|
||||
auctionTeams: [
|
||||
{
|
||||
...biddingState.auctionTeams[0],
|
||||
members: [
|
||||
{
|
||||
assignedPosition: 'MID',
|
||||
memberAcquisitionBidPointAmount: 120,
|
||||
userId: playerUserId.toString(),
|
||||
},
|
||||
],
|
||||
remainingBidPointAmount: 880,
|
||||
},
|
||||
],
|
||||
currentAuctionHistorySequence: 4,
|
||||
currentHighestBidPointAmount: 120,
|
||||
phase: 'sold',
|
||||
revision: 5,
|
||||
};
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
auctionRedisStateReaderService.readAuctionStateView
|
||||
.mockResolvedValueOnce(biddingState)
|
||||
.mockResolvedValueOnce(soldState);
|
||||
|
||||
await expect(
|
||||
service.markSold({
|
||||
auctionActionRequestId: '00000000-0000-4000-8000-000000000061',
|
||||
clientObservedAuctionLifecycleId: 'life-1',
|
||||
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
||||
clientObservedCurrentBidRoundPlayerUserId: playerUserId.toString(),
|
||||
clientObservedPhase: 'bidding',
|
||||
clientObservedRevision: 4,
|
||||
matchId,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
phase: 'sold',
|
||||
revision: 5,
|
||||
});
|
||||
|
||||
const transitionInput =
|
||||
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
||||
expect(durabilityPayload.snapshotBefore).toMatchObject({
|
||||
phase: 'bidding',
|
||||
revision: 4,
|
||||
});
|
||||
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual(
|
||||
[],
|
||||
);
|
||||
expect(
|
||||
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
memberAcquisitionBidPointAmount: 120,
|
||||
userId: playerUserId.toString(),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns bid deltas without re-reading the full Redis state', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
@@ -1189,8 +1379,7 @@ describe('AuctionService', () => {
|
||||
auctionRedisStateReaderService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
} =
|
||||
createService({
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
@@ -1377,8 +1566,7 @@ describe('AuctionService', () => {
|
||||
|
||||
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
|
||||
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
|
||||
(player: { userId: mongoose.Types.ObjectId }) =>
|
||||
player.userId.toString(),
|
||||
(player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
|
||||
);
|
||||
|
||||
expect(auctionOrder).not.toEqual(signupOrder);
|
||||
@@ -1647,9 +1835,7 @@ describe('AuctionService', () => {
|
||||
amount: 20,
|
||||
});
|
||||
|
||||
expect(auction.currentDeadline).toEqual(
|
||||
new Date(now.getTime() + 12000),
|
||||
);
|
||||
expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -2151,8 +2337,12 @@ describe('AuctionService', () => {
|
||||
const auctionReplaceOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const { service, connectionService, tournamentCodeService, tournamentResultService } =
|
||||
createService({
|
||||
const {
|
||||
service,
|
||||
connectionService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
||||
replaceOne: auctionReplaceOne,
|
||||
@@ -2261,8 +2451,12 @@ describe('AuctionService', () => {
|
||||
}),
|
||||
};
|
||||
const auctionReplaceOne = jest.fn();
|
||||
const { service, connectionService, auctionRedisCommandService, auctionRedisStateReaderService } =
|
||||
createService({
|
||||
const {
|
||||
service,
|
||||
connectionService,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(auction),
|
||||
@@ -2298,7 +2492,9 @@ describe('AuctionService', () => {
|
||||
).resolves.toBe(restoredRedisState);
|
||||
|
||||
expect(auctionReplaceOne).not.toHaveBeenCalled();
|
||||
expect(auctionRedisCommandService.reserveActionRequest).toHaveBeenCalledWith(
|
||||
expect(
|
||||
auctionRedisCommandService.reserveActionRequest,
|
||||
).toHaveBeenCalledWith(
|
||||
matchId.toString(),
|
||||
expect.objectContaining({
|
||||
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
|
||||
@@ -2319,9 +2515,7 @@ describe('AuctionService', () => {
|
||||
durationSeconds: 30,
|
||||
mode: 'set-relative',
|
||||
});
|
||||
const durabilityPayload = JSON.parse(
|
||||
transitionInput.durabilityPayloadJson,
|
||||
);
|
||||
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
|
||||
expect(durabilityPayload).toMatchObject({
|
||||
auctionActionType: 'undo',
|
||||
historyMutation: {
|
||||
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
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;
|
||||
@@ -56,6 +58,9 @@ 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;
|
||||
@@ -139,6 +144,17 @@ export interface AuctionHistoryView {
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionHistorySummaryRecord {
|
||||
sequence: number;
|
||||
action: AuctionActionType;
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionHistoryListCacheEntry {
|
||||
entries: AuctionHistoryView[];
|
||||
expiresAtTimestampMS: number;
|
||||
}
|
||||
|
||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||
|
||||
export interface AuctionBidDeltaResponse {
|
||||
@@ -181,6 +197,10 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
|
||||
@Injectable()
|
||||
export class AuctionService {
|
||||
private readonly logger = new Logger(AuctionService.name);
|
||||
private readonly auctionHistoryListCache = new Map<
|
||||
string,
|
||||
AuctionHistoryListCacheEntry
|
||||
>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
@@ -230,7 +250,9 @@ export class AuctionService {
|
||||
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) {
|
||||
@@ -262,7 +284,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 }];
|
||||
@@ -316,8 +339,7 @@ export class AuctionService {
|
||||
const legacyTeams = params.captains.map((c) => ({
|
||||
teamIndex: c.teamIndex,
|
||||
captainUserId: c.userId,
|
||||
points:
|
||||
c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
||||
points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
||||
members: [],
|
||||
}));
|
||||
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
|
||||
@@ -391,14 +413,18 @@ export class AuctionService {
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isMongoDuplicateKeyError(error)) throw error;
|
||||
const raceWinner = await AuctionModel.findOne({ matchId: params.matchId });
|
||||
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(), {
|
||||
await this.auctionRedisCommandService.hydrateState(
|
||||
params.matchId.toString(),
|
||||
{
|
||||
auctionHistorySequence: 1,
|
||||
auctionLifecycleId,
|
||||
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
||||
@@ -407,10 +433,10 @@ export class AuctionService {
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
structureStateJson,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
this.enqueueBackgroundOrderEnrichment({
|
||||
auctionId: auction._id,
|
||||
@@ -543,18 +569,64 @@ 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(
|
||||
@@ -624,9 +696,8 @@ export class AuctionService {
|
||||
params: PlaceBidParams,
|
||||
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
|
||||
this.assertValidBidPointAmount(params.amount);
|
||||
const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState(
|
||||
params,
|
||||
);
|
||||
const redisBidDelta =
|
||||
await this.tryPlaceRedisBidDeltaFromRealtimeState(params);
|
||||
if (redisBidDelta) return redisBidDelta;
|
||||
|
||||
const auction = await this.getByMatchId(params.matchId);
|
||||
@@ -712,8 +783,7 @@ export class AuctionService {
|
||||
const serviceStartedAtMS = performance.now();
|
||||
const matchId = params.matchId.toString();
|
||||
const bidContextReadStartedAtMS = performance.now();
|
||||
const bidContext =
|
||||
await this.auctionRedisStateReaderService.readBidContext(
|
||||
const bidContext = await this.auctionRedisStateReaderService.readBidContext(
|
||||
matchId,
|
||||
params.teamIndex,
|
||||
);
|
||||
@@ -905,6 +975,33 @@ export class AuctionService {
|
||||
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 ?? []),
|
||||
@@ -1321,12 +1418,10 @@ export class AuctionService {
|
||||
if (!session) {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
let redisRuntimeToClear:
|
||||
| {
|
||||
let redisRuntimeToClear: {
|
||||
auctionLifecycleId?: string;
|
||||
matchId: string;
|
||||
}
|
||||
| null = null;
|
||||
} | null = null;
|
||||
try {
|
||||
session.startTransaction();
|
||||
const auction = await AuctionModel.findOne({
|
||||
@@ -1349,15 +1444,15 @@ export class AuctionService {
|
||||
await AuctionSideEffectApplicationModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
}).session(session);
|
||||
await AuctionHistoryModel.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,
|
||||
);
|
||||
await AuctionHistoryModel.deleteMany({
|
||||
auctionId: auction._id,
|
||||
}).session(session);
|
||||
if (match.status === 'team-built') {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.status = 'recruiting';
|
||||
@@ -1410,15 +1505,13 @@ export class AuctionService {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
|
||||
let redisUndoContext:
|
||||
| {
|
||||
let redisUndoContext: {
|
||||
actionRequestParams?: AuctionStructureActionRequestParams;
|
||||
auction: AuctionDocument;
|
||||
snapshot: Record<string, unknown>;
|
||||
targetHistorySequence: number;
|
||||
undoingCompletedAuction: boolean;
|
||||
}
|
||||
| null = null;
|
||||
} | null = null;
|
||||
let restored: AuctionDocument | null = null;
|
||||
|
||||
try {
|
||||
@@ -1534,8 +1627,7 @@ export class AuctionService {
|
||||
const processingOwnerToken = randomUUID();
|
||||
const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`;
|
||||
|
||||
const reserved =
|
||||
await this.auctionRedisCommandService.reserveActionRequest(
|
||||
const reserved = await this.auctionRedisCommandService.reserveActionRequest(
|
||||
params.matchId,
|
||||
{
|
||||
auctionActionRequestId,
|
||||
@@ -1579,8 +1671,7 @@ export class AuctionService {
|
||||
|
||||
return {
|
||||
actionRequest: {
|
||||
observedProcessingLeaseVersion:
|
||||
reserved.observedProcessingLeaseVersion,
|
||||
observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion,
|
||||
processingOwnerToken,
|
||||
scopeKey: reserved.actionRequestScopeKey,
|
||||
},
|
||||
@@ -1627,7 +1718,10 @@ export class AuctionService {
|
||||
| { durationSeconds: number; mode: 'set-relative' };
|
||||
expectedPhase: string;
|
||||
historyMutation?: Record<string, unknown>;
|
||||
liveStatePatch: Record<string, string | number | boolean | null | undefined>;
|
||||
liveStatePatch: Record<
|
||||
string,
|
||||
string | number | boolean | null | undefined
|
||||
>;
|
||||
matchSideEffectMutation?: Record<string, unknown>;
|
||||
shouldBroadcastStateAfterDurability?: boolean;
|
||||
shouldResetBidRuntime?: boolean;
|
||||
@@ -1644,8 +1738,7 @@ export class AuctionService {
|
||||
const expectedAuctionHistorySequence = this.numberFromState(
|
||||
params.state.currentAuctionHistorySequence,
|
||||
);
|
||||
const auctionHistorySequence =
|
||||
expectedAuctionHistorySequence + 1;
|
||||
const auctionHistorySequence = expectedAuctionHistorySequence + 1;
|
||||
const auctionStateTransitionId =
|
||||
params.actionRequest?.auctionStateTransitionId ||
|
||||
params.auctionStateTransitionId ||
|
||||
@@ -1671,6 +1764,7 @@ export class AuctionService {
|
||||
(params.auction.matchSideEffectRevision ?? 0) + 1;
|
||||
afterAuctionMongoProjection.matchSideEffectError = undefined;
|
||||
}
|
||||
|
||||
const durabilityPayload = {
|
||||
afterAuctionMongoProjection,
|
||||
auctionActionType: params.action,
|
||||
@@ -1695,7 +1789,8 @@ export class AuctionService {
|
||||
),
|
||||
auctionHistorySequence,
|
||||
auctionLifecycleId:
|
||||
params.actionRequest?.expectedAuctionLifecycleId ?? auctionLifecycleId,
|
||||
params.actionRequest?.expectedAuctionLifecycleId ??
|
||||
auctionLifecycleId,
|
||||
auctionStateTransitionId,
|
||||
broadcastStateRevision: expectedRevision + 1,
|
||||
deadline: params.deadline,
|
||||
@@ -1709,7 +1804,8 @@ export class AuctionService {
|
||||
? this.stringFromState(params.state.currentBidRoundPlayerUserId)
|
||||
: undefined),
|
||||
expectedAuctionHistorySequence,
|
||||
expectedPhase: params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
||||
expectedPhase:
|
||||
params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
||||
expectedRevision,
|
||||
liveStatePatch: params.liveStatePatch,
|
||||
matchId,
|
||||
@@ -1719,6 +1815,27 @@ export class AuctionService {
|
||||
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 자리에 풀 문장이 들어가 매핑이 어렵다).
|
||||
@@ -1762,9 +1879,8 @@ export class AuctionService {
|
||||
)) {
|
||||
const teamIndex = this.numberFromState(team.teamIndex);
|
||||
if (teamIndex < 1) continue;
|
||||
clearedTeamLiveStatePatch[
|
||||
`team:${teamIndex}:remainingBidPointAmount`
|
||||
] = 0;
|
||||
clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] =
|
||||
0;
|
||||
clearedTeamLiveStatePatch[
|
||||
`team:${teamIndex}:assignedAuctionTeamMemberCount`
|
||||
] = 0;
|
||||
@@ -1829,10 +1945,40 @@ export class AuctionService {
|
||||
-1,
|
||||
);
|
||||
const currentHighestBidPointAmount = this.numberFromState(
|
||||
params.snapshot.currentHighestBidPointAmount ?? params.snapshot.currentBid,
|
||||
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,
|
||||
@@ -1874,8 +2020,10 @@ export class AuctionService {
|
||||
state: Record<string, unknown>,
|
||||
): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
|
||||
return {
|
||||
auctionPlayerOrder: this.arrayFromState(state.auctionPlayerOrder),
|
||||
auctionTeams: this.arrayFromState(state.auctionTeams),
|
||||
auctionPlayerOrder: this.cloneRedisStructureArray(
|
||||
state.auctionPlayerOrder,
|
||||
),
|
||||
auctionTeams: this.cloneRedisStructureArray(state.auctionTeams),
|
||||
bidRoundExtensionSeconds: this.numberFromState(
|
||||
state.bidRoundExtensionSeconds,
|
||||
5,
|
||||
@@ -1888,18 +2036,19 @@ export class AuctionService {
|
||||
state.initialTeamBidPointAmount,
|
||||
1000,
|
||||
),
|
||||
manualTopTierAuctionPriorityUserIds: this.arrayFromState(
|
||||
manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
|
||||
state.manualTopTierAuctionPriorityUserIds,
|
||||
),
|
||||
maximumBidRoundDurationSeconds: this.numberFromState(
|
||||
state.maximumBidRoundDurationSeconds,
|
||||
30,
|
||||
),
|
||||
passedAuctionPlayerQueue: this.arrayFromState(
|
||||
passedAuctionPlayerQueue: this.cloneRedisStructureArray(
|
||||
state.passedAuctionPlayerQueue,
|
||||
),
|
||||
topTierAuctionPriorityThreshold:
|
||||
this.isAuctionTopTierThreshold(state.topTierAuctionPriorityThreshold)
|
||||
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
||||
state.topTierAuctionPriorityThreshold,
|
||||
)
|
||||
? state.topTierAuctionPriorityThreshold
|
||||
: 'NONE',
|
||||
};
|
||||
@@ -1908,13 +2057,15 @@ export class AuctionService {
|
||||
private buildRedisStructureInputFromAuctionSnapshot(
|
||||
snapshot: Record<string, unknown>,
|
||||
): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
|
||||
const legacyTeams = this.arrayFromState(snapshot.teams);
|
||||
const legacyTeams = this.cloneRedisStructureArray(snapshot.teams);
|
||||
const auctionTeams = this.cloneRedisStructureArray(snapshot.auctionTeams);
|
||||
return {
|
||||
auctionPlayerOrder: this.arrayFromState(
|
||||
auctionPlayerOrder: this.cloneRedisStructureArray(
|
||||
snapshot.auctionPlayerOrder ?? snapshot.order,
|
||||
),
|
||||
auctionTeams: this.arrayFromState(snapshot.auctionTeams).length > 0
|
||||
? this.arrayFromState(snapshot.auctionTeams)
|
||||
auctionTeams:
|
||||
auctionTeams.length > 0
|
||||
? auctionTeams
|
||||
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
|
||||
bidRoundExtensionSeconds: this.numberFromState(
|
||||
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
|
||||
@@ -1931,7 +2082,7 @@ export class AuctionService {
|
||||
snapshot.initialTeamBidPointAmount ?? snapshot.initialPoints,
|
||||
1000,
|
||||
),
|
||||
manualTopTierAuctionPriorityUserIds: this.arrayFromState(
|
||||
manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
|
||||
snapshot.manualTopTierAuctionPriorityUserIds ??
|
||||
snapshot.manualTopTierUserIds,
|
||||
),
|
||||
@@ -1939,14 +2090,14 @@ export class AuctionService {
|
||||
snapshot.maximumBidRoundDurationSeconds ?? snapshot.maxTimerSeconds,
|
||||
30,
|
||||
),
|
||||
passedAuctionPlayerQueue: this.arrayFromState(
|
||||
passedAuctionPlayerQueue: this.cloneRedisStructureArray(
|
||||
snapshot.passedAuctionPlayerQueue ?? snapshot.passedQueue,
|
||||
),
|
||||
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
||||
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
|
||||
)
|
||||
? (snapshot.topTierAuctionPriorityThreshold ??
|
||||
snapshot.topTierThreshold) as never
|
||||
? ((snapshot.topTierAuctionPriorityThreshold ??
|
||||
snapshot.topTierThreshold) as never)
|
||||
: 'NONE',
|
||||
};
|
||||
}
|
||||
@@ -2064,7 +2215,9 @@ export class AuctionService {
|
||||
}
|
||||
|
||||
private convertRedisTeamsToLegacyTeams(
|
||||
auctionTeams: Parameters<typeof stringifyAuctionRedisStructureState>[0]['auctionTeams'],
|
||||
auctionTeams: Parameters<
|
||||
typeof stringifyAuctionRedisStructureState
|
||||
>[0]['auctionTeams'],
|
||||
): AuctionTeam[] {
|
||||
return auctionTeams.map((team) => ({
|
||||
captainUserId: team.captainUserId as mongoose.Types.ObjectId,
|
||||
@@ -2090,13 +2243,20 @@ export class AuctionService {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
private cloneRedisStructureArray<T = never>(value: unknown): T[] {
|
||||
// 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다.
|
||||
// structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로
|
||||
// JSON 클론으로 깊은 복사 + ObjectId/Date 정규화를 함께 수행한다.
|
||||
return JSON.parse(JSON.stringify(this.arrayFromState<T>(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() ?? '';
|
||||
return typeof value === 'string' ? value : (value?.toString() ?? '');
|
||||
}
|
||||
|
||||
private isAuctionTopTierThreshold(
|
||||
@@ -2218,7 +2378,9 @@ export class AuctionService {
|
||||
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
|
||||
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
|
||||
@@ -2507,7 +2669,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[] = [
|
||||
{
|
||||
@@ -2531,6 +2693,12 @@ export class AuctionService {
|
||||
members,
|
||||
};
|
||||
});
|
||||
if (matchTeams.length === 0) {
|
||||
throw new Error(
|
||||
`Auction completed without teams for match ${match._id.toString()}.`,
|
||||
);
|
||||
}
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
@@ -2557,7 +2725,7 @@ export class AuctionService {
|
||||
structureInput.auctionTeams,
|
||||
);
|
||||
|
||||
match.teams = teams.map((team) => {
|
||||
const matchTeams = teams.map((team) => {
|
||||
const captain = participantByUserId.get(team.captainUserId.toString());
|
||||
const members: MatchTeamMember[] = [
|
||||
{
|
||||
@@ -2566,7 +2734,10 @@ export class AuctionService {
|
||||
cost: 0,
|
||||
},
|
||||
...team.members
|
||||
.filter((member) => member.userId.toString() !== team.captainUserId.toString())
|
||||
.filter(
|
||||
(member) =>
|
||||
member.userId.toString() !== team.captainUserId.toString(),
|
||||
)
|
||||
.map((member) => ({
|
||||
userId: member.userId,
|
||||
assignedPosition: member.assignedPosition,
|
||||
@@ -2581,6 +2752,12 @@ export class AuctionService {
|
||||
members,
|
||||
};
|
||||
});
|
||||
if (matchTeams.length === 0) {
|
||||
throw new Error(
|
||||
`Redis auction completed without teams for match ${match._id.toString()}.`,
|
||||
);
|
||||
}
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
@@ -2602,7 +2779,8 @@ export class AuctionService {
|
||||
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
|
||||
currentAuctionPlayerOrderIndex:
|
||||
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
|
||||
currentAuctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
||||
currentAuctionRound:
|
||||
auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
||||
initialTeamBidPointAmount:
|
||||
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
|
||||
manualTopTierAuctionPriorityUserIds:
|
||||
@@ -2614,7 +2792,9 @@ export class AuctionService {
|
||||
passedAuctionPlayerQueue:
|
||||
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
|
||||
topTierAuctionPriorityThreshold:
|
||||
auction.topTierAuctionPriorityThreshold ?? auction.topTierThreshold ?? 'NONE',
|
||||
auction.topTierAuctionPriorityThreshold ??
|
||||
auction.topTierThreshold ??
|
||||
'NONE',
|
||||
};
|
||||
await this.auctionRedisCommandService.hydrateState(
|
||||
auction.matchId.toString(),
|
||||
@@ -2647,14 +2827,16 @@ export class AuctionService {
|
||||
expectedAuctionLifecycleId?: string,
|
||||
): Promise<void> {
|
||||
const keys = buildAuctionRedisKeys(matchId);
|
||||
const cleared = await this.auctionRedisService.raw().sendCommand([
|
||||
const cleared = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'EVAL',
|
||||
[
|
||||
"local expectedAuctionLifecycleId = ARGV[2]",
|
||||
'local expectedAuctionLifecycleId = ARGV[2]',
|
||||
"if expectedAuctionLifecycleId ~= '' then",
|
||||
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
|
||||
" if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
|
||||
" return 0",
|
||||
' if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
|
||||
' return 0',
|
||||
' end',
|
||||
'end',
|
||||
"redis.call('ZREM', KEYS[2], ARGV[1])",
|
||||
@@ -2689,7 +2871,9 @@ export class AuctionService {
|
||||
): Promise<void> {
|
||||
let cursor = '0';
|
||||
do {
|
||||
const reply = await this.auctionRedisService.raw().sendCommand([
|
||||
const reply = await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'SCAN',
|
||||
cursor,
|
||||
'MATCH',
|
||||
@@ -2714,20 +2898,23 @@ export class AuctionService {
|
||||
);
|
||||
if (payloadKeysToDelete.length === 0) continue;
|
||||
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZREM',
|
||||
keys.durabilityRetryQueueKey,
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand([
|
||||
'ZREM',
|
||||
keys.durabilityDeadLetterQueueKey,
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService.raw().sendCommand([
|
||||
'DEL',
|
||||
...payloadKeysToDelete,
|
||||
]);
|
||||
await this.auctionRedisService
|
||||
.raw()
|
||||
.sendCommand(['DEL', ...payloadKeysToDelete]);
|
||||
} while (cursor !== '0');
|
||||
}
|
||||
|
||||
@@ -2742,7 +2929,9 @@ export class AuctionService {
|
||||
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
|
||||
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
|
||||
} catch {
|
||||
this.logger.warn(`Failed to parse auction durability payload ${payloadKey}.`);
|
||||
this.logger.warn(
|
||||
`Failed to parse auction durability payload ${payloadKey}.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2855,13 +3044,16 @@ async function runWithConcurrency<T>(
|
||||
if (items.length === 0) return;
|
||||
|
||||
const queue = [...items];
|
||||
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
|
||||
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);
|
||||
}
|
||||
@@ -191,4 +191,142 @@ describe('CommunityStatsService', () => {
|
||||
response,
|
||||
);
|
||||
});
|
||||
|
||||
it('includes internal match route fields in user internal history matches', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const participant = record(matchId);
|
||||
participant.userId = userId.toString();
|
||||
participant.gameNumber = 2;
|
||||
participant.riotMatchId = 'KR_1234';
|
||||
|
||||
const cacheService = {
|
||||
get: jest.fn().mockResolvedValue(null),
|
||||
set: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||
const matchStatsRepository = {
|
||||
findUserRecordFragments: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ matchId, records: [participant] }]),
|
||||
findDetailsByMatches: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ matchId, gameDetails: [] }]),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const service = new CommunityStatsService(
|
||||
{} as ConnectionService,
|
||||
cacheService,
|
||||
matchStatsRepository,
|
||||
{} as MatchStatsService,
|
||||
);
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
|
||||
jest.fn().mockResolvedValue({
|
||||
community: {},
|
||||
season: {
|
||||
id: 'all',
|
||||
label: '전체',
|
||||
startedAt: null,
|
||||
endedAt: null,
|
||||
},
|
||||
from: null,
|
||||
to: null,
|
||||
});
|
||||
const buildBaseDataset = jest.spyOn(
|
||||
service as unknown as { buildBaseDataset: jest.Mock },
|
||||
'buildBaseDataset',
|
||||
);
|
||||
|
||||
const response = await service.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { limit: 5 },
|
||||
});
|
||||
|
||||
expect(response.matches[0]).toMatchObject({
|
||||
matchId: 'KR_1234',
|
||||
internalMatchId: matchId.toString(),
|
||||
gameNumber: 2,
|
||||
queueLabel: '내전',
|
||||
});
|
||||
expect(matchStatsRepository.findUserRecordFragments).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
userId,
|
||||
fromGameCreation: undefined,
|
||||
toGameCreation: undefined,
|
||||
limit: 300,
|
||||
});
|
||||
expect(
|
||||
matchStatsRepository.findDetailsByMatches.mock.calls[0][0].matchIds.map(
|
||||
(id) => id.toString(),
|
||||
),
|
||||
).toEqual([matchId.toString()]);
|
||||
expect(buildBaseDataset).not.toHaveBeenCalled();
|
||||
expect(cacheService.set).toHaveBeenCalledWith(
|
||||
expect.stringContaining(`userInternal:v3:${userId.toString()}`),
|
||||
response,
|
||||
);
|
||||
});
|
||||
|
||||
it('coalesces concurrent user internal history cache misses', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const participant = record(matchId);
|
||||
participant.userId = userId.toString();
|
||||
|
||||
let resolveFragments:
|
||||
| ((fragments: Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>) => void)
|
||||
| undefined;
|
||||
const fragmentsPromise = new Promise<
|
||||
Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>
|
||||
>((resolve) => {
|
||||
resolveFragments = resolve;
|
||||
});
|
||||
const cacheService = {
|
||||
get: jest.fn().mockResolvedValue(null),
|
||||
set: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||
const matchStatsRepository = {
|
||||
findUserRecordFragments: jest.fn().mockReturnValue(fragmentsPromise),
|
||||
findDetailsByMatches: jest.fn().mockResolvedValue([]),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const service = new CommunityStatsService(
|
||||
{} as ConnectionService,
|
||||
cacheService,
|
||||
matchStatsRepository,
|
||||
{} as MatchStatsService,
|
||||
);
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
|
||||
jest.fn().mockResolvedValue({
|
||||
community: {},
|
||||
season: {
|
||||
id: 'all',
|
||||
label: '전체',
|
||||
startedAt: null,
|
||||
endedAt: null,
|
||||
},
|
||||
from: null,
|
||||
to: null,
|
||||
});
|
||||
|
||||
const first = service.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { limit: 5 },
|
||||
});
|
||||
const second = service.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { limit: 5 },
|
||||
});
|
||||
await Promise.resolve();
|
||||
resolveFragments?.([{ matchId, records: [participant] }]);
|
||||
const [firstResponse, secondResponse] = await Promise.all([first, second]);
|
||||
|
||||
expect(firstResponse).toBe(secondResponse);
|
||||
expect(matchStatsRepository.findUserRecordFragments).toHaveBeenCalledTimes(
|
||||
1,
|
||||
);
|
||||
expect(cacheService.set).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,11 @@ import type {
|
||||
TeamInsightsResponse,
|
||||
UserInternalHistoryResponse,
|
||||
} from './community-stats.types';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import {
|
||||
MatchStatsDetailFragment,
|
||||
MatchStatsRepository,
|
||||
MatchStatsUserRecordFragment,
|
||||
} from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
import {
|
||||
InternalGameDetail,
|
||||
@@ -55,6 +59,10 @@ interface BaseDataset {
|
||||
@Injectable()
|
||||
export class CommunityStatsService {
|
||||
private readonly logger = new Logger(CommunityStatsService.name);
|
||||
private readonly userInternalHistoryInFlight = new Map<
|
||||
string,
|
||||
Promise<UserInternalHistoryResponse>
|
||||
>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
@@ -293,7 +301,7 @@ export class CommunityStatsService {
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<UserInternalHistoryResponse> {
|
||||
const key = this.cacheKey(
|
||||
`userInternal:${params.userId.toString()}`,
|
||||
`userInternal:v3:${params.userId.toString()}`,
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
@@ -301,38 +309,20 @@ export class CommunityStatsService {
|
||||
await this.cacheService.get<UserInternalHistoryResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const allUserRecords = dataset.records
|
||||
.filter((record) => record.userId === params.userId.toString())
|
||||
.sort((left, right) => right.gameCreation - left.gameCreation);
|
||||
const records = this.applyChampionFilter(allUserRecords, params.filters);
|
||||
const limit = this.clampLimit(params.filters.limit, 30, 50);
|
||||
const cursor = params.filters.cursor;
|
||||
const page = records
|
||||
.filter((record) => !cursor || record.gameCreation < cursor)
|
||||
.slice(0, limit + 1);
|
||||
const visible = page.slice(0, limit);
|
||||
const response: UserInternalHistoryResponse = {
|
||||
season: dataset.season,
|
||||
championStats: this.buildUserChampionStats(
|
||||
allUserRecords,
|
||||
dataset.season,
|
||||
),
|
||||
summary: this.buildUserSummary(records, visible.length || limit),
|
||||
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
|
||||
nextCursor:
|
||||
page.length > limit
|
||||
? (visible[visible.length - 1]?.gameCreation ?? null)
|
||||
: null,
|
||||
lastFetchedAt: records[0]
|
||||
? new Date(records[0].gameCreation).toISOString()
|
||||
: null,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
// Auction viewers can all request the same next player's internal history
|
||||
// at once. Coalesce local cache misses so one player change does one DB read.
|
||||
const inFlight = this.userInternalHistoryInFlight.get(key);
|
||||
if (inFlight) return inFlight;
|
||||
|
||||
const promise = this.buildUserInternalHistoryResponse(params, key);
|
||||
this.userInternalHistoryInFlight.set(key, promise);
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
if (this.userInternalHistoryInFlight.get(key) === promise) {
|
||||
this.userInternalHistoryInFlight.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public invalidateCommunity(
|
||||
@@ -397,6 +387,120 @@ export class CommunityStatsService {
|
||||
};
|
||||
}
|
||||
|
||||
private async buildUserInternalHistoryResponse(
|
||||
params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
},
|
||||
cacheKey: string,
|
||||
): Promise<UserInternalHistoryResponse> {
|
||||
const context = await this.resolveContext(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const userId = params.userId.toString();
|
||||
const fragments = await this.matchStatsRepository.findUserRecordFragments({
|
||||
communityId: params.communityId,
|
||||
userId: params.userId,
|
||||
fromGameCreation: context.from?.getTime(),
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
});
|
||||
const allUserRecords = this.extractUserRecords(
|
||||
fragments,
|
||||
userId,
|
||||
context,
|
||||
);
|
||||
const records = this.applyChampionFilter(allUserRecords, params.filters);
|
||||
const limit = this.clampLimit(params.filters.limit, 30, 50);
|
||||
const cursor = params.filters.cursor;
|
||||
const page = records
|
||||
.filter((record) => !cursor || record.gameCreation < cursor)
|
||||
.slice(0, limit + 1);
|
||||
const visible = page.slice(0, limit);
|
||||
const detailsByMatchId = await this.loadVisibleDetails(
|
||||
params.communityId,
|
||||
visible,
|
||||
context,
|
||||
);
|
||||
const dataset: BaseDataset = {
|
||||
season: context.season,
|
||||
matches: [],
|
||||
records: allUserRecords,
|
||||
detailsByMatchId,
|
||||
};
|
||||
const response: UserInternalHistoryResponse = {
|
||||
season: context.season,
|
||||
championStats: this.buildUserChampionStats(
|
||||
allUserRecords,
|
||||
context.season,
|
||||
),
|
||||
summary: this.buildUserSummary(records, visible.length || limit),
|
||||
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
|
||||
nextCursor:
|
||||
page.length > limit
|
||||
? (visible[visible.length - 1]?.gameCreation ?? null)
|
||||
: null,
|
||||
lastFetchedAt: records[0]
|
||||
? new Date(records[0].gameCreation).toISOString()
|
||||
: null,
|
||||
};
|
||||
await this.cacheService.set(cacheKey, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
private extractUserRecords(
|
||||
fragments: MatchStatsUserRecordFragment[],
|
||||
userId: string,
|
||||
context: CommunityStatsContext,
|
||||
): InternalRecord[] {
|
||||
return fragments
|
||||
.flatMap((fragment) =>
|
||||
(fragment.records as InternalRecord[]).filter(
|
||||
(record) =>
|
||||
record.userId === userId &&
|
||||
this.isGameInRange(record.gameCreation, context),
|
||||
),
|
||||
)
|
||||
.sort((left, right) => right.gameCreation - left.gameCreation);
|
||||
}
|
||||
|
||||
private async loadVisibleDetails(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
visible: InternalRecord[],
|
||||
context: CommunityStatsContext,
|
||||
): Promise<Map<string, InternalGameDetail[]>> {
|
||||
const matchIds = [
|
||||
...new Set(
|
||||
visible
|
||||
.map((record) => record.matchId)
|
||||
.filter((matchId) => mongoose.isValidObjectId(matchId)),
|
||||
),
|
||||
].map((matchId) => new mongoose.Types.ObjectId(matchId));
|
||||
const fragments = await this.matchStatsRepository.findDetailsByMatches({
|
||||
communityId,
|
||||
matchIds,
|
||||
});
|
||||
return this.toDetailsByMatchId(fragments, context);
|
||||
}
|
||||
|
||||
private toDetailsByMatchId(
|
||||
fragments: MatchStatsDetailFragment[],
|
||||
context: CommunityStatsContext,
|
||||
): Map<string, InternalGameDetail[]> {
|
||||
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
|
||||
for (const fragment of fragments) {
|
||||
detailsByMatchId.set(
|
||||
fragment.matchId.toString(),
|
||||
(fragment.gameDetails as InternalGameDetail[]).filter((game) =>
|
||||
this.isGameInRange(game.gameCreation, context),
|
||||
),
|
||||
);
|
||||
}
|
||||
return detailsByMatchId;
|
||||
}
|
||||
|
||||
private async rebuildMissingOrStaleFragments(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<number> {
|
||||
@@ -789,6 +893,8 @@ export class CommunityStatsService {
|
||||
?.find((game) => game.riotMatchId === record.riotMatchId);
|
||||
return {
|
||||
matchId: record.riotMatchId,
|
||||
internalMatchId: record.matchId,
|
||||
gameNumber: record.gameNumber,
|
||||
queueId: 0,
|
||||
queueLabel: '내전',
|
||||
gameCreation: record.gameCreation,
|
||||
|
||||
@@ -3,6 +3,16 @@ import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||
|
||||
export type MatchStatsUserRecordFragment = Pick<
|
||||
MatchStats,
|
||||
'matchId' | 'records'
|
||||
>;
|
||||
|
||||
export type MatchStatsDetailFragment = Pick<
|
||||
MatchStats,
|
||||
'matchId' | 'gameDetails'
|
||||
>;
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsRepository {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
@@ -68,6 +78,53 @@ export class MatchStatsRepository {
|
||||
toGameCreation?: number;
|
||||
}): Promise<MatchStatsDocument[]> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
const filter = this.buildUserFilter(params);
|
||||
|
||||
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
||||
}
|
||||
|
||||
public async findUserRecordFragments(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
fromGameCreation?: number;
|
||||
toGameCreation?: number;
|
||||
limit?: number;
|
||||
}): Promise<MatchStatsUserRecordFragment[]> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
const filter = this.buildUserFilter(params);
|
||||
|
||||
// User history only needs records for summaries/page selection; gameDetails
|
||||
// are much larger and are fetched separately for the visible page.
|
||||
return MatchStatsModel.find(filter)
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(params.limit ?? 300)
|
||||
.select({ _id: 0, matchId: 1, records: 1 })
|
||||
.lean<MatchStatsUserRecordFragment[]>()
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async findDetailsByMatches(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchIds: mongoose.Types.ObjectId[];
|
||||
}): Promise<MatchStatsDetailFragment[]> {
|
||||
if (params.matchIds.length === 0) return [];
|
||||
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
return MatchStatsModel.find({
|
||||
communityId: params.communityId,
|
||||
matchId: { $in: params.matchIds },
|
||||
})
|
||||
.select({ _id: 0, matchId: 1, gameDetails: 1 })
|
||||
.lean<MatchStatsDetailFragment[]>()
|
||||
.exec();
|
||||
}
|
||||
|
||||
private buildUserFilter(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
fromGameCreation?: number;
|
||||
toGameCreation?: number;
|
||||
}): Record<string, unknown> {
|
||||
const filter: Record<string, unknown> = {
|
||||
communityId: params.communityId,
|
||||
userIds: params.userId,
|
||||
@@ -78,7 +135,6 @@ export class MatchStatsRepository {
|
||||
if (params.toGameCreation !== undefined) {
|
||||
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||
}
|
||||
|
||||
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,13 @@ import {
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||
|
||||
const SWEEP_INTERVAL_MS = 60 * 1000;
|
||||
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
||||
const SWEEP_LOCK_KEY = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
|
||||
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
|
||||
|
||||
@Injectable()
|
||||
export class DakaoOutboxSweeperService
|
||||
@@ -16,7 +19,10 @@ export class DakaoOutboxSweeperService
|
||||
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
|
||||
private timer: NodeJS.Timeout | undefined;
|
||||
|
||||
constructor(private readonly outboxService: DakaoOutboxService) {}
|
||||
constructor(
|
||||
private readonly outboxService: DakaoOutboxService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.timer = setInterval(() => {
|
||||
@@ -31,12 +37,23 @@ export class DakaoOutboxSweeperService
|
||||
|
||||
private async sweep(): Promise<void> {
|
||||
try {
|
||||
const swept = await this.outboxService.sweepStale({
|
||||
const swept = await this.distributedLockService.runWithLock(
|
||||
{
|
||||
lockKey: SWEEP_LOCK_KEY,
|
||||
lockExpirationDurationMilliseconds:
|
||||
SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
},
|
||||
async () =>
|
||||
this.outboxService.sweepStale({
|
||||
staleMs: STALE_OUTBOX_MS,
|
||||
limit: 20,
|
||||
});
|
||||
if (swept > 0) {
|
||||
this.logger.warn(`Re-published ${swept} stale Dakao outbox messages.`);
|
||||
}),
|
||||
);
|
||||
const sweptCount = swept ?? 0;
|
||||
if (sweptCount > 0) {
|
||||
this.logger.warn(
|
||||
`Re-published ${sweptCount} stale Dakao outbox messages.`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error(
|
||||
|
||||
@@ -70,8 +70,7 @@ describe('DakaoOutboxService', () => {
|
||||
process.env.NODE_ENV = 'staging';
|
||||
|
||||
try {
|
||||
const exec = jest.fn().mockResolvedValue([
|
||||
{
|
||||
const staleRow = {
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
type: 'chat.send-message',
|
||||
eventSource: 'lolympus',
|
||||
@@ -81,33 +80,45 @@ describe('DakaoOutboxService', () => {
|
||||
chatroomId: '18474390111480678',
|
||||
segments: [{ kind: 'text', text: 'done' }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
};
|
||||
const exec = jest.fn().mockResolvedValue([staleRow]);
|
||||
const lean = jest.fn().mockReturnValue({ exec });
|
||||
const limit = jest.fn().mockReturnValue({ lean });
|
||||
const sort = jest.fn().mockReturnValue({ limit });
|
||||
const claimExec = jest.fn().mockResolvedValue(staleRow);
|
||||
const claimLean = jest.fn().mockReturnValue({ exec: claimExec });
|
||||
const outboxModel = {
|
||||
find: jest.fn().mockReturnValue({ sort }),
|
||||
findOneAndUpdate: jest.fn().mockReturnValue({ lean: claimLean }),
|
||||
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
|
||||
};
|
||||
const { service } = makeService(outboxModel);
|
||||
const enqueue = jest
|
||||
.spyOn(service, 'enqueueAndPublish')
|
||||
.mockResolvedValue(undefined);
|
||||
const { service, natsService } = makeService(outboxModel);
|
||||
|
||||
await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe(
|
||||
1,
|
||||
);
|
||||
|
||||
expect(enqueue).toHaveBeenCalledWith(
|
||||
expect(outboxModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
publishLeaseOwnerIdentifier: expect.any(String),
|
||||
publishLeaseExpiresAt: expect.any(Date),
|
||||
}),
|
||||
}),
|
||||
{ returnDocument: 'after' },
|
||||
);
|
||||
expect(natsService.publishJetStream).toHaveBeenCalledWith(
|
||||
'staging.dakao.chat.send-message.v1',
|
||||
expect.objectContaining({
|
||||
envelope: expect.objectContaining({
|
||||
resultSubjects: {
|
||||
succeeded:
|
||||
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
{ messageId: 'lolympus:chat.send-message:chat-log-1' },
|
||||
);
|
||||
} finally {
|
||||
process.env.NODE_ENV = previousNodeEnv;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { NatsService } from '../global/nats/nats.service';
|
||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
|
||||
const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message';
|
||||
const TERMINAL_STATES = ['sent', 'failed'] as const;
|
||||
const DEFAULT_PUBLISH_LEASE_DURATION_MILLISECONDS = 60_000;
|
||||
|
||||
@Injectable()
|
||||
export class DakaoOutboxService {
|
||||
@@ -50,35 +52,59 @@ export class DakaoOutboxService {
|
||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||
).exec();
|
||||
|
||||
await this.publishCommand({
|
||||
subject: params.subject,
|
||||
eventId: params.eventId,
|
||||
envelope: params.envelope,
|
||||
});
|
||||
}
|
||||
|
||||
private async publishCommand<TPayload>(params: {
|
||||
subject: string;
|
||||
eventId: string;
|
||||
envelope: DakaoCommandEnvelope<TPayload>;
|
||||
publishLeaseOwnerIdentifier?: string;
|
||||
}): Promise<void> {
|
||||
const OutboxModel =
|
||||
await this.connectionService.getModel('dakaoOutboxMessage');
|
||||
const updateFilter = {
|
||||
eventId: params.eventId,
|
||||
state: { $nin: TERMINAL_STATES },
|
||||
...(params.publishLeaseOwnerIdentifier
|
||||
? { publishLeaseOwnerIdentifier: params.publishLeaseOwnerIdentifier }
|
||||
: {}),
|
||||
};
|
||||
try {
|
||||
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
||||
messageId: params.eventId,
|
||||
});
|
||||
await OutboxModel.updateOne(
|
||||
{
|
||||
eventId: params.eventId,
|
||||
state: { $nin: TERMINAL_STATES },
|
||||
},
|
||||
updateFilter,
|
||||
{
|
||||
$set: {
|
||||
state: 'published',
|
||||
publishedAt: new Date(),
|
||||
},
|
||||
$inc: { publishAttempts: 1 },
|
||||
$unset: { lastPublishError: '' },
|
||||
$unset: {
|
||||
lastPublishError: '',
|
||||
publishLeaseOwnerIdentifier: '',
|
||||
publishLeaseExpiresAt: '',
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
} catch (err) {
|
||||
await OutboxModel.updateOne(
|
||||
{
|
||||
eventId: params.eventId,
|
||||
state: { $nin: TERMINAL_STATES },
|
||||
},
|
||||
updateFilter,
|
||||
{
|
||||
$inc: { publishAttempts: 1 },
|
||||
$set: {
|
||||
lastPublishError: (err as Error)?.message ?? String(err),
|
||||
},
|
||||
$unset: {
|
||||
publishLeaseOwnerIdentifier: '',
|
||||
publishLeaseExpiresAt: '',
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
this.logger.error(
|
||||
@@ -146,40 +172,77 @@ export class DakaoOutboxService {
|
||||
|
||||
public async sweepStale(params?: {
|
||||
staleMs?: number;
|
||||
publishLeaseDurationMilliseconds?: number;
|
||||
limit?: number;
|
||||
}): Promise<number> {
|
||||
const OutboxModel =
|
||||
await this.connectionService.getModel('dakaoOutboxMessage');
|
||||
const currentTimestamp = new Date();
|
||||
const staleBefore = new Date(
|
||||
Date.now() - (params?.staleMs ?? 5 * 60 * 1000),
|
||||
currentTimestamp.getTime() - (params?.staleMs ?? 5 * 60 * 1000),
|
||||
);
|
||||
const publishLeaseOwnerIdentifier = `dakao-outbox-sweeper:${process.pid}:${randomUUID()}`;
|
||||
const publishLeaseExpiresAt = new Date(
|
||||
currentTimestamp.getTime() +
|
||||
(params?.publishLeaseDurationMilliseconds ??
|
||||
DEFAULT_PUBLISH_LEASE_DURATION_MILLISECONDS),
|
||||
);
|
||||
const rows = await OutboxModel.find({
|
||||
state: { $in: ['pending', 'published'] },
|
||||
updatedAt: { $lte: staleBefore },
|
||||
$or: [
|
||||
{ publishLeaseExpiresAt: { $exists: false } },
|
||||
{ publishLeaseExpiresAt: { $lte: currentTimestamp } },
|
||||
],
|
||||
})
|
||||
.sort({ updatedAt: 1 })
|
||||
.limit(params?.limit ?? 20)
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
let swept = 0;
|
||||
for (const row of rows) {
|
||||
await this.enqueueAndPublish({
|
||||
subject: row.subject,
|
||||
const claimedRow = await OutboxModel.findOneAndUpdate(
|
||||
{
|
||||
eventId: row.eventId,
|
||||
state: { $in: ['pending', 'published'] },
|
||||
$or: [
|
||||
{ publishLeaseExpiresAt: { $exists: false } },
|
||||
{ publishLeaseExpiresAt: { $lte: currentTimestamp } },
|
||||
],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
publishLeaseOwnerIdentifier,
|
||||
publishLeaseExpiresAt,
|
||||
},
|
||||
},
|
||||
{ returnDocument: 'after' },
|
||||
)
|
||||
.lean()
|
||||
.exec();
|
||||
if (!claimedRow) continue;
|
||||
|
||||
await this.publishCommand({
|
||||
subject: claimedRow.subject,
|
||||
eventId: claimedRow.eventId,
|
||||
publishLeaseOwnerIdentifier,
|
||||
envelope: {
|
||||
schema: 'dakao.command.v1',
|
||||
eventId: row.eventId,
|
||||
type: row.type,
|
||||
eventSource: row.eventSource,
|
||||
correlationId: row.correlationId,
|
||||
eventId: claimedRow.eventId,
|
||||
type: claimedRow.type,
|
||||
eventSource: claimedRow.eventSource,
|
||||
correlationId: claimedRow.correlationId,
|
||||
resultSubjects:
|
||||
row.resultSubjects ?? this.resolveDefaultResultSubjects(row.type),
|
||||
payload: row.payload,
|
||||
claimedRow.resultSubjects ??
|
||||
this.resolveDefaultResultSubjects(claimedRow.type),
|
||||
payload: claimedRow.payload,
|
||||
},
|
||||
});
|
||||
swept += 1;
|
||||
}
|
||||
|
||||
return rows.length;
|
||||
return swept;
|
||||
}
|
||||
|
||||
private resolveDefaultResultSubjects(
|
||||
|
||||
@@ -56,20 +56,20 @@ describe('DakaoSubscriber', () => {
|
||||
|
||||
expect(segments).toEqual([
|
||||
{ kind: 'mention', userId: '12345', displayText: '프리리' },
|
||||
{ kind: 'text', text: ' 사용법\n' },
|
||||
{ kind: 'text', text: ' 내전 명령어 사용법\n' },
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{ kind: 'text', text: ' !내전 일정\n' },
|
||||
{ kind: 'text', text: ' !내전 일정\u3000\n' },
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{
|
||||
kind: 'text',
|
||||
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\n',
|
||||
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
|
||||
},
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\n' },
|
||||
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{
|
||||
kind: 'text',
|
||||
text: ' !내전 선호포지션등록 포지션1,포지션2\n',
|
||||
text: ' !내전 선호포지션등록 포지션1,포지션2\u3000\n',
|
||||
},
|
||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||
{
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import {
|
||||
buildDoubleEliminationGameSlots,
|
||||
buildDoubleEliminationBracket,
|
||||
cancelDoubleEliminationBracketMatch,
|
||||
completeDoubleEliminationBracketMatch,
|
||||
resolveDoubleEliminationSeriesWinner,
|
||||
reshuffleDoubleEliminationSeeds,
|
||||
swapDoubleEliminationSeeds,
|
||||
} from './double-elimination.util';
|
||||
|
||||
function mongooseSubdocumentLike<T extends object>(value: T): T {
|
||||
const wrapper = {
|
||||
toObject: () => value,
|
||||
} as T & { toObject: () => T };
|
||||
|
||||
for (const [key, entryValue] of Object.entries(value)) {
|
||||
Object.defineProperty(wrapper, key, {
|
||||
enumerable: false,
|
||||
get: () => entryValue,
|
||||
});
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
describe('double-elimination util', () => {
|
||||
it('builds a 4-team bracket with winner, loser, and grand final matches', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
});
|
||||
|
||||
expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual(
|
||||
['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'],
|
||||
);
|
||||
expect(
|
||||
bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === 'WB_R1_M1',
|
||||
),
|
||||
).toMatchObject({
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 4,
|
||||
winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' },
|
||||
loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' },
|
||||
state: 'ready',
|
||||
});
|
||||
});
|
||||
|
||||
it('assigns extensible series rules to winner-bracket matches', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
winnerBracketGameCount: 5,
|
||||
});
|
||||
|
||||
expect(
|
||||
bracket.bracketMatches
|
||||
.filter((match) => match.bracketSide === 'winner')
|
||||
.map((match) => ({
|
||||
bracketMatchId: match.bracketMatchId,
|
||||
gameCount: match.gameCount,
|
||||
requiredWins: match.requiredWins,
|
||||
})),
|
||||
).toEqual([
|
||||
{ bracketMatchId: 'WB_R1_M1', gameCount: 5, requiredWins: 3 },
|
||||
{ bracketMatchId: 'WB_R1_M2', gameCount: 5, requiredWins: 3 },
|
||||
{ bracketMatchId: 'WB_FINAL', gameCount: 5, requiredWins: 3 },
|
||||
]);
|
||||
expect(
|
||||
bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === 'LB_R1_M1',
|
||||
),
|
||||
).toMatchObject({ gameCount: 1, requiredWins: 1 });
|
||||
expect(
|
||||
bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF'),
|
||||
).toMatchObject({ gameCount: 1, requiredWins: 1 });
|
||||
});
|
||||
|
||||
it('expands bracket match series into game slots', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
buildDoubleEliminationGameSlots(bracket.bracketMatches).slice(0, 7),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
gameNumber: 1,
|
||||
seriesGameNumber: 1,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 2,
|
||||
seriesGameNumber: 2,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 3,
|
||||
seriesGameNumber: 3,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M1' }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 4,
|
||||
seriesGameNumber: 1,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 5,
|
||||
seriesGameNumber: 2,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 6,
|
||||
seriesGameNumber: 3,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_R1_M2' }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 7,
|
||||
seriesGameNumber: 1,
|
||||
bracketMatch: expect.objectContaining({ bracketMatchId: 'WB_FINAL' }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('requires the configured number of wins before resolving a series winner', () => {
|
||||
const bracketMatch = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
}).bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1');
|
||||
|
||||
expect(
|
||||
resolveDoubleEliminationSeriesWinner(
|
||||
{ teamAIndex: 1, teamBIndex: 4, teamAWins: 1, teamBWins: 0 },
|
||||
bracketMatch!,
|
||||
),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
resolveDoubleEliminationSeriesWinner(
|
||||
{ teamAIndex: 1, teamBIndex: 4, teamAWins: 2, teamBWins: 1 },
|
||||
bracketMatch!,
|
||||
),
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it('completes a hydrated Mongoose-style bracket without losing subdocument fields', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
const hydratedLikeBracket = {
|
||||
...bracket,
|
||||
seeds: bracket.seeds.map(mongooseSubdocumentLike),
|
||||
bracketMatches: bracket.bracketMatches.map(mongooseSubdocumentLike),
|
||||
events: bracket.events.map(mongooseSubdocumentLike),
|
||||
};
|
||||
|
||||
const next = completeDoubleEliminationBracketMatch(hydratedLikeBracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
|
||||
expect(
|
||||
next.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL'),
|
||||
).toMatchObject({ teamAIndex: 1 });
|
||||
expect(
|
||||
next.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1'),
|
||||
).toMatchObject({ teamAIndex: 4 });
|
||||
});
|
||||
|
||||
it('moves winners and losers through a 4-team bracket and records top 3', () => {
|
||||
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
completedAt: new Date('2026-06-01T10:00:00.000Z'),
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
winnerTeamIndex: 2,
|
||||
completedBy: 'riot-result',
|
||||
completedAt: new Date('2026-06-01T10:30:00.000Z'),
|
||||
});
|
||||
|
||||
expect(
|
||||
bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === 'WB_FINAL',
|
||||
),
|
||||
).toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' });
|
||||
expect(
|
||||
bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === 'LB_R1_M1',
|
||||
),
|
||||
).toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' });
|
||||
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'LB_R1_M1',
|
||||
winnerTeamIndex: 3,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'LB_FINAL',
|
||||
winnerTeamIndex: 2,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'GF',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
|
||||
expect(bracket.placements).toEqual({
|
||||
firstTeamIndex: 1,
|
||||
secondTeamIndex: 2,
|
||||
thirdTeamIndex: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('creates reset final only when the loser bracket finalist wins grand final', () => {
|
||||
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
});
|
||||
for (const [bracketMatchId, winnerTeamIndex] of [
|
||||
['WB_R1_M1', 1],
|
||||
['WB_R1_M2', 2],
|
||||
['WB_FINAL', 1],
|
||||
['LB_R1_M1', 3],
|
||||
['LB_FINAL', 2],
|
||||
['GF', 2],
|
||||
] as const) {
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId,
|
||||
winnerTeamIndex,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
}
|
||||
|
||||
expect(bracket.resetFinalCreated).toBe(true);
|
||||
expect(bracket.placements).toEqual({ thirdTeamIndex: 3 });
|
||||
expect(
|
||||
bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === 'GF_RESET',
|
||||
),
|
||||
).toMatchObject({
|
||||
gameNumber: 7,
|
||||
bracketSide: 'reset-final',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
state: 'ready',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects completion cancellation when downstream matches are already completed', () => {
|
||||
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
winnerTeamIndex: 2,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
bracket = completeDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
winnerTeamIndex: 1,
|
||||
completedBy: 'riot-result',
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
cancelDoubleEliminationBracketMatch(bracket, {
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
}),
|
||||
).toThrow('downstream');
|
||||
});
|
||||
|
||||
it('allows changing seeds before the bracket has completed matches', () => {
|
||||
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: false,
|
||||
});
|
||||
|
||||
const swapped = swapDoubleEliminationSeeds(bracket, {
|
||||
leftSeedNumber: 1,
|
||||
rightSeedNumber: 4,
|
||||
});
|
||||
expect(swapped.seeds).toEqual([
|
||||
{ seedNumber: 1, teamIndex: 4 },
|
||||
{ seedNumber: 2, teamIndex: 2 },
|
||||
{ seedNumber: 3, teamIndex: 3 },
|
||||
{ seedNumber: 4, teamIndex: 1 },
|
||||
]);
|
||||
expect(
|
||||
reshuffleDoubleEliminationSeeds(bracket, () => 0).seeds.map(
|
||||
(seed) => seed.teamIndex,
|
||||
),
|
||||
).toEqual([2, 3, 4, 1]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,834 @@
|
||||
import type mongoose from 'mongoose';
|
||||
|
||||
export type DoubleEliminationBracketSide =
|
||||
| 'winner'
|
||||
| 'loser'
|
||||
| 'grand-final'
|
||||
| 'reset-final';
|
||||
|
||||
export type DoubleEliminationBracketMatchState =
|
||||
| 'pending'
|
||||
| 'ready'
|
||||
| 'completed';
|
||||
|
||||
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
|
||||
|
||||
export interface DoubleEliminationSeed {
|
||||
seedNumber: number;
|
||||
teamIndex: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchSource {
|
||||
type: 'seed' | 'winner' | 'loser';
|
||||
seedNumber?: number;
|
||||
bracketMatchId?: string;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchDestination {
|
||||
bracketMatchId: string;
|
||||
position: 'A' | 'B';
|
||||
}
|
||||
|
||||
export interface DoubleEliminationWalkover {
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
awardedBy?: mongoose.Types.ObjectId;
|
||||
awardedAt: Date;
|
||||
cancelledBy?: mongoose.Types.ObjectId;
|
||||
cancelledAt?: Date;
|
||||
cancelReason?: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatch {
|
||||
bracketMatchId: string;
|
||||
gameNumber: number;
|
||||
gameCount: number;
|
||||
requiredWins: number;
|
||||
bracketSide: DoubleEliminationBracketSide;
|
||||
roundNumber: number;
|
||||
matchNumber: number;
|
||||
state: DoubleEliminationBracketMatchState;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
teamASource?: DoubleEliminationBracketMatchSource;
|
||||
teamBSource?: DoubleEliminationBracketMatchSource;
|
||||
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
winnerTeamIndex?: number;
|
||||
loserTeamIndex?: number;
|
||||
completedBy?: DoubleEliminationCompletionType;
|
||||
completedAt?: Date;
|
||||
walkover?: DoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationPlacements {
|
||||
firstTeamIndex?: number;
|
||||
secondTeamIndex?: number;
|
||||
thirdTeamIndex?: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationEvent {
|
||||
type:
|
||||
| 'bracket-created'
|
||||
| 'seeds-reshuffled'
|
||||
| 'seeds-swapped'
|
||||
| 'bracket-match-completed'
|
||||
| 'bracket-match-cancelled'
|
||||
| 'walkover-awarded'
|
||||
| 'walkover-cancelled'
|
||||
| 'reset-final-created'
|
||||
| 'riot-result-cancelled';
|
||||
bracketMatchId?: string;
|
||||
actorUserId?: mongoose.Types.ObjectId;
|
||||
reason?: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracket {
|
||||
teamCount: 4 | 8;
|
||||
resetFinalEnabled: boolean;
|
||||
resetFinalCreated: boolean;
|
||||
seeds: DoubleEliminationSeed[];
|
||||
bracketMatches: DoubleEliminationBracketMatch[];
|
||||
placements: DoubleEliminationPlacements;
|
||||
events: DoubleEliminationEvent[];
|
||||
}
|
||||
|
||||
export interface BuildDoubleEliminationBracketOptions {
|
||||
resetFinalEnabled: boolean;
|
||||
winnerBracketGameCount?: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationSeriesRule {
|
||||
gameCount: number;
|
||||
requiredWins: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationGameSlot {
|
||||
gameNumber: number;
|
||||
seriesGameNumber: number;
|
||||
seriesGameCount: number;
|
||||
seriesRequiredWins: number;
|
||||
bracketMatch: DoubleEliminationBracketMatch;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationSeriesScore {
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
}
|
||||
|
||||
export interface CompleteDoubleEliminationBracketMatchParams {
|
||||
bracketMatchId: string;
|
||||
winnerTeamIndex: number;
|
||||
completedBy: DoubleEliminationCompletionType;
|
||||
completedAt?: Date;
|
||||
walkover?: DoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface CancelDoubleEliminationBracketMatchParams {
|
||||
bracketMatchId: string;
|
||||
cancelledBy?: mongoose.Types.ObjectId;
|
||||
cancelReason?: string;
|
||||
}
|
||||
|
||||
export function buildDoubleEliminationBracket(
|
||||
seededTeamIndexes: number[],
|
||||
options: BuildDoubleEliminationBracketOptions,
|
||||
): DoubleEliminationBracket {
|
||||
assertSupportedTeamCount(seededTeamIndexes.length);
|
||||
const seeds = seededTeamIndexes.map((teamIndex, index) => ({
|
||||
seedNumber: index + 1,
|
||||
teamIndex,
|
||||
}));
|
||||
const bracket: DoubleEliminationBracket = {
|
||||
teamCount: seededTeamIndexes.length as 4 | 8,
|
||||
resetFinalEnabled: options.resetFinalEnabled,
|
||||
resetFinalCreated: false,
|
||||
seeds,
|
||||
bracketMatches:
|
||||
seededTeamIndexes.length === 4
|
||||
? buildFourTeamBracketMatches(options)
|
||||
: buildEightTeamBracketMatches(options),
|
||||
placements: {},
|
||||
events: [
|
||||
{
|
||||
type: 'bracket-created',
|
||||
createdAt: new Date(),
|
||||
},
|
||||
],
|
||||
};
|
||||
applySeedTeams(bracket);
|
||||
refreshBracketMatchStates(bracket);
|
||||
return bracket;
|
||||
}
|
||||
|
||||
export function resolveDoubleEliminationSeriesRule(
|
||||
params: {
|
||||
bracketSide: DoubleEliminationBracketSide;
|
||||
bracketMatchId: string;
|
||||
roundNumber: number;
|
||||
},
|
||||
options: { winnerBracketGameCount?: number } = {},
|
||||
): DoubleEliminationSeriesRule {
|
||||
if (params.bracketSide === 'winner') {
|
||||
return seriesRule(options.winnerBracketGameCount ?? 3);
|
||||
}
|
||||
return seriesRule(1);
|
||||
}
|
||||
|
||||
export function buildDoubleEliminationGameSlots(
|
||||
bracketMatches: DoubleEliminationBracketMatch[],
|
||||
): DoubleEliminationGameSlot[] {
|
||||
const slots: DoubleEliminationGameSlot[] = [];
|
||||
let gameNumber = 1;
|
||||
for (const bracketMatch of bracketMatches) {
|
||||
const seriesGameCount = normalizeSeriesGameCount(bracketMatch.gameCount);
|
||||
const seriesRequiredWins =
|
||||
bracketMatch.requiredWins ?? requiredWinsForGameCount(seriesGameCount);
|
||||
for (
|
||||
let seriesGameNumber = 1;
|
||||
seriesGameNumber <= seriesGameCount;
|
||||
seriesGameNumber += 1
|
||||
) {
|
||||
slots.push({
|
||||
gameNumber,
|
||||
seriesGameNumber,
|
||||
seriesGameCount,
|
||||
seriesRequiredWins,
|
||||
bracketMatch,
|
||||
});
|
||||
gameNumber += 1;
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
export function resolveDoubleEliminationSeriesWinner(
|
||||
series: DoubleEliminationSeriesScore | undefined,
|
||||
bracketMatch: Pick<
|
||||
DoubleEliminationBracketMatch,
|
||||
'requiredWins' | 'teamAIndex' | 'teamBIndex'
|
||||
>,
|
||||
): number | undefined {
|
||||
if (!series) return undefined;
|
||||
const requiredWins = bracketMatch.requiredWins ?? 1;
|
||||
if (
|
||||
bracketMatch.teamAIndex &&
|
||||
series.teamAWins >= requiredWins &&
|
||||
series.teamAWins > series.teamBWins
|
||||
) {
|
||||
return bracketMatch.teamAIndex;
|
||||
}
|
||||
if (
|
||||
bracketMatch.teamBIndex &&
|
||||
series.teamBWins >= requiredWins &&
|
||||
series.teamBWins > series.teamAWins
|
||||
) {
|
||||
return bracketMatch.teamBIndex;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function reshuffleDoubleEliminationSeeds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
rng: () => number = Math.random,
|
||||
): DoubleEliminationBracket {
|
||||
assertSeedChangeAllowed(bracket);
|
||||
const teamIndexes = shuffleInPlace(
|
||||
bracket.seeds.map((seed) => seed.teamIndex),
|
||||
rng,
|
||||
);
|
||||
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-reshuffled');
|
||||
}
|
||||
|
||||
export function swapDoubleEliminationSeeds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
params: { leftSeedNumber: number; rightSeedNumber: number },
|
||||
): DoubleEliminationBracket {
|
||||
assertSeedChangeAllowed(bracket);
|
||||
const teamIndexes = [...bracket.seeds]
|
||||
.sort((left, right) => left.seedNumber - right.seedNumber)
|
||||
.map((seed) => seed.teamIndex);
|
||||
const leftIndex = params.leftSeedNumber - 1;
|
||||
const rightIndex = params.rightSeedNumber - 1;
|
||||
if (!teamIndexes[leftIndex] || !teamIndexes[rightIndex]) {
|
||||
throw new Error('Invalid seed number.');
|
||||
}
|
||||
[teamIndexes[leftIndex], teamIndexes[rightIndex]] = [
|
||||
teamIndexes[rightIndex],
|
||||
teamIndexes[leftIndex],
|
||||
];
|
||||
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-swapped');
|
||||
}
|
||||
|
||||
export function completeDoubleEliminationBracketMatch(
|
||||
bracket: DoubleEliminationBracket,
|
||||
params: CompleteDoubleEliminationBracketMatchParams,
|
||||
): DoubleEliminationBracket {
|
||||
const next = cloneBracket(bracket);
|
||||
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
|
||||
if (bracketMatch.state !== 'ready') {
|
||||
throw new Error('Bracket match is not ready.');
|
||||
}
|
||||
if (
|
||||
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
|
||||
bracketMatch.teamBIndex !== params.winnerTeamIndex
|
||||
) {
|
||||
throw new Error('Winner team is not assigned to this bracket match.');
|
||||
}
|
||||
|
||||
const loserTeamIndex =
|
||||
bracketMatch.teamAIndex === params.winnerTeamIndex
|
||||
? bracketMatch.teamBIndex
|
||||
: bracketMatch.teamAIndex;
|
||||
if (!loserTeamIndex) throw new Error('Loser team is missing.');
|
||||
|
||||
bracketMatch.state = 'completed';
|
||||
bracketMatch.winnerTeamIndex = params.winnerTeamIndex;
|
||||
bracketMatch.loserTeamIndex = loserTeamIndex;
|
||||
bracketMatch.completedBy = params.completedBy;
|
||||
bracketMatch.completedAt = params.completedAt ?? new Date();
|
||||
if (params.walkover) {
|
||||
bracketMatch.walkover = params.walkover;
|
||||
}
|
||||
|
||||
advanceTeam(next, bracketMatch.winnerAdvancesTo, params.winnerTeamIndex);
|
||||
advanceTeam(next, bracketMatch.loserAdvancesTo, loserTeamIndex);
|
||||
if (bracketMatch.bracketMatchId === 'LB_FINAL') {
|
||||
next.placements.thirdTeamIndex = loserTeamIndex;
|
||||
}
|
||||
if (bracketMatch.bracketMatchId === 'GF') {
|
||||
completeGrandFinal(next, bracketMatch);
|
||||
}
|
||||
if (bracketMatch.bracketMatchId === 'GF_RESET') {
|
||||
next.placements.firstTeamIndex = params.winnerTeamIndex;
|
||||
next.placements.secondTeamIndex = loserTeamIndex;
|
||||
}
|
||||
|
||||
refreshBracketMatchStates(next);
|
||||
next.events.push({
|
||||
type:
|
||||
params.completedBy === 'walkover'
|
||||
? 'walkover-awarded'
|
||||
: 'bracket-match-completed',
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
createdAt: bracketMatch.completedAt,
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export function cancelDoubleEliminationBracketMatch(
|
||||
bracket: DoubleEliminationBracket,
|
||||
params: CancelDoubleEliminationBracketMatchParams,
|
||||
): DoubleEliminationBracket {
|
||||
const next = cloneBracket(bracket);
|
||||
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
|
||||
if (bracketMatch.state !== 'completed') {
|
||||
throw new Error('Bracket match is not completed.');
|
||||
}
|
||||
|
||||
const descendants = collectDescendantBracketMatchIds(
|
||||
next,
|
||||
bracketMatch.bracketMatchId,
|
||||
);
|
||||
const completedDescendant = next.bracketMatches.find(
|
||||
(match) =>
|
||||
descendants.has(match.bracketMatchId) && match.state === 'completed',
|
||||
);
|
||||
if (completedDescendant) {
|
||||
throw new Error(
|
||||
'Cannot cancel because a downstream bracket match is completed.',
|
||||
);
|
||||
}
|
||||
|
||||
if (bracketMatch.bracketMatchId === 'GF') {
|
||||
next.bracketMatches = next.bracketMatches.filter(
|
||||
(match) => match.bracketMatchId !== 'GF_RESET',
|
||||
);
|
||||
next.resetFinalCreated = false;
|
||||
}
|
||||
|
||||
for (const descendantId of descendants) {
|
||||
const descendant = next.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === descendantId,
|
||||
);
|
||||
if (!descendant) continue;
|
||||
if (
|
||||
referencesBracketMatch(
|
||||
descendant.teamASource,
|
||||
bracketMatch.bracketMatchId,
|
||||
)
|
||||
) {
|
||||
descendant.teamAIndex = undefined;
|
||||
}
|
||||
if (
|
||||
referencesBracketMatch(
|
||||
descendant.teamBSource,
|
||||
bracketMatch.bracketMatchId,
|
||||
)
|
||||
) {
|
||||
descendant.teamBIndex = undefined;
|
||||
}
|
||||
descendant.winnerTeamIndex = undefined;
|
||||
descendant.loserTeamIndex = undefined;
|
||||
descendant.completedBy = undefined;
|
||||
descendant.completedAt = undefined;
|
||||
}
|
||||
|
||||
bracketMatch.winnerTeamIndex = undefined;
|
||||
bracketMatch.loserTeamIndex = undefined;
|
||||
bracketMatch.completedBy = undefined;
|
||||
bracketMatch.completedAt = undefined;
|
||||
if (bracketMatch.walkover?.active) {
|
||||
bracketMatch.walkover = {
|
||||
...bracketMatch.walkover,
|
||||
active: false,
|
||||
cancelledBy: params.cancelledBy,
|
||||
cancelledAt: new Date(),
|
||||
cancelReason: params.cancelReason,
|
||||
};
|
||||
}
|
||||
next.placements = {};
|
||||
refreshBracketMatchStates(next);
|
||||
next.events.push({
|
||||
type:
|
||||
bracketMatch.walkover && !bracketMatch.walkover.active
|
||||
? 'walkover-cancelled'
|
||||
: 'bracket-match-cancelled',
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
actorUserId: params.cancelledBy,
|
||||
reason: params.cancelReason,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export function findNextReadyDoubleEliminationBracketMatches(
|
||||
bracket: DoubleEliminationBracket | undefined,
|
||||
): DoubleEliminationBracketMatch[] {
|
||||
return (bracket?.bracketMatches ?? []).filter(
|
||||
(bracketMatch) => bracketMatch.state === 'ready',
|
||||
);
|
||||
}
|
||||
|
||||
export function hasCompletedDoubleEliminationBracketMatches(
|
||||
bracket: DoubleEliminationBracket | undefined,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
bracket?.bracketMatches.some(
|
||||
(bracketMatch) => bracketMatch.state === 'completed',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function rebuildWithSeeds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
teamIndexes: number[],
|
||||
eventType: DoubleEliminationEvent['type'],
|
||||
): DoubleEliminationBracket {
|
||||
const next = buildDoubleEliminationBracket(teamIndexes, {
|
||||
resetFinalEnabled: bracket.resetFinalEnabled,
|
||||
});
|
||||
next.events = [
|
||||
...bracket.events,
|
||||
{
|
||||
type: eventType,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
];
|
||||
return next;
|
||||
}
|
||||
|
||||
function completeGrandFinal(
|
||||
bracket: DoubleEliminationBracket,
|
||||
grandFinal: DoubleEliminationBracketMatch,
|
||||
): void {
|
||||
if (!grandFinal.winnerTeamIndex || !grandFinal.loserTeamIndex) return;
|
||||
const winnerBracketTeamIndex = grandFinal.teamAIndex;
|
||||
if (
|
||||
bracket.resetFinalEnabled &&
|
||||
!bracket.resetFinalCreated &&
|
||||
grandFinal.winnerTeamIndex !== winnerBracketTeamIndex
|
||||
) {
|
||||
bracket.resetFinalCreated = true;
|
||||
const resetRule = seriesRule(1);
|
||||
bracket.bracketMatches.push({
|
||||
bracketMatchId: 'GF_RESET',
|
||||
gameNumber: nextGameNumber(bracket),
|
||||
gameCount: resetRule.gameCount,
|
||||
requiredWins: resetRule.requiredWins,
|
||||
bracketSide: 'reset-final',
|
||||
roundNumber: 1,
|
||||
matchNumber: 1,
|
||||
state: 'ready',
|
||||
teamAIndex: grandFinal.teamAIndex,
|
||||
teamBIndex: grandFinal.teamBIndex,
|
||||
teamASource: { type: 'winner', bracketMatchId: 'GF' },
|
||||
teamBSource: { type: 'loser', bracketMatchId: 'GF' },
|
||||
});
|
||||
bracket.events.push({
|
||||
type: 'reset-final-created',
|
||||
bracketMatchId: 'GF_RESET',
|
||||
createdAt: new Date(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
bracket.placements.firstTeamIndex = grandFinal.winnerTeamIndex;
|
||||
bracket.placements.secondTeamIndex = grandFinal.loserTeamIndex;
|
||||
}
|
||||
|
||||
function advanceTeam(
|
||||
bracket: DoubleEliminationBracket,
|
||||
destination: DoubleEliminationBracketMatchDestination | undefined,
|
||||
teamIndex: number,
|
||||
): void {
|
||||
if (!destination) return;
|
||||
const target = requireBracketMatch(bracket, destination.bracketMatchId);
|
||||
if (destination.position === 'A') {
|
||||
target.teamAIndex = teamIndex;
|
||||
} else {
|
||||
target.teamBIndex = teamIndex;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshBracketMatchStates(bracket: DoubleEliminationBracket): void {
|
||||
for (const bracketMatch of bracket.bracketMatches) {
|
||||
if (bracketMatch.winnerTeamIndex) {
|
||||
bracketMatch.state = 'completed';
|
||||
continue;
|
||||
}
|
||||
bracketMatch.state =
|
||||
bracketMatch.teamAIndex && bracketMatch.teamBIndex ? 'ready' : 'pending';
|
||||
}
|
||||
}
|
||||
|
||||
function applySeedTeams(bracket: DoubleEliminationBracket): void {
|
||||
const bySeedNumber = new Map(
|
||||
bracket.seeds.map((seed) => [seed.seedNumber, seed.teamIndex]),
|
||||
);
|
||||
for (const bracketMatch of bracket.bracketMatches) {
|
||||
if (bracketMatch.teamASource?.type === 'seed') {
|
||||
bracketMatch.teamAIndex = bySeedNumber.get(
|
||||
bracketMatch.teamASource.seedNumber ?? 0,
|
||||
);
|
||||
}
|
||||
if (bracketMatch.teamBSource?.type === 'seed') {
|
||||
bracketMatch.teamBIndex = bySeedNumber.get(
|
||||
bracketMatch.teamBSource.seedNumber ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildFourTeamBracketMatches(
|
||||
options: BuildDoubleEliminationBracketOptions,
|
||||
): DoubleEliminationBracketMatch[] {
|
||||
return [
|
||||
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, {
|
||||
teamASource: seedSource(1),
|
||||
teamBSource: seedSource(4),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, {
|
||||
teamASource: seedSource(2),
|
||||
teamBSource: seedSource(3),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, options, {
|
||||
teamASource: winnerSource('WB_R1_M1'),
|
||||
teamBSource: winnerSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('GF', 'A'),
|
||||
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
||||
}),
|
||||
bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, options, {
|
||||
teamASource: loserSource('WB_R1_M1'),
|
||||
teamBSource: loserSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, options, {
|
||||
teamASource: winnerSource('LB_R1_M1'),
|
||||
teamBSource: loserSource('WB_FINAL'),
|
||||
winnerAdvancesTo: destination('GF', 'B'),
|
||||
}),
|
||||
bracketMatch('GF', 6, 'grand-final', 1, 1, options, {
|
||||
teamASource: winnerSource('WB_FINAL'),
|
||||
teamBSource: winnerSource('LB_FINAL'),
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function buildEightTeamBracketMatches(
|
||||
options: BuildDoubleEliminationBracketOptions,
|
||||
): DoubleEliminationBracketMatch[] {
|
||||
return [
|
||||
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, options, {
|
||||
teamASource: seedSource(1),
|
||||
teamBSource: seedSource(8),
|
||||
winnerAdvancesTo: destination('WB_R2_M1', 'A'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, options, {
|
||||
teamASource: seedSource(4),
|
||||
teamBSource: seedSource(5),
|
||||
winnerAdvancesTo: destination('WB_R2_M1', 'B'),
|
||||
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, options, {
|
||||
teamASource: seedSource(2),
|
||||
teamBSource: seedSource(7),
|
||||
winnerAdvancesTo: destination('WB_R2_M2', 'A'),
|
||||
loserAdvancesTo: destination('LB_R1_M2', 'A'),
|
||||
}),
|
||||
bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, options, {
|
||||
teamASource: seedSource(3),
|
||||
teamBSource: seedSource(6),
|
||||
winnerAdvancesTo: destination('WB_R2_M2', 'B'),
|
||||
loserAdvancesTo: destination('LB_R1_M2', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, options, {
|
||||
teamASource: winnerSource('WB_R1_M1'),
|
||||
teamBSource: winnerSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'A'),
|
||||
loserAdvancesTo: destination('LB_R2_M2', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, options, {
|
||||
teamASource: winnerSource('WB_R1_M3'),
|
||||
teamBSource: winnerSource('WB_R1_M4'),
|
||||
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||
loserAdvancesTo: destination('LB_R2_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('WB_FINAL', 7, 'winner', 3, 1, options, {
|
||||
teamASource: winnerSource('WB_R2_M1'),
|
||||
teamBSource: winnerSource('WB_R2_M2'),
|
||||
winnerAdvancesTo: destination('GF', 'A'),
|
||||
loserAdvancesTo: destination('LB_FINAL', 'B'),
|
||||
}),
|
||||
bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, options, {
|
||||
teamASource: loserSource('WB_R1_M1'),
|
||||
teamBSource: loserSource('WB_R1_M2'),
|
||||
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, options, {
|
||||
teamASource: loserSource('WB_R1_M3'),
|
||||
teamBSource: loserSource('WB_R1_M4'),
|
||||
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, options, {
|
||||
teamASource: winnerSource('LB_R1_M1'),
|
||||
teamBSource: loserSource('WB_R2_M2'),
|
||||
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, options, {
|
||||
teamASource: winnerSource('LB_R1_M2'),
|
||||
teamBSource: loserSource('WB_R2_M1'),
|
||||
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
|
||||
}),
|
||||
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, options, {
|
||||
teamASource: winnerSource('LB_R2_M1'),
|
||||
teamBSource: winnerSource('LB_R2_M2'),
|
||||
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||
}),
|
||||
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, options, {
|
||||
teamASource: winnerSource('LB_R3_M1'),
|
||||
teamBSource: loserSource('WB_FINAL'),
|
||||
winnerAdvancesTo: destination('GF', 'B'),
|
||||
}),
|
||||
bracketMatch('GF', 14, 'grand-final', 1, 1, options, {
|
||||
teamASource: winnerSource('WB_FINAL'),
|
||||
teamBSource: winnerSource('LB_FINAL'),
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function bracketMatch(
|
||||
bracketMatchId: string,
|
||||
gameNumber: number,
|
||||
bracketSide: DoubleEliminationBracketSide,
|
||||
roundNumber: number,
|
||||
matchNumber: number,
|
||||
options: BuildDoubleEliminationBracketOptions,
|
||||
params: Partial<DoubleEliminationBracketMatch>,
|
||||
): DoubleEliminationBracketMatch {
|
||||
const rule = resolveDoubleEliminationSeriesRule(
|
||||
{ bracketMatchId, bracketSide, roundNumber },
|
||||
options,
|
||||
);
|
||||
return {
|
||||
bracketMatchId,
|
||||
gameNumber,
|
||||
gameCount: params.gameCount ?? rule.gameCount,
|
||||
requiredWins: params.requiredWins ?? rule.requiredWins,
|
||||
bracketSide,
|
||||
roundNumber,
|
||||
matchNumber,
|
||||
state: 'pending',
|
||||
...params,
|
||||
};
|
||||
}
|
||||
|
||||
function seedSource(seedNumber: number): DoubleEliminationBracketMatchSource {
|
||||
return { type: 'seed', seedNumber };
|
||||
}
|
||||
|
||||
function winnerSource(
|
||||
bracketMatchId: string,
|
||||
): DoubleEliminationBracketMatchSource {
|
||||
return { type: 'winner', bracketMatchId };
|
||||
}
|
||||
|
||||
function loserSource(
|
||||
bracketMatchId: string,
|
||||
): DoubleEliminationBracketMatchSource {
|
||||
return { type: 'loser', bracketMatchId };
|
||||
}
|
||||
|
||||
function destination(
|
||||
bracketMatchId: string,
|
||||
position: 'A' | 'B',
|
||||
): DoubleEliminationBracketMatchDestination {
|
||||
return { bracketMatchId, position };
|
||||
}
|
||||
|
||||
function collectDescendantBracketMatchIds(
|
||||
bracket: DoubleEliminationBracket,
|
||||
bracketMatchId: string,
|
||||
): Set<string> {
|
||||
const descendants = new Set<string>();
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const match of bracket.bracketMatches) {
|
||||
const sourceIds = [
|
||||
match.teamASource?.bracketMatchId,
|
||||
match.teamBSource?.bracketMatchId,
|
||||
].filter((id): id is string => Boolean(id));
|
||||
if (
|
||||
sourceIds.some((id) => id === bracketMatchId || descendants.has(id)) &&
|
||||
!descendants.has(match.bracketMatchId)
|
||||
) {
|
||||
descendants.add(match.bracketMatchId);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return descendants;
|
||||
}
|
||||
|
||||
function referencesBracketMatch(
|
||||
source: DoubleEliminationBracketMatchSource | undefined,
|
||||
bracketMatchId: string,
|
||||
): boolean {
|
||||
return source?.bracketMatchId === bracketMatchId;
|
||||
}
|
||||
|
||||
function requireBracketMatch(
|
||||
bracket: DoubleEliminationBracket,
|
||||
bracketMatchId: string,
|
||||
): DoubleEliminationBracketMatch {
|
||||
const bracketMatch = bracket.bracketMatches.find(
|
||||
(match) => match.bracketMatchId === bracketMatchId,
|
||||
);
|
||||
if (!bracketMatch) {
|
||||
throw new Error(
|
||||
`Bracket match not found: ${bracketMatchId}. Available: ${bracket.bracketMatches
|
||||
.map((match) => match.bracketMatchId)
|
||||
.filter(Boolean)
|
||||
.join(', ')}`,
|
||||
);
|
||||
}
|
||||
return bracketMatch;
|
||||
}
|
||||
|
||||
function assertSeedChangeAllowed(bracket: DoubleEliminationBracket): void {
|
||||
if (hasCompletedDoubleEliminationBracketMatches(bracket)) {
|
||||
throw new Error('Cannot change seeds after a bracket match is completed.');
|
||||
}
|
||||
}
|
||||
|
||||
function assertSupportedTeamCount(
|
||||
teamCount: number,
|
||||
): asserts teamCount is 4 | 8 {
|
||||
if (teamCount !== 4 && teamCount !== 8) {
|
||||
throw new Error('Double elimination supports only 4 or 8 teams.');
|
||||
}
|
||||
}
|
||||
|
||||
function nextGameNumber(bracket: DoubleEliminationBracket): number {
|
||||
return (
|
||||
Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1
|
||||
);
|
||||
}
|
||||
|
||||
function seriesRule(gameCount: number): DoubleEliminationSeriesRule {
|
||||
const normalizedGameCount = normalizeSeriesGameCount(gameCount);
|
||||
return {
|
||||
gameCount: normalizedGameCount,
|
||||
requiredWins: requiredWinsForGameCount(normalizedGameCount),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSeriesGameCount(gameCount: number | undefined): number {
|
||||
if (!Number.isInteger(gameCount) || !gameCount || gameCount < 1) return 1;
|
||||
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
|
||||
}
|
||||
|
||||
function requiredWinsForGameCount(gameCount: number): number {
|
||||
return Math.floor(gameCount / 2) + 1;
|
||||
}
|
||||
|
||||
function cloneBracket(
|
||||
bracket: DoubleEliminationBracket,
|
||||
): DoubleEliminationBracket {
|
||||
const plainBracket = toPlainObject(bracket);
|
||||
return {
|
||||
...plainBracket,
|
||||
seeds: plainBracket.seeds.map((seed) => ({ ...toPlainObject(seed) })),
|
||||
bracketMatches: plainBracket.bracketMatches.map((rawMatch) => {
|
||||
const match = toPlainObject(rawMatch);
|
||||
return {
|
||||
...match,
|
||||
teamASource: match.teamASource
|
||||
? { ...toPlainObject(match.teamASource) }
|
||||
: undefined,
|
||||
teamBSource: match.teamBSource
|
||||
? { ...toPlainObject(match.teamBSource) }
|
||||
: undefined,
|
||||
winnerAdvancesTo: match.winnerAdvancesTo
|
||||
? { ...toPlainObject(match.winnerAdvancesTo) }
|
||||
: undefined,
|
||||
loserAdvancesTo: match.loserAdvancesTo
|
||||
? { ...toPlainObject(match.loserAdvancesTo) }
|
||||
: undefined,
|
||||
walkover: match.walkover
|
||||
? { ...toPlainObject(match.walkover) }
|
||||
: undefined,
|
||||
};
|
||||
}),
|
||||
placements: { ...toPlainObject(plainBracket.placements) },
|
||||
events: plainBracket.events.map((event) => ({
|
||||
...toPlainObject(event),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function toPlainObject<T>(value: T): T {
|
||||
const candidate = value as { toObject?: () => T };
|
||||
if (candidate && typeof candidate.toObject === 'function') {
|
||||
return candidate.toObject();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function shuffleInPlace<T>(items: T[], rng: () => number = Math.random): T[] {
|
||||
for (let index = items.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(rng() * (index + 1));
|
||||
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
|
||||
}
|
||||
return items;
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { resolveMongoDbName } from './connection.service';
|
||||
import {
|
||||
resolveMongoAppName,
|
||||
resolveMongoConnectionOptions,
|
||||
resolveMongoDbName,
|
||||
} from './connection.service';
|
||||
|
||||
describe('resolveMongoDbName', () => {
|
||||
it('uses production database only for prod', () => {
|
||||
@@ -12,3 +16,47 @@ describe('resolveMongoDbName', () => {
|
||||
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveMongoAppName', () => {
|
||||
it('identifies api environment and process for MongoDB connection tracking', () => {
|
||||
expect(resolveMongoAppName('staging', 1234)).toBe(
|
||||
'lolympus-api:staging:1234',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses dev as the fallback environment label', () => {
|
||||
expect(resolveMongoAppName('', 1234)).toBe('lolympus-api:dev:1234');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveMongoConnectionOptions', () => {
|
||||
it('disables automatic collection and index creation by default', () => {
|
||||
expect(
|
||||
resolveMongoConnectionOptions('lolympus-dev', 'lolympus-api:dev:1'),
|
||||
).toEqual({
|
||||
dbName: 'lolympus-dev',
|
||||
appName: 'lolympus-api:dev:1',
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('enables automatic index creation when explicitly requested', () => {
|
||||
expect(
|
||||
resolveMongoConnectionOptions(
|
||||
'lolympus-staging',
|
||||
'lolympus-api:staging:1',
|
||||
'true',
|
||||
),
|
||||
).toEqual({
|
||||
dbName: 'lolympus-staging',
|
||||
appName: 'lolympus-api:staging:1',
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
autoIndex: true,
|
||||
autoCreate: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
|
||||
import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
||||
|
||||
@@ -9,15 +10,44 @@ export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
||||
return 'lolympus-dev';
|
||||
}
|
||||
|
||||
export function resolveMongoAppName(
|
||||
nodeEnv = process.env.NODE_ENV,
|
||||
pid = process.pid,
|
||||
): string {
|
||||
return `lolympus-api:${nodeEnv || 'dev'}:${pid}`;
|
||||
}
|
||||
|
||||
export function resolveMongoConnectionOptions(
|
||||
dbName: string,
|
||||
appName: string,
|
||||
mongoAutoIndex = process.env.MONGODB_AUTO_INDEX,
|
||||
): mongoose.ConnectOptions {
|
||||
const shouldEnableMongoAutoIndex =
|
||||
mongoAutoIndex?.trim().toLowerCase() === 'true';
|
||||
|
||||
return {
|
||||
dbName,
|
||||
appName,
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
autoIndex: shouldEnableMongoAutoIndex,
|
||||
autoCreate: false,
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable({ scope: Scope.DEFAULT })
|
||||
export class ConnectionService implements OnModuleInit {
|
||||
private readonly logger = new Logger(ConnectionService.name);
|
||||
private connection: mongoose.Connection | null = null;
|
||||
constructor(private readonly secretService: SecretService) {}
|
||||
|
||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
||||
|
||||
public async getConnection(): Promise<mongoose.Connection> {
|
||||
if (this.connection !== null && this.connection.readyState === 1) {
|
||||
if (
|
||||
this.connection !== null &&
|
||||
this.connection.readyState === mongoose.ConnectionStates.connected
|
||||
) {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
@@ -25,15 +55,17 @@ export class ConnectionService implements OnModuleInit {
|
||||
'MONGODB_CONNECTION_STRING',
|
||||
);
|
||||
const dbName = resolveMongoDbName();
|
||||
const appName = resolveMongoAppName();
|
||||
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
|
||||
const defaultConnection = await mongoose
|
||||
.createConnection(connectionString, {
|
||||
dbName,
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
})
|
||||
.createConnection(connectionString, connectionOptions)
|
||||
.asPromise();
|
||||
this.connection = defaultConnection;
|
||||
console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`);
|
||||
this.logger.log(
|
||||
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
|
||||
connectionOptions.autoIndex === true
|
||||
}`,
|
||||
);
|
||||
|
||||
return this.connection;
|
||||
}
|
||||
@@ -50,6 +82,7 @@ export class ConnectionService implements OnModuleInit {
|
||||
const connection = await this.getConnection();
|
||||
|
||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||
applyMongoosePerformancePlugin(modelDefinition.schema);
|
||||
// 이미 생성된 경우 컴파일 스킵.
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
@@ -86,15 +119,24 @@ export class ConnectionService implements OnModuleInit {
|
||||
const session = await connection.startSession(options);
|
||||
return session as unknown as mongoose.ClientSession;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
this.logError('Failed to start MongoDB session', error);
|
||||
}
|
||||
}
|
||||
|
||||
public async onModuleInit() {
|
||||
await this.getConnection().catch(console.error);
|
||||
await this.getConnection().catch((error: unknown) => {
|
||||
this.logError('Failed to initialize MongoDB connection', error);
|
||||
});
|
||||
}
|
||||
|
||||
public async onModuleDestroy() {
|
||||
await this.connection?.close();
|
||||
}
|
||||
|
||||
private logError(message: string, error: unknown): void {
|
||||
this.logger.error(
|
||||
`${message}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
);
|
||||
}
|
||||
}
|
||||
+618
@@ -0,0 +1,618 @@
|
||||
import { migrateTournamentCodeUniqueIndexes } from './20260627-tournament-code-unique-indexes';
|
||||
|
||||
type Doc = Record<string, unknown> & { _id: string };
|
||||
type FakeIndex = {
|
||||
commitQuorum?: number | string;
|
||||
key: Record<string, 1 | -1>;
|
||||
maxTimeMS?: number;
|
||||
name: string;
|
||||
partialFilterExpression?: Record<string, unknown>;
|
||||
unique?: boolean;
|
||||
};
|
||||
type Projection = Record<string, 0 | 1>;
|
||||
|
||||
function createDb(params: {
|
||||
codes?: Doc[];
|
||||
indexes?: FakeIndex[];
|
||||
matches?: Doc[];
|
||||
missingTournamentCodeNamespace?: boolean;
|
||||
}) {
|
||||
const collections = {
|
||||
match: params.matches ?? [],
|
||||
tournamentCode: params.codes ?? [],
|
||||
};
|
||||
const indexes = [...(params.indexes ?? [])];
|
||||
const collectionNames: string[] = [];
|
||||
let tournamentCodeNamespaceMissing =
|
||||
params.missingTournamentCodeNamespace ?? false;
|
||||
|
||||
return {
|
||||
collectionNames,
|
||||
collections,
|
||||
indexes,
|
||||
db: {
|
||||
collection(name: string) {
|
||||
collectionNames.push(name);
|
||||
const docs =
|
||||
name === 'tournamentCode'
|
||||
? collections.tournamentCode
|
||||
: name === 'match'
|
||||
? collections.match
|
||||
: [];
|
||||
|
||||
return {
|
||||
find(
|
||||
filter: Record<string, unknown> = {},
|
||||
options?: { projection?: Projection },
|
||||
) {
|
||||
return {
|
||||
limit() {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
if (!matchesFilter(doc, filter)) continue;
|
||||
yield applyProjection(doc, options?.projection);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
async updateMany(
|
||||
filter: Record<string, unknown>,
|
||||
update: {
|
||||
$pull?: Record<string, unknown>;
|
||||
$set?: Record<string, unknown>;
|
||||
$unset?: Record<string, ''>;
|
||||
},
|
||||
) {
|
||||
let matchedCount = 0;
|
||||
let modifiedCount = 0;
|
||||
|
||||
for (const doc of docs) {
|
||||
if (!matchesFilter(doc, filter)) continue;
|
||||
matchedCount += 1;
|
||||
const before = JSON.stringify(doc);
|
||||
applyUpdate(doc, update);
|
||||
if (JSON.stringify(doc) !== before) modifiedCount += 1;
|
||||
}
|
||||
|
||||
return { matchedCount, modifiedCount };
|
||||
},
|
||||
async indexes() {
|
||||
if (name === 'tournamentCode' && tournamentCodeNamespaceMissing) {
|
||||
const error = new Error(
|
||||
'ns does not exist: lolympus.tournamentCode',
|
||||
) as Error & { code: number; codeName: string };
|
||||
error.code = 26;
|
||||
error.codeName = 'NamespaceNotFound';
|
||||
throw error;
|
||||
}
|
||||
return indexes.map((index) => ({ ...index }));
|
||||
},
|
||||
async dropIndex(name: string) {
|
||||
const index = indexes.findIndex((item) => item.name === name);
|
||||
if (index >= 0) indexes.splice(index, 1);
|
||||
},
|
||||
async createIndex(
|
||||
key: Record<string, 1 | -1>,
|
||||
options: {
|
||||
name: string;
|
||||
partialFilterExpression?: Record<string, unknown>;
|
||||
unique?: boolean;
|
||||
},
|
||||
) {
|
||||
if (name === 'tournamentCode') {
|
||||
tournamentCodeNamespaceMissing = false;
|
||||
}
|
||||
indexes.push({ key, ...options });
|
||||
return options.name;
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
|
||||
const clauses = filter.$or;
|
||||
if (Array.isArray(clauses)) {
|
||||
return clauses.some((clause) => matchesFilter(doc, clause));
|
||||
}
|
||||
|
||||
return Object.entries(filter).every(([key, value]) => {
|
||||
if (key === '$or') return true;
|
||||
return matchesValue(readPath(doc, key), value);
|
||||
});
|
||||
}
|
||||
|
||||
function matchesValue(actual: unknown, expectedValue: unknown): boolean {
|
||||
if (isRecord(expectedValue)) {
|
||||
if ('$exists' in expectedValue) {
|
||||
const exists = actual !== undefined;
|
||||
if (exists !== expectedValue.$exists) return false;
|
||||
}
|
||||
if ('$in' in expectedValue) {
|
||||
const expected = (expectedValue.$in as unknown[]).map(String);
|
||||
if (Array.isArray(actual)) {
|
||||
if (!actual.some((item) => expected.includes(String(item)))) {
|
||||
return false;
|
||||
}
|
||||
} else if (!expected.includes(String(actual))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if ('$ne' in expectedValue) {
|
||||
if (JSON.stringify(actual) === JSON.stringify(expectedValue.$ne)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if ('$type' in expectedValue) {
|
||||
if (expectedValue.$type === 'string' && typeof actual !== 'string') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return actual === expectedValue;
|
||||
}
|
||||
|
||||
function applyUpdate(
|
||||
doc: Doc,
|
||||
update: {
|
||||
$pull?: Record<string, unknown>;
|
||||
$set?: Record<string, unknown>;
|
||||
$unset?: Record<string, ''>;
|
||||
},
|
||||
) {
|
||||
Object.assign(doc, update.$set ?? {});
|
||||
|
||||
for (const key of Object.keys(update.$unset ?? {})) {
|
||||
delete doc[key];
|
||||
}
|
||||
|
||||
for (const [key, pull] of Object.entries(update.$pull ?? {})) {
|
||||
const current = doc[key];
|
||||
if (!Array.isArray(current)) continue;
|
||||
if (!isRecord(pull) || !('$in' in pull)) continue;
|
||||
const pulled = (pull.$in as unknown[]).map(String);
|
||||
doc[key] = current.filter((item) => !pulled.includes(String(item)));
|
||||
}
|
||||
}
|
||||
|
||||
function applyProjection(doc: Doc, projection?: Projection): Doc {
|
||||
if (!projection) return doc;
|
||||
const projected: Doc = { _id: doc._id };
|
||||
for (const [key, value] of Object.entries(projection)) {
|
||||
if (value !== 1 || key === '_id') continue;
|
||||
const actual = readPath(doc, key);
|
||||
if (actual !== undefined) projected[key] = actual;
|
||||
}
|
||||
return projected;
|
||||
}
|
||||
|
||||
function readPath(doc: Record<string, unknown>, path: string): unknown {
|
||||
const parts = path.split('.');
|
||||
let current: unknown = doc;
|
||||
for (const part of parts) {
|
||||
if (Array.isArray(current) && /^\d+$/.test(part)) {
|
||||
current = current[Number(part)];
|
||||
continue;
|
||||
}
|
||||
if (!isRecord(current)) return undefined;
|
||||
current = current[part];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value && typeof value === 'object' && !Array.isArray(value));
|
||||
}
|
||||
|
||||
describe('migrateTournamentCodeUniqueIndexes', () => {
|
||||
it('dry-runs duplicate cleanup without mutating documents or indexes', async () => {
|
||||
const { db, collectionNames, collections, indexes } = createDb({
|
||||
codes: [
|
||||
{
|
||||
_id: 'code-1',
|
||||
code: 'A',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
reservedAt: new Date('2026-06-01T00:00:00.000Z'),
|
||||
state: 'reserved',
|
||||
},
|
||||
{
|
||||
_id: 'code-2',
|
||||
code: 'B',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
reservedAt: new Date('2026-06-02T00:00:00.000Z'),
|
||||
state: 'reserved',
|
||||
},
|
||||
{
|
||||
_id: 'code-3',
|
||||
code: 'C',
|
||||
riotMatchId: 'KR_1',
|
||||
state: 'released',
|
||||
},
|
||||
{
|
||||
_id: 'code-4',
|
||||
code: 'D',
|
||||
riotMatchId: 'KR_1',
|
||||
state: 'used',
|
||||
},
|
||||
{
|
||||
_id: 'code-5',
|
||||
code: 'E',
|
||||
riotMatchId: ' ',
|
||||
state: 'reserved',
|
||||
},
|
||||
],
|
||||
indexes: [{ key: { riotMatchId: 1 }, name: 'riotMatchId_1' }],
|
||||
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
|
||||
});
|
||||
|
||||
const beforeCodes = JSON.stringify(collections.tournamentCode);
|
||||
const beforeIndexes = JSON.stringify(indexes);
|
||||
const progressPhases: string[] = [];
|
||||
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||
dryRun: true,
|
||||
onProgress: (progress) => progressPhases.push(progress.phase),
|
||||
});
|
||||
|
||||
expect(result.stats).toMatchObject({
|
||||
blankRiotMatchIdsToUnset: 1,
|
||||
blankRiotMatchIdsUnset: 0,
|
||||
duplicateCodesReleased: 0,
|
||||
duplicateCodesToRelease: 2,
|
||||
duplicateGameNumberGroups: 1,
|
||||
duplicateRiotMatchGroups: 1,
|
||||
indexesCreated: 0,
|
||||
indexesDropped: 0,
|
||||
scannedCodes: 5,
|
||||
scannedMatches: 1,
|
||||
});
|
||||
expect(result.sampleDuplicateGroups).toHaveLength(2);
|
||||
expect(progressPhases).toEqual(
|
||||
expect.arrayContaining(['scanMatches', 'scanTournamentCodes']),
|
||||
);
|
||||
expect(collectionNames).toContain('tournamentCode');
|
||||
expect(collectionNames).not.toContain('tournament_code');
|
||||
expect(JSON.stringify(collections.tournamentCode)).toBe(beforeCodes);
|
||||
expect(JSON.stringify(indexes)).toBe(beforeIndexes);
|
||||
});
|
||||
|
||||
it('releases duplicate losers, pulls them from matches, and replaces old indexes', async () => {
|
||||
const now = new Date('2026-06-27T00:00:00.000Z');
|
||||
const { db, collections, indexes } = createDb({
|
||||
codes: [
|
||||
{
|
||||
_id: 'code-1',
|
||||
code: 'A',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
reservedAt: new Date('2026-06-01T00:00:00.000Z'),
|
||||
state: 'reserved',
|
||||
},
|
||||
{
|
||||
_id: 'code-2',
|
||||
code: 'B',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
reservedAt: new Date('2026-06-02T00:00:00.000Z'),
|
||||
state: 'reserved',
|
||||
},
|
||||
{
|
||||
_id: 'code-3',
|
||||
code: 'C',
|
||||
riotMatchId: 'KR_1',
|
||||
state: 'used',
|
||||
},
|
||||
{
|
||||
_id: 'code-4',
|
||||
code: 'D',
|
||||
riotMatchId: 'KR_1',
|
||||
state: 'released',
|
||||
},
|
||||
{
|
||||
_id: 'code-5',
|
||||
code: 'E',
|
||||
riotMatchId: '',
|
||||
state: 'reserved',
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{ key: { matchId: 1, gameNumber: 1 }, name: 'matchId_1_gameNumber_1' },
|
||||
{
|
||||
key: { matchId: 1, bracketMatchId: 1 },
|
||||
name: 'matchId_1_bracketMatchId_1',
|
||||
},
|
||||
{ key: { riotMatchId: 1 }, name: 'riotMatchId_1' },
|
||||
],
|
||||
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-4'] }],
|
||||
});
|
||||
|
||||
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||
dryRun: false,
|
||||
now,
|
||||
});
|
||||
|
||||
expect(result.stats).toMatchObject({
|
||||
blankRiotMatchIdsToUnset: 1,
|
||||
blankRiotMatchIdsUnset: 1,
|
||||
duplicateCodesReleased: 2,
|
||||
duplicateCodesToRelease: 2,
|
||||
indexesCreated: 3,
|
||||
indexesDropped: 3,
|
||||
matchesUpdated: 1,
|
||||
});
|
||||
expect(
|
||||
collections.tournamentCode.find((code) => code._id === 'code-2'),
|
||||
).toMatchObject({
|
||||
code: 'B',
|
||||
releasedAt: now,
|
||||
state: 'released',
|
||||
});
|
||||
expect(
|
||||
collections.tournamentCode.find((code) => code._id === 'code-2'),
|
||||
).not.toHaveProperty('matchId');
|
||||
expect(
|
||||
collections.tournamentCode.find((code) => code._id === 'code-4'),
|
||||
).not.toHaveProperty('riotMatchId');
|
||||
expect(
|
||||
collections.tournamentCode.find((code) => code._id === 'code-5'),
|
||||
).not.toHaveProperty('riotMatchId');
|
||||
expect(collections.match[0].tournamentCodeIds).toEqual(['code-1']);
|
||||
expect(indexes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
key: { matchId: 1, gameNumber: 1 },
|
||||
name: 'matchId_1_gameNumber_1',
|
||||
partialFilterExpression: expect.objectContaining({
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
}),
|
||||
unique: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
key: { matchId: 1, bracketMatchId: 1 },
|
||||
name: 'matchId_1_bracketMatchId_1',
|
||||
partialFilterExpression: expect.objectContaining({
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
key: { riotMatchId: 1 },
|
||||
name: 'riotMatchId_1',
|
||||
partialFilterExpression: { riotMatchId: { $type: 'string' } },
|
||||
unique: true,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('creates indexes when the tournament code collection does not exist yet', async () => {
|
||||
const { db, indexes } = createDb({
|
||||
missingTournamentCodeNamespace: true,
|
||||
});
|
||||
const progress: string[] = [];
|
||||
|
||||
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||
dryRun: false,
|
||||
indexCommitQuorum: 1,
|
||||
indexMaxTimeMS: 60_000,
|
||||
onProgress: (event) =>
|
||||
progress.push(`${event.action ?? ''}:${event.indexName ?? ''}`),
|
||||
});
|
||||
|
||||
expect(result.stats).toMatchObject({
|
||||
duplicateCodesReleased: 0,
|
||||
indexesAlreadyCorrect: 0,
|
||||
indexesCreated: 3,
|
||||
indexesDropped: 0,
|
||||
scannedCodes: 0,
|
||||
scannedMatches: 0,
|
||||
});
|
||||
expect(indexes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
commitQuorum: 1,
|
||||
key: { matchId: 1, gameNumber: 1 },
|
||||
maxTimeMS: 60_000,
|
||||
name: 'matchId_1_gameNumber_1',
|
||||
unique: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
key: { matchId: 1, bracketMatchId: 1 },
|
||||
name: 'matchId_1_bracketMatchId_1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
key: { riotMatchId: 1 },
|
||||
name: 'riotMatchId_1',
|
||||
unique: true,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(progress).toEqual(
|
||||
expect.arrayContaining([
|
||||
'create:matchId_1_gameNumber_1',
|
||||
'created:matchId_1_gameNumber_1',
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses to release used duplicate losers by default', async () => {
|
||||
const { db, collections } = createDb({
|
||||
codes: [
|
||||
{
|
||||
_id: 'code-1',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
state: 'used',
|
||||
usedAt: new Date('2026-06-01T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
_id: 'code-2',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
state: 'used',
|
||||
usedAt: new Date('2026-06-02T00:00:00.000Z'),
|
||||
},
|
||||
],
|
||||
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
|
||||
});
|
||||
|
||||
await expect(
|
||||
migrateTournamentCodeUniqueIndexes(db, { dryRun: false }),
|
||||
).rejects.toThrow('Refusing to release 1 used duplicate tournament codes');
|
||||
expect(collections.tournamentCode[0]).toMatchObject({
|
||||
matchId: 'match-1',
|
||||
state: 'used',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the match-referenced slot code before state priority', async () => {
|
||||
const { db, collections } = createDb({
|
||||
codes: [
|
||||
{
|
||||
_id: 'code-1',
|
||||
code: 'USED-NOT-REFERENCED',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
state: 'used',
|
||||
usedAt: new Date('2026-06-02T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
_id: 'code-2',
|
||||
code: 'RESERVED-REFERENCED',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
state: 'reserved',
|
||||
reservedAt: new Date('2026-06-01T00:00:00.000Z'),
|
||||
},
|
||||
],
|
||||
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-2'] }],
|
||||
});
|
||||
|
||||
const beforeCodes = JSON.stringify(collections.tournamentCode);
|
||||
const beforeMatches = JSON.stringify(collections.match);
|
||||
|
||||
await expect(
|
||||
migrateTournamentCodeUniqueIndexes(db, { dryRun: false }),
|
||||
).rejects.toThrow('Refusing to release 1 used duplicate tournament codes');
|
||||
expect(JSON.stringify(collections.tournamentCode)).toBe(beforeCodes);
|
||||
expect(JSON.stringify(collections.match)).toBe(beforeMatches);
|
||||
});
|
||||
|
||||
it('allows multiple active codes for the same double-elimination bracket match', async () => {
|
||||
const { db, collections } = createDb({
|
||||
codes: [
|
||||
{
|
||||
_id: 'code-1',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
state: 'reserved',
|
||||
},
|
||||
{
|
||||
_id: 'code-2',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 2,
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
state: 'reserved',
|
||||
},
|
||||
],
|
||||
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
|
||||
});
|
||||
|
||||
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||
dryRun: false,
|
||||
createIndexes: false,
|
||||
});
|
||||
|
||||
expect(result.stats).toMatchObject({
|
||||
duplicateBracketMatchGroups: 0,
|
||||
duplicateCodesReleased: 0,
|
||||
duplicateCodesToRelease: 0,
|
||||
});
|
||||
expect(collections.tournamentCode).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ _id: 'code-1', state: 'reserved' }),
|
||||
expect.objectContaining({ _id: 'code-2', state: 'reserved' }),
|
||||
]),
|
||||
);
|
||||
expect(collections.match[0].tournamentCodeIds).toEqual([
|
||||
'code-1',
|
||||
'code-2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('unsets blank riot match ids without treating them as duplicate releases', async () => {
|
||||
const { db, collections } = createDb({
|
||||
codes: [
|
||||
{ _id: 'code-1', riotMatchId: '', state: 'reserved' },
|
||||
{ _id: 'code-2', riotMatchId: ' ', state: 'available' },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||
dryRun: false,
|
||||
createIndexes: false,
|
||||
});
|
||||
|
||||
expect(result.stats).toMatchObject({
|
||||
blankRiotMatchIdsToUnset: 2,
|
||||
blankRiotMatchIdsUnset: 2,
|
||||
duplicateCodesReleased: 0,
|
||||
duplicateCodesToRelease: 0,
|
||||
duplicateRiotMatchGroups: 0,
|
||||
});
|
||||
expect(collections.tournamentCode[0]).toMatchObject({
|
||||
_id: 'code-1',
|
||||
state: 'reserved',
|
||||
});
|
||||
expect(collections.tournamentCode[0]).not.toHaveProperty('riotMatchId');
|
||||
expect(collections.tournamentCode[1]).not.toHaveProperty('riotMatchId');
|
||||
});
|
||||
|
||||
it('allows used duplicate cleanup only when explicitly requested', async () => {
|
||||
const now = new Date('2026-06-27T00:00:00.000Z');
|
||||
const { db, collections } = createDb({
|
||||
codes: [
|
||||
{
|
||||
_id: 'code-1',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
state: 'used',
|
||||
usedAt: new Date('2026-06-01T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
_id: 'code-2',
|
||||
matchId: 'match-1',
|
||||
gameNumber: 1,
|
||||
state: 'used',
|
||||
usedAt: new Date('2026-06-02T00:00:00.000Z'),
|
||||
},
|
||||
],
|
||||
matches: [{ _id: 'match-1', tournamentCodeIds: ['code-1', 'code-2'] }],
|
||||
});
|
||||
|
||||
const result = await migrateTournamentCodeUniqueIndexes(db, {
|
||||
allowUsedDuplicateRelease: true,
|
||||
dryRun: false,
|
||||
now,
|
||||
});
|
||||
|
||||
expect(result.stats).toMatchObject({
|
||||
duplicateCodesReleased: 1,
|
||||
unsafeUsedDuplicateCodes: 1,
|
||||
unsafeUsedDuplicateGroups: 1,
|
||||
});
|
||||
expect(collections.tournamentCode[0]).toMatchObject({
|
||||
releasedAt: now,
|
||||
state: 'released',
|
||||
});
|
||||
expect(collections.tournamentCode[0]).not.toHaveProperty('usedAt');
|
||||
expect(collections.match[0].tournamentCodeIds).toEqual(['code-2']);
|
||||
});
|
||||
});
|
||||
+764
@@ -0,0 +1,764 @@
|
||||
type TournamentCodeState =
|
||||
| 'available'
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'released'
|
||||
| 'expired'
|
||||
| 'voided'
|
||||
| string;
|
||||
|
||||
type AnyDoc = Record<string, unknown> & { _id: unknown };
|
||||
type IndexKey = Record<string, 1 | -1>;
|
||||
type PartialFilterExpression = Record<string, unknown>;
|
||||
type Projection = Record<string, 0 | 1>;
|
||||
|
||||
interface MigrationCursor {
|
||||
limit(limit: number): AsyncIterable<AnyDoc>;
|
||||
}
|
||||
|
||||
interface MigrationIndex {
|
||||
key: IndexKey;
|
||||
name: string;
|
||||
partialFilterExpression?: PartialFilterExpression;
|
||||
unique?: boolean;
|
||||
}
|
||||
|
||||
interface MigrationCollection {
|
||||
find(
|
||||
filter: Record<string, unknown>,
|
||||
options?: { projection?: Projection },
|
||||
): MigrationCursor;
|
||||
updateMany(
|
||||
filter: Record<string, unknown>,
|
||||
update: {
|
||||
$pull?: Record<string, unknown>;
|
||||
$set?: Record<string, unknown>;
|
||||
$unset?: Record<string, ''>;
|
||||
},
|
||||
options?: { ordered?: boolean },
|
||||
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>;
|
||||
indexes?(): Promise<MigrationIndex[]>;
|
||||
dropIndex?(name: string): Promise<unknown>;
|
||||
createIndex?(
|
||||
key: IndexKey,
|
||||
options: {
|
||||
commitQuorum?: number | string;
|
||||
maxTimeMS?: number;
|
||||
name: string;
|
||||
partialFilterExpression?: PartialFilterExpression;
|
||||
unique?: boolean;
|
||||
},
|
||||
): Promise<string>;
|
||||
}
|
||||
|
||||
interface MigrationDb {
|
||||
collection(name: string): MigrationCollection;
|
||||
}
|
||||
|
||||
interface TournamentCodeDoc extends AnyDoc {
|
||||
bracketMatchId?: unknown;
|
||||
code?: unknown;
|
||||
createdAt?: unknown;
|
||||
gameNumber?: unknown;
|
||||
matchId?: unknown;
|
||||
reservedAt?: unknown;
|
||||
riotMatchId?: unknown;
|
||||
state?: TournamentCodeState;
|
||||
updatedAt?: unknown;
|
||||
uploadedAt?: unknown;
|
||||
usedAt?: unknown;
|
||||
}
|
||||
|
||||
interface MatchDoc extends AnyDoc {
|
||||
tournamentCodeIds?: unknown;
|
||||
}
|
||||
|
||||
interface DesiredIndex {
|
||||
key: IndexKey;
|
||||
options: {
|
||||
name: string;
|
||||
partialFilterExpression?: PartialFilterExpression;
|
||||
unique?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
interface DuplicateGroup {
|
||||
codeDocs: TournamentCodeDoc[];
|
||||
key: string;
|
||||
kind: TournamentCodeDuplicateKind;
|
||||
}
|
||||
|
||||
interface ReleasePlanEntry {
|
||||
code: TournamentCodeDoc;
|
||||
reasons: string[];
|
||||
}
|
||||
|
||||
export type TournamentCodeDuplicateKind =
|
||||
| 'gameNumber'
|
||||
| 'bracketMatchId'
|
||||
| 'riotMatchId';
|
||||
|
||||
export interface TournamentCodeDuplicateSummary {
|
||||
bracketMatchId?: string;
|
||||
code?: string;
|
||||
gameNumber?: string;
|
||||
id: string;
|
||||
matchId?: string;
|
||||
riotMatchId?: string;
|
||||
state?: string;
|
||||
}
|
||||
|
||||
export interface TournamentCodeDuplicateGroupSummary {
|
||||
keeper: TournamentCodeDuplicateSummary;
|
||||
key: string;
|
||||
kind: TournamentCodeDuplicateKind;
|
||||
losers: TournamentCodeDuplicateSummary[];
|
||||
}
|
||||
|
||||
export interface TournamentCodeUniqueIndexMigrationOptions {
|
||||
allowUsedDuplicateRelease?: boolean;
|
||||
createIndexes?: boolean;
|
||||
dryRun?: boolean;
|
||||
duplicateSampleLimit?: number;
|
||||
indexCommitQuorum?: number | string;
|
||||
indexMaxTimeMS?: number;
|
||||
now?: Date;
|
||||
onProgress?: (progress: TournamentCodeUniqueIndexMigrationProgress) => void;
|
||||
progressInterval?: number;
|
||||
}
|
||||
|
||||
export interface TournamentCodeUniqueIndexMigrationStats {
|
||||
blankRiotMatchIdsToUnset: number;
|
||||
blankRiotMatchIdsUnset: number;
|
||||
duplicateBracketMatchGroups: number;
|
||||
duplicateCodesReleased: number;
|
||||
duplicateCodesToRelease: number;
|
||||
duplicateGameNumberGroups: number;
|
||||
duplicateRiotMatchGroups: number;
|
||||
indexesAlreadyCorrect: number;
|
||||
indexesCreated: number;
|
||||
indexesDropped: number;
|
||||
matchesUpdated: number;
|
||||
scannedCodes: number;
|
||||
scannedMatches: number;
|
||||
unsafeUsedDuplicateCodes: number;
|
||||
unsafeUsedDuplicateGroups: number;
|
||||
}
|
||||
|
||||
export interface TournamentCodeUniqueIndexMigrationResult {
|
||||
sampleDuplicateGroups: TournamentCodeDuplicateGroupSummary[];
|
||||
stats: TournamentCodeUniqueIndexMigrationStats;
|
||||
}
|
||||
|
||||
export interface TournamentCodeUniqueIndexMigrationProgress {
|
||||
action?:
|
||||
| 'alreadyCorrect'
|
||||
| 'create'
|
||||
| 'created'
|
||||
| 'drop'
|
||||
| 'dropped'
|
||||
| 'list';
|
||||
phase:
|
||||
| 'scanMatches'
|
||||
| 'scanTournamentCodes'
|
||||
| 'cleanupBlankRiotMatchIds'
|
||||
| 'cleanupDuplicateCodes'
|
||||
| 'ensureIndexes';
|
||||
scanned?: number;
|
||||
indexName?: string;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
const ACTIVE_CODE_STATES = new Set(['reserved', 'used']);
|
||||
|
||||
const MATCH_SCAN_FILTER = { 'tournamentCodeIds.0': { $exists: true } };
|
||||
const MATCH_SCAN_PROJECTION: Projection = { _id: 1, tournamentCodeIds: 1 };
|
||||
const TOURNAMENT_CODE_SCAN_FILTER = {
|
||||
$or: [
|
||||
{ state: { $in: ['reserved', 'used'] }, matchId: { $exists: true } },
|
||||
{ riotMatchId: { $type: 'string' } },
|
||||
],
|
||||
};
|
||||
const TOURNAMENT_CODE_SCAN_PROJECTION: Projection = {
|
||||
_id: 1,
|
||||
bracketMatchId: 1,
|
||||
code: 1,
|
||||
createdAt: 1,
|
||||
gameNumber: 1,
|
||||
matchId: 1,
|
||||
reservedAt: 1,
|
||||
riotMatchId: 1,
|
||||
state: 1,
|
||||
updatedAt: 1,
|
||||
uploadedAt: 1,
|
||||
usedAt: 1,
|
||||
};
|
||||
|
||||
const DESIRED_TOURNAMENT_CODE_INDEXES: DesiredIndex[] = [
|
||||
{
|
||||
key: { matchId: 1, gameNumber: 1 },
|
||||
options: {
|
||||
name: 'matchId_1_gameNumber_1',
|
||||
unique: true,
|
||||
partialFilterExpression: {
|
||||
matchId: { $exists: true },
|
||||
gameNumber: { $exists: true },
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
key: { matchId: 1, bracketMatchId: 1 },
|
||||
options: {
|
||||
name: 'matchId_1_bracketMatchId_1',
|
||||
partialFilterExpression: {
|
||||
matchId: { $exists: true },
|
||||
bracketMatchId: { $exists: true },
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
key: { riotMatchId: 1 },
|
||||
options: {
|
||||
name: 'riotMatchId_1',
|
||||
unique: true,
|
||||
partialFilterExpression: { riotMatchId: { $type: 'string' } },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export async function migrateTournamentCodeUniqueIndexes(
|
||||
db: MigrationDb,
|
||||
options: TournamentCodeUniqueIndexMigrationOptions = {},
|
||||
): Promise<TournamentCodeUniqueIndexMigrationResult> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const now = options.now ?? new Date();
|
||||
const tournamentCodeCollection = db.collection('tournamentCode');
|
||||
const matchCollection = db.collection('match');
|
||||
const matchScan = await readReferencedTournamentCodeIds(
|
||||
matchCollection,
|
||||
options,
|
||||
);
|
||||
const codeDocs = await readTournamentCodes(tournamentCodeCollection, options);
|
||||
const groups = findDuplicateGroups(codeDocs, matchScan.referencedCodeIds);
|
||||
const releasePlan = buildReleasePlan(groups, matchScan.referencedCodeIds);
|
||||
const blankRiotMatchCodeIds = codeDocs
|
||||
.filter(hasBlankRiotMatchId)
|
||||
.map((code) => code._id);
|
||||
const unsafePlanEntries = releasePlan.filter(
|
||||
(entry) => entry.code.state === 'used',
|
||||
);
|
||||
const unsafeGroupCount = groups.filter((group) => {
|
||||
const keeper = chooseKeeper(group, matchScan.referencedCodeIds);
|
||||
const keeperId = stringifyId(keeper._id);
|
||||
return group.codeDocs.some(
|
||||
(code) => stringifyId(code._id) !== keeperId && code.state === 'used',
|
||||
);
|
||||
}).length;
|
||||
|
||||
const stats: TournamentCodeUniqueIndexMigrationStats = {
|
||||
blankRiotMatchIdsToUnset: blankRiotMatchCodeIds.length,
|
||||
blankRiotMatchIdsUnset: 0,
|
||||
duplicateBracketMatchGroups: groups.filter(
|
||||
(group) => group.kind === 'bracketMatchId',
|
||||
).length,
|
||||
duplicateCodesReleased: 0,
|
||||
duplicateCodesToRelease: releasePlan.length,
|
||||
duplicateGameNumberGroups: groups.filter(
|
||||
(group) => group.kind === 'gameNumber',
|
||||
).length,
|
||||
duplicateRiotMatchGroups: groups.filter(
|
||||
(group) => group.kind === 'riotMatchId',
|
||||
).length,
|
||||
indexesAlreadyCorrect: 0,
|
||||
indexesCreated: 0,
|
||||
indexesDropped: 0,
|
||||
matchesUpdated: 0,
|
||||
scannedCodes: codeDocs.length,
|
||||
scannedMatches: matchScan.scannedMatches,
|
||||
unsafeUsedDuplicateCodes: unsafePlanEntries.length,
|
||||
unsafeUsedDuplicateGroups: unsafeGroupCount,
|
||||
};
|
||||
|
||||
if (
|
||||
!dryRun &&
|
||||
unsafePlanEntries.length > 0 &&
|
||||
options.allowUsedDuplicateRelease !== true
|
||||
) {
|
||||
throw new Error(
|
||||
`Refusing to release ${unsafePlanEntries.length} used duplicate tournament codes. ` +
|
||||
'Review the duplicate groups manually or re-run with --allow-used-duplicate-release.',
|
||||
);
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
if (blankRiotMatchCodeIds.length > 0) {
|
||||
emitProgress(options, 'cleanupBlankRiotMatchIds', {
|
||||
total: blankRiotMatchCodeIds.length,
|
||||
});
|
||||
const result = await tournamentCodeCollection.updateMany(
|
||||
{ _id: { $in: blankRiotMatchCodeIds } },
|
||||
{ $unset: { riotMatchId: '' } },
|
||||
);
|
||||
stats.blankRiotMatchIdsUnset = readModifiedCount(result);
|
||||
}
|
||||
|
||||
if (releasePlan.length > 0) {
|
||||
const releaseIds = releasePlan.map((entry) => entry.code._id);
|
||||
emitProgress(options, 'cleanupDuplicateCodes', {
|
||||
total: releaseIds.length,
|
||||
});
|
||||
const releaseResult = await tournamentCodeCollection.updateMany(
|
||||
{ _id: { $in: releaseIds } },
|
||||
{
|
||||
$set: { releasedAt: now, state: 'released' },
|
||||
$unset: {
|
||||
bracketMatchId: '',
|
||||
gameNumber: '',
|
||||
matchId: '',
|
||||
reservedAt: '',
|
||||
riotMatchId: '',
|
||||
usedAt: '',
|
||||
},
|
||||
},
|
||||
);
|
||||
stats.duplicateCodesReleased = readModifiedCount(releaseResult);
|
||||
|
||||
const matchResult = await matchCollection.updateMany(
|
||||
{ tournamentCodeIds: { $in: releaseIds } },
|
||||
{ $pull: { tournamentCodeIds: { $in: releaseIds } } },
|
||||
);
|
||||
stats.matchesUpdated = readModifiedCount(matchResult);
|
||||
}
|
||||
|
||||
if (options.createIndexes ?? true) {
|
||||
emitProgress(options, 'ensureIndexes');
|
||||
const indexStats = await ensureTournamentCodeUniqueIndexes(
|
||||
tournamentCodeCollection,
|
||||
options,
|
||||
);
|
||||
stats.indexesAlreadyCorrect = indexStats.indexesAlreadyCorrect;
|
||||
stats.indexesCreated = indexStats.indexesCreated;
|
||||
stats.indexesDropped = indexStats.indexesDropped;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sampleDuplicateGroups: summarizeGroups(
|
||||
groups,
|
||||
matchScan.referencedCodeIds,
|
||||
options.duplicateSampleLimit ?? 20,
|
||||
),
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
async function readTournamentCodes(
|
||||
collection: MigrationCollection,
|
||||
options: TournamentCodeUniqueIndexMigrationOptions,
|
||||
): Promise<TournamentCodeDoc[]> {
|
||||
const docs: TournamentCodeDoc[] = [];
|
||||
for await (const doc of collection
|
||||
.find(TOURNAMENT_CODE_SCAN_FILTER, {
|
||||
projection: TOURNAMENT_CODE_SCAN_PROJECTION,
|
||||
})
|
||||
.limit(0)) {
|
||||
docs.push(doc as TournamentCodeDoc);
|
||||
emitScanProgress(options, 'scanTournamentCodes', docs.length);
|
||||
}
|
||||
emitProgress(options, 'scanTournamentCodes', { scanned: docs.length });
|
||||
return docs;
|
||||
}
|
||||
|
||||
async function readReferencedTournamentCodeIds(
|
||||
collection: MigrationCollection,
|
||||
options: TournamentCodeUniqueIndexMigrationOptions,
|
||||
): Promise<{ referencedCodeIds: Set<string>; scannedMatches: number }> {
|
||||
const referencedCodeIds = new Set<string>();
|
||||
let scannedMatches = 0;
|
||||
|
||||
for await (const doc of collection
|
||||
.find(MATCH_SCAN_FILTER, { projection: MATCH_SCAN_PROJECTION })
|
||||
.limit(0)) {
|
||||
scannedMatches += 1;
|
||||
emitScanProgress(options, 'scanMatches', scannedMatches);
|
||||
const ids = (doc as MatchDoc).tournamentCodeIds;
|
||||
if (!Array.isArray(ids)) continue;
|
||||
for (const id of ids) {
|
||||
const stringId = stringifyId(id);
|
||||
if (stringId) referencedCodeIds.add(stringId);
|
||||
}
|
||||
}
|
||||
|
||||
emitProgress(options, 'scanMatches', { scanned: scannedMatches });
|
||||
return { referencedCodeIds, scannedMatches };
|
||||
}
|
||||
|
||||
function emitScanProgress(
|
||||
options: TournamentCodeUniqueIndexMigrationOptions,
|
||||
phase: TournamentCodeUniqueIndexMigrationProgress['phase'],
|
||||
scanned: number,
|
||||
) {
|
||||
const interval = options.progressInterval ?? 5_000;
|
||||
if (interval < 1 || scanned % interval !== 0) return;
|
||||
emitProgress(options, phase, { scanned });
|
||||
}
|
||||
|
||||
function emitProgress(
|
||||
options: TournamentCodeUniqueIndexMigrationOptions,
|
||||
phase: TournamentCodeUniqueIndexMigrationProgress['phase'],
|
||||
values: Omit<TournamentCodeUniqueIndexMigrationProgress, 'phase'> = {},
|
||||
) {
|
||||
options.onProgress?.({ phase, ...values });
|
||||
}
|
||||
|
||||
function findDuplicateGroups(
|
||||
docs: TournamentCodeDoc[],
|
||||
referencedCodeIds: Set<string>,
|
||||
): DuplicateGroup[] {
|
||||
return [
|
||||
...duplicateGroupsFor(docs, referencedCodeIds, 'gameNumber'),
|
||||
...duplicateGroupsFor(docs, referencedCodeIds, 'riotMatchId'),
|
||||
];
|
||||
}
|
||||
|
||||
function duplicateGroupsFor(
|
||||
docs: TournamentCodeDoc[],
|
||||
referencedCodeIds: Set<string>,
|
||||
kind: TournamentCodeDuplicateKind,
|
||||
): DuplicateGroup[] {
|
||||
const groups = new Map<string, TournamentCodeDoc[]>();
|
||||
|
||||
for (const doc of docs) {
|
||||
const key = duplicateKey(doc, kind);
|
||||
if (!key) continue;
|
||||
const group = groups.get(key) ?? [];
|
||||
group.push(doc);
|
||||
groups.set(key, group);
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.filter(([, groupDocs]) => groupDocs.length > 1)
|
||||
.map(([key, groupDocs]) => ({
|
||||
codeDocs: sortCodesByKeeperPriority(groupDocs, referencedCodeIds, kind),
|
||||
key,
|
||||
kind,
|
||||
}));
|
||||
}
|
||||
|
||||
function duplicateKey(
|
||||
doc: TournamentCodeDoc,
|
||||
kind: TournamentCodeDuplicateKind,
|
||||
): string | null {
|
||||
if (kind === 'riotMatchId') {
|
||||
if (typeof doc.riotMatchId !== 'string') return null;
|
||||
if (doc.riotMatchId.trim() === '') return null;
|
||||
return `riotMatchId:${doc.riotMatchId}`;
|
||||
}
|
||||
|
||||
if (!ACTIVE_CODE_STATES.has(String(doc.state))) return null;
|
||||
if (!hasField(doc, 'matchId')) return null;
|
||||
|
||||
if (kind === 'gameNumber') {
|
||||
if (!hasField(doc, 'gameNumber')) return null;
|
||||
return `matchId:${stringifyKeyPart(doc.matchId)}:gameNumber:${stringifyKeyPart(
|
||||
doc.gameNumber,
|
||||
)}`;
|
||||
}
|
||||
|
||||
if (!hasField(doc, 'bracketMatchId')) return null;
|
||||
return `matchId:${stringifyKeyPart(
|
||||
doc.matchId,
|
||||
)}:bracketMatchId:${stringifyKeyPart(doc.bracketMatchId)}`;
|
||||
}
|
||||
|
||||
function buildReleasePlan(
|
||||
groups: DuplicateGroup[],
|
||||
referencedCodeIds: Set<string>,
|
||||
): ReleasePlanEntry[] {
|
||||
const byCodeId = new Map<string, ReleasePlanEntry>();
|
||||
|
||||
for (const group of groups) {
|
||||
const keeper = chooseKeeper(group, referencedCodeIds);
|
||||
const keeperId = stringifyId(keeper._id);
|
||||
for (const code of group.codeDocs) {
|
||||
const codeId = stringifyId(code._id);
|
||||
if (!codeId || codeId === keeperId) continue;
|
||||
const entry = byCodeId.get(codeId) ?? { code, reasons: [] };
|
||||
entry.reasons.push(`${group.kind}:${group.key}`);
|
||||
byCodeId.set(codeId, entry);
|
||||
}
|
||||
}
|
||||
|
||||
return [...byCodeId.values()];
|
||||
}
|
||||
|
||||
function summarizeGroups(
|
||||
groups: DuplicateGroup[],
|
||||
referencedCodeIds: Set<string>,
|
||||
limit: number,
|
||||
): TournamentCodeDuplicateGroupSummary[] {
|
||||
return groups.slice(0, limit).map((group) => {
|
||||
const keeper = chooseKeeper(group, referencedCodeIds);
|
||||
const keeperId = stringifyId(keeper._id);
|
||||
return {
|
||||
keeper: summarizeCode(keeper),
|
||||
key: group.key,
|
||||
kind: group.kind,
|
||||
losers: group.codeDocs
|
||||
.filter((code) => stringifyId(code._id) !== keeperId)
|
||||
.map(summarizeCode),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
|
||||
return {
|
||||
bracketMatchId:
|
||||
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId),
|
||||
code: doc.code === undefined ? undefined : String(doc.code),
|
||||
gameNumber:
|
||||
doc.gameNumber === undefined ? undefined : String(doc.gameNumber),
|
||||
id: stringifyId(doc._id) ?? '',
|
||||
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
|
||||
riotMatchId:
|
||||
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId),
|
||||
state: doc.state === undefined ? undefined : String(doc.state),
|
||||
};
|
||||
}
|
||||
|
||||
function chooseKeeper(
|
||||
group: DuplicateGroup,
|
||||
referencedCodeIds: Set<string>,
|
||||
): TournamentCodeDoc {
|
||||
return sortCodesByKeeperPriority(
|
||||
group.codeDocs,
|
||||
referencedCodeIds,
|
||||
group.kind,
|
||||
)[0];
|
||||
}
|
||||
|
||||
function sortCodesByKeeperPriority(
|
||||
docs: TournamentCodeDoc[],
|
||||
referencedCodeIds: Set<string>,
|
||||
kind: TournamentCodeDuplicateKind,
|
||||
): TournamentCodeDoc[] {
|
||||
return [...docs].sort((left, right) =>
|
||||
compareCodePriority(left, right, referencedCodeIds, kind),
|
||||
);
|
||||
}
|
||||
|
||||
function compareCodePriority(
|
||||
left: TournamentCodeDoc,
|
||||
right: TournamentCodeDoc,
|
||||
referencedCodeIds: Set<string>,
|
||||
kind: TournamentCodeDuplicateKind,
|
||||
): number {
|
||||
if (kind !== 'riotMatchId') {
|
||||
const leftReferenced = referencedCodeIds.has(stringifyId(left._id) ?? '');
|
||||
const rightReferenced = referencedCodeIds.has(stringifyId(right._id) ?? '');
|
||||
if (leftReferenced !== rightReferenced) return leftReferenced ? -1 : 1;
|
||||
}
|
||||
|
||||
const leftStateRank = stateRank(left.state);
|
||||
const rightStateRank = stateRank(right.state);
|
||||
if (leftStateRank !== rightStateRank) return leftStateRank - rightStateRank;
|
||||
|
||||
if (kind === 'riotMatchId') {
|
||||
const leftReferenced = referencedCodeIds.has(stringifyId(left._id) ?? '');
|
||||
const rightReferenced = referencedCodeIds.has(stringifyId(right._id) ?? '');
|
||||
if (leftReferenced !== rightReferenced) return leftReferenced ? -1 : 1;
|
||||
}
|
||||
|
||||
const leftHasRiotMatch = hasNonBlankRiotMatchId(left);
|
||||
const rightHasRiotMatch = hasNonBlankRiotMatchId(right);
|
||||
if (leftHasRiotMatch !== rightHasRiotMatch) {
|
||||
return leftHasRiotMatch ? -1 : 1;
|
||||
}
|
||||
|
||||
const leftDate = latestTimestamp(left);
|
||||
const rightDate = latestTimestamp(right);
|
||||
if (leftDate !== rightDate) return rightDate - leftDate;
|
||||
|
||||
return (stringifyId(left._id) ?? '').localeCompare(
|
||||
stringifyId(right._id) ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
function stateRank(state: unknown): number {
|
||||
if (state === 'used') return 0;
|
||||
if (state === 'reserved') return 1;
|
||||
if (state === 'available') return 2;
|
||||
if (state === 'released') return 3;
|
||||
if (state === 'expired') return 4;
|
||||
if (state === 'voided') return 5;
|
||||
return 10;
|
||||
}
|
||||
|
||||
function latestTimestamp(doc: TournamentCodeDoc): number {
|
||||
return Math.max(
|
||||
toTimestamp(doc.usedAt),
|
||||
toTimestamp(doc.reservedAt),
|
||||
toTimestamp(doc.updatedAt),
|
||||
toTimestamp(doc.createdAt),
|
||||
toTimestamp(doc.uploadedAt),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
function toTimestamp(value: unknown): number {
|
||||
if (value instanceof Date) return value.getTime();
|
||||
if (typeof value === 'number') return value;
|
||||
if (typeof value !== 'string') return 0;
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
|
||||
function hasBlankRiotMatchId(doc: TournamentCodeDoc): boolean {
|
||||
return typeof doc.riotMatchId === 'string' && doc.riotMatchId.trim() === '';
|
||||
}
|
||||
|
||||
function hasNonBlankRiotMatchId(doc: TournamentCodeDoc): boolean {
|
||||
return typeof doc.riotMatchId === 'string' && doc.riotMatchId.trim() !== '';
|
||||
}
|
||||
|
||||
async function ensureTournamentCodeUniqueIndexes(
|
||||
collection: MigrationCollection,
|
||||
options: TournamentCodeUniqueIndexMigrationOptions,
|
||||
): Promise<{
|
||||
indexesAlreadyCorrect: number;
|
||||
indexesCreated: number;
|
||||
indexesDropped: number;
|
||||
}> {
|
||||
if (!collection.indexes || !collection.dropIndex || !collection.createIndex) {
|
||||
throw new Error('Migration collection does not support index operations.');
|
||||
}
|
||||
|
||||
emitProgress(options, 'ensureIndexes', { action: 'list' });
|
||||
let indexes = await listCollectionIndexes(collection);
|
||||
let indexesAlreadyCorrect = 0;
|
||||
let indexesCreated = 0;
|
||||
let indexesDropped = 0;
|
||||
|
||||
for (const desired of DESIRED_TOURNAMENT_CODE_INDEXES) {
|
||||
const matchingIndexes = indexes.filter(
|
||||
(index) =>
|
||||
index.name === desired.options.name ||
|
||||
sameObject(index.key, desired.key),
|
||||
);
|
||||
const correctIndex = matchingIndexes.find((index) =>
|
||||
sameIndex(index, desired),
|
||||
);
|
||||
|
||||
if (correctIndex) {
|
||||
emitProgress(options, 'ensureIndexes', {
|
||||
action: 'alreadyCorrect',
|
||||
indexName: desired.options.name,
|
||||
});
|
||||
indexesAlreadyCorrect += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const index of matchingIndexes) {
|
||||
if (index.name === '_id_') continue;
|
||||
emitProgress(options, 'ensureIndexes', {
|
||||
action: 'drop',
|
||||
indexName: index.name,
|
||||
});
|
||||
await collection.dropIndex(index.name);
|
||||
emitProgress(options, 'ensureIndexes', {
|
||||
action: 'dropped',
|
||||
indexName: index.name,
|
||||
});
|
||||
indexesDropped += 1;
|
||||
}
|
||||
|
||||
emitProgress(options, 'ensureIndexes', {
|
||||
action: 'create',
|
||||
indexName: desired.options.name,
|
||||
});
|
||||
await collection.createIndex(desired.key, {
|
||||
...desired.options,
|
||||
...(options.indexCommitQuorum !== undefined
|
||||
? { commitQuorum: options.indexCommitQuorum }
|
||||
: {}),
|
||||
...(options.indexMaxTimeMS !== undefined
|
||||
? { maxTimeMS: options.indexMaxTimeMS }
|
||||
: {}),
|
||||
});
|
||||
emitProgress(options, 'ensureIndexes', {
|
||||
action: 'created',
|
||||
indexName: desired.options.name,
|
||||
});
|
||||
indexesCreated += 1;
|
||||
emitProgress(options, 'ensureIndexes', { action: 'list' });
|
||||
indexes = await listCollectionIndexes(collection);
|
||||
}
|
||||
|
||||
return { indexesAlreadyCorrect, indexesCreated, indexesDropped };
|
||||
}
|
||||
|
||||
async function listCollectionIndexes(
|
||||
collection: MigrationCollection,
|
||||
): Promise<MigrationIndex[]> {
|
||||
if (!collection.indexes) {
|
||||
throw new Error('Migration collection does not support index operations.');
|
||||
}
|
||||
|
||||
try {
|
||||
return await collection.indexes();
|
||||
} catch (error) {
|
||||
if (isNamespaceNotFoundError(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isNamespaceNotFoundError(error: unknown): boolean {
|
||||
const candidate = error as {
|
||||
code?: number;
|
||||
codeName?: string;
|
||||
message?: string;
|
||||
};
|
||||
return Boolean(
|
||||
candidate?.code === 26 ||
|
||||
candidate?.codeName === 'NamespaceNotFound' ||
|
||||
candidate?.message?.includes('ns does not exist'),
|
||||
);
|
||||
}
|
||||
|
||||
function sameIndex(index: MigrationIndex, desired: DesiredIndex): boolean {
|
||||
return (
|
||||
sameObject(index.key, desired.key) &&
|
||||
index.unique === desired.options.unique &&
|
||||
sameObject(
|
||||
index.partialFilterExpression ?? {},
|
||||
desired.options.partialFilterExpression ?? {},
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function sameObject(left: unknown, right: unknown): boolean {
|
||||
return JSON.stringify(left) === JSON.stringify(right);
|
||||
}
|
||||
|
||||
function readModifiedCount(result: unknown): number {
|
||||
if (!result || typeof result !== 'object') return 0;
|
||||
const modifiedCount = (result as { modifiedCount?: unknown }).modifiedCount;
|
||||
return typeof modifiedCount === 'number' ? modifiedCount : 0;
|
||||
}
|
||||
|
||||
function hasField(doc: Record<string, unknown>, key: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(doc, key);
|
||||
}
|
||||
|
||||
function stringifyKeyPart(value: unknown): string {
|
||||
if (value === null) return '<null>';
|
||||
if (value === undefined) return '<undefined>';
|
||||
return stringifyId(value) ?? String(value);
|
||||
}
|
||||
|
||||
function stringifyId(value: unknown): string | undefined {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
return typeof value === 'string' ? value : String(value);
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { buildRepairPlan } from './repair-double-elimination-series-rules';
|
||||
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
||||
|
||||
function createMatch(overrides: Partial<MatchDocument>): MatchDocument {
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
gameCount: 3,
|
||||
tournamentCodeIds: [],
|
||||
doubleElimination: {
|
||||
teamCount: 8,
|
||||
resetFinalEnabled: false,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
|
||||
function createCode(
|
||||
overrides: Partial<TournamentCodeDocument>,
|
||||
): TournamentCodeDocument {
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
code: 'CODE',
|
||||
state: 'reserved',
|
||||
...overrides,
|
||||
} as unknown as TournamentCodeDocument;
|
||||
}
|
||||
|
||||
describe('repair-double-elimination-series-rules buildRepairPlan', () => {
|
||||
it('plans missing ready series slots even when result games already exist', () => {
|
||||
const match = createMatch({
|
||||
result: {
|
||||
riotMatchIds: ['KR_1'],
|
||||
games: [
|
||||
{
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 'WB_R2_M1',
|
||||
},
|
||||
],
|
||||
seriesResults: [],
|
||||
},
|
||||
doubleElimination: {
|
||||
teamCount: 8,
|
||||
resetFinalEnabled: false,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [
|
||||
{
|
||||
bracketMatchId: 'WB_R2_M1',
|
||||
gameNumber: 1,
|
||||
gameCount: 3,
|
||||
requiredWins: 2,
|
||||
bracketSide: 'winner',
|
||||
roundNumber: 2,
|
||||
matchNumber: 1,
|
||||
state: 'ready',
|
||||
teamAIndex: 4,
|
||||
teamBIndex: 6,
|
||||
},
|
||||
],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
});
|
||||
const existingFirstSetCode = createCode({
|
||||
bracketMatchId: 'WB_R2_M1',
|
||||
gameNumber: 1,
|
||||
});
|
||||
|
||||
const plan = buildRepairPlan(match, [existingFirstSetCode], 3);
|
||||
|
||||
expect(plan.ruleRepairSkippedReason).toBe('result-games-exist');
|
||||
expect(plan.codeUpdates).toEqual([]);
|
||||
expect(plan.missingReadySlots).toEqual([
|
||||
{
|
||||
bracketMatchId: 'WB_R2_M1',
|
||||
gameNumber: 2,
|
||||
seriesGameNumber: 2,
|
||||
seriesGameCount: 3,
|
||||
},
|
||||
{
|
||||
bracketMatchId: 'WB_R2_M1',
|
||||
gameNumber: 3,
|
||||
seriesGameNumber: 3,
|
||||
seriesGameCount: 3,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
+470
@@ -0,0 +1,470 @@
|
||||
import 'reflect-metadata';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
buildDoubleEliminationGameSlots,
|
||||
type DoubleEliminationBracketMatch,
|
||||
} from '../../../double-elimination/double-elimination.util';
|
||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
|
||||
import { ConnectionService } from '../connection.service';
|
||||
import type { MatchDocument, TournamentCodeDocument } from '../schema';
|
||||
import { SecretModule } from '../../secret/secret.module';
|
||||
|
||||
interface CliOptions {
|
||||
dryRun: boolean;
|
||||
matchId?: mongoose.Types.ObjectId;
|
||||
nodeEnv: string;
|
||||
winnerGameCount: number;
|
||||
}
|
||||
|
||||
interface CodeUpdatePlan {
|
||||
codeId: mongoose.Types.ObjectId;
|
||||
code: string;
|
||||
bracketMatchId: string;
|
||||
currentGameNumber: number | undefined;
|
||||
nextGameNumber: number;
|
||||
}
|
||||
|
||||
interface MissingReadySlotPlan {
|
||||
bracketMatchId: string;
|
||||
gameNumber: number;
|
||||
seriesGameNumber: number;
|
||||
seriesGameCount: number;
|
||||
}
|
||||
|
||||
interface MatchRepairPlan {
|
||||
codeUpdates: CodeUpdatePlan[];
|
||||
currentGameCount: number;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
missingReadySlots: MissingReadySlotPlan[];
|
||||
nextGameCount: number;
|
||||
nextBracketMatches: DoubleEliminationBracketMatch[];
|
||||
ruleRepairSkippedReason?: string;
|
||||
skippedReason?: string;
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: [
|
||||
resolve(__dirname, '../../../../../../project.env'),
|
||||
resolve(process.cwd(), '../project.env'),
|
||||
resolve(process.cwd(), 'apps/project.env'),
|
||||
resolve(process.cwd(), 'project.env'),
|
||||
],
|
||||
}),
|
||||
SecretModule,
|
||||
],
|
||||
providers: [ConnectionService],
|
||||
})
|
||||
class RepairModule {}
|
||||
|
||||
async function loadMachineEnvFile() {
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||
if (!homeDir) return;
|
||||
|
||||
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||
|
||||
try {
|
||||
const file = await readFile(machineEnvFile, 'utf8');
|
||||
for (const rawLine of file.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (!matched) continue;
|
||||
const [, key, rawValue] = matched;
|
||||
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||
}
|
||||
} catch {
|
||||
// Local machine env is optional for one-off migrations.
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): CliOptions {
|
||||
let dryRun = true;
|
||||
let matchId: mongoose.Types.ObjectId | undefined;
|
||||
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||
let winnerGameCount = 3;
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === '--apply') {
|
||||
dryRun = false;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--dry-run') {
|
||||
dryRun = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--env') {
|
||||
const value = argv[index + 1];
|
||||
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||
nodeEnv = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--env=')) {
|
||||
nodeEnv = arg.slice('--env='.length);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--match-id') {
|
||||
matchId = parseObjectId(argv[index + 1], '--match-id');
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--match-id=')) {
|
||||
matchId = parseObjectId(arg.slice('--match-id='.length), '--match-id');
|
||||
continue;
|
||||
}
|
||||
if (arg === '--winner-game-count') {
|
||||
winnerGameCount = parseOddPositiveInteger(
|
||||
argv[index + 1],
|
||||
'--winner-game-count',
|
||||
);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--winner-game-count=')) {
|
||||
winnerGameCount = parseOddPositiveInteger(
|
||||
arg.slice('--winner-game-count='.length),
|
||||
'--winner-game-count',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||
throw new Error('--env must be dev, staging, or prod.');
|
||||
}
|
||||
|
||||
return { dryRun, matchId, nodeEnv, winnerGameCount };
|
||||
}
|
||||
|
||||
function parseObjectId(value: string | undefined, label: string) {
|
||||
if (!value || !mongoose.isValidObjectId(value)) {
|
||||
throw new Error(`${label} requires a valid ObjectId.`);
|
||||
}
|
||||
return new mongoose.Types.ObjectId(value);
|
||||
}
|
||||
|
||||
function parseOddPositiveInteger(value: string | undefined, label: string) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < 1 || parsed % 2 === 0) {
|
||||
throw new Error(`${label} requires a positive odd integer.`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage:
|
||||
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --dry-run
|
||||
pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id <id> --env prod --apply
|
||||
|
||||
Options:
|
||||
--match-id <id> Optional match ObjectId. If omitted, scans all double-elimination matches.
|
||||
--winner-game-count <n> Winner-bracket series size. Must be odd. Default: 3.
|
||||
--dry-run Print the repair plan without writing. Default.
|
||||
--apply Apply match and tournament code updates.
|
||||
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||
`);
|
||||
}
|
||||
|
||||
function requiredWinsFor(gameCount: number): number {
|
||||
return Math.floor(gameCount / 2) + 1;
|
||||
}
|
||||
|
||||
function codeSlotKey(
|
||||
bracketMatchId: string | undefined,
|
||||
gameNumber: number | undefined,
|
||||
): string | undefined {
|
||||
if (!bracketMatchId || typeof gameNumber !== 'number') return undefined;
|
||||
return `${bracketMatchId}:${gameNumber}`;
|
||||
}
|
||||
|
||||
function buildActiveCodeSlotKeys(
|
||||
codes: TournamentCodeDocument[],
|
||||
codeUpdates: CodeUpdatePlan[] = [],
|
||||
): Set<string> {
|
||||
const updateByCodeId = new Map(
|
||||
codeUpdates.map((update) => [update.codeId.toString(), update]),
|
||||
);
|
||||
const activeSlotKeys = new Set<string>();
|
||||
|
||||
for (const code of codes) {
|
||||
if (code.state !== 'reserved' && code.state !== 'used') continue;
|
||||
const update = updateByCodeId.get(code._id.toString());
|
||||
const key = codeSlotKey(
|
||||
update?.bracketMatchId ?? code.bracketMatchId,
|
||||
update?.nextGameNumber ?? code.gameNumber,
|
||||
);
|
||||
if (key) activeSlotKeys.add(key);
|
||||
}
|
||||
|
||||
return activeSlotKeys;
|
||||
}
|
||||
|
||||
function buildMissingReadySlots(
|
||||
bracketMatches: DoubleEliminationBracketMatch[],
|
||||
codes: TournamentCodeDocument[],
|
||||
codeUpdates: CodeUpdatePlan[] = [],
|
||||
): MissingReadySlotPlan[] {
|
||||
const activeSlotKeys = buildActiveCodeSlotKeys(codes, codeUpdates);
|
||||
|
||||
return buildDoubleEliminationGameSlots(bracketMatches)
|
||||
.filter((slot) => slot.bracketMatch.state === 'ready')
|
||||
.filter(
|
||||
(slot) =>
|
||||
!activeSlotKeys.has(
|
||||
`${slot.bracketMatch.bracketMatchId}:${slot.gameNumber}`,
|
||||
),
|
||||
)
|
||||
.map((slot) => ({
|
||||
bracketMatchId: slot.bracketMatch.bracketMatchId,
|
||||
gameNumber: slot.gameNumber,
|
||||
seriesGameNumber: slot.seriesGameNumber,
|
||||
seriesGameCount: slot.seriesGameCount,
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildRepairPlan(
|
||||
match: MatchDocument,
|
||||
codes: TournamentCodeDocument[],
|
||||
winnerGameCount: number,
|
||||
): MatchRepairPlan {
|
||||
const currentGameCount = match.gameCount;
|
||||
const resultGames = match.result?.games ?? [];
|
||||
const currentBracketMatches = [
|
||||
...(match.doubleElimination?.bracketMatches ?? []),
|
||||
];
|
||||
if (resultGames.length > 0) {
|
||||
return {
|
||||
codeUpdates: [],
|
||||
currentGameCount,
|
||||
matchId: match._id,
|
||||
missingReadySlots: buildMissingReadySlots(currentBracketMatches, codes),
|
||||
nextBracketMatches: currentBracketMatches,
|
||||
nextGameCount: currentGameCount,
|
||||
ruleRepairSkippedReason: 'result-games-exist',
|
||||
};
|
||||
}
|
||||
|
||||
const nextBracketMatches = currentBracketMatches.map((bracketMatch) => {
|
||||
const gameCount =
|
||||
bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1;
|
||||
return {
|
||||
...bracketMatch,
|
||||
gameCount,
|
||||
requiredWins: requiredWinsFor(gameCount),
|
||||
};
|
||||
});
|
||||
const firstSlotByBracketMatchId = new Map(
|
||||
buildDoubleEliminationGameSlots(nextBracketMatches)
|
||||
.filter((slot) => slot.seriesGameNumber === 1)
|
||||
.map((slot) => [slot.bracketMatch.bracketMatchId, slot]),
|
||||
);
|
||||
const codeUpdates = codes
|
||||
.filter((code) => code.bracketMatchId)
|
||||
.map((code) => {
|
||||
const slot = firstSlotByBracketMatchId.get(code.bracketMatchId!);
|
||||
if (!slot) return null;
|
||||
if (code.gameNumber === slot.gameNumber) return null;
|
||||
return {
|
||||
codeId: code._id,
|
||||
code: code.code,
|
||||
bracketMatchId: code.bracketMatchId!,
|
||||
currentGameNumber: code.gameNumber,
|
||||
nextGameNumber: slot.gameNumber,
|
||||
} satisfies CodeUpdatePlan;
|
||||
})
|
||||
.filter((entry): entry is CodeUpdatePlan => Boolean(entry));
|
||||
const missingReadySlots = buildMissingReadySlots(
|
||||
nextBracketMatches,
|
||||
codes,
|
||||
codeUpdates,
|
||||
);
|
||||
|
||||
return {
|
||||
codeUpdates,
|
||||
currentGameCount,
|
||||
matchId: match._id,
|
||||
missingReadySlots,
|
||||
nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount),
|
||||
nextBracketMatches,
|
||||
};
|
||||
}
|
||||
|
||||
function printPlan(plan: MatchRepairPlan) {
|
||||
console.log(`match=${plan.matchId.toString()}`);
|
||||
if (plan.skippedReason) {
|
||||
console.log(` skipped=${plan.skippedReason}`);
|
||||
return;
|
||||
}
|
||||
if (plan.ruleRepairSkippedReason) {
|
||||
console.log(` ruleRepairSkipped=${plan.ruleRepairSkippedReason}`);
|
||||
} else {
|
||||
console.log(
|
||||
` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`,
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length} missingReadySlots=${plan.missingReadySlots.length}`,
|
||||
);
|
||||
for (const update of plan.codeUpdates) {
|
||||
console.log(
|
||||
` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`,
|
||||
);
|
||||
}
|
||||
for (const slot of plan.missingReadySlots) {
|
||||
console.log(
|
||||
` missing ${slot.bracketMatchId}: game ${slot.gameNumber} (${slot.seriesGameNumber}/${slot.seriesGameCount})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyPlan(
|
||||
match: MatchDocument,
|
||||
plan: MatchRepairPlan,
|
||||
TournamentCodeModel: mongoose.Model<any>,
|
||||
session: mongoose.ClientSession,
|
||||
) {
|
||||
if (plan.skippedReason) return;
|
||||
for (const update of plan.codeUpdates) {
|
||||
await TournamentCodeModel.updateOne(
|
||||
{ _id: update.codeId },
|
||||
{
|
||||
$set: {
|
||||
gameNumber: update.nextGameNumber,
|
||||
bracketMatchId: update.bracketMatchId,
|
||||
},
|
||||
},
|
||||
{ session },
|
||||
).exec();
|
||||
}
|
||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
for (const slot of plan.missingReadySlots) {
|
||||
const existingSlotCode = await TournamentCodeModel.exists({
|
||||
matchId: match._id,
|
||||
gameNumber: slot.gameNumber,
|
||||
bracketMatchId: slot.bracketMatchId,
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
})
|
||||
.session(session)
|
||||
.exec();
|
||||
if (existingSlotCode) continue;
|
||||
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: 'kr',
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: slot.gameNumber,
|
||||
bracketMatchId: slot.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
}
|
||||
|
||||
if (reservedIds.length > 0) {
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
}
|
||||
|
||||
if (!plan.ruleRepairSkippedReason) {
|
||||
match.gameCount = plan.nextGameCount;
|
||||
if (match.doubleElimination) {
|
||||
match.doubleElimination.bracketMatches = plan.nextBracketMatches;
|
||||
match.markModified('doubleElimination');
|
||||
}
|
||||
}
|
||||
|
||||
if (reservedIds.length > 0 || !plan.ruleRepairSkippedReason) {
|
||||
await match.save({ session });
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
process.env.NODE_ENV = options.nodeEnv;
|
||||
process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical';
|
||||
await loadMachineEnvFile();
|
||||
|
||||
const app = await NestFactory.createApplicationContext(RepairModule, {
|
||||
logger: ['log', 'warn', 'error'],
|
||||
});
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const MatchModel = await connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await connectionService.getModel('tournamentCode');
|
||||
const matches = await MatchModel.find({
|
||||
gameMode: 'double-elimination',
|
||||
...(options.matchId ? { _id: options.matchId } : {}),
|
||||
}).exec();
|
||||
|
||||
const plans: Array<{ match: MatchDocument; plan: MatchRepairPlan }> = [];
|
||||
for (const match of matches) {
|
||||
const codes = await TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds ?? [] },
|
||||
}).exec();
|
||||
const plan = buildRepairPlan(match, codes, options.winnerGameCount);
|
||||
plans.push({ match, plan });
|
||||
printPlan(plan);
|
||||
}
|
||||
|
||||
if (options.dryRun) {
|
||||
console.log(
|
||||
'No writes were made. Re-run with --apply to update MongoDB.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const session = await (
|
||||
await connectionService.getConnection()
|
||||
).startSession();
|
||||
try {
|
||||
await session.withTransaction(async () => {
|
||||
for (const { match, plan } of plans) {
|
||||
await applyPlan(match, plan, TournamentCodeModel, session);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
await session.endSession();
|
||||
}
|
||||
console.log(
|
||||
`Applied ${plans.filter(({ plan }) => !plan.skippedReason).length} match repairs.`,
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
import 'reflect-metadata';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||
import { SecretModule } from '../../secret/secret.module';
|
||||
import {
|
||||
migrateTournamentCodeUniqueIndexes,
|
||||
TournamentCodeDuplicateGroupSummary,
|
||||
TournamentCodeUniqueIndexMigrationProgress,
|
||||
} from './20260627-tournament-code-unique-indexes';
|
||||
|
||||
interface CliOptions {
|
||||
allowUsedDuplicateRelease: boolean;
|
||||
createIndexes: boolean;
|
||||
dryRun: boolean;
|
||||
duplicateSampleLimit: number;
|
||||
indexCommitQuorum?: number | string;
|
||||
indexMaxTimeMS?: number;
|
||||
listDuplicates: boolean;
|
||||
nodeEnv: string;
|
||||
}
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: [
|
||||
resolve(__dirname, '../../../../../../project.env'),
|
||||
resolve(process.cwd(), '../project.env'),
|
||||
resolve(process.cwd(), 'apps/project.env'),
|
||||
resolve(process.cwd(), 'project.env'),
|
||||
],
|
||||
}),
|
||||
SecretModule,
|
||||
],
|
||||
providers: [ConnectionService],
|
||||
})
|
||||
class MigrationModule {}
|
||||
|
||||
async function loadMachineEnvFile() {
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE;
|
||||
if (!homeDir) return;
|
||||
|
||||
const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt');
|
||||
|
||||
try {
|
||||
const file = await readFile(machineEnvFile, 'utf8');
|
||||
for (const rawLine of file.split(/\r?\n/)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
|
||||
const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
||||
if (!matched) continue;
|
||||
|
||||
const [, key, rawValue] = matched;
|
||||
process.env[key] = rawValue.replace(/^["']|["']$/g, '');
|
||||
}
|
||||
} catch {
|
||||
// Local machine env is optional for one-off migrations.
|
||||
}
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): CliOptions {
|
||||
let allowUsedDuplicateRelease = false;
|
||||
let createIndexes = true;
|
||||
let dryRun = true;
|
||||
let duplicateSampleLimit = 20;
|
||||
let indexCommitQuorum: number | string | undefined;
|
||||
let indexMaxTimeMS: number | undefined;
|
||||
let listDuplicates = false;
|
||||
let nodeEnv = process.env.NODE_ENV ?? 'dev';
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === '--allow-used-duplicate-release') {
|
||||
allowUsedDuplicateRelease = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--apply') {
|
||||
dryRun = false;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--dry-run') {
|
||||
dryRun = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--duplicate-sample-limit') {
|
||||
duplicateSampleLimit = parsePositiveInteger(
|
||||
argv[index + 1],
|
||||
'--duplicate-sample-limit',
|
||||
);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--duplicate-sample-limit=')) {
|
||||
duplicateSampleLimit = parsePositiveInteger(
|
||||
arg.slice('--duplicate-sample-limit='.length),
|
||||
'--duplicate-sample-limit',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--env') {
|
||||
const value = argv[index + 1];
|
||||
if (!value) throw new Error('--env requires dev, staging, or prod.');
|
||||
nodeEnv = value;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--env=')) {
|
||||
nodeEnv = arg.slice('--env='.length);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--index-commit-quorum') {
|
||||
indexCommitQuorum = parseCommitQuorum(
|
||||
argv[index + 1],
|
||||
'--index-commit-quorum',
|
||||
);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--index-commit-quorum=')) {
|
||||
indexCommitQuorum = parseCommitQuorum(
|
||||
arg.slice('--index-commit-quorum='.length),
|
||||
'--index-commit-quorum',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--index-max-time-ms') {
|
||||
indexMaxTimeMS = parsePositiveInteger(
|
||||
argv[index + 1],
|
||||
'--index-max-time-ms',
|
||||
);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--index-max-time-ms=')) {
|
||||
indexMaxTimeMS = parsePositiveInteger(
|
||||
arg.slice('--index-max-time-ms='.length),
|
||||
'--index-max-time-ms',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--list-duplicates') {
|
||||
listDuplicates = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--skip-indexes') {
|
||||
createIndexes = false;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
throw new Error(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
|
||||
throw new Error('--env must be dev, staging, or prod.');
|
||||
}
|
||||
|
||||
return {
|
||||
allowUsedDuplicateRelease,
|
||||
createIndexes,
|
||||
dryRun,
|
||||
duplicateSampleLimit,
|
||||
indexCommitQuorum,
|
||||
indexMaxTimeMS,
|
||||
listDuplicates,
|
||||
nodeEnv,
|
||||
};
|
||||
}
|
||||
|
||||
function parseCommitQuorum(value: string | undefined, label: string) {
|
||||
if (!value) {
|
||||
throw new Error(`${label} requires a positive integer, majority, or votingMembers.`);
|
||||
}
|
||||
if (value === 'majority' || value === 'votingMembers') return value;
|
||||
return parsePositiveInteger(value, label);
|
||||
}
|
||||
|
||||
function parsePositiveInteger(value: string | undefined, label: string) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < 1) {
|
||||
throw new Error(`${label} requires a positive integer.`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage:
|
||||
pnpm --filter api exec ts-node src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts [--dry-run]
|
||||
pnpm --filter api exec ts-node src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts --env staging --apply
|
||||
|
||||
Options:
|
||||
--dry-run Print affected counts without writing. Default.
|
||||
--apply Release duplicate losers, pull them from matches, and create unique indexes.
|
||||
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
|
||||
--list-duplicates
|
||||
Print duplicate tournamentCode group samples.
|
||||
--duplicate-sample-limit <n>
|
||||
Max duplicate groups to print. Default: 20.
|
||||
--index-commit-quorum <n|majority|votingMembers>
|
||||
Override MongoDB index build commitQuorum. Use 1 only after checking replica health.
|
||||
--index-max-time-ms <n>
|
||||
Abort an individual index command after n milliseconds.
|
||||
--skip-indexes Apply document cleanup without creating indexes.
|
||||
--allow-used-duplicate-release
|
||||
Allow releasing duplicate codes whose state is used. Default refuses this.
|
||||
`);
|
||||
}
|
||||
|
||||
function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) {
|
||||
if (groups.length === 0) {
|
||||
console.log('No duplicate tournamentCode groups found.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Duplicate tournamentCode groups:');
|
||||
console.table(
|
||||
groups.map((group) => ({
|
||||
keeperCode: group.keeper.code ?? '',
|
||||
keeperId: group.keeper.id,
|
||||
keeperState: group.keeper.state ?? '',
|
||||
key: group.key,
|
||||
kind: group.kind,
|
||||
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
|
||||
loserIds: group.losers.map((loser) => loser.id).join(', '),
|
||||
loserStates: group.losers
|
||||
.map((loser) => loser.state ?? '')
|
||||
.join(', '),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
function printProgress(progress: TournamentCodeUniqueIndexMigrationProgress) {
|
||||
const count =
|
||||
progress.scanned !== undefined
|
||||
? ` scanned=${progress.scanned}`
|
||||
: progress.total !== undefined
|
||||
? ` total=${progress.total}`
|
||||
: '';
|
||||
const index = progress.indexName ? ` index=${progress.indexName}` : '';
|
||||
const action = progress.action ? ` action=${progress.action}` : '';
|
||||
console.log(
|
||||
`[tournament-code unique index migration] ${progress.phase}${action}${index}${count}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
process.env.NODE_ENV = options.nodeEnv;
|
||||
process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical';
|
||||
await loadMachineEnvFile();
|
||||
|
||||
const app = await NestFactory.createApplicationContext(MigrationModule, {
|
||||
logger: ['log', 'warn', 'error'],
|
||||
});
|
||||
|
||||
try {
|
||||
const connectionService = app.get(ConnectionService);
|
||||
const connection = await connectionService.getConnection();
|
||||
if (!connection.db) {
|
||||
throw new Error('MongoDB connection has no db handle.');
|
||||
}
|
||||
|
||||
const dbName = resolveMongoDbName(options.nodeEnv);
|
||||
console.log(
|
||||
`[tournament-code unique index migration] mode=${
|
||||
options.dryRun ? 'dry-run' : 'apply'
|
||||
} env=${options.nodeEnv} db=${dbName}`,
|
||||
);
|
||||
|
||||
const result = await migrateTournamentCodeUniqueIndexes(
|
||||
connection.db as Parameters<typeof migrateTournamentCodeUniqueIndexes>[0],
|
||||
{
|
||||
allowUsedDuplicateRelease: options.allowUsedDuplicateRelease,
|
||||
createIndexes: options.createIndexes,
|
||||
dryRun: options.dryRun,
|
||||
duplicateSampleLimit: options.duplicateSampleLimit,
|
||||
indexCommitQuorum: options.indexCommitQuorum,
|
||||
indexMaxTimeMS: options.indexMaxTimeMS,
|
||||
onProgress: printProgress,
|
||||
},
|
||||
);
|
||||
|
||||
console.table(result.stats);
|
||||
if (options.listDuplicates) {
|
||||
printDuplicateGroups(result.sampleDuplicateGroups);
|
||||
}
|
||||
if (result.stats.unsafeUsedDuplicateCodes > 0 && options.dryRun) {
|
||||
console.log(
|
||||
'Apply will refuse used duplicate cleanup unless --allow-used-duplicate-release is provided.',
|
||||
);
|
||||
}
|
||||
if (options.dryRun) {
|
||||
console.log(
|
||||
'No writes were made. Re-run with --apply to clean documents and create indexes.',
|
||||
);
|
||||
} else if (options.createIndexes) {
|
||||
console.log('Migration applied and indexes ensured.');
|
||||
} else {
|
||||
console.log('Migration applied without index creation.');
|
||||
}
|
||||
} finally {
|
||||
await app.close();
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -32,11 +32,16 @@ export const MATCH_STATUSES: MatchStatus[] = [
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||
|
||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
||||
export type MatchGameMode =
|
||||
| 'pair'
|
||||
| 'bracket'
|
||||
| 'round-robin'
|
||||
| 'double-elimination';
|
||||
export const MATCH_GAME_MODES: MatchGameMode[] = [
|
||||
'pair',
|
||||
'bracket',
|
||||
'round-robin',
|
||||
'double-elimination',
|
||||
];
|
||||
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
@@ -47,13 +52,15 @@ export type TournamentCodeState =
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'expired'
|
||||
| 'released';
|
||||
| 'released'
|
||||
| 'voided';
|
||||
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
|
||||
'available',
|
||||
'reserved',
|
||||
'used',
|
||||
'expired',
|
||||
'released',
|
||||
'voided',
|
||||
];
|
||||
export type TournamentMapType = 'SUMMONERS_RIFT';
|
||||
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
|
||||
@@ -385,6 +392,8 @@ export interface DakaoOutboxMessage extends MongooseTimestamps {
|
||||
payload: Record<string, unknown>;
|
||||
state: DakaoOutboxMessageState;
|
||||
publishAttempts: number;
|
||||
publishLeaseOwnerIdentifier?: string;
|
||||
publishLeaseExpiresAt?: Date;
|
||||
publishedAt?: Date;
|
||||
terminalAt?: Date;
|
||||
resultEventId?: string;
|
||||
@@ -445,6 +454,7 @@ export interface TournamentCode extends MongooseTimestamps {
|
||||
state: TournamentCodeState;
|
||||
matchId?: mongoose.Types.ObjectId;
|
||||
gameNumber?: number;
|
||||
bracketMatchId?: string;
|
||||
reservedAt?: Date;
|
||||
usedAt?: Date;
|
||||
releasedAt?: Date;
|
||||
@@ -497,6 +507,7 @@ export interface MatchGameResultParticipant {
|
||||
|
||||
export interface MatchGameResult {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
riotMatchId: string;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
@@ -508,6 +519,7 @@ export interface MatchGameResult {
|
||||
}
|
||||
|
||||
export interface MatchSeriesResult {
|
||||
bracketMatchId?: string;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
@@ -515,6 +527,120 @@ export interface MatchSeriesResult {
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
|
||||
export type DoubleEliminationBracketSide =
|
||||
| 'winner'
|
||||
| 'loser'
|
||||
| 'grand-final'
|
||||
| 'reset-final';
|
||||
export const DOUBLE_ELIMINATION_BRACKET_SIDES: DoubleEliminationBracketSide[] =
|
||||
['winner', 'loser', 'grand-final', 'reset-final'];
|
||||
|
||||
export type DoubleEliminationBracketMatchState =
|
||||
| 'pending'
|
||||
| 'ready'
|
||||
| 'completed';
|
||||
export const DOUBLE_ELIMINATION_BRACKET_MATCH_STATES: DoubleEliminationBracketMatchState[] =
|
||||
['pending', 'ready', 'completed'];
|
||||
|
||||
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
|
||||
export const DOUBLE_ELIMINATION_COMPLETION_TYPES: DoubleEliminationCompletionType[] =
|
||||
['riot-result', 'walkover'];
|
||||
|
||||
export type DoubleEliminationEventType =
|
||||
| 'bracket-created'
|
||||
| 'seeds-reshuffled'
|
||||
| 'seeds-swapped'
|
||||
| 'bracket-match-completed'
|
||||
| 'bracket-match-cancelled'
|
||||
| 'walkover-awarded'
|
||||
| 'walkover-cancelled'
|
||||
| 'reset-final-created'
|
||||
| 'riot-result-cancelled';
|
||||
export const DOUBLE_ELIMINATION_EVENT_TYPES: DoubleEliminationEventType[] = [
|
||||
'bracket-created',
|
||||
'seeds-reshuffled',
|
||||
'seeds-swapped',
|
||||
'bracket-match-completed',
|
||||
'bracket-match-cancelled',
|
||||
'walkover-awarded',
|
||||
'walkover-cancelled',
|
||||
'reset-final-created',
|
||||
'riot-result-cancelled',
|
||||
];
|
||||
|
||||
export interface DoubleEliminationSeed {
|
||||
seedNumber: number;
|
||||
teamIndex: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchSource {
|
||||
type: 'seed' | 'winner' | 'loser';
|
||||
seedNumber?: number;
|
||||
bracketMatchId?: string;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatchDestination {
|
||||
bracketMatchId: string;
|
||||
position: 'A' | 'B';
|
||||
}
|
||||
|
||||
export interface DoubleEliminationWalkover {
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
awardedBy?: mongoose.Types.ObjectId;
|
||||
awardedAt: Date;
|
||||
cancelledBy?: mongoose.Types.ObjectId;
|
||||
cancelledAt?: Date;
|
||||
cancelReason?: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketMatch {
|
||||
bracketMatchId: string;
|
||||
gameNumber: number;
|
||||
gameCount: number;
|
||||
requiredWins: number;
|
||||
bracketSide: DoubleEliminationBracketSide;
|
||||
roundNumber: number;
|
||||
matchNumber: number;
|
||||
state: DoubleEliminationBracketMatchState;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
teamASource?: DoubleEliminationBracketMatchSource;
|
||||
teamBSource?: DoubleEliminationBracketMatchSource;
|
||||
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
|
||||
winnerTeamIndex?: number;
|
||||
loserTeamIndex?: number;
|
||||
completedBy?: DoubleEliminationCompletionType;
|
||||
completedAt?: Date;
|
||||
walkover?: DoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationPlacements {
|
||||
firstTeamIndex?: number;
|
||||
secondTeamIndex?: number;
|
||||
thirdTeamIndex?: number;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationEvent {
|
||||
type: DoubleEliminationEventType;
|
||||
bracketMatchId?: string;
|
||||
actorUserId?: mongoose.Types.ObjectId;
|
||||
reason?: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracket {
|
||||
teamCount: 4 | 8;
|
||||
resetFinalEnabled: boolean;
|
||||
resetFinalCreated: boolean;
|
||||
seeds: DoubleEliminationSeed[];
|
||||
bracketMatches: DoubleEliminationBracketMatch[];
|
||||
placements: DoubleEliminationPlacements;
|
||||
events: DoubleEliminationEvent[];
|
||||
}
|
||||
|
||||
export interface MatchGameAssignment {
|
||||
gameNumber: number;
|
||||
roundNumber?: number;
|
||||
@@ -564,6 +690,7 @@ export interface Match extends MongooseTimestamps {
|
||||
teams: MatchTeam[];
|
||||
result?: MatchResult;
|
||||
resultPollState?: MatchResultPollState;
|
||||
doubleElimination?: DoubleEliminationBracket;
|
||||
legacyImported?: boolean;
|
||||
legacyImportSource?: {
|
||||
importedAt: Date;
|
||||
@@ -610,6 +737,7 @@ export interface LegacyImportJob extends MongooseTimestamps {
|
||||
totalSkippedDuplicate: number;
|
||||
totalErrors: number;
|
||||
averageMemberSeconds?: number;
|
||||
completedMemberJobIds: string[];
|
||||
errors?: LegacyImportJobError[];
|
||||
}
|
||||
|
||||
@@ -1159,6 +1287,8 @@ export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
|
||||
default: 'pending',
|
||||
},
|
||||
publishAttempts: { type: Number, required: true, default: 0 },
|
||||
publishLeaseOwnerIdentifier: { type: String },
|
||||
publishLeaseExpiresAt: { type: Date },
|
||||
publishedAt: { type: Date },
|
||||
terminalAt: { type: Date },
|
||||
resultEventId: { type: String },
|
||||
@@ -1179,6 +1309,11 @@ export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
|
||||
);
|
||||
|
||||
DakaoOutboxMessageSchema.index({ state: 1, updatedAt: 1 });
|
||||
DakaoOutboxMessageSchema.index({
|
||||
state: 1,
|
||||
publishLeaseExpiresAt: 1,
|
||||
updatedAt: 1,
|
||||
});
|
||||
DakaoOutboxMessageSchema.index({ correlationId: 1 }, { sparse: true });
|
||||
|
||||
export const DakaoSendResultEventSchema = new Schema<DakaoSendResultEvent>(
|
||||
@@ -1351,6 +1486,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
},
|
||||
matchId: { type: Schema.Types.ObjectId, ref: 'match' },
|
||||
gameNumber: { type: Number },
|
||||
bracketMatchId: { type: String },
|
||||
reservedAt: { type: Date },
|
||||
usedAt: { type: Date },
|
||||
releasedAt: { type: Date },
|
||||
@@ -1368,9 +1504,35 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
|
||||
TournamentCodeSchema.index({ code: 1 }, { unique: true });
|
||||
TournamentCodeSchema.index({ state: 1, expiresAt: 1 });
|
||||
TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 });
|
||||
TournamentCodeSchema.index(
|
||||
{ matchId: 1, gameNumber: 1 },
|
||||
{
|
||||
unique: true,
|
||||
partialFilterExpression: {
|
||||
matchId: { $exists: true },
|
||||
gameNumber: { $exists: true },
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
},
|
||||
},
|
||||
);
|
||||
TournamentCodeSchema.index(
|
||||
{ matchId: 1, bracketMatchId: 1 },
|
||||
{
|
||||
partialFilterExpression: {
|
||||
matchId: { $exists: true },
|
||||
bracketMatchId: { $exists: true },
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
},
|
||||
},
|
||||
);
|
||||
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 });
|
||||
TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true });
|
||||
TournamentCodeSchema.index(
|
||||
{ riotMatchId: 1 },
|
||||
{
|
||||
unique: true,
|
||||
partialFilterExpression: { riotMatchId: { $type: 'string' } },
|
||||
},
|
||||
);
|
||||
|
||||
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||
{
|
||||
@@ -1428,6 +1590,7 @@ const MatchGameResultParticipantSubSchema =
|
||||
const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{
|
||||
gameNumber: { type: Number, required: true },
|
||||
bracketMatchId: { type: String, required: false },
|
||||
riotMatchId: { type: String, required: true },
|
||||
blueTeamIndex: { type: Number, required: true, min: 1 },
|
||||
redTeamIndex: { type: Number, required: true, min: 1 },
|
||||
@@ -1446,6 +1609,7 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
|
||||
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
|
||||
{
|
||||
bracketMatchId: { type: String, required: false },
|
||||
teamAIndex: { type: Number, required: true, min: 1 },
|
||||
teamBIndex: { type: Number, required: true, min: 1 },
|
||||
teamAWins: { type: Number, required: true, default: 0 },
|
||||
@@ -1465,6 +1629,159 @@ const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationSeedSubSchema = new Schema<DoubleEliminationSeed>(
|
||||
{
|
||||
seedNumber: { type: Number, required: true, min: 1 },
|
||||
teamIndex: { type: Number, required: true, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketMatchSourceSubSchema =
|
||||
new Schema<DoubleEliminationBracketMatchSource>(
|
||||
{
|
||||
type: {
|
||||
type: String,
|
||||
enum: ['seed', 'winner', 'loser'],
|
||||
required: true,
|
||||
},
|
||||
seedNumber: { type: Number, required: false, min: 1 },
|
||||
bracketMatchId: { type: String, required: false },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketMatchDestinationSubSchema =
|
||||
new Schema<DoubleEliminationBracketMatchDestination>(
|
||||
{
|
||||
bracketMatchId: { type: String, required: true },
|
||||
position: { type: String, enum: ['A', 'B'], required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationWalkoverSubSchema =
|
||||
new Schema<DoubleEliminationWalkover>(
|
||||
{
|
||||
winnerTeamIndex: { type: Number, required: true, min: 1 },
|
||||
reason: { type: String, required: false },
|
||||
awardedBy: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
awardedAt: { type: Date, required: true },
|
||||
cancelledBy: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
cancelledAt: { type: Date },
|
||||
cancelReason: { type: String },
|
||||
active: { type: Boolean, required: true, default: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketMatchSubSchema =
|
||||
new Schema<DoubleEliminationBracketMatch>(
|
||||
{
|
||||
bracketMatchId: { type: String, required: true },
|
||||
gameNumber: { type: Number, required: true, min: 1 },
|
||||
gameCount: { type: Number, required: true, min: 1, default: 1 },
|
||||
requiredWins: { type: Number, required: true, min: 1, default: 1 },
|
||||
bracketSide: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
|
||||
required: true,
|
||||
},
|
||||
roundNumber: { type: Number, required: true, min: 1 },
|
||||
matchNumber: { type: Number, required: true, min: 1 },
|
||||
state: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_BRACKET_MATCH_STATES,
|
||||
required: true,
|
||||
},
|
||||
teamAIndex: { type: Number, required: false, min: 1 },
|
||||
teamBIndex: { type: Number, required: false, min: 1 },
|
||||
teamASource: {
|
||||
type: DoubleEliminationBracketMatchSourceSubSchema,
|
||||
required: false,
|
||||
},
|
||||
teamBSource: {
|
||||
type: DoubleEliminationBracketMatchSourceSubSchema,
|
||||
required: false,
|
||||
},
|
||||
winnerAdvancesTo: {
|
||||
type: DoubleEliminationBracketMatchDestinationSubSchema,
|
||||
required: false,
|
||||
},
|
||||
loserAdvancesTo: {
|
||||
type: DoubleEliminationBracketMatchDestinationSubSchema,
|
||||
required: false,
|
||||
},
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
loserTeamIndex: { type: Number, required: false, min: 1 },
|
||||
completedBy: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_COMPLETION_TYPES,
|
||||
required: false,
|
||||
},
|
||||
completedAt: { type: Date, required: false },
|
||||
walkover: {
|
||||
type: DoubleEliminationWalkoverSubSchema,
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationPlacementsSubSchema =
|
||||
new Schema<DoubleEliminationPlacements>(
|
||||
{
|
||||
firstTeamIndex: { type: Number, required: false, min: 1 },
|
||||
secondTeamIndex: { type: Number, required: false, min: 1 },
|
||||
thirdTeamIndex: { type: Number, required: false, min: 1 },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationEventSubSchema = new Schema<DoubleEliminationEvent>(
|
||||
{
|
||||
type: {
|
||||
type: String,
|
||||
enum: DOUBLE_ELIMINATION_EVENT_TYPES,
|
||||
required: true,
|
||||
},
|
||||
bracketMatchId: { type: String, required: false },
|
||||
actorUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
reason: { type: String, required: false },
|
||||
createdAt: { type: Date, required: true },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
|
||||
{
|
||||
teamCount: { type: Number, enum: [4, 8], required: true },
|
||||
resetFinalEnabled: { type: Boolean, required: true, default: false },
|
||||
resetFinalCreated: { type: Boolean, required: true, default: false },
|
||||
seeds: {
|
||||
type: [DoubleEliminationSeedSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
bracketMatches: {
|
||||
type: [DoubleEliminationBracketMatchSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
placements: {
|
||||
type: DoubleEliminationPlacementsSubSchema,
|
||||
required: true,
|
||||
default: () => ({}),
|
||||
},
|
||||
events: {
|
||||
type: [DoubleEliminationEventSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||
@@ -1595,6 +1912,10 @@ export const MatchSchema = new Schema<Match>(
|
||||
type: MatchResultPollStateSubSchema,
|
||||
required: false,
|
||||
},
|
||||
doubleElimination: {
|
||||
type: DoubleEliminationBracketSubSchema,
|
||||
required: false,
|
||||
},
|
||||
legacyImported: { type: Boolean, required: false, default: false },
|
||||
legacyImportSource: {
|
||||
type: MatchLegacyImportSourceSubSchema,
|
||||
@@ -1679,6 +2000,11 @@ export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
|
||||
totalSkippedDuplicate: { type: Number, required: true, default: 0 },
|
||||
totalErrors: { type: Number, required: true, default: 0 },
|
||||
averageMemberSeconds: { type: Number },
|
||||
completedMemberJobIds: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
errors: {
|
||||
type: [LegacyImportJobErrorSubSchema],
|
||||
required: true,
|
||||
@@ -1694,6 +2020,7 @@ export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
|
||||
|
||||
LegacyImportJobSchema.index({ communityId: 1, startedAt: -1 });
|
||||
LegacyImportJobSchema.index({ communityId: 1, state: 1 });
|
||||
LegacyImportJobSchema.index({ jobId: 1, completedMemberJobIds: 1 });
|
||||
|
||||
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
||||
{
|
||||
@@ -2088,6 +2415,7 @@ MatchStatsSchema.index({
|
||||
gameCreationMax: 1,
|
||||
});
|
||||
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
||||
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
||||
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||
|
||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
|
||||
@@ -56,20 +56,25 @@ export interface JetStreamConsumeOptions {
|
||||
maxMessages?: number;
|
||||
expiresMs?: number;
|
||||
nakDelayMs?: number;
|
||||
restartDelayMilliseconds?: number;
|
||||
}
|
||||
|
||||
const JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS = 1_000;
|
||||
|
||||
@Injectable()
|
||||
export class NatsService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(NatsService.name);
|
||||
private readonly stringCodec = StringCodec();
|
||||
private readonly subscriptions = new Set<Subscription>();
|
||||
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
|
||||
private isDestroying = false;
|
||||
|
||||
constructor(
|
||||
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy() {
|
||||
this.isDestroying = true;
|
||||
for (const consumer of this.jetStreamConsumers) {
|
||||
try {
|
||||
await consumer.close();
|
||||
@@ -199,6 +204,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
options: JetStreamConsumeOptions,
|
||||
handler: JetStreamMessageHandler<T>,
|
||||
): Promise<void> {
|
||||
while (!this.isDestroying) {
|
||||
try {
|
||||
const consumer = await this.natsClient
|
||||
.jetstream()
|
||||
@@ -217,12 +223,19 @@ export class NatsService implements OnModuleDestroy {
|
||||
this.jetStreamConsumers.delete(messages);
|
||||
}
|
||||
} catch (err) {
|
||||
if (this.isDestroying) return;
|
||||
this.logger.error(
|
||||
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
|
||||
(err as Error)?.stack ?? err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
await this.sleep(
|
||||
options.restartDelayMilliseconds ??
|
||||
JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async consumeSubscription<T>(
|
||||
@@ -313,4 +326,8 @@ export class NatsService implements OnModuleDestroy {
|
||||
? RetentionPolicy.Workqueue
|
||||
: RetentionPolicy.Limits;
|
||||
}
|
||||
|
||||
private sleep(durationMilliseconds: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, durationMilliseconds));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { Observable, catchError, finalize, throwError } from 'rxjs';
|
||||
import { setNewRelicTransactionName } from './new-relic';
|
||||
import {
|
||||
buildApiRequestPerformanceEvent,
|
||||
createApiPerformanceRequestContext,
|
||||
isApiPerformanceObservabilityEnabled,
|
||||
recordApiRequestPerformance,
|
||||
runWithApiPerformanceContext,
|
||||
} from './performance-observer';
|
||||
|
||||
interface RequestLike {
|
||||
method?: string;
|
||||
originalUrl?: string;
|
||||
url?: string;
|
||||
path?: string;
|
||||
route?: {
|
||||
path?: string | RegExp | Array<string | RegExp>;
|
||||
};
|
||||
}
|
||||
|
||||
interface ResponseLike {
|
||||
statusCode?: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ApiPerformanceInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
if (!isApiPerformanceObservabilityEnabled()) {
|
||||
return next.handle();
|
||||
}
|
||||
|
||||
const http = context.switchToHttp();
|
||||
const request = http.getRequest<RequestLike>();
|
||||
const response = http.getResponse<ResponseLike>();
|
||||
const method = request.method ?? 'UNKNOWN';
|
||||
const route = resolveRouteTemplate(request);
|
||||
const path = resolveRequestPath(request);
|
||||
const requestContext = createApiPerformanceRequestContext({
|
||||
method,
|
||||
route,
|
||||
path,
|
||||
});
|
||||
const startedAt = process.hrtime.bigint();
|
||||
let thrownError: unknown;
|
||||
|
||||
setNewRelicTransactionName(`${method} ${route}`);
|
||||
|
||||
return runWithApiPerformanceContext(requestContext, () =>
|
||||
next.handle().pipe(
|
||||
catchError((error: unknown) => {
|
||||
thrownError = error;
|
||||
return throwError(() => error);
|
||||
}),
|
||||
finalize(() => {
|
||||
const statusCode = response.statusCode ?? (thrownError ? 500 : 200);
|
||||
const durationMs =
|
||||
Number(process.hrtime.bigint() - startedAt) / 1_000_000;
|
||||
recordApiRequestPerformance(
|
||||
buildApiRequestPerformanceEvent({
|
||||
context: requestContext,
|
||||
statusCode,
|
||||
durationMs,
|
||||
isError: Boolean(thrownError) || statusCode >= 400,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveRouteTemplate(request: RequestLike): string {
|
||||
const routePath = request.route?.path;
|
||||
if (Array.isArray(routePath)) {
|
||||
return normalizeRoute(routePath.map(String).join('|'));
|
||||
}
|
||||
if (routePath) return normalizeRoute(String(routePath));
|
||||
return normalizeRoute(resolveRequestPath(request));
|
||||
}
|
||||
|
||||
export function resolveRequestPath(request: RequestLike): string {
|
||||
const rawPath = request.originalUrl ?? request.path ?? request.url ?? '/';
|
||||
return rawPath.split('?')[0] || '/';
|
||||
}
|
||||
|
||||
function normalizeRoute(route: string): string {
|
||||
const normalized = route.startsWith('/') ? route : `/${route}`;
|
||||
return normalized.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {
|
||||
countHydratedDocuments,
|
||||
countReturnedDocuments,
|
||||
} from './mongoose-performance.plugin';
|
||||
|
||||
describe('Mongoose performance helpers', () => {
|
||||
it('counts returned documents for common query result shapes', () => {
|
||||
expect(countReturnedDocuments([{ id: 1 }, { id: 2 }])).toBe(2);
|
||||
expect(countReturnedDocuments({ id: 1 })).toBe(1);
|
||||
expect(countReturnedDocuments(null)).toBe(0);
|
||||
expect(countReturnedDocuments(7)).toBe(7);
|
||||
});
|
||||
|
||||
it('counts hydrated documents separately from lean documents', () => {
|
||||
const hydrated = { $__: {} };
|
||||
const lean = { id: 1 };
|
||||
|
||||
expect(countHydratedDocuments([hydrated, lean, hydrated])).toBe(2);
|
||||
expect(countHydratedDocuments(lean)).toBe(0);
|
||||
expect(countHydratedDocuments(hydrated)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { recordMongooseQueryPerformance } from './performance-observer';
|
||||
|
||||
const QUERY_PERFORMANCE_START = Symbol('queryPerformanceStart');
|
||||
const QUERY_PERFORMANCE_RECORDED = Symbol('queryPerformanceRecorded');
|
||||
const PERFORMANCE_PLUGIN_APPLIED = Symbol('performancePluginApplied');
|
||||
|
||||
const QUERY_OPERATIONS = [
|
||||
'countDocuments',
|
||||
'deleteMany',
|
||||
'deleteOne',
|
||||
'find',
|
||||
'findOne',
|
||||
'findOneAndDelete',
|
||||
'findOneAndReplace',
|
||||
'findOneAndUpdate',
|
||||
'replaceOne',
|
||||
'updateMany',
|
||||
'updateOne',
|
||||
] as const;
|
||||
const QUERY_OPERATION_REGEX = new RegExp(`^(${QUERY_OPERATIONS.join('|')})$`);
|
||||
|
||||
type QueryWithPerformanceState = mongoose.Query<unknown, unknown> & {
|
||||
[QUERY_PERFORMANCE_START]?: bigint;
|
||||
[QUERY_PERFORMANCE_RECORDED]?: boolean;
|
||||
};
|
||||
|
||||
type AggregateWithPerformanceState = mongoose.Aggregate<unknown[]> & {
|
||||
[QUERY_PERFORMANCE_START]?: bigint;
|
||||
[QUERY_PERFORMANCE_RECORDED]?: boolean;
|
||||
};
|
||||
|
||||
type SchemaWithPerformanceMarker = mongoose.Schema & {
|
||||
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
||||
};
|
||||
|
||||
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
|
||||
const markedSchema = schema as SchemaWithPerformanceMarker;
|
||||
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
||||
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
||||
const hookableSchema = schema as any;
|
||||
|
||||
hookableSchema.pre(QUERY_OPERATION_REGEX, function () {
|
||||
const query = this as QueryWithPerformanceState;
|
||||
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
||||
query[QUERY_PERFORMANCE_RECORDED] = false;
|
||||
});
|
||||
|
||||
hookableSchema.post(
|
||||
QUERY_OPERATION_REGEX,
|
||||
function (result: unknown) {
|
||||
recordQueryPerformance(
|
||||
this as unknown as QueryWithPerformanceState,
|
||||
result,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
hookableSchema.post(
|
||||
QUERY_OPERATION_REGEX,
|
||||
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
|
||||
recordQueryPerformance(
|
||||
this as unknown as QueryWithPerformanceState,
|
||||
undefined,
|
||||
error,
|
||||
);
|
||||
next(error);
|
||||
},
|
||||
);
|
||||
|
||||
hookableSchema.pre('aggregate', function () {
|
||||
const aggregate = this as AggregateWithPerformanceState;
|
||||
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
||||
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
|
||||
});
|
||||
|
||||
hookableSchema.post('aggregate', function (result: unknown) {
|
||||
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
|
||||
});
|
||||
|
||||
hookableSchema.post(
|
||||
'aggregate',
|
||||
function (error: unknown, _result: unknown, next: (error: unknown) => void) {
|
||||
recordAggregatePerformance(
|
||||
this as AggregateWithPerformanceState,
|
||||
undefined,
|
||||
error,
|
||||
);
|
||||
next(error);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function recordQueryPerformance(
|
||||
query: QueryWithPerformanceState,
|
||||
result: unknown,
|
||||
error?: unknown,
|
||||
): void {
|
||||
if (query[QUERY_PERFORMANCE_RECORDED]) return;
|
||||
query[QUERY_PERFORMANCE_RECORDED] = true;
|
||||
|
||||
const startedAt = query[QUERY_PERFORMANCE_START];
|
||||
if (!startedAt) return;
|
||||
|
||||
const hydratedDocsReturned = countHydratedDocuments(result);
|
||||
const model = query.model as mongoose.Model<unknown> | undefined;
|
||||
const options = query.getOptions();
|
||||
|
||||
recordMongooseQueryPerformance({
|
||||
operation: (query as unknown as { op?: string }).op ?? 'query',
|
||||
modelName: model?.modelName ?? 'unknown',
|
||||
collectionName: model?.collection?.name,
|
||||
durationMs: toDurationMs(startedAt),
|
||||
docsReturned: countReturnedDocuments(result),
|
||||
hydratedDocsReturned,
|
||||
lean: Boolean(query.mongooseOptions().lean),
|
||||
limit: numberOption(options.limit),
|
||||
skip: numberOption(options.skip),
|
||||
filterKeys: joinObjectKeys(query.getFilter()),
|
||||
projectionKeys: joinObjectKeys(query.projection()),
|
||||
sortKeys: joinObjectKeys(options.sort),
|
||||
errorName: errorName(error),
|
||||
});
|
||||
}
|
||||
|
||||
function recordAggregatePerformance(
|
||||
aggregate: AggregateWithPerformanceState,
|
||||
result: unknown,
|
||||
error?: unknown,
|
||||
): void {
|
||||
if (aggregate[QUERY_PERFORMANCE_RECORDED]) return;
|
||||
aggregate[QUERY_PERFORMANCE_RECORDED] = true;
|
||||
|
||||
const startedAt = aggregate[QUERY_PERFORMANCE_START];
|
||||
if (!startedAt) return;
|
||||
|
||||
const model = aggregate.model();
|
||||
recordMongooseQueryPerformance({
|
||||
operation: 'aggregate',
|
||||
modelName: model?.modelName ?? 'unknown',
|
||||
collectionName: model?.collection?.name,
|
||||
durationMs: toDurationMs(startedAt),
|
||||
docsReturned: countReturnedDocuments(result),
|
||||
hydratedDocsReturned: countHydratedDocuments(result),
|
||||
lean: true,
|
||||
errorName: errorName(error),
|
||||
});
|
||||
}
|
||||
|
||||
export function countReturnedDocuments(result: unknown): number {
|
||||
if (Array.isArray(result)) return result.length;
|
||||
if (result == null) return 0;
|
||||
if (typeof result === 'number') return result;
|
||||
return 1;
|
||||
}
|
||||
|
||||
export function countHydratedDocuments(result: unknown): number {
|
||||
if (Array.isArray(result)) {
|
||||
return result.filter((item) => isHydratedDocument(item)).length;
|
||||
}
|
||||
return isHydratedDocument(result) ? 1 : 0;
|
||||
}
|
||||
|
||||
function isHydratedDocument(value: unknown): boolean {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'$__' in (value as Record<string, unknown>),
|
||||
);
|
||||
}
|
||||
|
||||
function toDurationMs(startedAt: bigint): number {
|
||||
return Number(process.hrtime.bigint() - startedAt) / 1_000_000;
|
||||
}
|
||||
|
||||
function numberOption(value: unknown): number | undefined {
|
||||
return typeof value === 'number' ? value : undefined;
|
||||
}
|
||||
|
||||
function joinObjectKeys(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== 'object') return undefined;
|
||||
const keys = Object.keys(value as Record<string, unknown>).sort();
|
||||
return keys.length > 0 ? keys.join(',') : undefined;
|
||||
}
|
||||
|
||||
function errorName(error: unknown): string | undefined {
|
||||
return error instanceof Error ? error.name : undefined;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 서버 계측 래퍼. 조사 종료 후 호출부와 함께
|
||||
// 제거 대상(범용으로 남길 거면 이 마커만 떼면 됨).
|
||||
import newrelicAgent from 'newrelic';
|
||||
|
||||
export type NewRelicAttributeValue = string | number | boolean | null;
|
||||
|
||||
// newrelic 기본 export는 타입이 느슨해 unsafe-call로 잡힌다. 우리가 쓰는 부분만
|
||||
// 좁게 타입을 고정한다(에이전트는 -r newrelic로 이미 preload됨).
|
||||
interface NewRelicCustomEventApi {
|
||||
recordCustomEvent(
|
||||
eventType: string,
|
||||
attributes: Record<string, NewRelicAttributeValue>,
|
||||
): void;
|
||||
addCustomAttributes(
|
||||
attributes: Record<string, NewRelicAttributeValue>,
|
||||
): void;
|
||||
setTransactionName(name: string): void;
|
||||
}
|
||||
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
||||
|
||||
/**
|
||||
* 서버 커스텀 이벤트를 New Relic으로 보낸다(클라의 addPageAction 대응).
|
||||
*
|
||||
* - 에이전트는 `-r newrelic`로 이미 preload되어 있으므로 여기서 import만 하면 된다.
|
||||
* - `recordCustomEvent`는 활성 트랜잭션이 없어도 동작하므로 durability 스케줄러
|
||||
* tick이나 socket.io 핸들러처럼 HTTP 컨텍스트 밖에서도 그대로 호출할 수 있다.
|
||||
* - 평탄한 스칼라만 받는다(중첩 객체/배열 불가). undefined 속성은 제거한다.
|
||||
* - 에이전트 비활성/테스트 환경에서도 호출부가 깨지지 않도록 예외를 삼킨다.
|
||||
*/
|
||||
export function recordNewRelicCustomEvent(
|
||||
eventType: string,
|
||||
attributes: Record<string, NewRelicAttributeValue | undefined>,
|
||||
): void {
|
||||
try {
|
||||
const flat: Record<string, NewRelicAttributeValue> = {};
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
if (value !== undefined) flat[key] = value;
|
||||
}
|
||||
agent.recordCustomEvent(eventType, flat);
|
||||
} catch {
|
||||
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
|
||||
}
|
||||
}
|
||||
|
||||
export function addNewRelicCustomAttributes(
|
||||
attributes: Record<string, NewRelicAttributeValue | undefined>,
|
||||
): void {
|
||||
try {
|
||||
const flat: Record<string, NewRelicAttributeValue> = {};
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
if (value !== undefined) flat[key] = value;
|
||||
}
|
||||
agent.addCustomAttributes(flat);
|
||||
} catch {
|
||||
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
|
||||
}
|
||||
}
|
||||
|
||||
export function setNewRelicTransactionName(name: string): void {
|
||||
try {
|
||||
agent.setTransactionName(name);
|
||||
} catch {
|
||||
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
buildApiRequestPerformanceEvent,
|
||||
createApiPerformanceRequestContext,
|
||||
readBoolean,
|
||||
recordMongooseQueryPerformance,
|
||||
resolveApiPerformanceConfig,
|
||||
runWithApiPerformanceContext,
|
||||
} from './performance-observer';
|
||||
|
||||
describe('performance observer config', () => {
|
||||
it('keeps observability disabled by default', () => {
|
||||
expect(resolveApiPerformanceConfig({}).enabled).toBe(false);
|
||||
expect(resolveApiPerformanceConfig({}).localEventsEnabled).toBe(false);
|
||||
});
|
||||
|
||||
it('reads common boolean values', () => {
|
||||
expect(readBoolean(undefined, true)).toBe(true);
|
||||
expect(readBoolean('false', true)).toBe(false);
|
||||
expect(readBoolean('enabled', false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('API performance request context', () => {
|
||||
const originalEnv = process.env;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = {
|
||||
...originalEnv,
|
||||
API_PERF_OBSERVABILITY_ENABLED: 'true',
|
||||
API_PERF_LOCAL_EVENTS_ENABLED: 'false',
|
||||
API_PERF_NEW_RELIC_QUERY_EVENTS_ENABLED: 'false',
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
});
|
||||
|
||||
it('aggregates Mongoose document-return metrics into the request event', () => {
|
||||
const context = createApiPerformanceRequestContext({
|
||||
method: 'GET',
|
||||
route: '/communities/:communityId/internal-stats/matches',
|
||||
path: '/communities/abc/internal-stats/matches',
|
||||
});
|
||||
|
||||
const event = runWithApiPerformanceContext(context, () => {
|
||||
recordMongooseQueryPerformance({
|
||||
operation: 'find',
|
||||
modelName: 'matchStats',
|
||||
collectionName: 'match_stats',
|
||||
durationMs: 12,
|
||||
docsReturned: 300,
|
||||
hydratedDocsReturned: 300,
|
||||
lean: false,
|
||||
});
|
||||
recordMongooseQueryPerformance({
|
||||
operation: 'find',
|
||||
modelName: 'matchStats',
|
||||
collectionName: 'match_stats',
|
||||
durationMs: 3,
|
||||
docsReturned: 20,
|
||||
hydratedDocsReturned: 0,
|
||||
lean: true,
|
||||
});
|
||||
|
||||
return buildApiRequestPerformanceEvent({
|
||||
context,
|
||||
statusCode: 200,
|
||||
durationMs: 50,
|
||||
isError: false,
|
||||
});
|
||||
});
|
||||
|
||||
expect(event.queryCount).toBe(2);
|
||||
expect(event.mongooseDurationMs).toBe(15);
|
||||
expect(event.docsReturned).toBe(320);
|
||||
expect(event.hydratedDocsReturned).toBe(300);
|
||||
expect(event.leanQueryCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { appendFile } from 'node:fs/promises';
|
||||
import {
|
||||
addNewRelicCustomAttributes,
|
||||
NewRelicAttributeValue,
|
||||
recordNewRelicCustomEvent,
|
||||
} from './new-relic';
|
||||
|
||||
export type PerformanceEventType = 'api-request' | 'mongoose-query';
|
||||
|
||||
export interface ApiPerformanceConfig {
|
||||
enabled: boolean;
|
||||
localEventsEnabled: boolean;
|
||||
localEventFile: string;
|
||||
newRelicRequestEventsEnabled: boolean;
|
||||
newRelicQueryEventsEnabled: boolean;
|
||||
appName: string;
|
||||
nodeEnv: string;
|
||||
}
|
||||
|
||||
export interface MongooseQueryPerformance {
|
||||
operation: string;
|
||||
modelName: string;
|
||||
collectionName?: string;
|
||||
durationMs: number;
|
||||
docsReturned: number;
|
||||
hydratedDocsReturned: number;
|
||||
lean: boolean;
|
||||
limit?: number;
|
||||
skip?: number;
|
||||
filterKeys?: string;
|
||||
projectionKeys?: string;
|
||||
sortKeys?: string;
|
||||
errorName?: string;
|
||||
}
|
||||
|
||||
export interface ApiRequestPerformanceEvent {
|
||||
type: 'api-request';
|
||||
timestamp: string;
|
||||
requestId: string;
|
||||
method: string;
|
||||
route: string;
|
||||
path: string;
|
||||
statusCode: number;
|
||||
durationMs: number;
|
||||
isError: boolean;
|
||||
queryCount: number;
|
||||
mongooseDurationMs: number;
|
||||
docsReturned: number;
|
||||
hydratedDocsReturned: number;
|
||||
leanQueryCount: number;
|
||||
}
|
||||
|
||||
export interface MongooseQueryPerformanceEvent
|
||||
extends MongooseQueryPerformance {
|
||||
type: 'mongoose-query';
|
||||
timestamp: string;
|
||||
requestId?: string;
|
||||
method?: string;
|
||||
route?: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export type ApiPerformanceEvent =
|
||||
| ApiRequestPerformanceEvent
|
||||
| MongooseQueryPerformanceEvent;
|
||||
|
||||
export interface ApiPerformanceContext {
|
||||
requestId: string;
|
||||
method: string;
|
||||
route: string;
|
||||
path: string;
|
||||
queries: MongooseQueryPerformance[];
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<ApiPerformanceContext>();
|
||||
|
||||
export function readBoolean(
|
||||
value: string | undefined,
|
||||
defaultValue: boolean,
|
||||
): boolean {
|
||||
if (value == null || value.trim() === '') return defaultValue;
|
||||
return !['0', 'false', 'f', 'no', 'n', 'disabled', 'off'].includes(
|
||||
value.trim().toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveApiPerformanceConfig(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ApiPerformanceConfig {
|
||||
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
|
||||
return {
|
||||
enabled,
|
||||
localEventsEnabled: readBoolean(
|
||||
env.API_PERF_LOCAL_EVENTS_ENABLED,
|
||||
enabled,
|
||||
),
|
||||
localEventFile:
|
||||
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
|
||||
newRelicRequestEventsEnabled: readBoolean(
|
||||
env.API_PERF_NEW_RELIC_REQUEST_EVENTS_ENABLED,
|
||||
enabled,
|
||||
),
|
||||
newRelicQueryEventsEnabled: readBoolean(
|
||||
env.API_PERF_NEW_RELIC_QUERY_EVENTS_ENABLED,
|
||||
false,
|
||||
),
|
||||
appName: env.NEW_RELIC_APP_NAME || 'lolympus',
|
||||
nodeEnv: env.NODE_ENV || 'dev',
|
||||
};
|
||||
}
|
||||
|
||||
export function isApiPerformanceObservabilityEnabled(): boolean {
|
||||
return resolveApiPerformanceConfig().enabled;
|
||||
}
|
||||
|
||||
export function createApiPerformanceRequestContext(params: {
|
||||
method: string;
|
||||
route: string;
|
||||
path: string;
|
||||
}): ApiPerformanceContext {
|
||||
return {
|
||||
requestId: randomUUID(),
|
||||
method: params.method,
|
||||
route: params.route,
|
||||
path: params.path,
|
||||
queries: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function runWithApiPerformanceContext<T>(
|
||||
context: ApiPerformanceContext,
|
||||
callback: () => T,
|
||||
): T {
|
||||
return storage.run(context, callback);
|
||||
}
|
||||
|
||||
export function getCurrentApiPerformanceContext():
|
||||
| ApiPerformanceContext
|
||||
| undefined {
|
||||
return storage.getStore();
|
||||
}
|
||||
|
||||
export function recordMongooseQueryPerformance(
|
||||
query: MongooseQueryPerformance,
|
||||
): void {
|
||||
if (!isApiPerformanceObservabilityEnabled()) return;
|
||||
|
||||
const config = resolveApiPerformanceConfig();
|
||||
const context = storage.getStore();
|
||||
context?.queries.push(query);
|
||||
|
||||
const event: MongooseQueryPerformanceEvent = {
|
||||
...query,
|
||||
type: 'mongoose-query',
|
||||
timestamp: new Date().toISOString(),
|
||||
requestId: context?.requestId,
|
||||
method: context?.method,
|
||||
route: context?.route,
|
||||
path: context?.path,
|
||||
};
|
||||
if (config.localEventsEnabled) appendLocalPerformanceEvent(event, config);
|
||||
if (config.newRelicQueryEventsEnabled) {
|
||||
recordNewRelicCustomEvent('MongooseQueryPerformance', {
|
||||
appName: config.appName,
|
||||
nodeEnv: config.nodeEnv,
|
||||
requestId: event.requestId,
|
||||
method: event.method,
|
||||
route: event.route,
|
||||
operation: event.operation,
|
||||
modelName: event.modelName,
|
||||
collectionName: event.collectionName,
|
||||
durationMs: event.durationMs,
|
||||
docsReturned: event.docsReturned,
|
||||
hydratedDocsReturned: event.hydratedDocsReturned,
|
||||
lean: event.lean,
|
||||
limit: event.limit,
|
||||
skip: event.skip,
|
||||
errorName: event.errorName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function buildApiRequestPerformanceEvent(params: {
|
||||
context: ApiPerformanceContext;
|
||||
statusCode: number;
|
||||
durationMs: number;
|
||||
isError: boolean;
|
||||
}): ApiRequestPerformanceEvent {
|
||||
const queries = params.context.queries;
|
||||
return {
|
||||
type: 'api-request',
|
||||
timestamp: new Date().toISOString(),
|
||||
requestId: params.context.requestId,
|
||||
method: params.context.method,
|
||||
route: params.context.route,
|
||||
path: params.context.path,
|
||||
statusCode: params.statusCode,
|
||||
durationMs: params.durationMs,
|
||||
isError: params.isError,
|
||||
queryCount: queries.length,
|
||||
mongooseDurationMs: sum(queries.map((query) => query.durationMs)),
|
||||
docsReturned: sum(queries.map((query) => query.docsReturned)),
|
||||
hydratedDocsReturned: sum(
|
||||
queries.map((query) => query.hydratedDocsReturned),
|
||||
),
|
||||
leanQueryCount: queries.filter((query) => query.lean).length,
|
||||
};
|
||||
}
|
||||
|
||||
export function recordApiRequestPerformance(
|
||||
event: ApiRequestPerformanceEvent,
|
||||
): void {
|
||||
if (!isApiPerformanceObservabilityEnabled()) return;
|
||||
|
||||
const config = resolveApiPerformanceConfig();
|
||||
if (config.localEventsEnabled) appendLocalPerformanceEvent(event, config);
|
||||
if (config.newRelicRequestEventsEnabled) {
|
||||
recordNewRelicCustomEvent('ApiRequestPerformance', {
|
||||
appName: config.appName,
|
||||
nodeEnv: config.nodeEnv,
|
||||
requestId: event.requestId,
|
||||
method: event.method,
|
||||
route: event.route,
|
||||
statusCode: event.statusCode,
|
||||
durationMs: event.durationMs,
|
||||
isError: event.isError,
|
||||
queryCount: event.queryCount,
|
||||
mongooseDurationMs: event.mongooseDurationMs,
|
||||
docsReturned: event.docsReturned,
|
||||
hydratedDocsReturned: event.hydratedDocsReturned,
|
||||
leanQueryCount: event.leanQueryCount,
|
||||
});
|
||||
}
|
||||
|
||||
addNewRelicCustomAttributes({
|
||||
appName: config.appName,
|
||||
nodeEnv: config.nodeEnv,
|
||||
'api.request_id': event.requestId,
|
||||
'api.method': event.method,
|
||||
'api.route': event.route,
|
||||
'api.status_code': event.statusCode,
|
||||
'api.duration_ms': event.durationMs,
|
||||
'api.is_error': event.isError,
|
||||
'mongoose.query_count': event.queryCount,
|
||||
'mongoose.duration_ms': event.mongooseDurationMs,
|
||||
'mongoose.docs_returned': event.docsReturned,
|
||||
'mongoose.hydrated_docs_returned': event.hydratedDocsReturned,
|
||||
'mongoose.lean_query_count': event.leanQueryCount,
|
||||
});
|
||||
}
|
||||
|
||||
export function appendLocalPerformanceEvent(
|
||||
event: ApiPerformanceEvent,
|
||||
config: ApiPerformanceConfig = resolveApiPerformanceConfig(),
|
||||
): void {
|
||||
void appendFile(config.localEventFile, `${JSON.stringify(event)}\n`).catch(
|
||||
() => {
|
||||
// 관측성 실패가 API 응답을 막아선 안 된다.
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function toNewRelicAttributes(
|
||||
event: ApiRequestPerformanceEvent,
|
||||
): Record<string, NewRelicAttributeValue> {
|
||||
return {
|
||||
requestId: event.requestId,
|
||||
method: event.method,
|
||||
route: event.route,
|
||||
statusCode: event.statusCode,
|
||||
durationMs: event.durationMs,
|
||||
isError: event.isError,
|
||||
queryCount: event.queryCount,
|
||||
mongooseDurationMs: event.mongooseDurationMs,
|
||||
docsReturned: event.docsReturned,
|
||||
hydratedDocsReturned: event.hydratedDocsReturned,
|
||||
leanQueryCount: event.leanQueryCount,
|
||||
};
|
||||
}
|
||||
|
||||
function sum(values: number[]): number {
|
||||
return values.reduce((acc, value) => acc + value, 0);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { DistributedLockService } from './distributed-lock.service';
|
||||
import { RedisService } from './redis.service';
|
||||
|
||||
function createService(sendCommand: jest.Mock) {
|
||||
const redisService = {
|
||||
raw: jest.fn().mockReturnValue({ sendCommand }),
|
||||
} as unknown as RedisService;
|
||||
return new DistributedLockService(redisService);
|
||||
}
|
||||
|
||||
describe('DistributedLockService', () => {
|
||||
it('acquires a lock with a token and millisecond expiration', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue('OK');
|
||||
const service = createService(sendCommand);
|
||||
|
||||
const lockOwnership = await service.acquireLock({
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockOwnershipToken: 'owner-token',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
});
|
||||
|
||||
expect(lockOwnership).toEqual({
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockOwnershipToken: 'owner-token',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'SET',
|
||||
'distributed-lock:test',
|
||||
'owner-token',
|
||||
'NX',
|
||||
'PX',
|
||||
'30000',
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns null when another owner already holds the lock', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue(null);
|
||||
const service = createService(sendCommand);
|
||||
|
||||
await expect(
|
||||
service.acquireLock({
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
}),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('releases a lock only when the ownership token matches', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue(1);
|
||||
const service = createService(sendCommand);
|
||||
|
||||
await expect(
|
||||
service.releaseLockIfOwned({
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockOwnershipToken: 'owner-token',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'EVAL',
|
||||
expect.stringContaining('redis.call("GET", KEYS[1]) == ARGV[1]'),
|
||||
'1',
|
||||
'distributed-lock:test',
|
||||
'owner-token',
|
||||
]);
|
||||
});
|
||||
|
||||
it('extends a lock only when the ownership token matches', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue(1);
|
||||
const service = createService(sendCommand);
|
||||
|
||||
await expect(
|
||||
service.extendLockIfOwned(
|
||||
{
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockOwnershipToken: 'owner-token',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
},
|
||||
45_000,
|
||||
),
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'EVAL',
|
||||
expect.stringContaining('PEXPIRE'),
|
||||
'1',
|
||||
'distributed-lock:test',
|
||||
'owner-token',
|
||||
'45000',
|
||||
]);
|
||||
});
|
||||
|
||||
it('runs the operation and releases the lock afterward', async () => {
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce('OK')
|
||||
.mockResolvedValueOnce(1);
|
||||
const service = createService(sendCommand);
|
||||
const operation = jest.fn().mockResolvedValue('done');
|
||||
|
||||
await expect(
|
||||
service.runWithLock(
|
||||
{
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
},
|
||||
operation,
|
||||
),
|
||||
).resolves.toBe('done');
|
||||
|
||||
expect(operation).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
lockKey: 'distributed-lock:test',
|
||||
lockExpirationDurationMilliseconds: 30_000,
|
||||
}),
|
||||
);
|
||||
expect(sendCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { RedisService } from './redis.service';
|
||||
|
||||
const RELEASE_LOCK_IF_OWNED_SCRIPT = `
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
end
|
||||
return 0
|
||||
`;
|
||||
|
||||
const EXTEND_LOCK_IF_OWNED_SCRIPT = `
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
|
||||
end
|
||||
return 0
|
||||
`;
|
||||
|
||||
export interface DistributedLockOwnership {
|
||||
lockKey: string;
|
||||
lockOwnershipToken: string;
|
||||
lockExpirationDurationMilliseconds: number;
|
||||
}
|
||||
|
||||
export interface AcquireDistributedLockOptions {
|
||||
lockKey: string;
|
||||
lockExpirationDurationMilliseconds: number;
|
||||
lockOwnershipToken?: string;
|
||||
}
|
||||
|
||||
export interface RunWithDistributedLockOptions {
|
||||
lockKey: string;
|
||||
lockExpirationDurationMilliseconds: number;
|
||||
lockAcquireTimeoutMilliseconds?: number;
|
||||
lockRetryDelayMilliseconds?: number;
|
||||
}
|
||||
|
||||
export interface RunWithRenewedDistributedLockOptions
|
||||
extends RunWithDistributedLockOptions {
|
||||
lockRenewalIntervalMilliseconds: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class DistributedLockService {
|
||||
private readonly logger = new Logger(DistributedLockService.name);
|
||||
|
||||
constructor(private readonly redisService: RedisService) {}
|
||||
|
||||
public async acquireLock(
|
||||
options: AcquireDistributedLockOptions,
|
||||
): Promise<DistributedLockOwnership | null> {
|
||||
this.assertPositiveDuration(
|
||||
options.lockExpirationDurationMilliseconds,
|
||||
'lockExpirationDurationMilliseconds',
|
||||
);
|
||||
|
||||
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
|
||||
const result = await this.redisService.raw().sendCommand([
|
||||
'SET',
|
||||
options.lockKey,
|
||||
lockOwnershipToken,
|
||||
'NX',
|
||||
'PX',
|
||||
String(options.lockExpirationDurationMilliseconds),
|
||||
]);
|
||||
|
||||
if (String(result) !== 'OK') return null;
|
||||
return {
|
||||
lockKey: options.lockKey,
|
||||
lockOwnershipToken,
|
||||
lockExpirationDurationMilliseconds:
|
||||
options.lockExpirationDurationMilliseconds,
|
||||
};
|
||||
}
|
||||
|
||||
public async releaseLockIfOwned(
|
||||
lockOwnership: DistributedLockOwnership,
|
||||
): Promise<boolean> {
|
||||
const result = await this.redisService.raw().sendCommand([
|
||||
'EVAL',
|
||||
RELEASE_LOCK_IF_OWNED_SCRIPT,
|
||||
'1',
|
||||
lockOwnership.lockKey,
|
||||
lockOwnership.lockOwnershipToken,
|
||||
]);
|
||||
return Number(result) === 1;
|
||||
}
|
||||
|
||||
public async extendLockIfOwned(
|
||||
lockOwnership: DistributedLockOwnership,
|
||||
lockExpirationDurationMilliseconds =
|
||||
lockOwnership.lockExpirationDurationMilliseconds,
|
||||
): Promise<boolean> {
|
||||
this.assertPositiveDuration(
|
||||
lockExpirationDurationMilliseconds,
|
||||
'lockExpirationDurationMilliseconds',
|
||||
);
|
||||
|
||||
const result = await this.redisService.raw().sendCommand([
|
||||
'EVAL',
|
||||
EXTEND_LOCK_IF_OWNED_SCRIPT,
|
||||
'1',
|
||||
lockOwnership.lockKey,
|
||||
lockOwnership.lockOwnershipToken,
|
||||
String(lockExpirationDurationMilliseconds),
|
||||
]);
|
||||
return Number(result) === 1;
|
||||
}
|
||||
|
||||
public async runWithLock<TResult>(
|
||||
options: RunWithDistributedLockOptions,
|
||||
operation: (lockOwnership: DistributedLockOwnership) => Promise<TResult>,
|
||||
): Promise<TResult | null> {
|
||||
const lockOwnership = await this.acquireLockWithRetry(options);
|
||||
if (!lockOwnership) return null;
|
||||
|
||||
try {
|
||||
return await operation(lockOwnership);
|
||||
} finally {
|
||||
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async runWithRenewedLock<TResult>(
|
||||
options: RunWithRenewedDistributedLockOptions,
|
||||
operation: (lockOwnership: DistributedLockOwnership) => Promise<TResult>,
|
||||
): Promise<TResult | null> {
|
||||
this.assertPositiveDuration(
|
||||
options.lockRenewalIntervalMilliseconds,
|
||||
'lockRenewalIntervalMilliseconds',
|
||||
);
|
||||
|
||||
const lockOwnership = await this.acquireLockWithRetry(options);
|
||||
if (!lockOwnership) return null;
|
||||
|
||||
let lockRenewalTimer: NodeJS.Timeout | undefined;
|
||||
lockRenewalTimer = setInterval(() => {
|
||||
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
|
||||
if (wasExtended) return;
|
||||
this.logger.warn(
|
||||
`Lost distributed lock ownership before operation finished: ${lockOwnership.lockKey}`,
|
||||
);
|
||||
});
|
||||
}, options.lockRenewalIntervalMilliseconds);
|
||||
lockRenewalTimer.unref?.();
|
||||
|
||||
try {
|
||||
return await operation(lockOwnership);
|
||||
} finally {
|
||||
if (lockRenewalTimer) clearInterval(lockRenewalTimer);
|
||||
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Failed to release distributed lock ${lockOwnership.lockKey}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async acquireLockWithRetry(
|
||||
options: RunWithDistributedLockOptions,
|
||||
): Promise<DistributedLockOwnership | null> {
|
||||
const lockAcquireTimeoutMilliseconds =
|
||||
options.lockAcquireTimeoutMilliseconds ?? 0;
|
||||
const lockRetryDelayMilliseconds =
|
||||
options.lockRetryDelayMilliseconds ?? 100;
|
||||
const acquisitionStartedAtTimestampMilliseconds = Date.now();
|
||||
|
||||
while (true) {
|
||||
const lockOwnership = await this.acquireLock(options);
|
||||
if (lockOwnership) return lockOwnership;
|
||||
|
||||
if (lockAcquireTimeoutMilliseconds <= 0) return null;
|
||||
const elapsedMilliseconds =
|
||||
Date.now() - acquisitionStartedAtTimestampMilliseconds;
|
||||
if (elapsedMilliseconds >= lockAcquireTimeoutMilliseconds) return null;
|
||||
|
||||
await this.sleep(
|
||||
Math.min(lockRetryDelayMilliseconds, lockAcquireTimeoutMilliseconds),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private assertPositiveDuration(value: number, fieldName: string): void {
|
||||
if (Number.isFinite(value) && value > 0) return;
|
||||
throw new Error(`${fieldName} must be a positive finite number.`);
|
||||
}
|
||||
|
||||
private sleep(durationMilliseconds: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, durationMilliseconds));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { SecretModule } from '../secret/secret.module';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { REDIS_CLIENT } from './redis.constants';
|
||||
import { resolveRedisClientOptions } from './redis.config';
|
||||
import { DistributedLockService } from './distributed-lock.service';
|
||||
import { RedisService, type RedisClient } from './redis.service';
|
||||
|
||||
async function readFirstSecret(
|
||||
@@ -62,7 +63,8 @@ async function readFirstSecret(
|
||||
},
|
||||
},
|
||||
RedisService,
|
||||
DistributedLockService,
|
||||
],
|
||||
exports: [RedisService, REDIS_CLIENT],
|
||||
exports: [RedisService, DistributedLockService, REDIS_CLIENT],
|
||||
})
|
||||
export class RedisModule {}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { RedisService } from './redis.service';
|
||||
|
||||
function createRedisService(client: Record<string, unknown>) {
|
||||
return new RedisService(client as never);
|
||||
}
|
||||
|
||||
describe('RedisService stream pending recovery', () => {
|
||||
it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
|
||||
const sendCommand = jest.fn().mockResolvedValue([
|
||||
'0-0',
|
||||
[
|
||||
[
|
||||
'1700000000000-0',
|
||||
['job', '{"kind":"poll-tournament-result"}', 'source', 'test'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
const service = createRedisService({ sendCommand });
|
||||
|
||||
await expect(
|
||||
service.claimStalePendingStreamMessages({
|
||||
key: 'riot:queue:high',
|
||||
group: 'riot-refresh-worker',
|
||||
consumer: 'worker-1',
|
||||
stalePendingMessageMinimumIdleMilliseconds: 1_800_000,
|
||||
count: 1,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
nextStartId: '0-0',
|
||||
messages: [
|
||||
{
|
||||
id: '1700000000000-0',
|
||||
message: {
|
||||
job: '{"kind":"poll-tournament-result"}',
|
||||
source: 'test',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'XAUTOCLAIM',
|
||||
'riot:queue:high',
|
||||
'riot-refresh-worker',
|
||||
'worker-1',
|
||||
'1800000',
|
||||
'0-0',
|
||||
'COUNT',
|
||||
'1',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,11 @@ export interface StreamReadResult {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ClaimStalePendingStreamMessagesResult {
|
||||
messages: StreamEntry[];
|
||||
nextStartId: string;
|
||||
}
|
||||
|
||||
interface RawStreamMessage {
|
||||
deliveriesCounter?: number;
|
||||
id: string;
|
||||
@@ -29,6 +34,16 @@ interface RawStreamReadResult {
|
||||
}
|
||||
|
||||
function normalizeStreamFields(fields: unknown): Record<string, string> {
|
||||
if (Array.isArray(fields)) {
|
||||
const normalized: Record<string, string> = {};
|
||||
for (let index = 0; index < fields.length; index += 2) {
|
||||
const key = fields[index];
|
||||
if (key === undefined) continue;
|
||||
normalized[String(key)] = String(fields[index + 1] ?? '');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (fields instanceof Map) {
|
||||
return Object.fromEntries(
|
||||
[...fields.entries()].map(([key, value]) => [String(key), String(value)]),
|
||||
@@ -188,6 +203,38 @@ export class RedisService implements OnModuleDestroy {
|
||||
}));
|
||||
}
|
||||
|
||||
public async claimStalePendingStreamMessages(options: {
|
||||
key: string;
|
||||
group: string;
|
||||
consumer: string;
|
||||
stalePendingMessageMinimumIdleMilliseconds: number;
|
||||
startId?: string;
|
||||
count?: number;
|
||||
}): Promise<ClaimStalePendingStreamMessagesResult> {
|
||||
const response = (await this.client.sendCommand([
|
||||
'XAUTOCLAIM',
|
||||
options.key,
|
||||
options.group,
|
||||
options.consumer,
|
||||
String(options.stalePendingMessageMinimumIdleMilliseconds),
|
||||
options.startId ?? '0-0',
|
||||
'COUNT',
|
||||
String(options.count ?? 1),
|
||||
])) as unknown;
|
||||
|
||||
const responseItems = Array.isArray(response) ? response : [];
|
||||
const rawMessages = Array.isArray(responseItems[1])
|
||||
? responseItems[1]
|
||||
: [];
|
||||
|
||||
return {
|
||||
nextStartId: String(responseItems[0] ?? '0-0'),
|
||||
messages: rawMessages
|
||||
.map((rawMessage) => this.normalizeClaimedStreamMessage(rawMessage))
|
||||
.filter((message): message is StreamEntry => Boolean(message)),
|
||||
};
|
||||
}
|
||||
|
||||
public async acknowledgeStream(
|
||||
key: string,
|
||||
group: string,
|
||||
@@ -210,4 +257,37 @@ export class RedisService implements OnModuleDestroy {
|
||||
public async publish(channel: string, message: string): Promise<number> {
|
||||
return this.client.publish(channel, message);
|
||||
}
|
||||
|
||||
private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null {
|
||||
if (Array.isArray(rawMessage)) {
|
||||
const [id, fields] = rawMessage;
|
||||
if (id === undefined) return null;
|
||||
return {
|
||||
id: String(id),
|
||||
message: normalizeStreamFields(fields),
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
typeof rawMessage === 'object' &&
|
||||
rawMessage !== null &&
|
||||
'id' in rawMessage
|
||||
) {
|
||||
const message = rawMessage as RawStreamMessage;
|
||||
return {
|
||||
deliveriesCounter:
|
||||
typeof message.deliveriesCounter === 'number'
|
||||
? message.deliveriesCounter
|
||||
: undefined,
|
||||
id: String(message.id),
|
||||
message: normalizeStreamFields(message.message),
|
||||
millisElapsedFromDelivery:
|
||||
typeof message.millisElapsedFromDelivery === 'number'
|
||||
? message.millisElapsedFromDelivery
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import { RedisService } from '../global/redis/redis.service';
|
||||
import { RiotMatchService } from '../riot/riot-match.service';
|
||||
import { LegacyImportService } from './legacy-import.service';
|
||||
import type { LegacyImportMemberJob } from './legacy-import.types';
|
||||
|
||||
function execResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
}
|
||||
|
||||
describe('LegacyImportService member job completion', () => {
|
||||
it('increments aggregate counters only once for the same member job id', async () => {
|
||||
const legacyImportJobModel = {
|
||||
findOne: jest
|
||||
.fn()
|
||||
.mockReturnValueOnce(
|
||||
execResult({
|
||||
jobId: 'legacy-job-1',
|
||||
state: 'running',
|
||||
processedMembers: 0,
|
||||
totalMembers: 1,
|
||||
averageMemberSeconds: 60,
|
||||
completedMemberJobIds: [],
|
||||
}),
|
||||
)
|
||||
.mockReturnValueOnce({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue(
|
||||
execResult({
|
||||
state: 'running',
|
||||
processedMembers: 1,
|
||||
totalMembers: 1,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.mockReturnValueOnce(
|
||||
execResult({
|
||||
jobId: 'legacy-job-1',
|
||||
state: 'completed',
|
||||
processedMembers: 1,
|
||||
totalMembers: 1,
|
||||
averageMemberSeconds: 60,
|
||||
completedMemberJobIds: ['member-job-1'],
|
||||
}),
|
||||
),
|
||||
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue(legacyImportJobModel),
|
||||
} as unknown as jest.Mocked<ConnectionService>;
|
||||
const distributedLockService = {
|
||||
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
|
||||
} as unknown as jest.Mocked<DistributedLockService>;
|
||||
const communityStatsService = {
|
||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<CommunityStatsService>;
|
||||
const service = new LegacyImportService(
|
||||
connectionService,
|
||||
{} as RedisService,
|
||||
{} as RiotMatchService,
|
||||
communityStatsService,
|
||||
{} as MatchStatsService,
|
||||
distributedLockService,
|
||||
);
|
||||
const job: LegacyImportMemberJob = {
|
||||
kind: 'legacy-import-member',
|
||||
jobId: 'member-job-1',
|
||||
parentJobId: 'legacy-job-1',
|
||||
communityId: new mongoose.Types.ObjectId().toString(),
|
||||
userId: new mongoose.Types.ObjectId().toString(),
|
||||
puuid: 'puuid-1',
|
||||
startTime: 1,
|
||||
endTime: 2,
|
||||
triggeredBy: new mongoose.Types.ObjectId().toString(),
|
||||
region: 'asia',
|
||||
};
|
||||
|
||||
await (
|
||||
service as unknown as {
|
||||
finishMemberJob: (
|
||||
job: LegacyImportMemberJob,
|
||||
stats: {
|
||||
discovered: number;
|
||||
imported: number;
|
||||
duplicates: number;
|
||||
errors: number;
|
||||
elapsedSeconds: number;
|
||||
},
|
||||
) => Promise<void>;
|
||||
}
|
||||
).finishMemberJob(job, {
|
||||
discovered: 3,
|
||||
imported: 2,
|
||||
duplicates: 1,
|
||||
errors: 0,
|
||||
elapsedSeconds: 30,
|
||||
});
|
||||
await (
|
||||
service as unknown as {
|
||||
finishMemberJob: (
|
||||
job: LegacyImportMemberJob,
|
||||
stats: {
|
||||
discovered: number;
|
||||
imported: number;
|
||||
duplicates: number;
|
||||
errors: number;
|
||||
elapsedSeconds: number;
|
||||
},
|
||||
) => Promise<void>;
|
||||
}
|
||||
).finishMemberJob(job, {
|
||||
discovered: 3,
|
||||
imported: 2,
|
||||
duplicates: 1,
|
||||
errors: 0,
|
||||
elapsedSeconds: 30,
|
||||
});
|
||||
|
||||
expect(legacyImportJobModel.updateOne).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
{
|
||||
jobId: 'legacy-job-1',
|
||||
completedMemberJobIds: { $ne: 'member-job-1' },
|
||||
state: { $ne: 'cancelled' },
|
||||
},
|
||||
expect.objectContaining({
|
||||
$addToSet: { completedMemberJobIds: 'member-job-1' },
|
||||
$inc: expect.objectContaining({
|
||||
processedMembers: 1,
|
||||
totalDiscoveredMatchIds: 3,
|
||||
totalImportedMatches: 2,
|
||||
totalSkippedDuplicate: 1,
|
||||
totalErrors: 0,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(legacyImportJobModel.updateOne).toHaveBeenCalledTimes(2);
|
||||
expect(distributedLockService.releaseLockIfOwned).toHaveBeenCalledTimes(1);
|
||||
expect(communityStatsService.invalidateCommunity).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,10 @@ import mongoose from 'mongoose';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
type DistributedLockOwnership,
|
||||
DistributedLockService,
|
||||
} from '../global/redis/distributed-lock.service';
|
||||
import type {
|
||||
LegacyImportJobDocument,
|
||||
Match,
|
||||
@@ -57,6 +61,7 @@ export class LegacyImportService {
|
||||
private readonly riotMatchService: RiotMatchService,
|
||||
private readonly communityStatsService: CommunityStatsService,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {}
|
||||
|
||||
public async previewMembers(params: {
|
||||
@@ -80,12 +85,14 @@ export class LegacyImportService {
|
||||
}): Promise<StartLegacyImportResponse> {
|
||||
const lockKey = this.communityLockKey(params.communityId);
|
||||
const jobId = randomUUID();
|
||||
const acquired = await this.redisService.setStringIfAbsent(
|
||||
const communityImportLockOwnership =
|
||||
await this.distributedLockService.acquireLock({
|
||||
lockKey,
|
||||
jobId,
|
||||
LEGACY_IMPORT_LOCK_TTL_SECONDS,
|
||||
);
|
||||
if (!acquired) {
|
||||
lockOwnershipToken: jobId,
|
||||
lockExpirationDurationMilliseconds:
|
||||
LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||
});
|
||||
if (!communityImportLockOwnership) {
|
||||
throw new ConflictException('Legacy import is already running.');
|
||||
}
|
||||
|
||||
@@ -133,6 +140,7 @@ export class LegacyImportService {
|
||||
totalSkippedDuplicate: 0,
|
||||
totalErrors: 0,
|
||||
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||
completedMemberJobIds: [],
|
||||
});
|
||||
|
||||
for (const window of windows) {
|
||||
@@ -160,7 +168,7 @@ export class LegacyImportService {
|
||||
{ jobId },
|
||||
{ $set: { state: 'completed', completedAt: new Date() } },
|
||||
).exec();
|
||||
await this.redisService.delete(lockKey);
|
||||
await this.releaseDistributedLockSafely(communityImportLockOwnership);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -169,7 +177,7 @@ export class LegacyImportService {
|
||||
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||
};
|
||||
} catch (error) {
|
||||
await this.redisService.delete(lockKey);
|
||||
await this.releaseDistributedLockSafely(communityImportLockOwnership);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -220,7 +228,11 @@ export class LegacyImportService {
|
||||
).exec();
|
||||
if (!job)
|
||||
throw new NotFoundException('Running legacy import job not found.');
|
||||
await this.redisService.delete(this.communityLockKey(params.communityId));
|
||||
await this.distributedLockService.releaseLockIfOwned({
|
||||
lockKey: this.communityLockKey(params.communityId),
|
||||
lockOwnershipToken: job.jobId,
|
||||
lockExpirationDurationMilliseconds: LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||
});
|
||||
return job;
|
||||
}
|
||||
|
||||
@@ -228,6 +240,7 @@ export class LegacyImportService {
|
||||
const started = Date.now();
|
||||
const legacyJob = await this.getRunnableJob(job);
|
||||
if (!legacyJob) return;
|
||||
if (legacyJob.completedMemberJobIds?.includes(job.jobId)) return;
|
||||
|
||||
let discovered = 0;
|
||||
let imported = 0;
|
||||
@@ -500,14 +513,14 @@ export class LegacyImportService {
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): Promise<ImportOutcome> {
|
||||
const lockKey = `legacy-import:match:${riotMatchId}`;
|
||||
const acquired = await this.redisService.setStringIfAbsent(
|
||||
lockKey,
|
||||
job.parentJobId,
|
||||
MATCH_IMPORT_LOCK_TTL_SECONDS,
|
||||
);
|
||||
if (!acquired) return 'duplicate';
|
||||
|
||||
try {
|
||||
const importOutcome = await this.distributedLockService.runWithLock(
|
||||
{
|
||||
lockKey,
|
||||
lockExpirationDurationMilliseconds:
|
||||
MATCH_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||
},
|
||||
async () => {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const existing = await MatchModel.exists({
|
||||
'result.games.riotMatchId': riotMatchId,
|
||||
@@ -523,7 +536,9 @@ export class LegacyImportService {
|
||||
if (counts.total === 0) return 'skipped';
|
||||
|
||||
const gameResult = buildGameResult(detail, userByPuuid, 1);
|
||||
if (!gameResult || gameResult.participants.length === 0) return 'skipped';
|
||||
if (!gameResult || gameResult.participants.length === 0) {
|
||||
return 'skipped';
|
||||
}
|
||||
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
const matchPayload: Partial<Match> = {
|
||||
@@ -569,6 +584,10 @@ export class LegacyImportService {
|
||||
const match = await MatchModel.create(matchPayload);
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
return 'imported';
|
||||
},
|
||||
);
|
||||
if (importOutcome === null) return 'duplicate';
|
||||
return importOutcome;
|
||||
} catch (error) {
|
||||
await this.recordError(job.parentJobId, {
|
||||
puuid: job.puuid,
|
||||
@@ -576,8 +595,6 @@ export class LegacyImportService {
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return 'error';
|
||||
} finally {
|
||||
await this.redisService.delete(lockKey);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -626,6 +643,7 @@ export class LegacyImportService {
|
||||
jobId: job.parentJobId,
|
||||
}).exec();
|
||||
if (!current || current.state === 'cancelled') return;
|
||||
if (current.completedMemberJobIds?.includes(job.jobId)) return;
|
||||
|
||||
const average =
|
||||
current.averageMemberSeconds === undefined
|
||||
@@ -634,14 +652,14 @@ export class LegacyImportService {
|
||||
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
|
||||
);
|
||||
|
||||
const nextProcessed = current.processedMembers + 1;
|
||||
const completed = nextProcessed >= current.totalMembers;
|
||||
await LegacyImportJobModel.updateOne(
|
||||
{ jobId: job.parentJobId },
|
||||
const updateResult = await LegacyImportJobModel.updateOne(
|
||||
{
|
||||
jobId: job.parentJobId,
|
||||
completedMemberJobIds: { $ne: job.jobId },
|
||||
state: { $ne: 'cancelled' },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: completed ? 'completed' : current.state,
|
||||
completedAt: completed ? new Date() : current.completedAt,
|
||||
averageMemberSeconds: average,
|
||||
},
|
||||
$inc: {
|
||||
@@ -651,14 +669,49 @@ export class LegacyImportService {
|
||||
totalSkippedDuplicate: stats.duplicates,
|
||||
totalErrors: stats.errors,
|
||||
},
|
||||
$addToSet: {
|
||||
completedMemberJobIds: job.jobId,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
if (updateResult.modifiedCount === 0) return;
|
||||
|
||||
const updated = await LegacyImportJobModel.findOne({
|
||||
jobId: job.parentJobId,
|
||||
})
|
||||
.select({ processedMembers: 1, totalMembers: 1, state: 1, completedAt: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
const completed = Boolean(
|
||||
updated &&
|
||||
updated.state !== 'cancelled' &&
|
||||
updated.processedMembers >= updated.totalMembers,
|
||||
);
|
||||
if (completed) {
|
||||
await LegacyImportJobModel.updateOne(
|
||||
{
|
||||
jobId: job.parentJobId,
|
||||
state: { $ne: 'cancelled' },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'completed',
|
||||
completedAt: updated?.completedAt ?? new Date(),
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
if (completed) {
|
||||
await Promise.all([
|
||||
this.redisService.delete(
|
||||
this.communityLockKey(new mongoose.Types.ObjectId(job.communityId)),
|
||||
this.distributedLockService.releaseLockIfOwned({
|
||||
lockKey: this.communityLockKey(
|
||||
new mongoose.Types.ObjectId(job.communityId),
|
||||
),
|
||||
lockOwnershipToken: job.parentJobId,
|
||||
lockExpirationDurationMilliseconds:
|
||||
LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||
}),
|
||||
this.communityStatsService.invalidateCommunity(
|
||||
new mongoose.Types.ObjectId(job.communityId),
|
||||
),
|
||||
@@ -680,6 +733,20 @@ export class LegacyImportService {
|
||||
return legacyJob;
|
||||
}
|
||||
|
||||
private async releaseDistributedLockSafely(
|
||||
lockOwnership: DistributedLockOwnership,
|
||||
): Promise<void> {
|
||||
await this.distributedLockService
|
||||
.releaseLockIfOwned(lockOwnership)
|
||||
.catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Failed to release legacy import lock ${lockOwnership.lockKey}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async isCancelled(parentJobId: string): Promise<boolean> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchHistoryService } from './match-history.service';
|
||||
|
||||
describe('MatchHistoryService.getChampionStats', () => {
|
||||
it('aggregates champion stats in MongoDB with secondaryPreferred reads', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const aggregateExec = jest.fn().mockResolvedValue([
|
||||
{
|
||||
championId: 103,
|
||||
games: 2,
|
||||
wins: 1,
|
||||
totalKills: 15,
|
||||
totalDeaths: 5,
|
||||
totalAssists: 20,
|
||||
totalCs: 320,
|
||||
totalGameMinutes: 62,
|
||||
doubleKills: 2,
|
||||
tripleKills: 1,
|
||||
quadraKills: 0,
|
||||
pentaKills: 0,
|
||||
lastFetchedAt: new Date('2026-01-03T00:00:00.000Z'),
|
||||
},
|
||||
{
|
||||
championId: 64,
|
||||
games: 1,
|
||||
wins: 1,
|
||||
totalKills: 5,
|
||||
totalDeaths: 0,
|
||||
totalAssists: 7,
|
||||
totalCs: 110,
|
||||
totalGameMinutes: 25,
|
||||
doubleKills: 0,
|
||||
tripleKills: 0,
|
||||
quadraKills: 0,
|
||||
pentaKills: 0,
|
||||
lastFetchedAt: new Date('2026-01-04T00:00:00.000Z'),
|
||||
},
|
||||
]);
|
||||
const read = jest.fn().mockReturnThis();
|
||||
const aggregate = jest.fn().mockReturnValue({ read, exec: aggregateExec });
|
||||
const UserModel = {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
_id: userId,
|
||||
communityId,
|
||||
riotAccounts: [
|
||||
{
|
||||
puuid: 'puuid-1',
|
||||
isPrimary: true,
|
||||
recentStatsFetchedAt: new Date('2026-01-05T00:00:00.000Z'),
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const CommunityModel = {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
_id: communityId,
|
||||
seasonStartedAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
seasons: [
|
||||
{
|
||||
id: 'current',
|
||||
label: '현재 시즌',
|
||||
startedAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn(async (name: string) => {
|
||||
if (name === 'user') return UserModel;
|
||||
if (name === 'community') return CommunityModel;
|
||||
if (name === 'riotMatch') return { aggregate };
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
};
|
||||
const service = new MatchHistoryService(connectionService as never);
|
||||
|
||||
const response = await service.getChampionStats({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { queueGroup: 'summoners-rift', rank: 'all' },
|
||||
});
|
||||
|
||||
expect(aggregate).toHaveBeenCalledTimes(1);
|
||||
expect(read).toHaveBeenCalledWith('secondaryPreferred');
|
||||
expect(aggregateExec).toHaveBeenCalledTimes(1);
|
||||
expect(aggregate.mock.calls[0][0]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
$match: expect.objectContaining({
|
||||
participantPuuids: 'puuid-1',
|
||||
gameCreation: {
|
||||
$gte: new Date('2026-01-01T00:00:00.000Z').getTime(),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
{ $limit: 500 },
|
||||
expect.objectContaining({ $group: expect.any(Object) }),
|
||||
]),
|
||||
);
|
||||
expect(response.champions).toEqual([
|
||||
expect.objectContaining({
|
||||
championId: 103,
|
||||
games: 2,
|
||||
wins: 1,
|
||||
losses: 1,
|
||||
winRate: 50,
|
||||
avgKills: 7.5,
|
||||
avgDeaths: 2.5,
|
||||
avgAssists: 10,
|
||||
kda: 7,
|
||||
avgCs: 160,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
championId: 64,
|
||||
games: 1,
|
||||
wins: 1,
|
||||
losses: 0,
|
||||
winRate: 100,
|
||||
kda: 12,
|
||||
}),
|
||||
]);
|
||||
expect(response.totals).toEqual(
|
||||
expect.objectContaining({
|
||||
championId: 0,
|
||||
games: 3,
|
||||
wins: 2,
|
||||
losses: 1,
|
||||
totalKills: 20,
|
||||
totalDeaths: 5,
|
||||
totalAssists: 27,
|
||||
}),
|
||||
);
|
||||
expect(response.lastFetchedAt).toBe('2026-01-03T00:00:00.000Z');
|
||||
});
|
||||
});
|
||||
@@ -69,6 +69,10 @@ interface AggregatedChampion {
|
||||
pentaKills: number;
|
||||
}
|
||||
|
||||
interface ChampionAggregateRow extends AggregatedChampion {
|
||||
lastFetchedAt?: Date;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchHistoryService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
@@ -129,29 +133,17 @@ export class MatchHistoryService {
|
||||
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
|
||||
params.filters,
|
||||
);
|
||||
const docs = await this.findStoredMatches({
|
||||
const aggregates = await this.aggregateChampionStats({
|
||||
context,
|
||||
queueIds,
|
||||
limit: MAX_AGGREGATE_MATCHES,
|
||||
});
|
||||
const aggregates = new Map<number, AggregatedChampion>();
|
||||
|
||||
for (const doc of docs) {
|
||||
const dto = doc.raw as unknown as RiotMatchDto;
|
||||
const participant = this.findParticipant(dto, context.account.puuid);
|
||||
if (!participant) continue;
|
||||
const aggregate =
|
||||
aggregates.get(participant.championId) ??
|
||||
this.createChampionAggregate(participant.championId);
|
||||
this.addParticipantToChampionAggregate(aggregate, participant, dto);
|
||||
aggregates.set(participant.championId, aggregate);
|
||||
}
|
||||
|
||||
const champions = [...aggregates.values()]
|
||||
const champions = aggregates
|
||||
.map((aggregate) => this.toChampionStatsRow(aggregate))
|
||||
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
|
||||
const totals = this.toChampionStatsRow(
|
||||
[...aggregates.values()].reduce(
|
||||
aggregates.reduce(
|
||||
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
|
||||
this.createChampionAggregate(0),
|
||||
),
|
||||
@@ -162,7 +154,7 @@ export class MatchHistoryService {
|
||||
rank,
|
||||
queueIds,
|
||||
season: context.season,
|
||||
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
|
||||
lastFetchedAt: this.resolveAggregateLastFetchedAt(aggregates, context),
|
||||
champions,
|
||||
totals,
|
||||
};
|
||||
@@ -363,6 +355,101 @@ export class MatchHistoryService {
|
||||
.slice(0, params.limit);
|
||||
}
|
||||
|
||||
private async aggregateChampionStats(params: {
|
||||
context: HistoryContext;
|
||||
queueIds: number[];
|
||||
limit: number;
|
||||
}): Promise<ChampionAggregateRow[]> {
|
||||
if (params.queueIds.length === 0) return [];
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const gameCreation: Record<string, number> = {};
|
||||
if (params.context.seasonStartedAt) {
|
||||
gameCreation.$gte = params.context.seasonStartedAt.getTime();
|
||||
}
|
||||
|
||||
const match: Record<string, unknown> = {
|
||||
participantPuuids: params.context.account.puuid,
|
||||
queueId: { $in: params.queueIds },
|
||||
};
|
||||
if (Object.keys(gameCreation).length > 0) match.gameCreation = gameCreation;
|
||||
|
||||
return RiotMatchModel.aggregate<ChampionAggregateRow>([
|
||||
{ $match: match },
|
||||
{ $sort: { gameCreation: -1 } },
|
||||
{ $limit: params.limit },
|
||||
{
|
||||
$project: {
|
||||
fetchedAt: 1,
|
||||
gameDuration: '$raw.info.gameDuration',
|
||||
participant: {
|
||||
$first: {
|
||||
$filter: {
|
||||
input: '$raw.info.participants',
|
||||
as: 'participant',
|
||||
cond: {
|
||||
$eq: ['$$participant.puuid', params.context.account.puuid],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $match: { participant: { $ne: null } } },
|
||||
{
|
||||
$group: {
|
||||
_id: '$participant.championId',
|
||||
championId: { $first: '$participant.championId' },
|
||||
games: { $sum: 1 },
|
||||
wins: {
|
||||
$sum: { $cond: ['$participant.win', 1, 0] },
|
||||
},
|
||||
totalKills: { $sum: { $ifNull: ['$participant.kills', 0] } },
|
||||
totalDeaths: { $sum: { $ifNull: ['$participant.deaths', 0] } },
|
||||
totalAssists: { $sum: { $ifNull: ['$participant.assists', 0] } },
|
||||
totalCs: {
|
||||
$sum: {
|
||||
$add: [
|
||||
{ $ifNull: ['$participant.totalMinionsKilled', 0] },
|
||||
{ $ifNull: ['$participant.neutralMinionsKilled', 0] },
|
||||
],
|
||||
},
|
||||
},
|
||||
totalGameMinutes: {
|
||||
$sum: {
|
||||
$max: [
|
||||
{
|
||||
$divide: [
|
||||
{
|
||||
$ifNull: ['$participant.timePlayed', '$gameDuration'],
|
||||
},
|
||||
60,
|
||||
],
|
||||
},
|
||||
1,
|
||||
],
|
||||
},
|
||||
},
|
||||
doubleKills: {
|
||||
$sum: { $ifNull: ['$participant.doubleKills', 0] },
|
||||
},
|
||||
tripleKills: {
|
||||
$sum: { $ifNull: ['$participant.tripleKills', 0] },
|
||||
},
|
||||
quadraKills: {
|
||||
$sum: { $ifNull: ['$participant.quadraKills', 0] },
|
||||
},
|
||||
pentaKills: {
|
||||
$sum: { $ifNull: ['$participant.pentaKills', 0] },
|
||||
},
|
||||
lastFetchedAt: { $min: '$fetchedAt' },
|
||||
},
|
||||
},
|
||||
{ $sort: { games: -1, wins: -1, championId: 1 } },
|
||||
])
|
||||
.read('secondaryPreferred')
|
||||
.exec();
|
||||
}
|
||||
|
||||
private findParticipant(
|
||||
match: RiotMatchDto,
|
||||
puuid: string,
|
||||
@@ -760,6 +847,24 @@ export class MatchHistoryService {
|
||||
return oldest.toISOString();
|
||||
}
|
||||
|
||||
private resolveAggregateLastFetchedAt(
|
||||
rows: ChampionAggregateRow[],
|
||||
context: HistoryContext,
|
||||
): string | null {
|
||||
if (rows.length === 0) {
|
||||
return context.account.recentStatsFetchedAt?.toISOString() ?? null;
|
||||
}
|
||||
const oldest = rows
|
||||
.map((row) => row.lastFetchedAt)
|
||||
.filter((value): value is Date => value instanceof Date)
|
||||
.reduce<Date | null>(
|
||||
(acc, value) =>
|
||||
!acc || value.getTime() < acc.getTime() ? value : acc,
|
||||
null,
|
||||
);
|
||||
return oldest?.toISOString() ?? null;
|
||||
}
|
||||
|
||||
private clampLimit(value: number | undefined, fallback: number, max: number): number {
|
||||
if (!value || !Number.isFinite(value)) return fallback;
|
||||
return Math.max(1, Math.min(Math.floor(value), max));
|
||||
|
||||
@@ -135,6 +135,8 @@ export interface RecentMatchTeamParticipantView {
|
||||
|
||||
export interface RecentMatchView {
|
||||
matchId: string;
|
||||
internalMatchId?: string;
|
||||
gameNumber?: number;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
gameCreation: number;
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ArrayMinSize,
|
||||
registerDecorator,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsDate,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
@@ -106,6 +107,10 @@ export class CreateMatchDto {
|
||||
@Min(1)
|
||||
roundRobinMaxRounds?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -166,6 +171,10 @@ export class UpdateMatchDto {
|
||||
@Min(1)
|
||||
roundRobinMaxRounds?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -217,3 +226,31 @@ export class AddParticipantDto {
|
||||
@IsString()
|
||||
riotPuuid?: string;
|
||||
}
|
||||
|
||||
export class SwapDoubleEliminationSeedsDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
leftSeedNumber!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
rightSeedNumber!: number;
|
||||
}
|
||||
|
||||
export class ApplyDoubleEliminationWalkoverDto {
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
winnerTeamIndex!: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export class CancelDoubleEliminationActionDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
reason?: string;
|
||||
}
|
||||
@@ -25,8 +25,11 @@ import type {
|
||||
} from '../global/database/schema';
|
||||
import {
|
||||
AddParticipantDto,
|
||||
ApplyDoubleEliminationWalkoverDto,
|
||||
CancelDoubleEliminationActionDto,
|
||||
CreateMatchDto,
|
||||
JoinMatchDto,
|
||||
SwapDoubleEliminationSeedsDto,
|
||||
UpdateMatchDto,
|
||||
UpdateParticipantDto,
|
||||
} from './dto/create-match.dto';
|
||||
@@ -58,6 +61,8 @@ export class MatchController {
|
||||
gameCount: body.gameCount,
|
||||
gameMode: body.gameMode ?? 'pair',
|
||||
roundRobinMaxRounds: body.roundRobinMaxRounds,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
body.doubleEliminationResetFinalEnabled,
|
||||
prizes: body.prizes ?? [],
|
||||
notices: body.notices ?? [],
|
||||
schedule: body.schedule ?? [],
|
||||
@@ -121,6 +126,116 @@ export class MatchController {
|
||||
return this.matchService.update({ matchId, communityId, patch: body });
|
||||
}
|
||||
|
||||
@Post(':matchId/double-elimination/seeds/reshuffle')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async reshuffleDoubleEliminationSeeds(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.reshuffleDoubleEliminationSeeds({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(':matchId/double-elimination/seeds/swap')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async swapDoubleEliminationSeeds(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Body() body: SwapDoubleEliminationSeedsDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.swapDoubleEliminationSeeds({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
leftSeedNumber: body.leftSeedNumber,
|
||||
rightSeedNumber: body.rightSeedNumber,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async applyDoubleEliminationWalkover(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('bracketMatchId') bracketMatchId: string,
|
||||
@Body() body: ApplyDoubleEliminationWalkoverDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.applyDoubleEliminationWalkover({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
bracketMatchId,
|
||||
winnerTeamIndex: body.winnerTeamIndex,
|
||||
reason: body.reason,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(
|
||||
':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover/cancel',
|
||||
)
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async cancelDoubleEliminationWalkover(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('bracketMatchId') bracketMatchId: string,
|
||||
@Body() body: CancelDoubleEliminationActionDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.cancelDoubleEliminationWalkover({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
bracketMatchId,
|
||||
reason: body.reason,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Post(
|
||||
':matchId/double-elimination/bracket-matches/:bracketMatchId/result/cancel',
|
||||
)
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
public async cancelDoubleEliminationRiotResult(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Param('bracketMatchId') bracketMatchId: string,
|
||||
@Body() body: CancelDoubleEliminationActionDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
const match = await this.matchService.cancelDoubleEliminationRiotResult({
|
||||
matchId,
|
||||
communityId,
|
||||
actorUserId: currentUser._id,
|
||||
bracketMatchId,
|
||||
reason: body.reason,
|
||||
});
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Delete(':matchId')
|
||||
@Roles('admin', 'owner')
|
||||
@UseGuards(RolesGuard)
|
||||
|
||||
@@ -2,9 +2,62 @@ import mongoose from 'mongoose';
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
describe('MatchService', () => {
|
||||
function createService(match: Record<string, unknown>) {
|
||||
function createServiceWithCreateModels() {
|
||||
const createdPayloads: Record<string, unknown>[] = [];
|
||||
const MatchModel = {
|
||||
create: jest.fn().mockImplementation(async (payload) => {
|
||||
createdPayloads.push(payload);
|
||||
return payload;
|
||||
}),
|
||||
exists: jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const CommunityModel = {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchGameCount: 3 }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return MatchModel;
|
||||
if (name === 'community') return CommunityModel;
|
||||
return {};
|
||||
}),
|
||||
};
|
||||
const tournamentCodeService = {
|
||||
buildSlots: jest.fn().mockResolvedValue([]),
|
||||
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const communityStatsService = {
|
||||
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const matchStatsService = {
|
||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||
removeByMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
return {
|
||||
service: new MatchService(
|
||||
connectionService as never,
|
||||
tournamentCodeService as never,
|
||||
communityStatsService as never,
|
||||
matchStatsService as never,
|
||||
),
|
||||
MatchModel,
|
||||
createdPayloads,
|
||||
};
|
||||
}
|
||||
|
||||
function createService(
|
||||
match: Record<string, unknown>,
|
||||
updatedMatch: Record<string, unknown> | null = match,
|
||||
) {
|
||||
const MatchModel = {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
@@ -31,6 +84,7 @@ describe('MatchService', () => {
|
||||
communityStatsService as never,
|
||||
matchStatsService as never,
|
||||
),
|
||||
MatchModel,
|
||||
tournamentCodeService,
|
||||
matchStatsService,
|
||||
};
|
||||
@@ -83,12 +137,16 @@ describe('MatchService', () => {
|
||||
function createServiceWithJoinModels(params: {
|
||||
user: Record<string, unknown> | null;
|
||||
match: Record<string, unknown> | null;
|
||||
updatedMatch?: Record<string, unknown> | null;
|
||||
}) {
|
||||
const UserModel = {
|
||||
findById: jest.fn().mockResolvedValue(params.user),
|
||||
};
|
||||
const MatchModel = {
|
||||
findById: jest.fn().mockResolvedValue(params.match),
|
||||
findOneAndUpdate: jest
|
||||
.fn()
|
||||
.mockResolvedValue(params.updatedMatch ?? params.match),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
@@ -233,15 +291,43 @@ describe('MatchService', () => {
|
||||
participants: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const { service } = createServiceWithJoinModels({ user, match });
|
||||
const updatedMatch = {
|
||||
...match,
|
||||
participants: [
|
||||
{
|
||||
userId,
|
||||
puuid: 'puuid-1',
|
||||
gameName: 'Dahyeon',
|
||||
tagLine: 'KR1',
|
||||
profileIconId: 7,
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
excluded: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
const { service, MatchModel } = createServiceWithJoinModels({
|
||||
user,
|
||||
match,
|
||||
updatedMatch,
|
||||
});
|
||||
|
||||
await service.join({
|
||||
const joined = await service.join({
|
||||
matchId,
|
||||
userId,
|
||||
});
|
||||
|
||||
expect(match.participants).toEqual([
|
||||
expect(joined).toBe(updatedMatch);
|
||||
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': { $ne: userId },
|
||||
$expr: expect.any(Object),
|
||||
}),
|
||||
{
|
||||
$push: {
|
||||
participants: expect.objectContaining({
|
||||
userId,
|
||||
puuid: 'puuid-1',
|
||||
gameName: 'Dahyeon',
|
||||
@@ -250,8 +336,193 @@ describe('MatchService', () => {
|
||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||
excluded: false,
|
||||
}),
|
||||
]);
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
},
|
||||
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
|
||||
);
|
||||
expect(match.participants).toEqual([]);
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cancels a join with an atomic participant pull', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const user = {
|
||||
_id: userId,
|
||||
communityId,
|
||||
riotAccounts: [],
|
||||
preferredPositions: [],
|
||||
};
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
participants: [{ userId }],
|
||||
save: jest.fn(),
|
||||
};
|
||||
const updatedMatch = { ...match, participants: [] };
|
||||
const { service, MatchModel } = createServiceWithJoinModels({
|
||||
user,
|
||||
match,
|
||||
updatedMatch,
|
||||
});
|
||||
|
||||
await expect(service.cancelJoin({ matchId, userId })).resolves.toBe(
|
||||
updatedMatch,
|
||||
);
|
||||
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': userId,
|
||||
},
|
||||
{ $pull: { participants: { userId } } },
|
||||
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
|
||||
);
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes a participant with an atomic participant pull', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const targetUserId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
participants: [{ userId: targetUserId }],
|
||||
save: jest.fn(),
|
||||
};
|
||||
const updatedMatch = { ...match, participants: [] };
|
||||
const { service, MatchModel } = createService(match, updatedMatch);
|
||||
|
||||
await expect(
|
||||
service.removeParticipant({ matchId, communityId, targetUserId }),
|
||||
).resolves.toBe(updatedMatch);
|
||||
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': targetUserId,
|
||||
},
|
||||
{ $pull: { participants: { userId: targetUserId } } },
|
||||
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
|
||||
);
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updates participant positions with an array-filtered atomic update', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const targetUserId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
participants: [
|
||||
{
|
||||
userId: targetUserId,
|
||||
preferredPositions: [
|
||||
{ position: 'TOP', priority: 1 },
|
||||
{ position: 'JUNGLE', priority: 2 },
|
||||
{ position: 'MID', priority: 3 },
|
||||
],
|
||||
},
|
||||
],
|
||||
save: jest.fn(),
|
||||
};
|
||||
const updatedMatch = { ...match };
|
||||
const { service, MatchModel } = createService(match, updatedMatch);
|
||||
|
||||
await expect(
|
||||
service.updateParticipantPositions({
|
||||
matchId,
|
||||
communityId,
|
||||
targetUserId,
|
||||
mainPosition: 'MID',
|
||||
subPosition: 'SUPPORT',
|
||||
}),
|
||||
).resolves.toBe(updatedMatch);
|
||||
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{
|
||||
_id: matchId,
|
||||
communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': targetUserId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
'participants.$[participant].preferredPositions': [
|
||||
{ position: 'MID', priority: 1 },
|
||||
{ position: 'SUPPORT', priority: 2 },
|
||||
{ position: 'TOP', priority: 3 },
|
||||
{ position: 'JUNGLE', priority: 4 },
|
||||
],
|
||||
},
|
||||
},
|
||||
expect.objectContaining({
|
||||
arrayFilters: [{ 'participant.userId': targetUserId }],
|
||||
returnDocument: 'after',
|
||||
runValidators: true,
|
||||
}),
|
||||
);
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('normalizes double-elimination match creation', async () => {
|
||||
const { service, createdPayloads } = createServiceWithCreateModels();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
|
||||
await service.create({
|
||||
communityId,
|
||||
data: {
|
||||
title: 'Double elimination',
|
||||
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
|
||||
maxParticipants: 20,
|
||||
gameCount: 5,
|
||||
gameMode: 'double-elimination',
|
||||
doubleEliminationResetFinalEnabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(createdPayloads[0]).toMatchObject({
|
||||
communityId,
|
||||
maxParticipants: 20,
|
||||
gameCount: 5,
|
||||
gameMode: 'double-elimination',
|
||||
roundRobinMaxRounds: undefined,
|
||||
doubleElimination: {
|
||||
teamCount: 4,
|
||||
resetFinalEnabled: true,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects unsupported double-elimination participant counts', async () => {
|
||||
const { service, MatchModel } = createServiceWithCreateModels();
|
||||
|
||||
await expect(
|
||||
service.create({
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
data: {
|
||||
title: 'Invalid double elimination',
|
||||
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
|
||||
maxParticipants: 30,
|
||||
gameMode: 'double-elimination',
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'Double elimination supports only 20 or 40 participants.',
|
||||
);
|
||||
expect(MatchModel.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears game schedule when a built match returns to recruiting', async () => {
|
||||
@@ -310,7 +581,7 @@ describe('MatchService', () => {
|
||||
patch: { roundRobinMaxRounds: 3 },
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
|
||||
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
);
|
||||
expect(match.set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -5,12 +5,19 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
cancelDoubleEliminationBracketMatch,
|
||||
completeDoubleEliminationBracketMatch,
|
||||
reshuffleDoubleEliminationSeeds,
|
||||
swapDoubleEliminationSeeds,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
Match,
|
||||
MatchDocument,
|
||||
MatchGameMode,
|
||||
MatchSeriesResult,
|
||||
MatchStatus,
|
||||
POSITIONS,
|
||||
@@ -26,17 +33,25 @@ const MATCH_SHORT_CODE_LENGTH = 4;
|
||||
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
||||
const DEFAULT_MATCH_LIST_LIMIT = 50;
|
||||
const MAX_MATCH_LIST_LIMIT = 200;
|
||||
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
|
||||
const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
|
||||
|
||||
interface DoubleEliminationConfigInput {
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
}
|
||||
|
||||
interface CreateMatchParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>;
|
||||
data: Partial<Match> &
|
||||
Pick<Match, 'title' | 'scheduledAt'> &
|
||||
DoubleEliminationConfigInput;
|
||||
}
|
||||
|
||||
interface UpdateMatchParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
patch: Partial<Match>;
|
||||
patch: Partial<Match> & DoubleEliminationConfigInput;
|
||||
}
|
||||
|
||||
interface ListMatchesQuery {
|
||||
@@ -89,6 +104,28 @@ interface UpdateParticipantPositionsParams {
|
||||
subPosition: Position;
|
||||
}
|
||||
|
||||
interface DoubleEliminationAdminParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
actorUserId: mongoose.Types.ObjectId;
|
||||
}
|
||||
|
||||
interface SwapDoubleEliminationSeedsParams extends DoubleEliminationAdminParams {
|
||||
leftSeedNumber: number;
|
||||
rightSeedNumber: number;
|
||||
}
|
||||
|
||||
interface ApplyDoubleEliminationWalkoverParams extends DoubleEliminationAdminParams {
|
||||
bracketMatchId: string;
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface CancelDoubleEliminationActionParams extends DoubleEliminationAdminParams {
|
||||
bracketMatchId: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchService {
|
||||
constructor(
|
||||
@@ -105,15 +142,18 @@ export class MatchService {
|
||||
.select({ matchGameCount: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
return MatchModel.create({
|
||||
const normalizedData = this.normalizeMatchConfig({
|
||||
...params.data,
|
||||
shortCode:
|
||||
params.data.shortCode ??
|
||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||
gameCount:
|
||||
params.data.gameCount ??
|
||||
community?.matchGameCount ??
|
||||
DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
});
|
||||
return MatchModel.create({
|
||||
...normalizedData,
|
||||
shortCode:
|
||||
normalizedData.shortCode ??
|
||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||
communityId: params.communityId,
|
||||
hostUserId: params.hostUserId,
|
||||
});
|
||||
@@ -216,13 +256,30 @@ export class MatchService {
|
||||
previousStatus !== 'recruiting' &&
|
||||
('maxParticipants' in params.patch ||
|
||||
'gameMode' in params.patch ||
|
||||
'roundRobinMaxRounds' in params.patch)
|
||||
'roundRobinMaxRounds' in params.patch ||
|
||||
'doubleEliminationResetFinalEnabled' in params.patch)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.',
|
||||
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
|
||||
);
|
||||
}
|
||||
match.set(params.patch);
|
||||
const patchToSet =
|
||||
previousStatus === 'recruiting'
|
||||
? this.normalizeMatchConfig({
|
||||
...params.patch,
|
||||
gameMode: params.patch.gameMode ?? match.gameMode,
|
||||
maxParticipants:
|
||||
params.patch.maxParticipants ?? match.maxParticipants,
|
||||
gameCount: params.patch.gameCount ?? match.gameCount,
|
||||
roundRobinMaxRounds:
|
||||
params.patch.roundRobinMaxRounds ?? match.roundRobinMaxRounds,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
params.patch.doubleEliminationResetFinalEnabled ??
|
||||
params.patch.doubleElimination?.resetFinalEnabled ??
|
||||
match.doubleElimination?.resetFinalEnabled,
|
||||
})
|
||||
: this.stripMatchConfigInput(params.patch);
|
||||
match.set(patchToSet);
|
||||
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
||||
if (match.tournamentCodeIds.length > 0) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
@@ -260,6 +317,174 @@ export class MatchService {
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
}
|
||||
|
||||
public async reshuffleDoubleEliminationSeeds(
|
||||
params: DoubleEliminationAdminParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
await this.assertDoubleEliminationSeedsCanChange(match);
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = reshuffleDoubleEliminationSeeds(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
);
|
||||
match.doubleElimination!.events.push({
|
||||
type: 'seeds-reshuffled',
|
||||
actorUserId: params.actorUserId,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
match.markModified('doubleElimination');
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async swapDoubleEliminationSeeds(
|
||||
params: SwapDoubleEliminationSeedsParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
await this.assertDoubleEliminationSeedsCanChange(match);
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = swapDoubleEliminationSeeds(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
leftSeedNumber: params.leftSeedNumber,
|
||||
rightSeedNumber: params.rightSeedNumber,
|
||||
},
|
||||
);
|
||||
match.doubleElimination!.events.push({
|
||||
type: 'seeds-swapped',
|
||||
actorUserId: params.actorUserId,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
match.markModified('doubleElimination');
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async applyDoubleEliminationWalkover(
|
||||
params: ApplyDoubleEliminationWalkoverParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
const bracketMatch = this.requireDoubleEliminationBracketMatch(
|
||||
match,
|
||||
params.bracketMatchId,
|
||||
);
|
||||
if (bracketMatch.state !== 'ready') {
|
||||
throw new BadRequestException('Bracket match is not ready.');
|
||||
}
|
||||
if (
|
||||
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
|
||||
bracketMatch.teamBIndex !== params.winnerTeamIndex
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Winner team is not assigned to this bracket match.',
|
||||
);
|
||||
}
|
||||
|
||||
await this.releaseReservedDoubleEliminationCodes(match, [
|
||||
params.bracketMatchId,
|
||||
]);
|
||||
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
winnerTeamIndex: params.winnerTeamIndex,
|
||||
completedBy: 'walkover',
|
||||
completedAt: new Date(),
|
||||
walkover: {
|
||||
winnerTeamIndex: params.winnerTeamIndex,
|
||||
reason: params.reason,
|
||||
awardedBy: params.actorUserId,
|
||||
awardedAt: new Date(),
|
||||
active: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
match.markModified('doubleElimination');
|
||||
this.syncDoubleEliminationWinner(match);
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async cancelDoubleEliminationWalkover(
|
||||
params: CancelDoubleEliminationActionParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
const bracketMatch = this.requireDoubleEliminationBracketMatch(
|
||||
match,
|
||||
params.bracketMatchId,
|
||||
);
|
||||
if (
|
||||
bracketMatch.completedBy !== 'walkover' ||
|
||||
!bracketMatch.walkover?.active
|
||||
) {
|
||||
throw new BadRequestException('Active walkover was not found.');
|
||||
}
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = cancelDoubleEliminationBracketMatch(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
cancelledBy: params.actorUserId,
|
||||
cancelReason: params.reason,
|
||||
},
|
||||
);
|
||||
match.markModified('doubleElimination');
|
||||
this.syncDoubleEliminationWinner(match);
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async cancelDoubleEliminationRiotResult(
|
||||
params: CancelDoubleEliminationActionParams,
|
||||
): Promise<MatchDocument> {
|
||||
const match = await this.loadDoubleEliminationMatch(params);
|
||||
const game = match.result?.games?.find(
|
||||
(entry) => entry.bracketMatchId === params.bracketMatchId,
|
||||
);
|
||||
if (!game) throw new NotFoundException('Collected result not found.');
|
||||
await this.releaseReservedDoubleEliminationCodes(match);
|
||||
match.doubleElimination = cancelDoubleEliminationBracketMatch(
|
||||
match.doubleElimination as NonNullable<Match['doubleElimination']>,
|
||||
{
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
cancelledBy: params.actorUserId,
|
||||
cancelReason: params.reason,
|
||||
},
|
||||
);
|
||||
match.doubleElimination!.events.push({
|
||||
type: 'riot-result-cancelled',
|
||||
bracketMatchId: params.bracketMatchId,
|
||||
actorUserId: params.actorUserId,
|
||||
reason: params.reason,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
const games = (match.result?.games ?? []).filter(
|
||||
(entry) => entry.bracketMatchId !== params.bracketMatchId,
|
||||
);
|
||||
match.result = {
|
||||
winnerTeamIndex: undefined,
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: (match.result?.riotMatchIds ?? []).filter(
|
||||
(riotMatchId) => riotMatchId !== game.riotMatchId,
|
||||
),
|
||||
games,
|
||||
seriesResults: this.buildSeriesResults(games),
|
||||
};
|
||||
await this.voidDoubleEliminationCode(match, params.bracketMatchId);
|
||||
if (match.status === 'finished') match.status = 'in-progress';
|
||||
match.markModified('doubleElimination');
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return match;
|
||||
}
|
||||
|
||||
public async join(params: JoinMatchParams): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
@@ -267,29 +492,11 @@ export class MatchService {
|
||||
const user = await UserModel.findById(params.userId);
|
||||
if (!user) throw new NotFoundException('User not found.');
|
||||
|
||||
const match = await MatchModel.findById(params.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(user.communityId)) {
|
||||
throw new BadRequestException(
|
||||
'User and match belong to different communities.',
|
||||
);
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
if (match.participants.length >= match.maxParticipants) {
|
||||
throw new BadRequestException('Match is full.');
|
||||
}
|
||||
const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
|
||||
if (alreadyIn) {
|
||||
throw new BadRequestException('User already joined this match.');
|
||||
}
|
||||
|
||||
const selectedRiot = params.riotPuuid
|
||||
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
|
||||
: user.riotAccounts.find((a) => a.isPrimary);
|
||||
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
|
||||
match.participants.push({
|
||||
const participant = {
|
||||
userId: user._id,
|
||||
puuid: selectedRiot?.puuid,
|
||||
gameName: selectedRiot?.gameName,
|
||||
@@ -302,11 +509,219 @@ export class MatchService {
|
||||
),
|
||||
joinedAt: new Date(),
|
||||
excluded: false,
|
||||
});
|
||||
await match.save();
|
||||
};
|
||||
|
||||
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||
{
|
||||
_id: params.matchId,
|
||||
communityId: user.communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': { $ne: user._id },
|
||||
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
|
||||
},
|
||||
{ $push: { participants: participant } },
|
||||
{ returnDocument: 'after', runValidators: true },
|
||||
);
|
||||
if (updatedMatch) return updatedMatch;
|
||||
|
||||
return await this.throwJoinFailure(MatchModel, params.matchId, user);
|
||||
}
|
||||
|
||||
private normalizeMatchConfig<
|
||||
T extends Partial<Match> & DoubleEliminationConfigInput,
|
||||
>(input: T): Partial<Match> {
|
||||
const patch = this.stripMatchConfigInput(input);
|
||||
const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode;
|
||||
const maxParticipants = patch.maxParticipants ?? 10;
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
if (
|
||||
!DOUBLE_ELIMINATION_PARTICIPANT_COUNTS.includes(
|
||||
maxParticipants as (typeof DOUBLE_ELIMINATION_PARTICIPANT_COUNTS)[number],
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Double elimination supports only 20 or 40 participants.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
...patch,
|
||||
gameMode,
|
||||
maxParticipants,
|
||||
gameCount: this.normalizeDoubleEliminationSeriesGameCount(
|
||||
patch.gameCount ?? DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT,
|
||||
),
|
||||
roundRobinMaxRounds: undefined,
|
||||
gameSchedule: [],
|
||||
doubleElimination: {
|
||||
teamCount: (maxParticipants / 5) as 4 | 8,
|
||||
resetFinalEnabled:
|
||||
input.doubleEliminationResetFinalEnabled ??
|
||||
input.doubleElimination?.resetFinalEnabled ??
|
||||
false,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...patch,
|
||||
gameMode,
|
||||
doubleElimination: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
private stripMatchConfigInput<
|
||||
T extends Partial<Match> & DoubleEliminationConfigInput,
|
||||
>(input: T): Partial<Match> {
|
||||
const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input;
|
||||
return patch;
|
||||
}
|
||||
|
||||
private normalizeDoubleEliminationSeriesGameCount(gameCount: number): number {
|
||||
if (!Number.isInteger(gameCount) || gameCount < 1) {
|
||||
return DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT;
|
||||
}
|
||||
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
|
||||
}
|
||||
|
||||
private async loadDoubleEliminationMatch(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
let match = await MatchModel.findById(params.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') {
|
||||
throw new BadRequestException('Match is not double elimination.');
|
||||
}
|
||||
if (!match.doubleElimination?.bracketMatches?.length) {
|
||||
match = await this.tournamentCodeService.reserveForMatch(match);
|
||||
}
|
||||
if (!match.doubleElimination?.bracketMatches?.length) {
|
||||
throw new BadRequestException('Double elimination bracket is not ready.');
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
private async assertDoubleEliminationSeedsCanChange(
|
||||
match: MatchDocument,
|
||||
): Promise<void> {
|
||||
if (
|
||||
match.doubleElimination?.bracketMatches.some(
|
||||
(bracketMatch) => bracketMatch.state === 'completed',
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
'Seeds cannot be changed after a bracket match is completed.',
|
||||
);
|
||||
}
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const usedCode = await TournamentCodeModel.exists({
|
||||
_id: { $in: match.tournamentCodeIds ?? [] },
|
||||
$or: [{ state: 'used' }, { riotMatchId: { $exists: true } }],
|
||||
});
|
||||
if (usedCode) {
|
||||
throw new BadRequestException(
|
||||
'Seeds cannot be changed after a tournament code is used.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private requireDoubleEliminationBracketMatch(
|
||||
match: MatchDocument,
|
||||
bracketMatchId: string,
|
||||
) {
|
||||
const bracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.bracketMatchId === bracketMatchId,
|
||||
);
|
||||
if (!bracketMatch) throw new NotFoundException('Bracket match not found.');
|
||||
return bracketMatch;
|
||||
}
|
||||
|
||||
private async releaseReservedDoubleEliminationCodes(
|
||||
match: MatchDocument,
|
||||
bracketMatchIds?: string[],
|
||||
): Promise<void> {
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
if (ids.length === 0) return;
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const codes = await TournamentCodeModel.find({
|
||||
_id: { $in: ids },
|
||||
matchId: match._id,
|
||||
state: 'reserved',
|
||||
...(bracketMatchIds
|
||||
? { bracketMatchId: { $in: bracketMatchIds } }
|
||||
: { bracketMatchId: { $exists: true } }),
|
||||
}).exec();
|
||||
if (codes.length === 0) return;
|
||||
const releasedIds = codes.map((code) => code._id.toString());
|
||||
await TournamentCodeModel.updateMany(
|
||||
{ _id: { $in: codes.map((code) => code._id) } },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
match.tournamentCodeIds = ids.filter(
|
||||
(id) => !releasedIds.includes(id.toString()),
|
||||
);
|
||||
}
|
||||
|
||||
private async voidDoubleEliminationCode(
|
||||
match: MatchDocument,
|
||||
bracketMatchId: string,
|
||||
): Promise<void> {
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
await TournamentCodeModel.updateOne(
|
||||
{
|
||||
_id: { $in: match.tournamentCodeIds ?? [] },
|
||||
matchId: match._id,
|
||||
bracketMatchId,
|
||||
state: 'used',
|
||||
},
|
||||
{
|
||||
$set: { state: 'voided' },
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
private syncDoubleEliminationWinner(match: MatchDocument): void {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||
const firstTeamIndex = match.doubleElimination?.placements.firstTeamIndex;
|
||||
if (firstTeamIndex) {
|
||||
match.status = 'finished';
|
||||
match.result = match.result ?? {
|
||||
riotMatchIds: [],
|
||||
games: [],
|
||||
seriesResults: [],
|
||||
};
|
||||
match.result.winnerTeamIndex = firstTeamIndex;
|
||||
return;
|
||||
}
|
||||
if (match.status === 'finished') {
|
||||
match.status = 'in-progress';
|
||||
}
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async cancelJoin(
|
||||
params: CancelMatchJoinParams,
|
||||
): Promise<MatchDocument> {
|
||||
@@ -316,52 +731,57 @@ export class MatchService {
|
||||
const user = await UserModel.findById(params.userId);
|
||||
if (!user) throw new NotFoundException('User not found.');
|
||||
|
||||
const match = await MatchModel.findById(params.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!match.communityId.equals(user.communityId)) {
|
||||
throw new BadRequestException(
|
||||
'User and match belong to different communities.',
|
||||
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||
{
|
||||
_id: params.matchId,
|
||||
communityId: user.communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': user._id,
|
||||
},
|
||||
{ $pull: { participants: { userId: user._id } } },
|
||||
{ returnDocument: 'after', runValidators: true },
|
||||
);
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
if (updatedMatch) return updatedMatch;
|
||||
|
||||
const participantIndex = match.participants.findIndex((participant) =>
|
||||
participant.userId.equals(user._id),
|
||||
);
|
||||
if (participantIndex === -1) {
|
||||
throw new BadRequestException('User has not joined this match.');
|
||||
}
|
||||
|
||||
match.participants.splice(participantIndex, 1);
|
||||
await match.save();
|
||||
return match;
|
||||
return await this.throwCancelJoinFailure(MatchModel, params.matchId, user);
|
||||
}
|
||||
|
||||
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
|
||||
public async removeParticipant(
|
||||
params: RemoveParticipantParams,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||
{
|
||||
_id: params.matchId,
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': params.targetUserId,
|
||||
},
|
||||
{ $pull: { participants: { userId: params.targetUserId } } },
|
||||
{ returnDocument: 'after', runValidators: true },
|
||||
);
|
||||
if (updatedMatch) return updatedMatch;
|
||||
|
||||
const match = await this.loadRecruitingMatch(
|
||||
params.matchId,
|
||||
params.communityId,
|
||||
);
|
||||
const participantIndex = match.participants.findIndex((participant) =>
|
||||
participant.userId.equals(params.targetUserId),
|
||||
);
|
||||
if (participantIndex === -1) {
|
||||
if (
|
||||
!match.participants.some((participant) =>
|
||||
this.sameObjectId(participant.userId, params.targetUserId),
|
||||
)
|
||||
) {
|
||||
throw new NotFoundException('Participant not found.');
|
||||
}
|
||||
match.participants.splice(participantIndex, 1);
|
||||
await match.save();
|
||||
return match;
|
||||
throw new BadRequestException('Participant could not be removed.');
|
||||
}
|
||||
|
||||
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
|
||||
public async updateParticipantPositions(
|
||||
params: UpdateParticipantPositionsParams,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await this.loadRecruitingMatch(
|
||||
params.matchId,
|
||||
params.communityId,
|
||||
@@ -372,14 +792,36 @@ export class MatchService {
|
||||
if (!participant) {
|
||||
throw new NotFoundException('Participant not found.');
|
||||
}
|
||||
participant.preferredPositions = this.reorderPreferredPositions(
|
||||
const preferredPositions = this.reorderPreferredPositions(
|
||||
params.mainPosition,
|
||||
params.subPosition,
|
||||
participant.preferredPositions,
|
||||
);
|
||||
match.markModified('participants');
|
||||
await match.save();
|
||||
return match;
|
||||
|
||||
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||
{
|
||||
_id: params.matchId,
|
||||
communityId: params.communityId,
|
||||
status: 'recruiting',
|
||||
'participants.userId': params.targetUserId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
'participants.$[participant].preferredPositions': preferredPositions,
|
||||
},
|
||||
},
|
||||
{
|
||||
arrayFilters: [{ 'participant.userId': params.targetUserId }],
|
||||
returnDocument: 'after',
|
||||
runValidators: true,
|
||||
},
|
||||
);
|
||||
if (!updatedMatch) {
|
||||
throw new BadRequestException(
|
||||
'Participant positions could not be updated.',
|
||||
);
|
||||
}
|
||||
return updatedMatch;
|
||||
}
|
||||
|
||||
private async loadRecruitingMatch(
|
||||
@@ -398,6 +840,75 @@ export class MatchService {
|
||||
return match;
|
||||
}
|
||||
|
||||
private async throwJoinFailure(
|
||||
MatchModel: mongoose.Model<Match>,
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
user: {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
},
|
||||
): Promise<never> {
|
||||
const match = await MatchModel.findById(matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!this.sameObjectId(match.communityId, user.communityId)) {
|
||||
throw new BadRequestException(
|
||||
'User and match belong to different communities.',
|
||||
);
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
if (
|
||||
match.participants.some((participant) =>
|
||||
this.sameObjectId(participant.userId, user._id),
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException('User already joined this match.');
|
||||
}
|
||||
if (match.participants.length >= match.maxParticipants) {
|
||||
throw new BadRequestException('Match is full.');
|
||||
}
|
||||
throw new BadRequestException('Unable to join this match.');
|
||||
}
|
||||
|
||||
private async throwCancelJoinFailure(
|
||||
MatchModel: mongoose.Model<Match>,
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
user: {
|
||||
_id: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
},
|
||||
): Promise<never> {
|
||||
const match = await MatchModel.findById(matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (!this.sameObjectId(match.communityId, user.communityId)) {
|
||||
throw new BadRequestException(
|
||||
'User and match belong to different communities.',
|
||||
);
|
||||
}
|
||||
if (match.status !== 'recruiting') {
|
||||
throw new BadRequestException('Match is not recruiting.');
|
||||
}
|
||||
if (
|
||||
!match.participants.some((participant) =>
|
||||
this.sameObjectId(participant.userId, user._id),
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException('User has not joined this match.');
|
||||
}
|
||||
throw new BadRequestException('Unable to cancel match join.');
|
||||
}
|
||||
|
||||
private sameObjectId(
|
||||
left: mongoose.Types.ObjectId | { toString(): string },
|
||||
right: mongoose.Types.ObjectId | { toString(): string },
|
||||
): boolean {
|
||||
if (left instanceof mongoose.Types.ObjectId) {
|
||||
return left.equals(right.toString());
|
||||
}
|
||||
return left.toString() === right.toString();
|
||||
}
|
||||
|
||||
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
|
||||
private reorderPreferredPositions(
|
||||
mainPosition: Position,
|
||||
@@ -539,10 +1050,11 @@ export class MatchService {
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
||||
const current =
|
||||
bySeries.get(key) ??
|
||||
({
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import { RedisService } from '../global/redis/redis.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||
@@ -35,11 +36,18 @@ function makeScheduler() {
|
||||
};
|
||||
const redis = {
|
||||
getString: jest.fn().mockResolvedValue(null),
|
||||
setString: jest.fn().mockResolvedValue(undefined),
|
||||
setStringIfAbsent: jest.fn().mockResolvedValue(true),
|
||||
delete: jest.fn().mockResolvedValue(1),
|
||||
raw: jest.fn().mockReturnValue(rawClient),
|
||||
} as unknown as jest.Mocked<RedisService> & { raw: jest.Mock };
|
||||
const distributedLockService = {
|
||||
acquireLock: jest.fn().mockResolvedValue({
|
||||
lockKey: 'distributed-lock:riot-background-refresh:leader',
|
||||
lockOwnershipToken: 'lock-owner',
|
||||
lockExpirationDurationMilliseconds: 90_000,
|
||||
}),
|
||||
extendLockIfOwned: jest.fn().mockResolvedValue(true),
|
||||
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
|
||||
} as unknown as jest.Mocked<DistributedLockService>;
|
||||
const rateLimiter = {
|
||||
isRefreshWindowOpen: jest.fn().mockResolvedValue(true),
|
||||
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
||||
@@ -52,6 +60,7 @@ function makeScheduler() {
|
||||
} as unknown as jest.Mocked<StaleAccountRepository>;
|
||||
const scheduler = new BackgroundRefreshScheduler(
|
||||
redis,
|
||||
distributedLockService,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
@@ -60,6 +69,7 @@ function makeScheduler() {
|
||||
return {
|
||||
scheduler,
|
||||
redis,
|
||||
distributedLockService,
|
||||
rawClient,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
@@ -115,8 +125,9 @@ describe('BackgroundRefreshScheduler', () => {
|
||||
|
||||
it('does not query stale accounts when another leader holds the lock', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, redis, staleAccountRepository } = makeScheduler();
|
||||
redis.getString.mockResolvedValue('another-consumer');
|
||||
const { scheduler, distributedLockService, staleAccountRepository } =
|
||||
makeScheduler();
|
||||
distributedLockService.acquireLock.mockResolvedValueOnce(null);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
|
||||
@@ -9,13 +9,17 @@ import {
|
||||
RiotAccountEnrichmentService,
|
||||
} from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||
import {
|
||||
type DistributedLockOwnership,
|
||||
DistributedLockService,
|
||||
} from '../global/redis/distributed-lock.service';
|
||||
import { RedisService } from '../global/redis/redis.service';
|
||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||
import { StaleAccountRepository } from './stale-account.repository';
|
||||
|
||||
const TICK_INTERVAL_MS = 60_000;
|
||||
const LEADER_KEY = 'riot:bg-refresh:leader';
|
||||
const LEADER_TTL_SECONDS = 90;
|
||||
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
|
||||
const LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 90_000;
|
||||
const LEADER_RENEW_INTERVAL_MS = 30_000;
|
||||
const STALE_THRESHOLD_MS = 6 * 60 * 60 * 1000;
|
||||
const PER_TICK_CANDIDATE_LIMIT = 20;
|
||||
@@ -38,10 +42,11 @@ export class BackgroundRefreshScheduler
|
||||
private tickTimer?: NodeJS.Timeout;
|
||||
private leaderRenewTimer?: NodeJS.Timeout;
|
||||
private tickInProgress = false;
|
||||
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
private leaderLockOwnership: DistributedLockOwnership | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly redis: RedisService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
private readonly rateLimiter: RiotRateLimiterService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
private readonly staleAccountRepository: StaleAccountRepository,
|
||||
@@ -59,9 +64,20 @@ export class BackgroundRefreshScheduler
|
||||
void this.safeTick();
|
||||
}
|
||||
|
||||
public onModuleDestroy(): void {
|
||||
public async onModuleDestroy(): Promise<void> {
|
||||
if (this.tickTimer) clearInterval(this.tickTimer);
|
||||
if (this.leaderRenewTimer) clearInterval(this.leaderRenewTimer);
|
||||
if (!this.leaderLockOwnership) return;
|
||||
await this.distributedLockService
|
||||
.releaseLockIfOwned(this.leaderLockOwnership)
|
||||
.catch((err: unknown) => {
|
||||
this.logger.warn(
|
||||
`Background refresh leader release failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
});
|
||||
this.leaderLockOwnership = undefined;
|
||||
}
|
||||
|
||||
private async safeTick(): Promise<void> {
|
||||
@@ -158,33 +174,33 @@ export class BackgroundRefreshScheduler
|
||||
}
|
||||
|
||||
private async tryBecomeLeader(): Promise<boolean> {
|
||||
const current = await this.redis.getString(LEADER_KEY);
|
||||
if (current === this.consumer) {
|
||||
await this.redis.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
if (this.leaderLockOwnership) {
|
||||
const didExtendLeaderLock =
|
||||
await this.distributedLockService.extendLockIfOwned(
|
||||
this.leaderLockOwnership,
|
||||
);
|
||||
return true;
|
||||
if (didExtendLeaderLock) return true;
|
||||
this.leaderLockOwnership = undefined;
|
||||
}
|
||||
if (current) return false;
|
||||
|
||||
return this.redis.setStringIfAbsent(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
const leaderLockOwnership = await this.distributedLockService.acquireLock({
|
||||
lockKey: LEADER_LOCK_KEY,
|
||||
lockExpirationDurationMilliseconds:
|
||||
LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
});
|
||||
this.leaderLockOwnership = leaderLockOwnership ?? undefined;
|
||||
return Boolean(leaderLockOwnership);
|
||||
}
|
||||
|
||||
private async renewLeaderIfHeld(): Promise<void> {
|
||||
try {
|
||||
const current = await this.redis.getString(LEADER_KEY);
|
||||
if (current !== this.consumer) return;
|
||||
await this.redis.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
if (!this.leaderLockOwnership) return;
|
||||
const didExtendLeaderLock =
|
||||
await this.distributedLockService.extendLockIfOwned(
|
||||
this.leaderLockOwnership,
|
||||
);
|
||||
if (didExtendLeaderLock) return;
|
||||
this.leaderLockOwnership = undefined;
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Background refresh leader renew failed: ${
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import { RedisService } from '../global/redis/redis.service';
|
||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
@@ -19,6 +20,16 @@ function makeWorker() {
|
||||
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
|
||||
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<RedisService>;
|
||||
const distributedLockService = {
|
||||
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
|
||||
operation({
|
||||
lockKey: options.lockKey,
|
||||
lockOwnershipToken: 'lock-owner',
|
||||
lockExpirationDurationMilliseconds:
|
||||
options.lockExpirationDurationMilliseconds,
|
||||
}),
|
||||
),
|
||||
} as unknown as jest.Mocked<DistributedLockService>;
|
||||
const jobQueueService = {
|
||||
markProcessing: jest.fn().mockResolvedValue(undefined),
|
||||
markCompleted: jest.fn().mockResolvedValue({
|
||||
@@ -54,6 +65,7 @@ function makeWorker() {
|
||||
|
||||
const worker = new RiotJobWorkerService(
|
||||
redisService,
|
||||
distributedLockService,
|
||||
jobQueueService,
|
||||
recentMatchesService,
|
||||
connectionService,
|
||||
@@ -66,6 +78,7 @@ function makeWorker() {
|
||||
return {
|
||||
worker,
|
||||
redisService,
|
||||
distributedLockService,
|
||||
jobQueueService,
|
||||
recentMatchesService,
|
||||
connectionService,
|
||||
@@ -151,4 +164,37 @@ describe('RiotJobWorkerService', () => {
|
||||
redisService.deleteStreamEntries.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves a stream entry pending when another worker owns the job processing lock', async () => {
|
||||
const { worker, distributedLockService, redisService } = makeWorker();
|
||||
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
|
||||
const userId = new mongoose.Types.ObjectId().toString();
|
||||
const job: RiotRefreshSubJob = {
|
||||
jobId: 'job-1',
|
||||
parentJobId: 'parent-1',
|
||||
userId,
|
||||
puuid: 'puuid-1',
|
||||
region: 'asia',
|
||||
platform: 'kr',
|
||||
queueGroup: 'summoners-rift',
|
||||
queueIds: [420],
|
||||
requestedAt: Date.now(),
|
||||
priority: 'high',
|
||||
};
|
||||
|
||||
await (
|
||||
worker as unknown as {
|
||||
processEntry: (
|
||||
stream: string,
|
||||
entry: { id: string; message: Record<string, string> },
|
||||
) => Promise<void>;
|
||||
}
|
||||
).processEntry('riot:queue:high', {
|
||||
id: '1-0',
|
||||
message: { job: JSON.stringify(job) },
|
||||
});
|
||||
|
||||
expect(redisService.acknowledgeStream).not.toHaveBeenCalled();
|
||||
expect(redisService.deleteStreamEntries).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
DistributedLockOwnership,
|
||||
DistributedLockService,
|
||||
} from '../global/redis/distributed-lock.service';
|
||||
import { RedisService, StreamEntry } from '../global/redis/redis.service';
|
||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
||||
@@ -23,17 +27,24 @@ import {
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
|
||||
const LEADER_KEY = 'riot:worker:leader';
|
||||
const LEADER_TTL_SECONDS = 60;
|
||||
const RIOT_JOB_WORKER_LEADER_LOCK_KEY =
|
||||
'distributed-lock:riot-job-worker:leader';
|
||||
const RIOT_JOB_WORKER_LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 60_000;
|
||||
const RIOT_JOB_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 30 * 60_000;
|
||||
const RIOT_JOB_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 5 * 60_000;
|
||||
const STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS = 30 * 60_000;
|
||||
const STALE_PENDING_MESSAGE_CLAIM_COUNT = 1;
|
||||
|
||||
@Injectable()
|
||||
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(RiotJobWorkerService.name);
|
||||
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
private readonly consumerIdentifier = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
private leaderLockOwnership: DistributedLockOwnership | undefined;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly redisService: RedisService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
private readonly jobQueueService: RiotJobQueueService,
|
||||
private readonly recentMatchesService: RiotRecentMatchesService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
@@ -48,8 +59,19 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
void this.loop();
|
||||
}
|
||||
|
||||
public onModuleDestroy() {
|
||||
public async onModuleDestroy() {
|
||||
this.stopped = true;
|
||||
if (!this.leaderLockOwnership) return;
|
||||
await this.distributedLockService
|
||||
.releaseLockIfOwned(this.leaderLockOwnership)
|
||||
.catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Failed to release Riot job worker leader lock: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
this.leaderLockOwnership = undefined;
|
||||
}
|
||||
|
||||
private async loop(): Promise<void> {
|
||||
@@ -63,7 +85,9 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
await this.jobQueueService.promoteDueScheduledJobs();
|
||||
const entry =
|
||||
(await this.readOneStalePendingMessage(RIOT_JOB_HIGH_STREAM)) ??
|
||||
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
|
||||
(await this.readOneStalePendingMessage(RIOT_JOB_LOW_STREAM)) ??
|
||||
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
|
||||
if (!entry) continue;
|
||||
|
||||
@@ -89,6 +113,31 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
const didProcessJob = await this.distributedLockService.runWithRenewedLock(
|
||||
{
|
||||
lockKey: this.jobProcessingLockKey(job),
|
||||
lockExpirationDurationMilliseconds:
|
||||
RIOT_JOB_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
lockRenewalIntervalMilliseconds:
|
||||
RIOT_JOB_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
||||
},
|
||||
async () => {
|
||||
await this.processJob(job);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
if (!didProcessJob) {
|
||||
this.logger.debug(
|
||||
`Skipped Riot job ${job.jobId}; another worker still owns the processing lock.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.acknowledgeAndDelete(stream, entry.id);
|
||||
}
|
||||
|
||||
private async processJob(job: RiotJobPayload): Promise<void> {
|
||||
try {
|
||||
if (this.isTournamentResultJob(job)) {
|
||||
await this.tournamentResultService.processPollJob(job);
|
||||
@@ -136,8 +185,6 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
await this.acknowledgeAndDelete(stream, entry.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,7 +276,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
const result = await this.redisService.readGroup(
|
||||
stream,
|
||||
RIOT_JOB_GROUP,
|
||||
this.consumer,
|
||||
this.consumerIdentifier,
|
||||
'>',
|
||||
{ count: 1, blockMs },
|
||||
);
|
||||
@@ -237,6 +284,21 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
return message ? { stream, message } : null;
|
||||
}
|
||||
|
||||
private async readOneStalePendingMessage(
|
||||
stream: string,
|
||||
): Promise<{ stream: string; message: StreamEntry } | null> {
|
||||
const result = await this.redisService.claimStalePendingStreamMessages({
|
||||
key: stream,
|
||||
group: RIOT_JOB_GROUP,
|
||||
consumer: this.consumerIdentifier,
|
||||
stalePendingMessageMinimumIdleMilliseconds:
|
||||
STALE_PENDING_MESSAGE_MINIMUM_IDLE_MILLISECONDS,
|
||||
count: STALE_PENDING_MESSAGE_CLAIM_COUNT,
|
||||
});
|
||||
const message = result.messages[0];
|
||||
return message ? { stream, message } : null;
|
||||
}
|
||||
|
||||
private async ensureConsumerGroups(): Promise<void> {
|
||||
await Promise.all(
|
||||
[RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => {
|
||||
@@ -252,21 +314,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
}
|
||||
|
||||
private async tryBecomeLeader(): Promise<boolean> {
|
||||
const current = await this.redisService.getString(LEADER_KEY);
|
||||
if (current === this.consumer) {
|
||||
await this.redisService.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
if (this.leaderLockOwnership) {
|
||||
const didExtendLeaderLock =
|
||||
await this.distributedLockService.extendLockIfOwned(
|
||||
this.leaderLockOwnership,
|
||||
);
|
||||
return true;
|
||||
if (didExtendLeaderLock) return true;
|
||||
this.leaderLockOwnership = undefined;
|
||||
}
|
||||
if (current) return false;
|
||||
return this.redisService.setStringIfAbsent(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
|
||||
const leaderLockOwnership = await this.distributedLockService.acquireLock({
|
||||
lockKey: RIOT_JOB_WORKER_LEADER_LOCK_KEY,
|
||||
lockExpirationDurationMilliseconds:
|
||||
RIOT_JOB_WORKER_LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
});
|
||||
this.leaderLockOwnership = leaderLockOwnership ?? undefined;
|
||||
return Boolean(leaderLockOwnership);
|
||||
}
|
||||
|
||||
private jobProcessingLockKey(job: RiotJobPayload): string {
|
||||
return `distributed-lock:riot-job-worker:job:${job.kind ?? 'refresh-account'}:${job.jobId}`;
|
||||
}
|
||||
|
||||
private sleep(ms: number): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { RedisService } from '../global/redis/redis.service';
|
||||
import { RiotDdragonService } from './riot-ddragon.service';
|
||||
|
||||
function jsonResponse(payload: unknown): Response {
|
||||
return {
|
||||
ok: true,
|
||||
json: jest.fn().mockResolvedValue(payload),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
function makeRedisService() {
|
||||
return {
|
||||
getJson: jest.fn().mockResolvedValue(null),
|
||||
setJson: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<RedisService>;
|
||||
}
|
||||
|
||||
describe('RiotDdragonService', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('includes localized item, spell, and rune metadata in the manifest', async () => {
|
||||
const fetchMock = jest.fn(async (url: string) => {
|
||||
if (url.endsWith('/api/versions.json')) {
|
||||
return jsonResponse(['15.24.1']);
|
||||
}
|
||||
if (url.endsWith('/champion.json')) {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
Aatrox: { key: '266', id: 'Aatrox', name: '아트록스' },
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url.endsWith('/summoner.json')) {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
SummonerFlash: {
|
||||
key: '4',
|
||||
id: 'SummonerFlash',
|
||||
name: '점멸',
|
||||
description: '커서 방향으로 순간이동합니다.',
|
||||
tooltip: '<span>커서 방향으로 순간이동합니다.</span>',
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url.endsWith('/runesReforged.json')) {
|
||||
return jsonResponse([
|
||||
{
|
||||
id: 8000,
|
||||
key: 'Precision',
|
||||
icon: 'perk-images/Styles/7201_Precision.png',
|
||||
name: '정밀',
|
||||
slots: [
|
||||
{
|
||||
runes: [
|
||||
{
|
||||
id: 8005,
|
||||
key: 'PressTheAttack',
|
||||
icon: 'perk-images/Styles/Precision/PressTheAttack/PressTheAttack.png',
|
||||
name: '집중 공격',
|
||||
shortDesc: '연속 공격 시 추가 피해',
|
||||
longDesc:
|
||||
'<lol-uikit-tooltipped-keyword>기본 공격</lol-uikit-tooltipped-keyword>으로 적을 약화시킵니다.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (url.endsWith('/item.json')) {
|
||||
return jsonResponse({
|
||||
data: {
|
||||
'1055': {
|
||||
name: '도란의 검',
|
||||
description:
|
||||
'<mainText><stats>공격력 <attention>10</attention></stats></mainText>',
|
||||
plaintext: '공격력과 체력을 올려줍니다.',
|
||||
gold: {
|
||||
base: 450,
|
||||
total: 450,
|
||||
sell: 180,
|
||||
purchasable: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
throw new Error(`Unexpected URL: ${url}`);
|
||||
});
|
||||
jest.spyOn(global, 'fetch').mockImplementation(fetchMock as typeof fetch);
|
||||
|
||||
const redis = makeRedisService();
|
||||
const service = new RiotDdragonService(redis);
|
||||
|
||||
await expect(service.getManifest('ko_KR')).resolves.toMatchObject({
|
||||
version: '15.24.1',
|
||||
locale: 'ko_KR',
|
||||
summonerSpells: {
|
||||
'4': {
|
||||
key: 'SummonerFlash',
|
||||
name: '점멸',
|
||||
description: '커서 방향으로 순간이동합니다.',
|
||||
tooltip: '<span>커서 방향으로 순간이동합니다.</span>',
|
||||
},
|
||||
},
|
||||
runesReforged: [
|
||||
{
|
||||
id: 8000,
|
||||
name: '정밀',
|
||||
slots: [
|
||||
{
|
||||
runes: [
|
||||
{
|
||||
id: 8005,
|
||||
name: '집중 공격',
|
||||
shortDesc: '연속 공격 시 추가 피해',
|
||||
longDesc:
|
||||
'<lol-uikit-tooltipped-keyword>기본 공격</lol-uikit-tooltipped-keyword>으로 적을 약화시킵니다.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
items: {
|
||||
'1055': {
|
||||
name: '도란의 검',
|
||||
description:
|
||||
'<mainText><stats>공격력 <attention>10</attention></stats></mainText>',
|
||||
plaintext: '공격력과 체력을 올려줍니다.',
|
||||
gold: {
|
||||
base: 450,
|
||||
total: 450,
|
||||
sell: 180,
|
||||
purchasable: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/15.24.1/data/ko_KR/item.json'),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(redis.setJson).toHaveBeenCalledWith(
|
||||
'ddragon:manifest:v5:ko_KR',
|
||||
expect.objectContaining({
|
||||
summonerSpells: expect.objectContaining({
|
||||
'4': expect.objectContaining({ description: '커서 방향으로 순간이동합니다.' }),
|
||||
}),
|
||||
runesReforged: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
slots: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
runes: expect.arrayContaining([
|
||||
expect.objectContaining({ longDesc: expect.stringContaining('기본 공격') }),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
items: expect.objectContaining({
|
||||
'1055': expect.objectContaining({ name: '도란의 검' }),
|
||||
}),
|
||||
}),
|
||||
86_400,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com';
|
||||
const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
|
||||
const DEFAULT_LOCALE = 'ko_KR';
|
||||
const CACHE_TTL_SECONDS = 24 * 60 * 60;
|
||||
const CACHE_VERSION = 'v3';
|
||||
const CACHE_VERSION = 'v5';
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
export interface DdragonChampionEntry {
|
||||
@@ -16,6 +16,8 @@ export interface DdragonChampionEntry {
|
||||
export interface DdragonSummonerSpellEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
description: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneEntry {
|
||||
@@ -23,12 +25,26 @@ export interface DdragonRuneEntry {
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
shortDesc: string;
|
||||
longDesc: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
||||
slots: Array<{ runes: DdragonRuneEntry[] }>;
|
||||
}
|
||||
|
||||
export interface DdragonItemEntry {
|
||||
name: string;
|
||||
description: string;
|
||||
plaintext: string;
|
||||
gold: {
|
||||
base: number;
|
||||
total: number;
|
||||
sell: number;
|
||||
purchasable: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
@@ -36,6 +52,7 @@ export interface DdragonManifest {
|
||||
champions: Record<string, DdragonChampionEntry>;
|
||||
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
||||
runesReforged: DdragonRuneStyleEntry[];
|
||||
items: Record<string, DdragonItemEntry>;
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
@@ -53,6 +70,8 @@ interface SummonerSpellDataEntry {
|
||||
key: string;
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
tooltip?: string;
|
||||
}
|
||||
|
||||
interface SummonerSpellDataResponse {
|
||||
@@ -64,12 +83,30 @@ interface RuneDataEntry {
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
shortDesc?: string;
|
||||
longDesc?: string;
|
||||
}
|
||||
|
||||
interface RuneStyleDataEntry extends RuneDataEntry {
|
||||
slots?: Array<{ runes?: RuneDataEntry[] }>;
|
||||
}
|
||||
|
||||
interface ItemDataEntry {
|
||||
name?: string;
|
||||
description?: string;
|
||||
plaintext?: string;
|
||||
gold?: {
|
||||
base?: number;
|
||||
total?: number;
|
||||
sell?: number;
|
||||
purchasable?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
interface ItemDataResponse {
|
||||
data: Record<string, ItemDataEntry>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotDdragonService {
|
||||
private readonly logger = new Logger(RiotDdragonService.name);
|
||||
@@ -102,10 +139,11 @@ export class RiotDdragonService {
|
||||
|
||||
private async buildManifest(locale: string): Promise<DdragonManifest> {
|
||||
const version = await this.fetchLatestVersion();
|
||||
const [champions, summonerSpells, runesReforged] = await Promise.all([
|
||||
const [champions, summonerSpells, runesReforged, items] = await Promise.all([
|
||||
this.fetchChampionMap(version, locale),
|
||||
this.fetchSummonerSpellMap(version, locale),
|
||||
this.fetchRuneStyles(version, locale),
|
||||
this.fetchItemMap(version, locale),
|
||||
]);
|
||||
return {
|
||||
version,
|
||||
@@ -114,6 +152,7 @@ export class RiotDdragonService {
|
||||
champions,
|
||||
summonerSpells,
|
||||
runesReforged,
|
||||
items,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -164,6 +203,9 @@ export class RiotDdragonService {
|
||||
map[entry.key] = {
|
||||
key: entry.id,
|
||||
name: typeof entry.name === 'string' ? entry.name : entry.id,
|
||||
description:
|
||||
typeof entry.description === 'string' ? entry.description : '',
|
||||
tooltip: typeof entry.tooltip === 'string' ? entry.tooltip : '',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -187,6 +229,9 @@ export class RiotDdragonService {
|
||||
key: style.key,
|
||||
icon: style.icon,
|
||||
name: style.name,
|
||||
shortDesc:
|
||||
typeof style.shortDesc === 'string' ? style.shortDesc : '',
|
||||
longDesc: typeof style.longDesc === 'string' ? style.longDesc : '',
|
||||
slots: (style.slots ?? []).map((slot) => ({
|
||||
runes: (slot.runes ?? [])
|
||||
.filter((rune): rune is RuneDataEntry => isRuneEntry(rune))
|
||||
@@ -195,11 +240,46 @@ export class RiotDdragonService {
|
||||
key: rune.key,
|
||||
icon: rune.icon,
|
||||
name: rune.name,
|
||||
shortDesc:
|
||||
typeof rune.shortDesc === 'string' ? rune.shortDesc : '',
|
||||
longDesc: typeof rune.longDesc === 'string' ? rune.longDesc : '',
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchItemMap(
|
||||
version: string,
|
||||
locale: string,
|
||||
): Promise<Record<string, DdragonItemEntry>> {
|
||||
const url = `${DDRAGON_CDN}/${version}/data/${locale}/item.json`;
|
||||
const payload = await this.fetchJson<ItemDataResponse>(url);
|
||||
if (!payload || typeof payload !== 'object' || !payload.data) {
|
||||
throw new Error(`ddragon item.json response is malformed (${url}).`);
|
||||
}
|
||||
|
||||
const map: Record<string, DdragonItemEntry> = {};
|
||||
for (const [itemId, entry] of Object.entries(payload.data)) {
|
||||
if (!/^\d+$/.test(itemId) || typeof entry?.name !== 'string') {
|
||||
continue;
|
||||
}
|
||||
|
||||
map[itemId] = {
|
||||
name: entry.name,
|
||||
description:
|
||||
typeof entry.description === 'string' ? entry.description : '',
|
||||
plaintext: typeof entry.plaintext === 'string' ? entry.plaintext : '',
|
||||
gold: {
|
||||
base: numberOrZero(entry.gold?.base),
|
||||
total: numberOrZero(entry.gold?.total),
|
||||
sell: numberOrZero(entry.gold?.sell),
|
||||
purchasable: entry.gold?.purchasable ?? false,
|
||||
},
|
||||
};
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private async fetchJson<T>(url: string): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
@@ -245,6 +325,10 @@ function isRuneEntry(value: unknown): value is RuneDataEntry {
|
||||
);
|
||||
}
|
||||
|
||||
function numberOrZero(value: unknown): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
function manifestCacheKey(locale: string): string {
|
||||
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
|
||||
}
|
||||
@@ -4,14 +4,14 @@ import type {
|
||||
RiotMatch as StoredRiotMatch,
|
||||
} from '../global/database/schema';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { RedisService } from '../global/redis/redis.service';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import type { RiotRegionalRoute } from './riot.types';
|
||||
import { RiotMatchService } from './riot-match.service';
|
||||
|
||||
export const RIOT_RECENT_MATCH_LIMIT = 20;
|
||||
export const RIOT_SOLO_QUEUE_ID = 420;
|
||||
|
||||
const MATCH_ENRICHMENT_LOCK_TTL_SECONDS = 60;
|
||||
const MATCH_ENRICHMENT_LOCK_EXPIRATION_DURATION_MILLISECONDS = 60_000;
|
||||
const MATCH_DETAIL_CONCURRENCY = 2;
|
||||
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
|
||||
|
||||
@@ -22,7 +22,7 @@ export class RiotRecentMatchesService {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly matchService: RiotMatchService,
|
||||
private readonly redisService: RedisService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {}
|
||||
|
||||
public async syncRecentMatches(params: {
|
||||
@@ -34,39 +34,44 @@ export class RiotRecentMatchesService {
|
||||
const region = params.region ?? DEFAULT_REGION;
|
||||
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
|
||||
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
|
||||
const lockKey = `riot:enrich:matches:${params.puuid}`;
|
||||
const lockValue = `${process.pid}:${Date.now()}`;
|
||||
|
||||
const acquired = await this.redisService.setStringIfAbsent(
|
||||
lockKey,
|
||||
lockValue,
|
||||
MATCH_ENRICHMENT_LOCK_TTL_SECONDS,
|
||||
);
|
||||
if (!acquired) {
|
||||
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
||||
}
|
||||
|
||||
try {
|
||||
const matchIds = await this.matchService.getMatchIdsByPuuid(params.puuid, {
|
||||
const result = await this.distributedLockService.runWithLock(
|
||||
{
|
||||
lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`,
|
||||
lockExpirationDurationMilliseconds:
|
||||
MATCH_ENRICHMENT_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
},
|
||||
async () => {
|
||||
const matchIds = await this.matchService.getMatchIdsByPuuid(
|
||||
params.puuid,
|
||||
{
|
||||
region,
|
||||
queue: queueId,
|
||||
count: limit,
|
||||
});
|
||||
},
|
||||
);
|
||||
if (matchIds.length === 0) {
|
||||
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
||||
}
|
||||
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const RiotMatchModel =
|
||||
await this.connectionService.getModel('riotMatch');
|
||||
const existingMatches = await RiotMatchModel.find({
|
||||
matchId: { $in: matchIds },
|
||||
})
|
||||
.select({ matchId: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
const existingMatchIds = new Set(existingMatches.map((match) => match.matchId));
|
||||
const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId));
|
||||
const existingMatchIds = new Set(
|
||||
existingMatches.map((match) => match.matchId),
|
||||
);
|
||||
const missingMatchIds = matchIds.filter(
|
||||
(matchId) => !existingMatchIds.has(matchId),
|
||||
);
|
||||
|
||||
await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => {
|
||||
await runWithConcurrency(
|
||||
missingMatchIds,
|
||||
MATCH_DETAIL_CONCURRENCY,
|
||||
async (matchId) => {
|
||||
try {
|
||||
const dto = await this.matchService.getMatch(matchId, { region });
|
||||
if (dto.info.queueId !== queueId) {
|
||||
@@ -99,18 +104,14 @@ export class RiotRecentMatchesService {
|
||||
}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
||||
} finally {
|
||||
await this.redisService.delete(lockKey).catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Failed to release recent matches lock for ${params.puuid}: ${
|
||||
(error as Error)?.message ?? error
|
||||
}`,
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return result ?? this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
||||
}
|
||||
|
||||
public async ensureFreshForQueue(params: {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuctionRedisModule } from '../auction/redis/auction-redis.module';
|
||||
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
||||
import { TournamentCodeController } from './tournament-code.controller';
|
||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
|
||||
@@ -7,6 +9,7 @@ import { TournamentCodeService } from './tournament-code.service';
|
||||
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
|
||||
|
||||
@Module({
|
||||
imports: [TournamentResultModule, AuctionRedisModule],
|
||||
controllers: [TournamentCodeController, TournamentCodeReplacementController],
|
||||
providers: [
|
||||
TournamentCodeService,
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import { TournamentCodeScheduler } from './tournament-code.scheduler';
|
||||
|
||||
describe('TournamentCodeScheduler', () => {
|
||||
function createScheduler(params?: {
|
||||
attachedMatches?: unknown[];
|
||||
scheduleInitialPoll?: jest.Mock;
|
||||
}) {
|
||||
const tournamentCodeService = {
|
||||
attachPendingMatchDocuments: jest
|
||||
.fn()
|
||||
.mockResolvedValue(params?.attachedMatches ?? []),
|
||||
markExpired: jest.fn().mockResolvedValue(0),
|
||||
};
|
||||
const autoProvisionService = {
|
||||
ensurePool: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const tournamentResultService = {
|
||||
scheduleInitialPoll:
|
||||
params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const distributedLockService = {
|
||||
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
|
||||
operation({
|
||||
lockKey: options.lockKey,
|
||||
lockOwnershipToken: 'lock-owner',
|
||||
lockExpirationDurationMilliseconds:
|
||||
options.lockExpirationDurationMilliseconds,
|
||||
}),
|
||||
),
|
||||
} as unknown as jest.Mocked<DistributedLockService>;
|
||||
const scheduler = new TournamentCodeScheduler(
|
||||
tournamentCodeService as never,
|
||||
autoProvisionService as never,
|
||||
tournamentResultService as never,
|
||||
distributedLockService as never,
|
||||
) as unknown as { attachPending(): Promise<void> };
|
||||
|
||||
return {
|
||||
scheduler,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
distributedLockService,
|
||||
};
|
||||
}
|
||||
|
||||
it('starts result polling after attaching delayed tournament codes', async () => {
|
||||
const attachedMatches = [{ _id: 'match-1' }, { _id: 'match-2' }];
|
||||
const { scheduler, tournamentResultService } = createScheduler({
|
||||
attachedMatches,
|
||||
});
|
||||
|
||||
await scheduler.attachPending();
|
||||
|
||||
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledTimes(
|
||||
2,
|
||||
);
|
||||
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
attachedMatches[0],
|
||||
);
|
||||
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
attachedMatches[1],
|
||||
);
|
||||
});
|
||||
|
||||
it('does not schedule result polling when no match received new codes', async () => {
|
||||
const { scheduler, tournamentResultService } = createScheduler();
|
||||
|
||||
await scheduler.attachPending();
|
||||
|
||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not attach pending tournament codes when another instance owns the scheduler lock', async () => {
|
||||
const { scheduler, tournamentCodeService, distributedLockService } =
|
||||
createScheduler();
|
||||
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
|
||||
|
||||
await scheduler.attachPending();
|
||||
|
||||
expect(
|
||||
tournamentCodeService.attachPendingMatchDocuments,
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,18 @@
|
||||
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
|
||||
const ATTACH_PENDING_CODES_TO_MATCHES_LOCK_KEY =
|
||||
'distributed-lock:tournament-code:scheduler:attach-pending-codes-to-matches';
|
||||
const MARK_EXPIRED_ASSIGNED_CODES_LOCK_KEY =
|
||||
'distributed-lock:tournament-code:scheduler:mark-expired-assigned-codes';
|
||||
const ENSURE_VENDOR_CODE_POOL_LOCK_KEY =
|
||||
'distributed-lock:tournament-code:scheduler:ensure-vendor-code-pool';
|
||||
const SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 10 * 60_000;
|
||||
const SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 2 * 60_000;
|
||||
|
||||
@Injectable()
|
||||
export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(TournamentCodeScheduler.name);
|
||||
@@ -12,6 +23,8 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
constructor(
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {}
|
||||
|
||||
public onModuleInit() {
|
||||
@@ -45,10 +58,27 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
private async attachPending() {
|
||||
try {
|
||||
const touched = await this.tournamentCodeService.attachPendingMatches();
|
||||
if (touched > 0) {
|
||||
this.logger.debug(`Attached tournament codes for ${touched} matches.`);
|
||||
await this.distributedLockService.runWithRenewedLock(
|
||||
{
|
||||
lockKey: ATTACH_PENDING_CODES_TO_MATCHES_LOCK_KEY,
|
||||
lockExpirationDurationMilliseconds:
|
||||
SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
lockRenewalIntervalMilliseconds:
|
||||
SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
||||
},
|
||||
async () => {
|
||||
const matches =
|
||||
await this.tournamentCodeService.attachPendingMatchDocuments();
|
||||
if (matches.length > 0) {
|
||||
this.logger.debug(
|
||||
`Attached tournament codes for ${matches.length} matches.`,
|
||||
);
|
||||
for (const match of matches) {
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Failed to attach pending tournament codes: ${
|
||||
@@ -60,7 +90,18 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
private async markExpired() {
|
||||
try {
|
||||
await this.distributedLockService.runWithRenewedLock(
|
||||
{
|
||||
lockKey: MARK_EXPIRED_ASSIGNED_CODES_LOCK_KEY,
|
||||
lockExpirationDurationMilliseconds:
|
||||
SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
lockRenewalIntervalMilliseconds:
|
||||
SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
||||
},
|
||||
async () => {
|
||||
await this.tournamentCodeService.markExpired();
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Failed to mark expired tournament codes: ${
|
||||
@@ -72,7 +113,18 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||
|
||||
private async ensureVendorPool() {
|
||||
try {
|
||||
await this.distributedLockService.runWithRenewedLock(
|
||||
{
|
||||
lockKey: ENSURE_VENDOR_CODE_POOL_LOCK_KEY,
|
||||
lockExpirationDurationMilliseconds:
|
||||
SCHEDULER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
lockRenewalIntervalMilliseconds:
|
||||
SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
||||
},
|
||||
async () => {
|
||||
await this.autoProvisionService.ensurePool();
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Failed to auto-provision tournament codes: ${
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
} from '../global/database/schema';
|
||||
import mongoose from 'mongoose';
|
||||
import { TournamentCodeService } from './tournament-code.service';
|
||||
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
|
||||
|
||||
type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||
resolveRequiredSlots(match: MatchDocument): number;
|
||||
@@ -20,18 +21,36 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
|
||||
};
|
||||
|
||||
function createAuctionRedisService() {
|
||||
return {
|
||||
acquireTokenLock: jest.fn().mockResolvedValue(true),
|
||||
releaseTokenLock: jest.fn().mockResolvedValue(true),
|
||||
};
|
||||
}
|
||||
|
||||
function createSession() {
|
||||
return {
|
||||
startTransaction: jest.fn(),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
function createService() {
|
||||
return new TournamentCodeService(
|
||||
{} as never,
|
||||
createAuctionRedisService() as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
}
|
||||
|
||||
interface MatchOverrides {
|
||||
gameCount?: number;
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
|
||||
roundRobinMaxRounds?: number;
|
||||
participants?: Array<{ excluded?: boolean }>;
|
||||
teams?: Array<{ teamIndex: number }>;
|
||||
doubleElimination?: MatchDocument['doubleElimination'];
|
||||
gameSchedule?: Array<{
|
||||
gameNumber: number;
|
||||
roundNumber?: number;
|
||||
@@ -51,6 +70,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||
tournamentCodeIds: [],
|
||||
gameSchedule: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
markModified: jest.fn(),
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
@@ -206,6 +226,100 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
expect(pair.gameSchedule).toEqual([]);
|
||||
});
|
||||
|
||||
it('creates a double-elimination bracket from built teams', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({
|
||||
gameMode: 'double-elimination',
|
||||
gameCount: 3,
|
||||
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||
teamIndex: index + 1,
|
||||
})),
|
||||
doubleElimination: {
|
||||
teamCount: 4,
|
||||
resetFinalEnabled: true,
|
||||
resetFinalCreated: false,
|
||||
seeds: [],
|
||||
bracketMatches: [],
|
||||
placements: {},
|
||||
events: [],
|
||||
},
|
||||
});
|
||||
|
||||
service.ensureGameSchedule(match);
|
||||
|
||||
expect(match.doubleElimination?.seeds).toHaveLength(4);
|
||||
expect(match.doubleElimination?.bracketMatches).toHaveLength(6);
|
||||
expect(
|
||||
match.doubleElimination?.bracketMatches.filter(
|
||||
(bracketMatch) => bracketMatch.state === 'ready',
|
||||
),
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
match.doubleElimination?.bracketMatches.find(
|
||||
(bracketMatch) => bracketMatch.bracketMatchId === 'WB_R1_M1',
|
||||
),
|
||||
).toMatchObject({ gameCount: 3, requiredWins: 2 });
|
||||
});
|
||||
|
||||
it('expands double-elimination winner bracket series into code slots', async () => {
|
||||
const TournamentCodeModel = {
|
||||
find: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue([]),
|
||||
}),
|
||||
};
|
||||
const service = new TournamentCodeService(
|
||||
{ getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never,
|
||||
createAuctionRedisService() as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
const match = createMatch({
|
||||
gameMode: 'double-elimination',
|
||||
gameCount: 3,
|
||||
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||
teamIndex: index + 1,
|
||||
})),
|
||||
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
}),
|
||||
});
|
||||
|
||||
const slots = await service.buildSlots(match);
|
||||
|
||||
expect(slots.slice(0, 6)).toEqual([
|
||||
expect.objectContaining({
|
||||
gameNumber: 1,
|
||||
seriesGameNumber: 1,
|
||||
seriesGameCount: 3,
|
||||
seriesRequiredWins: 2,
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 2,
|
||||
seriesGameNumber: 2,
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 3,
|
||||
seriesGameNumber: 3,
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 4,
|
||||
seriesGameNumber: 1,
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 5,
|
||||
seriesGameNumber: 2,
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
gameNumber: 6,
|
||||
seriesGameNumber: 3,
|
||||
bracketMatchId: 'WB_R1_M2',
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
||||
const service = createService();
|
||||
const roundRobin = createMatch({
|
||||
@@ -226,8 +340,10 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
(game) => game.roundNumber === roundNumber,
|
||||
);
|
||||
expect(round).toHaveLength(4);
|
||||
expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size)
|
||||
.toBe(8);
|
||||
expect(
|
||||
new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))
|
||||
.size,
|
||||
).toBe(8);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -264,6 +380,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
};
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
createAuctionRedisService() as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
|
||||
const slots = await service.buildSlots(
|
||||
@@ -323,6 +440,39 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
||||
});
|
||||
|
||||
describe('TournamentCodeService bulk upload', () => {
|
||||
it('defines slot and riot match indexes for multi-instance safety', () => {
|
||||
const indexes = TournamentCodeSchema.indexes();
|
||||
|
||||
expect(indexes).toContainEqual([
|
||||
{ matchId: 1, gameNumber: 1 },
|
||||
expect.objectContaining({
|
||||
unique: true,
|
||||
partialFilterExpression: {
|
||||
matchId: { $exists: true },
|
||||
gameNumber: { $exists: true },
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
expect(indexes).toContainEqual([
|
||||
{ matchId: 1, bracketMatchId: 1 },
|
||||
expect.objectContaining({
|
||||
partialFilterExpression: {
|
||||
matchId: { $exists: true },
|
||||
bracketMatchId: { $exists: true },
|
||||
state: { $in: ['reserved', 'used'] },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
expect(indexes).toContainEqual([
|
||||
{ riotMatchId: 1 },
|
||||
expect.objectContaining({
|
||||
unique: true,
|
||||
partialFilterExpression: { riotMatchId: { $type: 'string' } },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves tournament code casing at the schema layer', async () => {
|
||||
const connection = mongoose.createConnection();
|
||||
try {
|
||||
@@ -360,6 +510,7 @@ describe('TournamentCodeService bulk upload', () => {
|
||||
};
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
createAuctionRedisService() as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
service.attachPendingMatches = jest.fn().mockResolvedValue(0);
|
||||
|
||||
@@ -393,7 +544,10 @@ describe('TournamentCodeService pool stats', () => {
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ countDocuments }),
|
||||
};
|
||||
const service = new TournamentCodeService(connectionService as never);
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
createAuctionRedisService() as never,
|
||||
);
|
||||
|
||||
await expect(service.countUsableAvailable()).resolves.toBe(12);
|
||||
expect(countDocuments).toHaveBeenCalledWith({
|
||||
@@ -405,6 +559,86 @@ describe('TournamentCodeService pool stats', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentCodeService pending match attachment', () => {
|
||||
it('does not attach tournament codes before match teams are built', async () => {
|
||||
const invalidMatch = {
|
||||
...createMatch({
|
||||
status: 'team-built',
|
||||
teams: [],
|
||||
tournamentCodeIds: [],
|
||||
} as unknown as MatchOverrides),
|
||||
isModified: jest.fn().mockReturnValue(false),
|
||||
};
|
||||
const validMatch = {
|
||||
...createMatch({
|
||||
status: 'team-built',
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
members: [{ userId: new mongoose.Types.ObjectId() }],
|
||||
},
|
||||
{
|
||||
teamIndex: 2,
|
||||
members: [{ userId: new mongoose.Types.ObjectId() }],
|
||||
},
|
||||
],
|
||||
tournamentCodeIds: [],
|
||||
} as unknown as MatchOverrides),
|
||||
isModified: jest.fn().mockReturnValue(false),
|
||||
};
|
||||
const codeId = new mongoose.Types.ObjectId();
|
||||
const MatchModel = {
|
||||
find: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue([invalidMatch, validMatch]),
|
||||
}),
|
||||
findById: jest.fn().mockResolvedValue(validMatch),
|
||||
};
|
||||
const TournamentCodeModel = {
|
||||
findOneAndUpdate: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ _id: codeId }),
|
||||
}),
|
||||
};
|
||||
const session = createSession();
|
||||
const connectionService = {
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn().mockImplementation((modelName: string) => {
|
||||
if (modelName === 'match') return Promise.resolve(MatchModel);
|
||||
if (modelName === 'tournamentCode') {
|
||||
return Promise.resolve(TournamentCodeModel);
|
||||
}
|
||||
throw new Error(`Unexpected model: ${modelName}`);
|
||||
}),
|
||||
};
|
||||
const auctionRedisService = createAuctionRedisService();
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
auctionRedisService as never,
|
||||
);
|
||||
|
||||
const matches = await service.attachPendingMatchDocuments();
|
||||
|
||||
expect(matches).toEqual([validMatch]);
|
||||
expect(MatchModel.findById).toHaveBeenCalledTimes(1);
|
||||
expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id);
|
||||
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
|
||||
`tournament-code:match:${validMatch._id.toString()}:lock`,
|
||||
expect.any(String),
|
||||
expect.any(Number),
|
||||
);
|
||||
expect(session.startTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith(
|
||||
`tournament-code:match:${validMatch._id.toString()}:lock`,
|
||||
expect.any(String),
|
||||
);
|
||||
expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([
|
||||
codeId.toString(),
|
||||
]);
|
||||
expect(invalidMatch.tournamentCodeIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentCodeService code replacement', () => {
|
||||
function queryResult<T>(value: T) {
|
||||
return { exec: jest.fn().mockResolvedValue(value) };
|
||||
@@ -473,8 +707,11 @@ describe('TournamentCodeService code replacement', () => {
|
||||
const TournamentCodeModel = {
|
||||
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
|
||||
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
|
||||
updateOne: jest.fn().mockReturnValue(queryResult({ modifiedCount: 1 })),
|
||||
};
|
||||
const session = createSession();
|
||||
const connectionService = {
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn().mockImplementation((modelName: string) => {
|
||||
if (modelName === 'match') return Promise.resolve(MatchModel);
|
||||
if (modelName === 'tournamentCode') {
|
||||
@@ -483,8 +720,10 @@ describe('TournamentCodeService code replacement', () => {
|
||||
throw new Error(`Unexpected model: ${modelName}`);
|
||||
}),
|
||||
};
|
||||
const auctionRedisService = createAuctionRedisService();
|
||||
const service = new TournamentCodeService(
|
||||
connectionService as never,
|
||||
auctionRedisService as never,
|
||||
) as unknown as TournamentCodeServiceInternals;
|
||||
|
||||
return {
|
||||
@@ -495,6 +734,8 @@ describe('TournamentCodeService code replacement', () => {
|
||||
replacementCode,
|
||||
MatchModel,
|
||||
TournamentCodeModel,
|
||||
auctionRedisService,
|
||||
session,
|
||||
service,
|
||||
};
|
||||
}
|
||||
@@ -508,6 +749,8 @@ describe('TournamentCodeService code replacement', () => {
|
||||
replacementCode,
|
||||
MatchModel,
|
||||
TournamentCodeModel,
|
||||
auctionRedisService,
|
||||
session,
|
||||
service,
|
||||
} = createReplacementFixture();
|
||||
|
||||
@@ -546,10 +789,30 @@ describe('TournamentCodeService code replacement', () => {
|
||||
}),
|
||||
expect.objectContaining({ returnDocument: 'after' }),
|
||||
);
|
||||
expect(currentCode?.state).toBe('released');
|
||||
expect(currentCode?.matchId).toBeUndefined();
|
||||
expect(currentCode?.gameNumber).toBeUndefined();
|
||||
expect(currentCode?.save).toHaveBeenCalled();
|
||||
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
|
||||
`tournament-code:match:${matchId.toString()}:lock`,
|
||||
expect.any(String),
|
||||
expect.any(Number),
|
||||
);
|
||||
expect(session.startTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith(
|
||||
`tournament-code:match:${matchId.toString()}:lock`,
|
||||
expect.any(String),
|
||||
);
|
||||
expect(TournamentCodeModel.updateOne).toHaveBeenCalledWith(
|
||||
{ _id: currentCode?._id },
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({ state: 'released' }),
|
||||
$unset: expect.objectContaining({
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(currentCode?.save).not.toHaveBeenCalled();
|
||||
expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([
|
||||
replacementCode?._id.toString(),
|
||||
]);
|
||||
@@ -587,8 +850,8 @@ describe('TournamentCodeService code replacement', () => {
|
||||
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves the current code untouched when no replacement code is available', async () => {
|
||||
const { match, communityId, matchId, currentCode, service } =
|
||||
it('aborts the transaction when no replacement code is available', async () => {
|
||||
const { match, communityId, matchId, currentCode, session, service } =
|
||||
createReplacementFixture({
|
||||
replacementCode: null,
|
||||
});
|
||||
@@ -598,5 +861,6 @@ describe('TournamentCodeService code replacement', () => {
|
||||
).rejects.toThrow('No available tournament code');
|
||||
expect(currentCode?.save).not.toHaveBeenCalled();
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,18 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
buildDoubleEliminationGameSlots,
|
||||
buildDoubleEliminationBracket,
|
||||
type DoubleEliminationGameSlot,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { AuctionRedisService } from '../auction/redis/auction-redis.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
MatchGameAssignment,
|
||||
@@ -31,10 +40,15 @@ import {
|
||||
|
||||
const DEFAULT_REGION = 'kr';
|
||||
const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
|
||||
const TOURNAMENT_CODE_MATCH_LOCK_TTL_MS = 30_000;
|
||||
const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3;
|
||||
|
||||
@Injectable()
|
||||
export class TournamentCodeService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly auctionRedisService: AuctionRedisService,
|
||||
) {}
|
||||
|
||||
public async bulkUpload(params: {
|
||||
communityId?: mongoose.Types.ObjectId;
|
||||
@@ -164,10 +178,9 @@ export class TournamentCodeService {
|
||||
_id: TournamentCodeState;
|
||||
count: number;
|
||||
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
|
||||
const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record<
|
||||
TournamentCodeState,
|
||||
number
|
||||
>;
|
||||
const byState = Object.fromEntries(
|
||||
states.map((state) => [state, 0]),
|
||||
) as Record<TournamentCodeState, number>;
|
||||
for (const entry of counts) byState[entry._id] = entry.count;
|
||||
|
||||
const expiringSoon = await TournamentCodeModel.countDocuments({
|
||||
@@ -189,7 +202,9 @@ export class TournamentCodeService {
|
||||
state: 'available',
|
||||
}).exec();
|
||||
if (result.deletedCount === 0) {
|
||||
throw new BadRequestException('Only available tournament codes can be deleted.');
|
||||
throw new BadRequestException(
|
||||
'Only available tournament codes can be deleted.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,21 +240,38 @@ export class TournamentCodeService {
|
||||
|
||||
public async reserveForMatch(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
): Promise<MatchDocument> {
|
||||
const matchId = this.resolveMatchId(matchOrId);
|
||||
return this.withLockedMatchTransaction(matchId, (session) =>
|
||||
this.reserveForMatchInTransaction(matchId, session),
|
||||
);
|
||||
}
|
||||
|
||||
private async reserveForMatchInTransaction(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
session: mongoose.ClientSession,
|
||||
): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const match =
|
||||
matchOrId instanceof mongoose.Types.ObjectId
|
||||
? await MatchModel.findById(matchOrId)
|
||||
: await MatchModel.findById(matchOrId._id);
|
||||
const match = await this.execQuery<MatchDocument | null>(
|
||||
this.withQuerySession(MatchModel.findById(matchId), session),
|
||||
);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.reserveForDoubleEliminationMatch(
|
||||
match,
|
||||
TournamentCodeModel,
|
||||
session,
|
||||
);
|
||||
}
|
||||
const shouldSaveMetadata =
|
||||
match.isModified('gameCount') || match.isModified('gameSchedule');
|
||||
this.isMatchModified(match, 'gameCount') ||
|
||||
this.isMatchModified(match, 'gameSchedule');
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
const need = requiredSlots - match.tournamentCodeIds.length;
|
||||
if (need <= 0) {
|
||||
@@ -249,7 +281,9 @@ export class TournamentCodeService {
|
||||
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
const startGameNumber = match.tournamentCodeIds.length + 1;
|
||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||
const expiresAfter = new Date(
|
||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||
);
|
||||
|
||||
for (let index = 0; index < need; index += 1) {
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
@@ -269,7 +303,7 @@ export class TournamentCodeService {
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
@@ -279,7 +313,7 @@ export class TournamentCodeService {
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
}
|
||||
if (reservedIds.length > 0 || shouldSaveMetadata) {
|
||||
await match.save();
|
||||
await match.save({ session });
|
||||
}
|
||||
return match;
|
||||
}
|
||||
@@ -289,13 +323,31 @@ export class TournamentCodeService {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameNumber: number;
|
||||
}): Promise<TournamentCodeSlotView> {
|
||||
return this.withLockedMatchTransaction(params.matchId, (session) =>
|
||||
this.replaceForMatchGameInTransaction(params, session),
|
||||
);
|
||||
}
|
||||
|
||||
private async replaceForMatchGameInTransaction(
|
||||
params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
gameNumber: number;
|
||||
},
|
||||
session: mongoose.ClientSession,
|
||||
): Promise<TournamentCodeSlotView> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const match = await MatchModel.findOne({
|
||||
const match = await this.execQuery<MatchDocument | null>(
|
||||
this.withQuerySession(
|
||||
MatchModel.findOne({
|
||||
_id: params.matchId,
|
||||
communityId: params.communityId,
|
||||
}).exec();
|
||||
}),
|
||||
session,
|
||||
),
|
||||
);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (match.status !== 'team-built' && match.status !== 'in-progress') {
|
||||
throw new BadRequestException(
|
||||
@@ -306,6 +358,13 @@ export class TournamentCodeService {
|
||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||
this.ensureGameSchedule(match);
|
||||
const doubleEliminationSlot =
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? this.resolveDoubleEliminationGameSlotByGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const requiredSlots = this.resolveRequiredSlots(match);
|
||||
if (
|
||||
@@ -325,19 +384,53 @@ export class TournamentCodeService {
|
||||
);
|
||||
}
|
||||
|
||||
const currentCode = await TournamentCodeModel.findOne({
|
||||
const currentCode = await this.execQuery<TournamentCodeDocument | null>(
|
||||
this.withQuerySession(
|
||||
TournamentCodeModel.findOne({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
matchId: match._id,
|
||||
...(doubleEliminationSlot
|
||||
? {
|
||||
gameNumber: params.gameNumber,
|
||||
}).exec();
|
||||
bracketMatchId:
|
||||
doubleEliminationSlot.bracketMatch.bracketMatchId,
|
||||
}
|
||||
: { gameNumber: params.gameNumber }),
|
||||
}),
|
||||
session,
|
||||
),
|
||||
);
|
||||
if (!currentCode) {
|
||||
throw new NotFoundException('Assigned tournament code not found.');
|
||||
}
|
||||
if (currentCode.state === 'used' || currentCode.riotMatchId) {
|
||||
throw new BadRequestException('Used tournament codes cannot be replaced.');
|
||||
throw new BadRequestException(
|
||||
'Used tournament codes cannot be replaced.',
|
||||
);
|
||||
}
|
||||
|
||||
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||
const expiresAfter = new Date(
|
||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||
);
|
||||
await this.execQuery(
|
||||
this.withQuerySession(
|
||||
TournamentCodeModel.updateOne(
|
||||
{ _id: currentCode._id },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
riotMatchId: 1,
|
||||
},
|
||||
},
|
||||
),
|
||||
session,
|
||||
),
|
||||
);
|
||||
|
||||
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
@@ -351,32 +444,36 @@ export class TournamentCodeService {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationSlot
|
||||
? {
|
||||
bracketMatchId:
|
||||
doubleEliminationSlot.bracketMatch.bracketMatchId,
|
||||
}
|
||||
: {}),
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||
).exec();
|
||||
if (!replacement) {
|
||||
throw new BadRequestException('No available tournament code to replace with.');
|
||||
throw new BadRequestException(
|
||||
'No available tournament code to replace with.',
|
||||
);
|
||||
}
|
||||
|
||||
currentCode.state = 'released';
|
||||
currentCode.matchId = undefined;
|
||||
currentCode.gameNumber = undefined;
|
||||
currentCode.reservedAt = undefined;
|
||||
currentCode.releasedAt = new Date();
|
||||
currentCode.riotMatchId = undefined;
|
||||
match.tournamentCodeIds = this.replaceTournamentCodeId(
|
||||
match.tournamentCodeIds,
|
||||
currentCode._id,
|
||||
replacement._id,
|
||||
);
|
||||
await currentCode.save();
|
||||
await match.save();
|
||||
await match.save({ session });
|
||||
|
||||
return {
|
||||
gameNumber: params.gameNumber,
|
||||
...(doubleEliminationSlot
|
||||
? this.toDoubleEliminationSlotBase(doubleEliminationSlot)
|
||||
: {}),
|
||||
roundNumber: this.resolveRoundNumberForGameNumber(
|
||||
match,
|
||||
params.gameNumber,
|
||||
@@ -391,27 +488,46 @@ export class TournamentCodeService {
|
||||
|
||||
public async releaseFromMatch(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
): Promise<void> {
|
||||
const matchId = this.resolveMatchId(matchOrId);
|
||||
await this.withLockedMatchTransaction(matchId, (session) =>
|
||||
this.releaseFromMatchInTransaction(matchId, session),
|
||||
);
|
||||
}
|
||||
|
||||
private async releaseFromMatchInTransaction(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
session: mongoose.ClientSession,
|
||||
): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const match =
|
||||
matchOrId instanceof mongoose.Types.ObjectId
|
||||
? await MatchModel.findById(matchOrId)
|
||||
: await MatchModel.findById(matchOrId._id);
|
||||
const match = await this.execQuery<MatchDocument | null>(
|
||||
this.withQuerySession(MatchModel.findById(matchId), session),
|
||||
);
|
||||
if (!match) return;
|
||||
if (match.tournamentCodeIds.length === 0) return;
|
||||
|
||||
await TournamentCodeModel.updateMany(
|
||||
await this.execQuery(
|
||||
this.withQuerySession(
|
||||
TournamentCodeModel.updateMany(
|
||||
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: { matchId: 1, gameNumber: 1, reservedAt: 1 },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
},
|
||||
).exec();
|
||||
},
|
||||
),
|
||||
session,
|
||||
),
|
||||
);
|
||||
|
||||
match.tournamentCodeIds = [];
|
||||
await match.save();
|
||||
await match.save({ session });
|
||||
}
|
||||
|
||||
public async markExpired(): Promise<number> {
|
||||
@@ -430,6 +546,13 @@ export class TournamentCodeService {
|
||||
public async attachPendingMatches(
|
||||
communityId?: mongoose.Types.ObjectId,
|
||||
): Promise<number> {
|
||||
const matches = await this.attachPendingMatchDocuments(communityId);
|
||||
return matches.length;
|
||||
}
|
||||
|
||||
public async attachPendingMatchDocuments(
|
||||
communityId?: mongoose.Types.ObjectId,
|
||||
): Promise<MatchDocument[]> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const filter: {
|
||||
status: { $in: string[] };
|
||||
@@ -440,20 +563,36 @@ export class TournamentCodeService {
|
||||
if (communityId) filter.communityId = communityId;
|
||||
|
||||
const matches = await MatchModel.find(filter).exec();
|
||||
let touched = 0;
|
||||
const touched: MatchDocument[] = [];
|
||||
for (const match of matches) {
|
||||
if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) {
|
||||
if (!this.hasBuiltTeams(match)) continue;
|
||||
if (
|
||||
(match.tournamentCodeIds?.length ?? 0) >=
|
||||
this.resolveRequiredSlots(match)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const before = match.tournamentCodeIds?.length ?? 0;
|
||||
await this.reserveForMatch(match);
|
||||
const after = match.tournamentCodeIds?.length ?? 0;
|
||||
if (after > before) touched += 1;
|
||||
const updatedMatch = await this.reserveForMatch(match);
|
||||
const after = updatedMatch.tournamentCodeIds?.length ?? 0;
|
||||
if (after > before) touched.push(updatedMatch);
|
||||
}
|
||||
return touched;
|
||||
}
|
||||
|
||||
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
|
||||
private hasBuiltTeams(match: MatchDocument): boolean {
|
||||
return Boolean(
|
||||
match.teams.length >= 2 &&
|
||||
match.teams.every((team) => team.members.length > 0),
|
||||
);
|
||||
}
|
||||
|
||||
public async buildSlots(
|
||||
match: MatchDocument,
|
||||
): Promise<TournamentCodeSlotView[]> {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.buildDoubleEliminationSlots(match);
|
||||
}
|
||||
if (
|
||||
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||
@@ -521,10 +660,250 @@ export class TournamentCodeService {
|
||||
return next;
|
||||
}
|
||||
|
||||
private resolveMatchId(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
): mongoose.Types.ObjectId {
|
||||
return matchOrId instanceof mongoose.Types.ObjectId
|
||||
? matchOrId
|
||||
: matchOrId._id;
|
||||
}
|
||||
|
||||
private async withLockedMatchTransaction<T>(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
operation: (session: mongoose.ClientSession) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const lockKey = this.matchCodeLockKey(matchId);
|
||||
const token = randomUUID();
|
||||
const acquired = await this.auctionRedisService.acquireTokenLock(
|
||||
lockKey,
|
||||
token,
|
||||
TOURNAMENT_CODE_MATCH_LOCK_TTL_MS,
|
||||
);
|
||||
if (!acquired) {
|
||||
throw new ConflictException(
|
||||
'Tournament code operation is already running for this match.',
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.runTransactionWithRetry(operation);
|
||||
} finally {
|
||||
await this.auctionRedisService.releaseTokenLock(lockKey, token);
|
||||
}
|
||||
}
|
||||
|
||||
private async runTransactionWithRetry<T>(
|
||||
operation: (session: mongoose.ClientSession) => Promise<T>,
|
||||
): Promise<T> {
|
||||
let lastError: unknown;
|
||||
for (
|
||||
let attempt = 1;
|
||||
attempt <= TOURNAMENT_CODE_TRANSACTION_ATTEMPTS;
|
||||
attempt += 1
|
||||
) {
|
||||
const session = await this.connectionService.createSession();
|
||||
if (!session) {
|
||||
throw new InternalServerErrorException('Failed to start DB session.');
|
||||
}
|
||||
|
||||
try {
|
||||
session.startTransaction();
|
||||
const result = await operation(session);
|
||||
await session.commitTransaction();
|
||||
return result;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
await session.abortTransaction().catch(() => undefined);
|
||||
if (
|
||||
attempt >= TOURNAMENT_CODE_TRANSACTION_ATTEMPTS ||
|
||||
!this.isRetryableTransactionError(error)
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
} finally {
|
||||
await session.endSession().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
private isRetryableTransactionError(error: unknown): boolean {
|
||||
const candidate = error as {
|
||||
code?: number;
|
||||
codeName?: string;
|
||||
hasErrorLabel?: (label: string) => boolean;
|
||||
};
|
||||
return Boolean(
|
||||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
|
||||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult') ||
|
||||
candidate?.code === 112 ||
|
||||
candidate?.codeName === 'WriteConflict',
|
||||
);
|
||||
}
|
||||
|
||||
private matchCodeLockKey(matchId: mongoose.Types.ObjectId): string {
|
||||
return `tournament-code:match:${matchId.toString()}:lock`;
|
||||
}
|
||||
|
||||
private withQuerySession<T>(query: T, session: mongoose.ClientSession): T {
|
||||
const maybeQuery = query as {
|
||||
session?: (session: mongoose.ClientSession) => T;
|
||||
};
|
||||
if (maybeQuery && typeof maybeQuery.session === 'function') {
|
||||
return maybeQuery.session(session);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
private async execQuery<T = unknown>(query: unknown): Promise<T> {
|
||||
const maybeQuery = query as { exec?: () => Promise<T> };
|
||||
if (maybeQuery && typeof maybeQuery.exec === 'function') {
|
||||
return maybeQuery.exec();
|
||||
}
|
||||
return query as Promise<T>;
|
||||
}
|
||||
|
||||
private async reserveForDoubleEliminationMatch(
|
||||
match: MatchDocument,
|
||||
TournamentCodeModel: mongoose.Model<TournamentCode>,
|
||||
session: mongoose.ClientSession,
|
||||
): Promise<MatchDocument> {
|
||||
const readySlots = buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
).filter((slot) => slot.bracketMatch.state === 'ready');
|
||||
const existingCodes =
|
||||
match.tournamentCodeIds.length > 0
|
||||
? await this.execQuery<TournamentCodeDocument[]>(
|
||||
this.withQuerySession(
|
||||
TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
}),
|
||||
session,
|
||||
),
|
||||
)
|
||||
: [];
|
||||
const byGameNumber = new Map(
|
||||
existingCodes
|
||||
.filter(
|
||||
(code) =>
|
||||
typeof code.gameNumber === 'number' &&
|
||||
(code.state === 'reserved' || code.state === 'used'),
|
||||
)
|
||||
.map((code) => [code.gameNumber as number, code]),
|
||||
);
|
||||
const expiresAfter = new Date(
|
||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||
);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
|
||||
for (const slot of readySlots) {
|
||||
if (byGameNumber.has(slot.gameNumber)) continue;
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: DEFAULT_REGION,
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: slot.gameNumber,
|
||||
bracketMatchId: slot.bracketMatch.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
byGameNumber.set(slot.gameNumber, code);
|
||||
}
|
||||
|
||||
if (reservedIds.length > 0) {
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
}
|
||||
if (
|
||||
reservedIds.length > 0 ||
|
||||
this.isMatchModified(match, 'doubleElimination')
|
||||
) {
|
||||
await match.save({ session });
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
private async buildDoubleEliminationSlots(
|
||||
match: MatchDocument,
|
||||
): Promise<TournamentCodeSlotView[]> {
|
||||
this.ensureGameSchedule(match);
|
||||
const bracketMatches = match.doubleElimination?.bracketMatches ?? [];
|
||||
if (bracketMatches.length === 0) return [];
|
||||
const slots = buildDoubleEliminationGameSlots(bracketMatches);
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
const codes =
|
||||
ids.length > 0
|
||||
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
||||
: [];
|
||||
const byGameNumber = new Map(
|
||||
codes
|
||||
.filter(
|
||||
(code) =>
|
||||
typeof code.gameNumber === 'number' &&
|
||||
code.state !== 'released' &&
|
||||
code.state !== 'voided',
|
||||
)
|
||||
.map((code) => [code.gameNumber as number, code]),
|
||||
);
|
||||
|
||||
return slots.map((slot) => {
|
||||
const code = byGameNumber.get(slot.gameNumber);
|
||||
return {
|
||||
...this.toDoubleEliminationSlotBase(slot),
|
||||
code: code?.code ?? null,
|
||||
expiresAt: code?.expiresAt.toISOString() ?? null,
|
||||
state: code?.state ?? 'pending',
|
||||
riotMatchId: code?.riotMatchId ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private toDoubleEliminationSlotBase(
|
||||
slot: DoubleEliminationGameSlot,
|
||||
): Omit<
|
||||
TournamentCodeSlotView,
|
||||
'code' | 'expiresAt' | 'state' | 'riotMatchId'
|
||||
> {
|
||||
const bracketMatch = slot.bracketMatch;
|
||||
return {
|
||||
gameNumber: slot.gameNumber,
|
||||
seriesGameNumber: slot.seriesGameNumber,
|
||||
seriesGameCount: slot.seriesGameCount,
|
||||
seriesRequiredWins: slot.seriesRequiredWins,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
bracketSide: bracketMatch.bracketSide,
|
||||
roundNumber: bracketMatch.roundNumber,
|
||||
matchNumber: bracketMatch.matchNumber,
|
||||
teamAIndex: bracketMatch.teamAIndex,
|
||||
teamBIndex: bracketMatch.teamBIndex,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveRequiredSlots(match: MatchDocument): number {
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
return buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
).length;
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||
return match.gameSchedule.length;
|
||||
@@ -548,6 +927,17 @@ export class TournamentCodeService {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
const slot = this.resolveDoubleEliminationGameSlotByGameNumber(
|
||||
match,
|
||||
gameNumber,
|
||||
);
|
||||
return {
|
||||
teamAIndex: slot?.bracketMatch.teamAIndex ?? 1,
|
||||
teamBIndex: slot?.bracketMatch.teamBIndex ?? 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
@@ -582,6 +972,10 @@ export class TournamentCodeService {
|
||||
}
|
||||
|
||||
private ensureGameSchedule(match: MatchDocument): void {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
this.ensureDoubleEliminationBracket(match);
|
||||
return;
|
||||
}
|
||||
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) return;
|
||||
|
||||
@@ -591,6 +985,49 @@ export class TournamentCodeService {
|
||||
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
|
||||
}
|
||||
|
||||
private ensureDoubleEliminationBracket(match: MatchDocument): void {
|
||||
if ((match.doubleElimination?.bracketMatches.length ?? 0) > 0) return;
|
||||
const teamIndexes = [...(match.teams ?? [])]
|
||||
.map((team) => team.teamIndex)
|
||||
.sort((left, right) => left - right);
|
||||
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
|
||||
const shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
|
||||
match.doubleElimination = buildDoubleEliminationBracket(
|
||||
shuffledTeamIndexes,
|
||||
{
|
||||
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
|
||||
winnerBracketGameCount:
|
||||
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
},
|
||||
);
|
||||
match.markModified?.('doubleElimination');
|
||||
}
|
||||
|
||||
private resolveDoubleEliminationGameSlotByGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): DoubleEliminationGameSlot | undefined {
|
||||
return buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
).find((slot) => slot.gameNumber === gameNumber);
|
||||
}
|
||||
|
||||
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
|
||||
const shuffled = [...teamIndexes];
|
||||
for (let index = shuffled.length - 1; index > 0; index -= 1) {
|
||||
const swapIndex = Math.floor(Math.random() * (index + 1));
|
||||
[shuffled[index], shuffled[swapIndex]] = [
|
||||
shuffled[swapIndex],
|
||||
shuffled[index],
|
||||
];
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
private isMatchModified(match: MatchDocument, path: string): boolean {
|
||||
return typeof match.isModified === 'function' && match.isModified(path);
|
||||
}
|
||||
|
||||
private resolveRoundNumberForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
|
||||
@@ -24,9 +24,15 @@ export interface BulkUploadTournamentCodesResponse {
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
seriesGameNumber?: number;
|
||||
seriesGameCount?: number;
|
||||
seriesRequiredWins?: number;
|
||||
bracketMatchId?: string;
|
||||
bracketSide?: string;
|
||||
roundNumber?: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
matchNumber?: number;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeState | 'pending';
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util';
|
||||
import {
|
||||
collectCaptainAndLimitedTeamMemberUserIds,
|
||||
computeGameResult,
|
||||
type MatchPuuidLookup,
|
||||
} from './team-mapping.util';
|
||||
|
||||
function makeMatch(): {
|
||||
match: MatchDocument;
|
||||
@@ -9,8 +13,14 @@ function makeMatch(): {
|
||||
blueUserIds: mongoose.Types.ObjectId[];
|
||||
redUserIds: mongoose.Types.ObjectId[];
|
||||
} {
|
||||
const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId());
|
||||
const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId());
|
||||
const blueUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const redUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const puuidByUserId = new Map<string, string>();
|
||||
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
|
||||
|
||||
@@ -47,7 +57,12 @@ function makeMatch(): {
|
||||
})),
|
||||
} as unknown as MatchDocument;
|
||||
|
||||
return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds };
|
||||
return {
|
||||
match,
|
||||
lookup: { puuidByUserId, userIdByPuuid },
|
||||
blueUserIds,
|
||||
redUserIds,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRiotMatch(params: {
|
||||
@@ -154,3 +169,24 @@ describe('computeGameResult', () => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('collectCaptainAndLimitedTeamMemberUserIds', () => {
|
||||
it('keeps captains and caps extra members per team', () => {
|
||||
const { blueUserIds, match, redUserIds } = makeMatch();
|
||||
match.teams[0].captainUserId = blueUserIds[0];
|
||||
match.teams[1].captainUserId = redUserIds[0];
|
||||
|
||||
const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map(
|
||||
(userId) => userId.toString(),
|
||||
);
|
||||
|
||||
expect(userIds).toEqual([
|
||||
blueUserIds[0].toString(),
|
||||
blueUserIds[1].toString(),
|
||||
blueUserIds[2].toString(),
|
||||
redUserIds[0].toString(),
|
||||
redUserIds[1].toString(),
|
||||
redUserIds[2].toString(),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
|
||||
const RIOT_BLUE_TEAM_ID = 100;
|
||||
@@ -11,19 +15,46 @@ export interface MatchPuuidLookup {
|
||||
userIdByPuuid: Map<string, mongoose.Types.ObjectId>;
|
||||
}
|
||||
|
||||
export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] {
|
||||
export function collectCaptainUserIds(
|
||||
match: MatchDocument,
|
||||
): mongoose.Types.ObjectId[] {
|
||||
return match.teams
|
||||
.map((team) => team.captainUserId)
|
||||
.filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId));
|
||||
}
|
||||
|
||||
export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] {
|
||||
export function collectCaptainAndLimitedTeamMemberUserIds(
|
||||
match: MatchDocument,
|
||||
memberLimitPerTeam: number,
|
||||
): mongoose.Types.ObjectId[] {
|
||||
const ids = new Map<string, mongoose.Types.ObjectId>();
|
||||
for (const team of match.teams) {
|
||||
if (team.captainUserId) {
|
||||
ids.set(team.captainUserId.toString(), team.captainUserId);
|
||||
}
|
||||
let memberCount = 0;
|
||||
for (const member of team.members) {
|
||||
if (team.captainUserId?.toString() === member.userId.toString()) {
|
||||
continue;
|
||||
}
|
||||
if (memberCount >= memberLimitPerTeam) break;
|
||||
ids.set(member.userId.toString(), member.userId);
|
||||
memberCount += 1;
|
||||
}
|
||||
}
|
||||
return [...ids.values()];
|
||||
}
|
||||
|
||||
export function collectMatchUserIds(
|
||||
match: MatchDocument,
|
||||
): mongoose.Types.ObjectId[] {
|
||||
const ids = new Map<string, mongoose.Types.ObjectId>();
|
||||
for (const participant of match.participants) {
|
||||
ids.set(participant.userId.toString(), participant.userId);
|
||||
}
|
||||
for (const team of match.teams) {
|
||||
if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId);
|
||||
if (team.captainUserId)
|
||||
ids.set(team.captainUserId.toString(), team.captainUserId);
|
||||
for (const member of team.members) {
|
||||
ids.set(member.userId.toString(), member.userId);
|
||||
}
|
||||
@@ -78,8 +109,10 @@ export function computeGameResult(params: {
|
||||
const reversedOverlap =
|
||||
countOverlap(team100Puuids, teamBPuuids) +
|
||||
countOverlap(team200Puuids, teamAPuuids);
|
||||
const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
|
||||
const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
|
||||
const blueTeamIndex =
|
||||
normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
|
||||
const redTeamIndex =
|
||||
normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
|
||||
const teamIndexByRiotTeamId: Record<number, number> = {
|
||||
[RIOT_BLUE_TEAM_ID]: blueTeamIndex,
|
||||
[RIOT_RED_TEAM_ID]: redTeamIndex,
|
||||
|
||||
@@ -1,32 +1,70 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
import { TournamentResultService } from './tournament-result.service';
|
||||
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
|
||||
|
||||
type TournamentResultServiceInternals = TournamentResultService & {
|
||||
nextPollDelayMs(elapsedMs: number): number | null;
|
||||
resolveRequiredGameSlots(match: MatchDocument): number;
|
||||
resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { teamAIndex: number; teamBIndex: number };
|
||||
buildSeriesResults(
|
||||
games: NonNullable<MatchDocument['result']>['games'],
|
||||
): NonNullable<MatchDocument['result']>['seriesResults'];
|
||||
advanceDoubleEliminationIfNeeded(
|
||||
match: MatchDocument,
|
||||
gameResult: NonNullable<MatchDocument['result']>['games'][number],
|
||||
completedBy: 'riot-result' | 'walkover',
|
||||
): string | undefined;
|
||||
};
|
||||
|
||||
function createService() {
|
||||
const distributedLockService = createDistributedLockService();
|
||||
return new TournamentResultService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
distributedLockService as never,
|
||||
) as unknown as TournamentResultServiceInternals;
|
||||
}
|
||||
|
||||
function createDistributedLockService() {
|
||||
return {
|
||||
runWithLock: jest.fn().mockImplementation(async (options, operation) =>
|
||||
operation({
|
||||
lockKey: options.lockKey,
|
||||
lockOwnershipToken: 'lock-owner',
|
||||
lockExpirationDurationMilliseconds:
|
||||
options.lockExpirationDurationMilliseconds,
|
||||
}),
|
||||
),
|
||||
runWithRenewedLock: jest
|
||||
.fn()
|
||||
.mockImplementation(async (options, operation) =>
|
||||
operation({
|
||||
lockKey: options.lockKey,
|
||||
lockOwnershipToken: 'lock-owner',
|
||||
lockExpirationDurationMilliseconds:
|
||||
options.lockExpirationDurationMilliseconds,
|
||||
}),
|
||||
),
|
||||
} as unknown as jest.Mocked<DistributedLockService>;
|
||||
}
|
||||
|
||||
interface MatchOverrides {
|
||||
gameCount?: number;
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
|
||||
roundRobinMaxRounds?: number;
|
||||
participants?: Array<{ excluded?: boolean }>;
|
||||
teams?: Array<{ teamIndex: number }>;
|
||||
doubleElimination?: MatchDocument['doubleElimination'];
|
||||
result?: MatchDocument['result'];
|
||||
gameSchedule?: Array<{
|
||||
gameNumber: number;
|
||||
roundNumber?: number;
|
||||
@@ -42,6 +80,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||
participants: [],
|
||||
teams: [],
|
||||
gameSchedule: [],
|
||||
result: undefined,
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
@@ -99,6 +138,146 @@ describe('TournamentResultService round-robin scheduling', () => {
|
||||
teamBIndex: 4,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps double-elimination rematches separated by bracket match id', () => {
|
||||
const service = createService();
|
||||
|
||||
expect(
|
||||
service.buildSeriesResults([
|
||||
{
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
riotMatchId: 'KR_1',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
winnerSide: 'blue',
|
||||
gameCreation: 1,
|
||||
gameDuration: 1800,
|
||||
participants: [],
|
||||
},
|
||||
{
|
||||
gameNumber: 2,
|
||||
bracketMatchId: 'GF',
|
||||
riotMatchId: 'KR_2',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 2,
|
||||
winnerSide: 'red',
|
||||
gameCreation: 2,
|
||||
gameDuration: 1800,
|
||||
participants: [],
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
bracketMatchId: 'GF',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 0,
|
||||
teamBWins: 1,
|
||||
winnerTeamIndex: 2,
|
||||
},
|
||||
{
|
||||
bracketMatchId: 'WB_FINAL',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('maps double-elimination series game numbers to bracket matches', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({
|
||||
gameMode: 'double-elimination',
|
||||
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(service.resolveRequiredGameSlots(match)).toBe(12);
|
||||
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 4,
|
||||
});
|
||||
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
|
||||
teamAIndex: 2,
|
||||
teamBIndex: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it('advances double-elimination only after a team reaches required series wins', () => {
|
||||
const service = createService();
|
||||
const game = {
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
riotMatchId: 'KR_1',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 4,
|
||||
winnerTeamIndex: 1,
|
||||
winnerSide: 'blue',
|
||||
gameCreation: 1,
|
||||
gameDuration: 1800,
|
||||
participants: [],
|
||||
} as NonNullable<MatchDocument['result']>['games'][number];
|
||||
const match = createMatch({
|
||||
gameMode: 'double-elimination',
|
||||
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
|
||||
resetFinalEnabled: true,
|
||||
}),
|
||||
result: {
|
||||
riotMatchIds: ['KR_1'],
|
||||
games: [game],
|
||||
seriesResults: [
|
||||
{
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 4,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
} as MatchOverrides);
|
||||
|
||||
expect(
|
||||
service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'),
|
||||
).toBeUndefined();
|
||||
const firstGameBracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.bracketMatchId === 'WB_R1_M1',
|
||||
);
|
||||
expect(firstGameBracketMatch).toMatchObject({ state: 'ready' });
|
||||
expect(firstGameBracketMatch?.winnerTeamIndex).toBeUndefined();
|
||||
|
||||
match.result!.seriesResults = [
|
||||
{
|
||||
bracketMatchId: 'WB_R1_M1',
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 4,
|
||||
teamAWins: 2,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
];
|
||||
|
||||
expect(
|
||||
service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'),
|
||||
).toBe('WB_R1_M1');
|
||||
expect(
|
||||
match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.bracketMatchId === 'WB_R1_M1',
|
||||
),
|
||||
).toMatchObject({ state: 'completed', winnerTeamIndex: 1 });
|
||||
expect(
|
||||
match.doubleElimination?.bracketMatches.find(
|
||||
(entry) => entry.bracketMatchId === 'WB_FINAL',
|
||||
),
|
||||
).toMatchObject({ teamAIndex: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentResultService tournament code polling', () => {
|
||||
@@ -227,15 +406,17 @@ describe('TournamentResultService tournament code polling', () => {
|
||||
const riotJobQueueService = {
|
||||
enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const distributedLockService = createDistributedLockService();
|
||||
const service = new TournamentResultService(
|
||||
connectionService as never,
|
||||
riotMatchService as never,
|
||||
riotJobQueueService as never,
|
||||
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
distributedLockService as never,
|
||||
);
|
||||
|
||||
return { service, match, code };
|
||||
return { service, match, code, riotMatchService };
|
||||
}
|
||||
|
||||
it('matches Riot tournament codes using exact casing', async () => {
|
||||
@@ -256,6 +437,23 @@ describe('TournamentResultService tournament code polling', () => {
|
||||
expect(match.result?.games).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('limits expanded polling to two team members per team', async () => {
|
||||
const { service, match, riotMatchService } = createPollFixture({
|
||||
storedCode: 'AbC-12345',
|
||||
riotTournamentCode: 'AbC-12345',
|
||||
});
|
||||
|
||||
await service.processPollJob({
|
||||
matchId: match._id.toString(),
|
||||
attempt: 1,
|
||||
expandedToAllPuuids: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
riotMatchService.getMatchIdsByPuuid.mock.calls.map(([puuid]) => puuid),
|
||||
).toEqual(['poll-puuid-1', 'poll-puuid-2', 'poll-puuid-6', 'poll-puuid-7']);
|
||||
});
|
||||
|
||||
it('does not match tournament codes when casing differs', async () => {
|
||||
const { service, match, code } = createPollFixture({
|
||||
storedCode: 'ABC-12345',
|
||||
@@ -275,6 +473,15 @@ describe('TournamentResultService tournament code polling', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentResultService polling cadence', () => {
|
||||
it('polls every two minutes during the first hour', () => {
|
||||
const service = createService();
|
||||
|
||||
expect(service.nextPollDelayMs(0)).toBe(2 * 60_000);
|
||||
expect(service.nextPollDelayMs(60 * 60_000)).toBe(2 * 60_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TournamentResultService manual result collection', () => {
|
||||
function createManualFixture() {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
@@ -375,12 +582,14 @@ describe('TournamentResultService manual result collection', () => {
|
||||
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']),
|
||||
getMatch: jest.fn().mockResolvedValue(detail),
|
||||
};
|
||||
const distributedLockService = createDistributedLockService();
|
||||
const service = new TournamentResultService(
|
||||
connectionService as never,
|
||||
riotMatchService as never,
|
||||
{} as never,
|
||||
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
||||
distributedLockService as never,
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -5,12 +5,20 @@ import {
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import {
|
||||
buildDoubleEliminationGameSlots,
|
||||
completeDoubleEliminationBracketMatch,
|
||||
resolveDoubleEliminationSeriesWinner,
|
||||
type DoubleEliminationGameSlot,
|
||||
} from '../double-elimination/double-elimination.util';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
MatchSeriesResult,
|
||||
RiotMatch as StoredRiotMatch,
|
||||
TournamentCodeDocument,
|
||||
} from '../global/database/schema';
|
||||
@@ -22,7 +30,9 @@ import {
|
||||
roundRobinGameSchedule,
|
||||
resolveRoundRobinTeamCount,
|
||||
} from '../tournament-code/round-robin.util';
|
||||
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants';
|
||||
import {
|
||||
collectCaptainAndLimitedTeamMemberUserIds,
|
||||
collectCaptainUserIds,
|
||||
collectMatchUserIds,
|
||||
computeGameResult,
|
||||
@@ -34,14 +44,22 @@ import type {
|
||||
PollTournamentResultJob,
|
||||
} from './tournament-result.types';
|
||||
|
||||
const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000;
|
||||
const FIRST_HOUR_POLL_DELAY_MS = 2 * 60_000;
|
||||
const LATER_POLL_DELAY_MS = 60 * 60_000;
|
||||
const POLL_EXPIRY_MS = 24 * 60 * 60_000;
|
||||
const EXPAND_AFTER_MS = 60 * 60_000;
|
||||
const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2;
|
||||
const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
|
||||
const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS =
|
||||
30 * 60_000;
|
||||
const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS =
|
||||
5 * 60_000;
|
||||
const TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS =
|
||||
5 * 60_000;
|
||||
|
||||
interface ManualGameAssignment {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
}
|
||||
@@ -56,11 +74,29 @@ export class TournamentResultService {
|
||||
private readonly riotJobQueueService: RiotJobQueueService,
|
||||
private readonly communityStatsService: CommunityStatsService,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
private readonly distributedLockService: DistributedLockService,
|
||||
) {}
|
||||
|
||||
public async scheduleInitialPoll(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
priority: RiotJobPriority = 'high',
|
||||
): Promise<EnqueueTournamentResultPollResult | null> {
|
||||
const matchIdentifier = this.resolveMatchIdentifier(matchOrId);
|
||||
return this.distributedLockService.runWithLock(
|
||||
{
|
||||
lockKey: this.tournamentResultPollProcessingLockKey(matchIdentifier),
|
||||
lockExpirationDurationMilliseconds:
|
||||
TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
lockAcquireTimeoutMilliseconds: 1_000,
|
||||
lockRetryDelayMilliseconds: 100,
|
||||
},
|
||||
async () => this.scheduleInitialPollWhileLockOwned(matchOrId, priority),
|
||||
);
|
||||
}
|
||||
|
||||
private async scheduleInitialPollWhileLockOwned(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
priority: RiotJobPriority,
|
||||
): Promise<EnqueueTournamentResultPollResult | null> {
|
||||
const match = await this.loadMatch(matchOrId);
|
||||
if (match.status === 'finished') return null;
|
||||
@@ -187,6 +223,30 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
||||
const didProcessPollJob =
|
||||
await this.distributedLockService.runWithRenewedLock(
|
||||
{
|
||||
lockKey: this.tournamentResultPollProcessingLockKey(job.matchId),
|
||||
lockExpirationDurationMilliseconds:
|
||||
TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
lockRenewalIntervalMilliseconds:
|
||||
TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
|
||||
},
|
||||
async () => {
|
||||
await this.processPollJobWhileLockOwned(job);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
if (didProcessPollJob) return;
|
||||
this.logger.debug(
|
||||
`Skipped tournament result poll job ${job.jobId}; another worker is processing match ${job.matchId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
private async processPollJobWhileLockOwned(
|
||||
job: PollTournamentResultJob,
|
||||
): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
@@ -205,7 +265,11 @@ export class TournamentResultService {
|
||||
(code) => code.state === 'reserved' && !code.riotMatchId,
|
||||
);
|
||||
if (unmatched.length === 0) {
|
||||
await this.advanceMatchIfReady(match, codes);
|
||||
const completed = await this.advanceMatchIfReady(match, codes);
|
||||
if (!completed) {
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
await this.scheduleNextPoll(match, job);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -216,7 +280,13 @@ export class TournamentResultService {
|
||||
const region = community?.riotRegion ?? 'asia';
|
||||
const lookup = await this.buildPuuidLookup(match);
|
||||
const puuids = job.expandedToAllPuuids
|
||||
? this.collectPollingPuuids(collectMatchUserIds(match), lookup)
|
||||
? this.collectPollingPuuids(
|
||||
collectCaptainAndLimitedTeamMemberUserIds(
|
||||
match,
|
||||
EXPANDED_MEMBER_LIMIT_PER_TEAM,
|
||||
),
|
||||
lookup,
|
||||
)
|
||||
: this.collectPollingPuuids(collectCaptainUserIds(match), lookup);
|
||||
|
||||
const matchedGameNumbers = new Set<number>();
|
||||
@@ -316,6 +386,7 @@ export class TournamentResultService {
|
||||
return false;
|
||||
}
|
||||
|
||||
gameResult.bracketMatchId = code.bracketMatchId;
|
||||
code.state = 'used';
|
||||
code.usedAt = new Date(
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
@@ -324,10 +395,22 @@ export class TournamentResultService {
|
||||
await code.save();
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded(
|
||||
match,
|
||||
gameResult,
|
||||
'riot-result',
|
||||
);
|
||||
if (completedBracketMatchId) {
|
||||
await this.releaseUnusedReservedDoubleEliminationCodes(
|
||||
match,
|
||||
completedBracketMatchId,
|
||||
);
|
||||
}
|
||||
if (match.status === 'team-built') {
|
||||
match.status = 'in-progress';
|
||||
}
|
||||
await match.save();
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
return true;
|
||||
}
|
||||
@@ -357,6 +440,17 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded(
|
||||
match,
|
||||
gameResult,
|
||||
'riot-result',
|
||||
);
|
||||
if (completedBracketMatchId) {
|
||||
await this.releaseUnusedReservedDoubleEliminationCodes(
|
||||
match,
|
||||
completedBracketMatchId,
|
||||
);
|
||||
}
|
||||
await this.markTournamentCodeUsedForManualResult(
|
||||
match,
|
||||
gameResult,
|
||||
@@ -371,6 +465,9 @@ export class TournamentResultService {
|
||||
}
|
||||
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
||||
await match.save();
|
||||
if (appliedRiotMatchIds.length > 0) {
|
||||
await this.reserveReadyDoubleEliminationCodes(match);
|
||||
}
|
||||
if (appliedRiotMatchIds.length > 0) {
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
}
|
||||
@@ -391,6 +488,36 @@ export class TournamentResultService {
|
||||
match: MatchDocument,
|
||||
codes: TournamentCodeDocument[],
|
||||
): Promise<boolean> {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
if (!this.isDoubleEliminationComplete(match)) return false;
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex =
|
||||
match.doubleElimination?.placements.firstTeamIndex;
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
lastPolledAt: match.resultPollState?.lastPolledAt,
|
||||
lastPollOutcome: match.resultPollState?.lastPollOutcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids:
|
||||
match.resultPollState?.expandedToAllPuuids ?? false,
|
||||
state: 'complete',
|
||||
};
|
||||
await match.save();
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
void this.communityStatsService
|
||||
.invalidateCommunity(match.communityId)
|
||||
.catch((error) => {
|
||||
this.logger.warn(
|
||||
`Failed to invalidate community stats cache for ${match.communityId.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
|
||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||
return false;
|
||||
@@ -577,7 +704,10 @@ export class TournamentResultService {
|
||||
const seriesResults = this.buildSeriesResults(games);
|
||||
|
||||
match.result = {
|
||||
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
winnerTeamIndex:
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? match.doubleElimination?.placements.firstTeamIndex
|
||||
: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
@@ -599,7 +729,10 @@ export class TournamentResultService {
|
||||
teamAIndex: assignment.teamAIndex,
|
||||
teamBIndex: assignment.teamBIndex,
|
||||
});
|
||||
if (gameResult) return gameResult;
|
||||
if (gameResult) {
|
||||
gameResult.bracketMatchId = assignment.bracketMatchId;
|
||||
return gameResult;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -611,6 +744,23 @@ export class TournamentResultService {
|
||||
(match.result?.games ?? []).map((game) => game.gameNumber),
|
||||
);
|
||||
const assignments: ManualGameAssignment[] = [];
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
for (const slot of buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
)) {
|
||||
const bracketMatch = slot.bracketMatch;
|
||||
if (bracketMatch.state !== 'ready') continue;
|
||||
if (usedGameNumbers.has(slot.gameNumber)) continue;
|
||||
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
|
||||
assignments.push({
|
||||
gameNumber: slot.gameNumber,
|
||||
bracketMatchId: bracketMatch.bracketMatchId,
|
||||
teamAIndex: bracketMatch.teamAIndex,
|
||||
teamBIndex: bracketMatch.teamBIndex,
|
||||
});
|
||||
}
|
||||
return assignments;
|
||||
}
|
||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||
|
||||
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
|
||||
@@ -633,6 +783,9 @@ export class TournamentResultService {
|
||||
}
|
||||
|
||||
private hasAllRequiredGameResults(match: MatchDocument): boolean {
|
||||
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||
return this.isDoubleEliminationComplete(match);
|
||||
}
|
||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||
if (requiredSlots <= 0) return false;
|
||||
const resultGameNumbers = new Set(
|
||||
@@ -663,9 +816,10 @@ export class TournamentResultService {
|
||||
): Promise<void> {
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
|
||||
match.result.seriesResults ?? [],
|
||||
);
|
||||
match.result.winnerTeamIndex =
|
||||
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||
? match.doubleElimination?.placements.firstTeamIndex
|
||||
: this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []);
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
@@ -700,6 +854,141 @@ export class TournamentResultService {
|
||||
}
|
||||
}
|
||||
|
||||
private advanceDoubleEliminationIfNeeded(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
completedBy: 'riot-result' | 'walkover',
|
||||
): string | undefined {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return undefined;
|
||||
if (!match.doubleElimination || !gameResult.bracketMatchId)
|
||||
return undefined;
|
||||
const bracketMatch = match.doubleElimination.bracketMatches.find(
|
||||
(entry) => entry.bracketMatchId === gameResult.bracketMatchId,
|
||||
);
|
||||
if (!bracketMatch || bracketMatch.state !== 'ready') return undefined;
|
||||
const seriesResult = match.result?.seriesResults?.find(
|
||||
(entry) => entry.bracketMatchId === gameResult.bracketMatchId,
|
||||
);
|
||||
const winnerTeamIndex = resolveDoubleEliminationSeriesWinner(
|
||||
seriesResult,
|
||||
bracketMatch,
|
||||
);
|
||||
if (!winnerTeamIndex) return undefined;
|
||||
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||
match.doubleElimination,
|
||||
{
|
||||
bracketMatchId: gameResult.bracketMatchId,
|
||||
winnerTeamIndex,
|
||||
completedBy,
|
||||
completedAt: new Date(gameResult.gameCreation),
|
||||
},
|
||||
);
|
||||
if (match.result && this.isDoubleEliminationComplete(match)) {
|
||||
match.result.winnerTeamIndex =
|
||||
match.doubleElimination!.placements.firstTeamIndex;
|
||||
}
|
||||
match.markModified?.('doubleElimination');
|
||||
return gameResult.bracketMatchId;
|
||||
}
|
||||
|
||||
private isDoubleEliminationComplete(match: MatchDocument): boolean {
|
||||
const placements = match.doubleElimination?.placements;
|
||||
return Boolean(
|
||||
placements?.firstTeamIndex &&
|
||||
placements.secondTeamIndex &&
|
||||
placements.thirdTeamIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private async reserveReadyDoubleEliminationCodes(
|
||||
match: MatchDocument,
|
||||
): Promise<void> {
|
||||
await this.distributedLockService.runWithLock(
|
||||
{
|
||||
lockKey: this.tournamentResultReadyCodeReservationLockKey(
|
||||
match._id.toString(),
|
||||
),
|
||||
lockExpirationDurationMilliseconds:
|
||||
TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||
},
|
||||
async () => this.reserveReadyDoubleEliminationCodesWhileLockOwned(match),
|
||||
);
|
||||
}
|
||||
|
||||
private async reserveReadyDoubleEliminationCodesWhileLockOwned(
|
||||
match: MatchDocument,
|
||||
): Promise<void> {
|
||||
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||
const readySlots = buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
).filter((slot) => slot.bracketMatch.state === 'ready');
|
||||
if (readySlots.length === 0) return;
|
||||
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const existingCodes =
|
||||
match.tournamentCodeIds.length > 0
|
||||
? await TournamentCodeModel.find({
|
||||
_id: { $in: match.tournamentCodeIds },
|
||||
}).exec()
|
||||
: [];
|
||||
const existingByGameNumber = new Map(
|
||||
existingCodes
|
||||
.filter(
|
||||
(code) =>
|
||||
typeof code.gameNumber === 'number' &&
|
||||
(code.state === 'reserved' || code.state === 'used'),
|
||||
)
|
||||
.map((code) => [code.gameNumber as number, code]),
|
||||
);
|
||||
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||
const expiresAfter = new Date(
|
||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||
);
|
||||
|
||||
for (const slot of readySlots) {
|
||||
if (existingByGameNumber.has(slot.gameNumber)) continue;
|
||||
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||
{
|
||||
state: 'available',
|
||||
region: 'kr',
|
||||
mapType: 'SUMMONERS_RIFT',
|
||||
teamSize: 5,
|
||||
expiresAt: { $gt: expiresAfter },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
state: 'reserved',
|
||||
matchId: match._id,
|
||||
gameNumber: slot.gameNumber,
|
||||
bracketMatchId: slot.bracketMatch.bracketMatchId,
|
||||
reservedAt: new Date(),
|
||||
},
|
||||
$unset: { releasedAt: 1 },
|
||||
},
|
||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
}
|
||||
|
||||
if (reservedIds.length === 0) return;
|
||||
await MatchModel.updateOne(
|
||||
{ _id: match._id },
|
||||
{ $addToSet: { tournamentCodeIds: { $each: reservedIds } } },
|
||||
).exec();
|
||||
const existingTournamentCodeIds = new Set(
|
||||
match.tournamentCodeIds.map((tournamentCodeId) =>
|
||||
tournamentCodeId.toString(),
|
||||
),
|
||||
);
|
||||
for (const reservedId of reservedIds) {
|
||||
if (existingTournamentCodeIds.has(reservedId.toString())) continue;
|
||||
match.tournamentCodeIds.push(reservedId);
|
||||
}
|
||||
}
|
||||
|
||||
private async markTournamentCodeUsedForManualResult(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
@@ -711,6 +1000,9 @@ export class TournamentResultService {
|
||||
{
|
||||
matchId: match._id,
|
||||
gameNumber: gameResult.gameNumber,
|
||||
...(gameResult.bracketMatchId
|
||||
? { bracketMatchId: gameResult.bracketMatchId }
|
||||
: {}),
|
||||
state: { $in: ['reserved', 'released'] },
|
||||
},
|
||||
{
|
||||
@@ -720,30 +1012,64 @@ export class TournamentResultService {
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
),
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
...(gameResult.bracketMatchId
|
||||
? { bracketMatchId: gameResult.bracketMatchId }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
private async releaseUnusedReservedDoubleEliminationCodes(
|
||||
match: MatchDocument,
|
||||
bracketMatchId: string,
|
||||
): Promise<void> {
|
||||
const ids = match.tournamentCodeIds ?? [];
|
||||
if (ids.length === 0) return;
|
||||
const usedGameNumbers = new Set(
|
||||
(match.result?.games ?? [])
|
||||
.filter((game) => game.bracketMatchId === bracketMatchId)
|
||||
.map((game) => game.gameNumber),
|
||||
);
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const codes = await TournamentCodeModel.find({
|
||||
_id: { $in: ids },
|
||||
matchId: match._id,
|
||||
bracketMatchId,
|
||||
state: 'reserved',
|
||||
gameNumber: { $nin: [...usedGameNumbers] },
|
||||
}).exec();
|
||||
if (codes.length === 0) return;
|
||||
const releasedIds = codes.map((code) => code._id.toString());
|
||||
await TournamentCodeModel.updateMany(
|
||||
{ _id: { $in: codes.map((code) => code._id) } },
|
||||
{
|
||||
$set: { state: 'released', releasedAt: new Date() },
|
||||
$unset: {
|
||||
matchId: 1,
|
||||
gameNumber: 1,
|
||||
bracketMatchId: 1,
|
||||
reservedAt: 1,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
match.tournamentCodeIds = ids.filter(
|
||||
(id) => !releasedIds.includes(id.toString()),
|
||||
);
|
||||
}
|
||||
|
||||
private buildSeriesResults(
|
||||
games: MatchGameResult[],
|
||||
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
const bySeries = new Map<string, MatchSeriesResult>();
|
||||
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
||||
const current = bySeries.get(key) ?? {
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
@@ -762,6 +1088,7 @@ export class TournamentResultService {
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
(left.bracketMatchId ?? '').localeCompare(right.bracketMatchId ?? '') ||
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
@@ -773,6 +1100,22 @@ export class TournamentResultService {
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'double-elimination') {
|
||||
const slot = this.resolveDoubleEliminationGameSlotByGameNumber(
|
||||
match,
|
||||
gameNumber,
|
||||
);
|
||||
return slot
|
||||
? {
|
||||
teamAIndex: slot.bracketMatch.teamAIndex ?? 1,
|
||||
teamBIndex: slot.bracketMatch.teamBIndex ?? 2,
|
||||
}
|
||||
: {
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
};
|
||||
}
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
@@ -806,8 +1149,22 @@ export class TournamentResultService {
|
||||
};
|
||||
}
|
||||
|
||||
private resolveDoubleEliminationGameSlotByGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): DoubleEliminationGameSlot | undefined {
|
||||
return buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
).find((slot) => slot.gameNumber === gameNumber);
|
||||
}
|
||||
|
||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
if (gameMode === 'double-elimination') {
|
||||
return buildDoubleEliminationGameSlots(
|
||||
match.doubleElimination?.bracketMatches ?? [],
|
||||
).length;
|
||||
}
|
||||
if (gameMode === 'round-robin') {
|
||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||
return match.gameSchedule.length;
|
||||
@@ -933,6 +1290,26 @@ export class TournamentResultService {
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
return match;
|
||||
}
|
||||
|
||||
private resolveMatchIdentifier(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
): string {
|
||||
return matchOrId instanceof mongoose.Types.ObjectId
|
||||
? matchOrId.toString()
|
||||
: matchOrId._id.toString();
|
||||
}
|
||||
|
||||
private tournamentResultPollProcessingLockKey(
|
||||
matchIdentifier: string,
|
||||
): string {
|
||||
return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`;
|
||||
}
|
||||
|
||||
private tournamentResultReadyCodeReservationLockKey(
|
||||
matchIdentifier: string,
|
||||
): string {
|
||||
return `distributed-lock:tournament-result:reserve-ready-double-elimination-codes:match:${matchIdentifier}`;
|
||||
}
|
||||
}
|
||||
|
||||
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const CONFIG_PATH = '../newrelic.cjs';
|
||||
const requireConfig = createRequire(__filename);
|
||||
|
||||
interface NewRelicConfig {
|
||||
app_name: string[];
|
||||
license_key: string;
|
||||
agent_enabled: boolean;
|
||||
ai_monitoring: {
|
||||
enabled: boolean;
|
||||
};
|
||||
custom_insights_events: {
|
||||
max_samples_stored: number;
|
||||
};
|
||||
span_events: {
|
||||
max_samples_stored: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface NewRelicConfigModule {
|
||||
config: NewRelicConfig;
|
||||
}
|
||||
|
||||
function loadConfig(): NewRelicConfig {
|
||||
jest.resetModules();
|
||||
const module = requireConfig(CONFIG_PATH) as unknown as NewRelicConfigModule;
|
||||
return module.config;
|
||||
}
|
||||
|
||||
describe('New Relic config', () => {
|
||||
let originalEnv: NodeJS.ProcessEnv;
|
||||
|
||||
beforeEach(() => {
|
||||
originalEnv = { ...process.env };
|
||||
delete process.env.NEW_RELIC_ENABLED;
|
||||
delete process.env.NEW_RELIC_LICENSE_KEY;
|
||||
delete process.env.NEW_RELIC_APP_NAME;
|
||||
delete process.env.NEW_RELIC_AI_MONITORING_ENABLED;
|
||||
delete process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED;
|
||||
delete process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED;
|
||||
jest.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
jest.resetModules();
|
||||
});
|
||||
|
||||
it('uses safe defaults and stays disabled without a license key', () => {
|
||||
const config = loadConfig();
|
||||
|
||||
expect(config.app_name).toEqual(['lolympus']);
|
||||
expect(config.agent_enabled).toBe(false);
|
||||
expect(config.ai_monitoring.enabled).toBe(true);
|
||||
expect(config.custom_insights_events.max_samples_stored).toBe(100000);
|
||||
expect(config.span_events.max_samples_stored).toBe(10000);
|
||||
});
|
||||
|
||||
it('enables the agent when a license key exists and honors runtime overrides', () => {
|
||||
process.env.NEW_RELIC_LICENSE_KEY = 'test-license';
|
||||
process.env.NEW_RELIC_APP_NAME = 'lolympus-api-test';
|
||||
process.env.NEW_RELIC_AI_MONITORING_ENABLED = 'false';
|
||||
process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED = '5000';
|
||||
process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED = '4000';
|
||||
|
||||
const config = loadConfig();
|
||||
|
||||
expect(config.app_name).toEqual(['lolympus-api-test']);
|
||||
expect(config.license_key).toBe('test-license');
|
||||
expect(config.agent_enabled).toBe(true);
|
||||
expect(config.ai_monitoring.enabled).toBe(false);
|
||||
expect(config.custom_insights_events.max_samples_stored).toBe(5000);
|
||||
expect(config.span_events.max_samples_stored).toBe(4000);
|
||||
});
|
||||
|
||||
it('normalizes shorthand sample sizes before New Relic applies env overrides', () => {
|
||||
process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED = '100k';
|
||||
process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED = '10k';
|
||||
|
||||
const config = loadConfig();
|
||||
|
||||
expect(config.custom_insights_events.max_samples_stored).toBe(100000);
|
||||
expect(config.span_events.max_samples_stored).toBe(10000);
|
||||
expect(
|
||||
process.env.NEW_RELIC_CUSTOM_INSIGHTS_EVENTS_MAX_SAMPLES_STORED,
|
||||
).toBe('100000');
|
||||
expect(process.env.NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED).toBe('10000');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { INestApplicationContext } from '@nestjs/common';
|
||||
import { IoAdapter } from '@nestjs/platform-socket.io';
|
||||
import { createAdapter } from '@socket.io/redis-adapter';
|
||||
import type { ServerOptions } from 'socket.io';
|
||||
import type { Server, ServerOptions } from 'socket.io';
|
||||
import {
|
||||
AuctionRedisService,
|
||||
type AuctionRedisClient,
|
||||
@@ -26,8 +26,8 @@ export class RedisIoAdapter extends IoAdapter {
|
||||
this.adapterConstructor = createAdapter(pubClient, this.subClient);
|
||||
}
|
||||
|
||||
override createIOServer(port: number, options?: ServerOptions) {
|
||||
const server = super.createIOServer(port, options);
|
||||
override createIOServer(port: number, options?: ServerOptions): Server {
|
||||
const server = super.createIOServer(port, options) as Server;
|
||||
if (this.adapterConstructor) {
|
||||
server.adapter(this.adapterConstructor);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
buildEndpointReportFromLocalEvents,
|
||||
buildNewRelicCustomEventNrql,
|
||||
buildNewRelicTransactionNrql,
|
||||
discoverApiRoutes,
|
||||
formatMarkdownReport,
|
||||
mergeRowsWithManifest,
|
||||
} from './api-performance-report';
|
||||
import type { ApiPerformanceEvent } from '../modules/global/observability/performance-observer';
|
||||
|
||||
describe('api performance route discovery', () => {
|
||||
let rootDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
rootDir = await mkdtemp(path.join(os.tmpdir(), 'api-performance-routes-'));
|
||||
await mkdir(path.join(rootDir, 'modules', 'match'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(rootDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('discovers controller routes including multiline decorators', async () => {
|
||||
await writeFile(
|
||||
path.join(rootDir, 'modules', 'match', 'match.controller.ts'),
|
||||
`
|
||||
import { Controller, Get, Post } from '@nestjs/common';
|
||||
|
||||
@Controller('communities/:communityId/matches')
|
||||
export class MatchController {
|
||||
@Get()
|
||||
list() {}
|
||||
|
||||
@Post(
|
||||
':matchId/participants'
|
||||
)
|
||||
join() {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
await writeFile(
|
||||
path.join(rootDir, 'app.controller.ts'),
|
||||
`
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
@Get()
|
||||
root() {}
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
await expect(discoverApiRoutes(rootDir)).resolves.toEqual([
|
||||
{
|
||||
method: 'GET',
|
||||
route: '/',
|
||||
controllerFile: 'app.controller.ts',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
route: '/communities/:communityId/matches',
|
||||
controllerFile: 'modules/match/match.controller.ts',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
route: '/communities/:communityId/matches/:matchId/participants',
|
||||
controllerFile: 'modules/match/match.controller.ts',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('api performance report generation', () => {
|
||||
it('reports every manifest route, including routes with no samples', () => {
|
||||
const routes = [
|
||||
{
|
||||
method: 'GET',
|
||||
route: '/communities/:communityId/matches',
|
||||
controllerFile: 'match.controller.ts',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
route: '/communities/:communityId/matches',
|
||||
controllerFile: 'match.controller.ts',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
route: '/communities/:communityId/internal-stats/matches',
|
||||
controllerFile: 'community-stats.controller.ts',
|
||||
},
|
||||
];
|
||||
const events: ApiPerformanceEvent[] = [
|
||||
{
|
||||
type: 'api-request',
|
||||
timestamp: '2026-06-28T00:00:00.000Z',
|
||||
requestId: 'request-1',
|
||||
method: 'GET',
|
||||
route: '/communities/:communityId/matches',
|
||||
path: '/communities/abc/matches',
|
||||
statusCode: 200,
|
||||
durationMs: 100,
|
||||
isError: false,
|
||||
queryCount: 2,
|
||||
mongooseDurationMs: 40,
|
||||
docsReturned: 50,
|
||||
hydratedDocsReturned: 50,
|
||||
leanQueryCount: 0,
|
||||
},
|
||||
];
|
||||
|
||||
const rows = buildEndpointReportFromLocalEvents({
|
||||
routes,
|
||||
events,
|
||||
p95BudgetMs: 300,
|
||||
docsReturnedP95Budget: 500,
|
||||
hydratedDocsReturnedP95Budget: 0,
|
||||
});
|
||||
|
||||
expect(rows).toHaveLength(3);
|
||||
expect(
|
||||
rows.find(
|
||||
(row) => row.route === '/communities/:communityId/matches',
|
||||
)?.status,
|
||||
).toBe('document-heavy');
|
||||
expect(rows.filter((row) => row.status === 'no-samples')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('keeps observed-only New Relic rows while adding no-sample manifest routes', () => {
|
||||
const rows = mergeRowsWithManifest({
|
||||
routes: [
|
||||
{
|
||||
method: 'GET',
|
||||
route: '/known',
|
||||
controllerFile: 'known.controller.ts',
|
||||
},
|
||||
],
|
||||
measuredRows: [
|
||||
{
|
||||
method: 'GET',
|
||||
route: '/observed-only',
|
||||
source: 'newrelic-transaction',
|
||||
samples: 10,
|
||||
avgMs: 40,
|
||||
p50Ms: 35,
|
||||
p95Ms: 80,
|
||||
p99Ms: 120,
|
||||
maxMs: 130,
|
||||
errorRatePercentage: 0,
|
||||
queryCountP95: null,
|
||||
mongooseDurationP95Ms: null,
|
||||
docsReturnedP95: null,
|
||||
hydratedDocsReturnedP95: null,
|
||||
status: 'ok',
|
||||
},
|
||||
],
|
||||
fallbackSource: 'newrelic-transaction',
|
||||
p95BudgetMs: 300,
|
||||
docsReturnedP95Budget: 500,
|
||||
hydratedDocsReturnedP95Budget: 0,
|
||||
});
|
||||
|
||||
expect(rows.map((row) => `${row.method} ${row.route}`)).toEqual([
|
||||
'GET /known',
|
||||
'GET /observed-only',
|
||||
]);
|
||||
expect(rows[0].status).toBe('no-samples');
|
||||
expect(rows[1].samples).toBe(10);
|
||||
});
|
||||
|
||||
it('formats all rows instead of truncating to a top list', () => {
|
||||
const rows = Array.from({ length: 12 }, (_, index) => ({
|
||||
method: 'GET',
|
||||
route: `/route-${index}`,
|
||||
source: 'local' as const,
|
||||
samples: 1,
|
||||
avgMs: 10,
|
||||
p50Ms: 10,
|
||||
p95Ms: 10,
|
||||
p99Ms: 10,
|
||||
maxMs: 10,
|
||||
errorRatePercentage: 0,
|
||||
queryCountP95: 1,
|
||||
mongooseDurationP95Ms: 1,
|
||||
docsReturnedP95: 1,
|
||||
hydratedDocsReturnedP95: 0,
|
||||
status: 'ok' as const,
|
||||
}));
|
||||
|
||||
const report = formatMarkdownReport({
|
||||
rows,
|
||||
source: 'local',
|
||||
since: 'fixture',
|
||||
});
|
||||
|
||||
expect(report).toContain('/route-0');
|
||||
expect(report).toContain('/route-11');
|
||||
});
|
||||
|
||||
it('builds New Relic queries for custom events and transaction duration data', () => {
|
||||
expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain(
|
||||
'FROM ApiRequestPerformance',
|
||||
);
|
||||
expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain(
|
||||
'FACET method, route',
|
||||
);
|
||||
expect(
|
||||
buildNewRelicTransactionNrql('lolympus-api', '1 day ago'),
|
||||
).toContain('FROM Transaction');
|
||||
expect(
|
||||
buildNewRelicTransactionNrql('lolympus-api', '1 day ago'),
|
||||
).toContain('FACET name');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,808 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import { readdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import type {
|
||||
ApiPerformanceEvent,
|
||||
ApiRequestPerformanceEvent,
|
||||
} from '../modules/global/observability/performance-observer';
|
||||
|
||||
export type ReportSource =
|
||||
| 'local'
|
||||
| 'newrelic-custom'
|
||||
| 'newrelic-transaction';
|
||||
|
||||
export interface ApiRoute {
|
||||
method: string;
|
||||
route: string;
|
||||
controllerFile: string;
|
||||
}
|
||||
|
||||
export interface EndpointReportRow {
|
||||
method: string;
|
||||
route: string;
|
||||
controllerFile?: string;
|
||||
source: ReportSource | 'none';
|
||||
samples: number;
|
||||
avgMs: number | null;
|
||||
p50Ms: number | null;
|
||||
p95Ms: number | null;
|
||||
p99Ms: number | null;
|
||||
maxMs: number | null;
|
||||
errorRatePercentage: number | null;
|
||||
queryCountP95: number | null;
|
||||
mongooseDurationP95Ms: number | null;
|
||||
docsReturnedP95: number | null;
|
||||
hydratedDocsReturnedP95: number | null;
|
||||
status: 'ok' | 'slow' | 'document-heavy' | 'no-samples';
|
||||
}
|
||||
|
||||
interface ReportOptions {
|
||||
source: ReportSource;
|
||||
rootDir: string;
|
||||
inputFile: string;
|
||||
outputFile?: string;
|
||||
format: 'markdown' | 'json';
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
since: string;
|
||||
newRelicAccountId?: string;
|
||||
newRelicApiKey?: string;
|
||||
newRelicAppName: string;
|
||||
routesOnly: boolean;
|
||||
}
|
||||
|
||||
interface NewRelicNrqlResponse {
|
||||
data?: {
|
||||
actor?: {
|
||||
account?: {
|
||||
nrql?: {
|
||||
results?: Record<string, unknown>[];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
errors?: Array<{ message?: string }>;
|
||||
}
|
||||
|
||||
const HTTP_DECORATOR_TO_METHOD: Record<string, string> = {
|
||||
All: 'ALL',
|
||||
Delete: 'DELETE',
|
||||
Get: 'GET',
|
||||
Head: 'HEAD',
|
||||
Options: 'OPTIONS',
|
||||
Patch: 'PATCH',
|
||||
Post: 'POST',
|
||||
Put: 'PUT',
|
||||
};
|
||||
|
||||
export async function discoverApiRoutes(rootDir: string): Promise<ApiRoute[]> {
|
||||
const files = await listControllerFiles(rootDir);
|
||||
const routes = new Map<string, ApiRoute>();
|
||||
|
||||
for (const file of files) {
|
||||
const source = await readFile(file, 'utf8');
|
||||
const basePath = extractDecoratorStringArgument(source, 'Controller');
|
||||
if (basePath === undefined) continue;
|
||||
|
||||
const methodDecoratorRegex =
|
||||
/@(Get|Post|Patch|Put|Delete|Head|Options|All)\s*\(([\s\S]*?)\)/g;
|
||||
for (const match of source.matchAll(methodDecoratorRegex)) {
|
||||
const method = HTTP_DECORATOR_TO_METHOD[match[1]];
|
||||
const route = normalizeRoute(
|
||||
joinRouteParts(basePath, extractFirstStringLiteral(match[2]) ?? ''),
|
||||
);
|
||||
const key = routeKey(method, route);
|
||||
routes.set(key, {
|
||||
method,
|
||||
route,
|
||||
controllerFile: path.relative(rootDir, file),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [...routes.values()].sort(
|
||||
(left, right) =>
|
||||
left.route.localeCompare(right.route) ||
|
||||
left.method.localeCompare(right.method),
|
||||
);
|
||||
}
|
||||
|
||||
export async function readLocalPerformanceEvents(
|
||||
inputFile: string,
|
||||
): Promise<ApiPerformanceEvent[]> {
|
||||
if (!existsSync(inputFile)) return [];
|
||||
|
||||
const content = await readFile(inputFile, 'utf8');
|
||||
return content
|
||||
.split(/\r?\n/)
|
||||
.filter(Boolean)
|
||||
.flatMap((line) => {
|
||||
try {
|
||||
return [JSON.parse(line) as ApiPerformanceEvent];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function buildEndpointReportFromLocalEvents(params: {
|
||||
routes: ApiRoute[];
|
||||
events: ApiPerformanceEvent[];
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
}): EndpointReportRow[] {
|
||||
const requestsByRoute = new Map<string, ApiRequestPerformanceEvent[]>();
|
||||
for (const event of params.events) {
|
||||
if (event.type !== 'api-request') continue;
|
||||
const key = routeKey(event.method, event.route);
|
||||
requestsByRoute.set(key, [...(requestsByRoute.get(key) ?? []), event]);
|
||||
}
|
||||
|
||||
const rowsByKey = new Map<string, EndpointReportRow>();
|
||||
for (const route of params.routes) {
|
||||
const events = requestsByRoute.get(routeKey(route.method, route.route)) ?? [];
|
||||
rowsByKey.set(
|
||||
routeKey(route.method, route.route),
|
||||
summarizeRequestEvents(route, events, {
|
||||
source: 'local',
|
||||
p95BudgetMs: params.p95BudgetMs,
|
||||
docsReturnedP95Budget: params.docsReturnedP95Budget,
|
||||
hydratedDocsReturnedP95Budget: params.hydratedDocsReturnedP95Budget,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
for (const [key, events] of requestsByRoute.entries()) {
|
||||
if (rowsByKey.has(key)) continue;
|
||||
const first = events[0];
|
||||
rowsByKey.set(
|
||||
key,
|
||||
summarizeRequestEvents(
|
||||
{
|
||||
method: first.method,
|
||||
route: first.route,
|
||||
controllerFile: 'observed-only',
|
||||
},
|
||||
events,
|
||||
{
|
||||
source: 'local',
|
||||
p95BudgetMs: params.p95BudgetMs,
|
||||
docsReturnedP95Budget: params.docsReturnedP95Budget,
|
||||
hydratedDocsReturnedP95Budget: params.hydratedDocsReturnedP95Budget,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return [...rowsByKey.values()].sort(compareReportRows);
|
||||
}
|
||||
|
||||
export async function fetchNewRelicEndpointRows(params: {
|
||||
source: Exclude<ReportSource, 'local'>;
|
||||
accountId: string;
|
||||
apiKey: string;
|
||||
appName: string;
|
||||
since: string;
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
}): Promise<EndpointReportRow[]> {
|
||||
const nrql =
|
||||
params.source === 'newrelic-custom'
|
||||
? buildNewRelicCustomEventNrql(params.appName, params.since)
|
||||
: buildNewRelicTransactionNrql(params.appName, params.since);
|
||||
const response = await fetch('https://api.newrelic.com/graphql', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Api-Key': params.apiKey,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: `{
|
||||
actor {
|
||||
account(id: ${Number(params.accountId)}) {
|
||||
nrql(query: ${JSON.stringify(nrql)}) {
|
||||
results
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`New Relic query failed: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const json = (await response.json()) as NewRelicNrqlResponse;
|
||||
if (json.errors?.length) {
|
||||
throw new Error(
|
||||
`New Relic query failed: ${json.errors
|
||||
.map((error) => error.message ?? 'unknown error')
|
||||
.join('; ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
const results = json.data?.actor?.account?.nrql?.results ?? [];
|
||||
return results
|
||||
.map((result) =>
|
||||
params.source === 'newrelic-custom'
|
||||
? newRelicCustomResultToRow(result, params)
|
||||
: newRelicTransactionResultToRow(result, params),
|
||||
)
|
||||
.filter((row): row is EndpointReportRow => row !== null)
|
||||
.sort(compareReportRows);
|
||||
}
|
||||
|
||||
export function mergeRowsWithManifest(params: {
|
||||
routes: ApiRoute[];
|
||||
measuredRows: EndpointReportRow[];
|
||||
fallbackSource: ReportSource;
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
}): EndpointReportRow[] {
|
||||
const rowsByKey = new Map(
|
||||
params.measuredRows.map((row) => [routeKey(row.method, row.route), row]),
|
||||
);
|
||||
|
||||
for (const route of params.routes) {
|
||||
const key = routeKey(route.method, route.route);
|
||||
if (rowsByKey.has(key)) {
|
||||
rowsByKey.set(key, {
|
||||
...rowsByKey.get(key)!,
|
||||
controllerFile: route.controllerFile,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
rowsByKey.set(key, {
|
||||
method: route.method,
|
||||
route: route.route,
|
||||
controllerFile: route.controllerFile,
|
||||
source: 'none',
|
||||
samples: 0,
|
||||
avgMs: null,
|
||||
p50Ms: null,
|
||||
p95Ms: null,
|
||||
p99Ms: null,
|
||||
maxMs: null,
|
||||
errorRatePercentage: null,
|
||||
queryCountP95: null,
|
||||
mongooseDurationP95Ms: null,
|
||||
docsReturnedP95: null,
|
||||
hydratedDocsReturnedP95: null,
|
||||
status: 'no-samples',
|
||||
});
|
||||
}
|
||||
|
||||
return [...rowsByKey.values()].sort(compareReportRows);
|
||||
}
|
||||
|
||||
export function formatMarkdownReport(params: {
|
||||
rows: EndpointReportRow[];
|
||||
source: ReportSource;
|
||||
since: string;
|
||||
notes?: string[];
|
||||
}): string {
|
||||
const sampled = params.rows.filter((row) => row.samples > 0);
|
||||
const noSamples = params.rows.length - sampled.length;
|
||||
const slow = sampled.filter((row) => row.status === 'slow').length;
|
||||
const documentHeavy = sampled.filter(
|
||||
(row) => row.status === 'document-heavy',
|
||||
).length;
|
||||
|
||||
const lines = [
|
||||
'# API Performance Report',
|
||||
'',
|
||||
`- Source: ${params.source}`,
|
||||
`- Window: ${params.since}`,
|
||||
`- Routes: ${params.rows.length}`,
|
||||
`- Sampled routes: ${sampled.length}`,
|
||||
`- No-sample routes: ${noSamples}`,
|
||||
`- Slow routes: ${slow}`,
|
||||
`- Document-heavy routes: ${documentHeavy}`,
|
||||
];
|
||||
|
||||
if (params.notes?.length) {
|
||||
lines.push('', '## Notes', '');
|
||||
for (const note of params.notes) lines.push(`- ${note}`);
|
||||
}
|
||||
|
||||
lines.push(
|
||||
'',
|
||||
'| Method | Route | Samples | p95 ms | p99 ms | Avg ms | Error % | Query p95 | Docs p95 | Hydrated p95 | Status |',
|
||||
'|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|',
|
||||
);
|
||||
|
||||
for (const row of params.rows) {
|
||||
lines.push(
|
||||
[
|
||||
`| ${row.method}`,
|
||||
markdownCell(row.route),
|
||||
String(row.samples),
|
||||
formatNumber(row.p95Ms),
|
||||
formatNumber(row.p99Ms),
|
||||
formatNumber(row.avgMs),
|
||||
formatNumber(row.errorRatePercentage),
|
||||
formatNumber(row.queryCountP95),
|
||||
formatNumber(row.docsReturnedP95),
|
||||
formatNumber(row.hydratedDocsReturnedP95),
|
||||
`${row.status} |`,
|
||||
].join(' | '),
|
||||
);
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export function buildNewRelicCustomEventNrql(
|
||||
appName: string,
|
||||
since: string,
|
||||
): string {
|
||||
return [
|
||||
'FROM ApiRequestPerformance',
|
||||
'SELECT count(*) AS samples,',
|
||||
'average(durationMs) AS avgDurationMs,',
|
||||
'percentile(durationMs, 50, 95, 99) AS durationPercentilesMs,',
|
||||
'max(durationMs) AS maxDurationMs,',
|
||||
'percentage(count(*), WHERE isError IS true) AS errorRatePercentage,',
|
||||
'percentile(queryCount, 95) AS queryCountPercentiles,',
|
||||
'percentile(docsReturned, 95) AS docsReturnedPercentiles,',
|
||||
'percentile(hydratedDocsReturned, 95) AS hydratedDocsReturnedPercentiles,',
|
||||
'percentile(mongooseDurationMs, 95) AS mongooseDurationPercentiles',
|
||||
`WHERE appName = '${escapeNrqlString(appName)}'`,
|
||||
'FACET method, route',
|
||||
`SINCE ${since}`,
|
||||
'LIMIT MAX',
|
||||
].join(' ');
|
||||
}
|
||||
|
||||
export function buildNewRelicTransactionNrql(
|
||||
appName: string,
|
||||
since: string,
|
||||
): string {
|
||||
return [
|
||||
'FROM Transaction',
|
||||
'SELECT count(*) AS samples,',
|
||||
'average(duration) AS avgDurationSec,',
|
||||
'percentile(duration, 50, 95, 99) AS durationPercentilesSec,',
|
||||
'max(duration) AS maxDurationSec,',
|
||||
'percentage(count(*), WHERE error IS true) AS errorRatePercentage',
|
||||
`WHERE appName = '${escapeNrqlString(appName)}'`,
|
||||
'FACET name',
|
||||
`SINCE ${since}`,
|
||||
'LIMIT MAX',
|
||||
].join(' ');
|
||||
}
|
||||
|
||||
function summarizeRequestEvents(
|
||||
route: ApiRoute,
|
||||
events: ApiRequestPerformanceEvent[],
|
||||
options: {
|
||||
source: ReportSource;
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
},
|
||||
): EndpointReportRow {
|
||||
const row: EndpointReportRow = {
|
||||
method: route.method,
|
||||
route: route.route,
|
||||
controllerFile: route.controllerFile,
|
||||
source: events.length > 0 ? options.source : 'none',
|
||||
samples: events.length,
|
||||
avgMs: average(events.map((event) => event.durationMs)),
|
||||
p50Ms: percentile(
|
||||
events.map((event) => event.durationMs),
|
||||
50,
|
||||
),
|
||||
p95Ms: percentile(
|
||||
events.map((event) => event.durationMs),
|
||||
95,
|
||||
),
|
||||
p99Ms: percentile(
|
||||
events.map((event) => event.durationMs),
|
||||
99,
|
||||
),
|
||||
maxMs: max(events.map((event) => event.durationMs)),
|
||||
errorRatePercentage:
|
||||
events.length > 0
|
||||
? (events.filter((event) => event.isError).length / events.length) * 100
|
||||
: null,
|
||||
queryCountP95: percentile(
|
||||
events.map((event) => event.queryCount),
|
||||
95,
|
||||
),
|
||||
mongooseDurationP95Ms: percentile(
|
||||
events.map((event) => event.mongooseDurationMs),
|
||||
95,
|
||||
),
|
||||
docsReturnedP95: percentile(
|
||||
events.map((event) => event.docsReturned),
|
||||
95,
|
||||
),
|
||||
hydratedDocsReturnedP95: percentile(
|
||||
events.map((event) => event.hydratedDocsReturned),
|
||||
95,
|
||||
),
|
||||
status: 'ok',
|
||||
};
|
||||
row.status = classifyRow(row, options);
|
||||
return row;
|
||||
}
|
||||
|
||||
function newRelicCustomResultToRow(
|
||||
result: Record<string, unknown>,
|
||||
options: {
|
||||
source: ReportSource;
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
},
|
||||
): EndpointReportRow | null {
|
||||
const facet = result.facet;
|
||||
const method = Array.isArray(facet) ? String(facet[0] ?? '') : undefined;
|
||||
const route = Array.isArray(facet) ? String(facet[1] ?? '') : undefined;
|
||||
if (!method || !route) return null;
|
||||
|
||||
const row: EndpointReportRow = {
|
||||
method,
|
||||
route: normalizeRoute(route),
|
||||
source: 'newrelic-custom',
|
||||
samples: numberField(result.samples),
|
||||
avgMs: numberOrNull(result.avgDurationMs),
|
||||
p50Ms: percentileField(result.durationPercentilesMs, 50),
|
||||
p95Ms: percentileField(result.durationPercentilesMs, 95),
|
||||
p99Ms: percentileField(result.durationPercentilesMs, 99),
|
||||
maxMs: numberOrNull(result.maxDurationMs),
|
||||
errorRatePercentage: numberOrNull(result.errorRatePercentage),
|
||||
queryCountP95: percentileField(result.queryCountPercentiles, 95),
|
||||
mongooseDurationP95Ms: percentileField(
|
||||
result.mongooseDurationPercentiles,
|
||||
95,
|
||||
),
|
||||
docsReturnedP95: percentileField(result.docsReturnedPercentiles, 95),
|
||||
hydratedDocsReturnedP95: percentileField(
|
||||
result.hydratedDocsReturnedPercentiles,
|
||||
95,
|
||||
),
|
||||
status: 'ok',
|
||||
};
|
||||
row.status = classifyRow(row, options);
|
||||
return row;
|
||||
}
|
||||
|
||||
function newRelicTransactionResultToRow(
|
||||
result: Record<string, unknown>,
|
||||
options: {
|
||||
source: ReportSource;
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
},
|
||||
): EndpointReportRow | null {
|
||||
const parsed = parseTransactionName(String(result.facet ?? ''));
|
||||
if (!parsed) return null;
|
||||
|
||||
const row: EndpointReportRow = {
|
||||
method: parsed.method,
|
||||
route: parsed.route,
|
||||
source: 'newrelic-transaction',
|
||||
samples: numberField(result.samples),
|
||||
avgMs: secondsToMs(result.avgDurationSec),
|
||||
p50Ms: secondsToMs(percentileField(result.durationPercentilesSec, 50)),
|
||||
p95Ms: secondsToMs(percentileField(result.durationPercentilesSec, 95)),
|
||||
p99Ms: secondsToMs(percentileField(result.durationPercentilesSec, 99)),
|
||||
maxMs: secondsToMs(result.maxDurationSec),
|
||||
errorRatePercentage: numberOrNull(result.errorRatePercentage),
|
||||
queryCountP95: null,
|
||||
mongooseDurationP95Ms: null,
|
||||
docsReturnedP95: null,
|
||||
hydratedDocsReturnedP95: null,
|
||||
status: 'ok',
|
||||
};
|
||||
row.status = classifyRow(row, options);
|
||||
return row;
|
||||
}
|
||||
|
||||
function parseTransactionName(
|
||||
name: string,
|
||||
): { method: string; route: string } | null {
|
||||
const match = name.match(
|
||||
/\b(GET|POST|PATCH|PUT|DELETE|HEAD|OPTIONS|ALL)[\s/]+(\/.*)$/i,
|
||||
);
|
||||
if (!match) return null;
|
||||
return {
|
||||
method: match[1].toUpperCase(),
|
||||
route: normalizeRoute(match[2]),
|
||||
};
|
||||
}
|
||||
|
||||
function classifyRow(
|
||||
row: EndpointReportRow,
|
||||
options: {
|
||||
p95BudgetMs: number;
|
||||
docsReturnedP95Budget: number;
|
||||
hydratedDocsReturnedP95Budget: number;
|
||||
},
|
||||
): EndpointReportRow['status'] {
|
||||
if (row.samples === 0) return 'no-samples';
|
||||
if (row.p95Ms !== null && row.p95Ms > options.p95BudgetMs) return 'slow';
|
||||
if (
|
||||
(row.docsReturnedP95 !== null &&
|
||||
row.docsReturnedP95 > options.docsReturnedP95Budget) ||
|
||||
(row.hydratedDocsReturnedP95 !== null &&
|
||||
row.hydratedDocsReturnedP95 >
|
||||
options.hydratedDocsReturnedP95Budget)
|
||||
) {
|
||||
return 'document-heavy';
|
||||
}
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
async function listControllerFiles(rootDir: string): Promise<string[]> {
|
||||
const entries = await readdir(rootDir, { withFileTypes: true });
|
||||
const files = await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const fullPath = path.join(rootDir, entry.name);
|
||||
if (entry.isDirectory()) return listControllerFiles(fullPath);
|
||||
return entry.isFile() && entry.name.endsWith('.controller.ts')
|
||||
? [fullPath]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
return files.flat();
|
||||
}
|
||||
|
||||
function extractDecoratorStringArgument(
|
||||
source: string,
|
||||
decoratorName: string,
|
||||
): string | undefined {
|
||||
const regex = new RegExp(`@${decoratorName}\\s*\\(([\\s\\S]*?)\\)`);
|
||||
const match = source.match(regex);
|
||||
if (!match) return undefined;
|
||||
return extractFirstStringLiteral(match[1]) ?? '';
|
||||
}
|
||||
|
||||
function extractFirstStringLiteral(input: string): string | undefined {
|
||||
const match = input.match(/['"`]([^'"`]*)['"`]/);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
function joinRouteParts(basePath: string, routePath: string): string {
|
||||
return [basePath, routePath]
|
||||
.filter((part) => part !== '')
|
||||
.join('/')
|
||||
.replace(/\/+/g, '/');
|
||||
}
|
||||
|
||||
function normalizeRoute(route: string): string {
|
||||
const normalized = route.startsWith('/') ? route : `/${route}`;
|
||||
return normalized.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
||||
}
|
||||
|
||||
function routeKey(method: string, route: string): string {
|
||||
return `${method.toUpperCase()} ${normalizeRoute(route)}`;
|
||||
}
|
||||
|
||||
function compareReportRows(left: EndpointReportRow, right: EndpointReportRow) {
|
||||
return (
|
||||
left.route.localeCompare(right.route) ||
|
||||
left.method.localeCompare(right.method)
|
||||
);
|
||||
}
|
||||
|
||||
function percentile(values: number[], percentileValue: number): number | null {
|
||||
if (values.length === 0) return null;
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
const index = Math.ceil((percentileValue / 100) * sorted.length) - 1;
|
||||
return sorted[Math.max(0, Math.min(sorted.length - 1, index))];
|
||||
}
|
||||
|
||||
function average(values: number[]): number | null {
|
||||
if (values.length === 0) return null;
|
||||
return values.reduce((acc, value) => acc + value, 0) / values.length;
|
||||
}
|
||||
|
||||
function max(values: number[]): number | null {
|
||||
if (values.length === 0) return null;
|
||||
return Math.max(...values);
|
||||
}
|
||||
|
||||
function percentileField(value: unknown, percentileValue: number): number | null {
|
||||
if (!value || typeof value !== 'object') return null;
|
||||
const map = value as Record<string, unknown>;
|
||||
return numberOrNull(map[String(percentileValue)] ?? map[percentileValue]);
|
||||
}
|
||||
|
||||
function numberField(value: unknown): number {
|
||||
return numberOrNull(value) ?? 0;
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function secondsToMs(value: unknown): number | null {
|
||||
const seconds = numberOrNull(value);
|
||||
return seconds === null ? null : seconds * 1000;
|
||||
}
|
||||
|
||||
function formatNumber(value: number | null): string {
|
||||
return value === null ? '-' : value.toFixed(value >= 100 ? 0 : 1);
|
||||
}
|
||||
|
||||
function markdownCell(value: string): string {
|
||||
return value.replace(/\|/g, '\\|');
|
||||
}
|
||||
|
||||
function escapeNrqlString(value: string): string {
|
||||
return value.replace(/'/g, "\\'");
|
||||
}
|
||||
|
||||
function parseArgs(argv: string[]): ReportOptions {
|
||||
const args = new Map<string, string | boolean>();
|
||||
for (const arg of argv) {
|
||||
if (!arg.startsWith('--')) continue;
|
||||
const [key, rawValue] = arg.slice(2).split('=', 2);
|
||||
args.set(key, rawValue ?? true);
|
||||
}
|
||||
|
||||
const source = stringArg(args, 'source', defaultReportSource()) as ReportSource;
|
||||
return {
|
||||
source,
|
||||
rootDir: path.resolve(
|
||||
stringArg(args, 'root-dir', path.join(process.cwd(), 'src')),
|
||||
),
|
||||
inputFile: path.resolve(
|
||||
stringArg(
|
||||
args,
|
||||
'input',
|
||||
process.env.API_PERF_LOCAL_EVENT_FILE ??
|
||||
'/tmp/lolympus-api-performance.ndjson',
|
||||
),
|
||||
),
|
||||
outputFile: optionalStringArg(args, 'output'),
|
||||
format: stringArg(args, 'format', 'markdown') as 'markdown' | 'json',
|
||||
p95BudgetMs: numberArg(args, 'p95-budget-ms', 300),
|
||||
docsReturnedP95Budget: numberArg(args, 'docs-returned-p95-budget', 500),
|
||||
hydratedDocsReturnedP95Budget: numberArg(
|
||||
args,
|
||||
'hydrated-docs-returned-p95-budget',
|
||||
0,
|
||||
),
|
||||
since: stringArg(args, 'since', '1 day ago'),
|
||||
newRelicAccountId:
|
||||
optionalStringArg(args, 'new-relic-account-id') ??
|
||||
process.env.NEW_RELIC_ACCOUNT_ID,
|
||||
newRelicApiKey:
|
||||
optionalStringArg(args, 'new-relic-api-key') ??
|
||||
process.env.NEW_RELIC_USER_API_KEY ??
|
||||
process.env.NEW_RELIC_API_KEY,
|
||||
newRelicAppName:
|
||||
optionalStringArg(args, 'new-relic-app-name') ??
|
||||
process.env.NEW_RELIC_APP_NAME ??
|
||||
'lolympus',
|
||||
routesOnly: args.has('routes-only'),
|
||||
};
|
||||
}
|
||||
|
||||
function defaultReportSource(): ReportSource {
|
||||
return process.env.NEW_RELIC_ACCOUNT_ID &&
|
||||
(process.env.NEW_RELIC_USER_API_KEY || process.env.NEW_RELIC_API_KEY)
|
||||
? 'newrelic-custom'
|
||||
: 'local';
|
||||
}
|
||||
|
||||
function stringArg(
|
||||
args: Map<string, string | boolean>,
|
||||
name: string,
|
||||
defaultValue: string,
|
||||
): string {
|
||||
const value = args.get(name);
|
||||
return typeof value === 'string' && value !== '' ? value : defaultValue;
|
||||
}
|
||||
|
||||
function optionalStringArg(
|
||||
args: Map<string, string | boolean>,
|
||||
name: string,
|
||||
): string | undefined {
|
||||
const value = args.get(name);
|
||||
return typeof value === 'string' && value !== '' ? value : undefined;
|
||||
}
|
||||
|
||||
function numberArg(
|
||||
args: Map<string, string | boolean>,
|
||||
name: string,
|
||||
defaultValue: number,
|
||||
): number {
|
||||
const value = Number(stringArg(args, name, String(defaultValue)));
|
||||
return Number.isFinite(value) ? value : defaultValue;
|
||||
}
|
||||
|
||||
async function buildReport(options: ReportOptions): Promise<string> {
|
||||
const routes = await discoverApiRoutes(options.rootDir);
|
||||
if (options.routesOnly) {
|
||||
return `${JSON.stringify(routes, null, 2)}\n`;
|
||||
}
|
||||
|
||||
const measuredRows =
|
||||
options.source === 'local'
|
||||
? buildEndpointReportFromLocalEvents({
|
||||
routes,
|
||||
events: await readLocalPerformanceEvents(options.inputFile),
|
||||
p95BudgetMs: options.p95BudgetMs,
|
||||
docsReturnedP95Budget: options.docsReturnedP95Budget,
|
||||
hydratedDocsReturnedP95Budget:
|
||||
options.hydratedDocsReturnedP95Budget,
|
||||
})
|
||||
: await fetchNewRelicEndpointRows({
|
||||
source: options.source,
|
||||
accountId: requireOption(
|
||||
options.newRelicAccountId,
|
||||
'NEW_RELIC_ACCOUNT_ID',
|
||||
),
|
||||
apiKey: requireOption(options.newRelicApiKey, 'NEW_RELIC_API_KEY'),
|
||||
appName: options.newRelicAppName,
|
||||
since: options.since,
|
||||
p95BudgetMs: options.p95BudgetMs,
|
||||
docsReturnedP95Budget: options.docsReturnedP95Budget,
|
||||
hydratedDocsReturnedP95Budget:
|
||||
options.hydratedDocsReturnedP95Budget,
|
||||
});
|
||||
const notes =
|
||||
options.source === 'newrelic-custom' && measuredRows.length === 0
|
||||
? [
|
||||
'No ApiRequestPerformance custom events were found for this window and appName.',
|
||||
'Custom events are created only after the API runs with API_PERF_OBSERVABILITY_ENABLED=true and API_PERF_NEW_RELIC_REQUEST_EVENTS_ENABLED=true.',
|
||||
'Use --source=newrelic-transaction for historical latency before custom instrumentation was enabled.',
|
||||
]
|
||||
: [];
|
||||
const rows = mergeRowsWithManifest({
|
||||
routes,
|
||||
measuredRows,
|
||||
fallbackSource: options.source,
|
||||
p95BudgetMs: options.p95BudgetMs,
|
||||
docsReturnedP95Budget: options.docsReturnedP95Budget,
|
||||
hydratedDocsReturnedP95Budget: options.hydratedDocsReturnedP95Budget,
|
||||
});
|
||||
|
||||
return options.format === 'json'
|
||||
? `${JSON.stringify(rows, null, 2)}\n`
|
||||
: formatMarkdownReport({
|
||||
rows,
|
||||
source: options.source,
|
||||
since: options.since,
|
||||
notes,
|
||||
});
|
||||
}
|
||||
|
||||
function requireOption(value: string | undefined, name: string): string {
|
||||
if (value) return value;
|
||||
throw new Error(`${name} is required for New Relic report sources.`);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const report = await buildReport(options);
|
||||
if (options.outputFile) {
|
||||
await writeFile(path.resolve(options.outputFile), report);
|
||||
return;
|
||||
}
|
||||
process.stdout.write(report);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
void main().catch((error: unknown) => {
|
||||
process.stderr.write(
|
||||
`${error instanceof Error ? error.message : String(error)}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
@@ -5,3 +5,11 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html
|
||||
VITE_NEW_RELIC_ENABLED=false
|
||||
VITE_NEW_RELIC_APPLICATION_ID=601654991
|
||||
VITE_NEW_RELIC_ACCOUNT_ID=8100154
|
||||
VITE_NEW_RELIC_AGENT_ID=601654991
|
||||
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
|
||||
VITE_NEW_RELIC_TRUST_KEY=8100154
|
||||
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
||||
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
||||
@@ -5,3 +5,13 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/<tenant-id>
|
||||
VITE_MSAL_API_SCOPE=api://lolympus-api/access_as_user
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
VITE_MSAL_SILENT_REDIRECT_URI=http://localhost:5173/auth/silent-callback.html
|
||||
VITE_NEW_RELIC_ENABLED=false
|
||||
VITE_NEW_RELIC_APPLICATION_ID=
|
||||
VITE_NEW_RELIC_ACCOUNT_ID=
|
||||
VITE_NEW_RELIC_AGENT_ID=
|
||||
VITE_NEW_RELIC_LICENSE_KEY=
|
||||
VITE_NEW_RELIC_TRUST_KEY=
|
||||
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
||||
VITE_NEW_RELIC_APPLICATION_VERSION=
|
||||
VITE_NEW_RELIC_RELEASE_ID=
|
||||
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
||||
@@ -5,4 +5,13 @@ VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback
|
||||
VITE_MSAL_SILENT_REDIRECT_URI=https://lolympus.dahyeon.us/auth/silent-callback.html
|
||||
|
||||
VITE_NEW_RELIC_ENABLED=true
|
||||
VITE_NEW_RELIC_APPLICATION_ID=601654991
|
||||
VITE_NEW_RELIC_ACCOUNT_ID=8100154
|
||||
VITE_NEW_RELIC_AGENT_ID=601654991
|
||||
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
|
||||
VITE_NEW_RELIC_TRUST_KEY=8100154
|
||||
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
||||
VITE_NEW_RELIC_APPLICATION_VERSION=83
|
||||
VITE_NEW_RELIC_RELEASE_ID=release-83
|
||||
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
||||
+12
-2
@@ -1,6 +1,16 @@
|
||||
VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us
|
||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||
VITE_MSAL_CLIENT_ID=66dadf46-418c-43c8-a908-3c15dcc0465d
|
||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||
VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback
|
||||
VITE_MSAL_REDIRECT_URI=https://release-83.lolympus.pages.dev/auth/callback
|
||||
VITE_NEW_RELIC_ENABLED=true
|
||||
VITE_NEW_RELIC_APPLICATION_ID=601654991
|
||||
VITE_NEW_RELIC_ACCOUNT_ID=8100154
|
||||
VITE_NEW_RELIC_AGENT_ID=601654991
|
||||
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
|
||||
VITE_NEW_RELIC_TRUST_KEY=8100154
|
||||
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
||||
VITE_NEW_RELIC_APPLICATION_VERSION=83
|
||||
VITE_NEW_RELIC_RELEASE_ID=release-83
|
||||
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
||||
@@ -20,6 +20,7 @@
|
||||
"dependencies": {
|
||||
"@azure/msal-browser": "^5.8.0",
|
||||
"@azure/msal-react": "^5.3.1",
|
||||
"@newrelic/browser-agent": "^1.316.0",
|
||||
"@tanstack/react-query": "^5.100.1",
|
||||
"lucide-react": "^1.14.0",
|
||||
"react": "^19.2.4",
|
||||
|
||||
@@ -170,6 +170,10 @@ function App() {
|
||||
path="/communities/:cid/internal-stats/match/:matchId"
|
||||
element={<InternalMatchDetailPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/communities/:cid/internal-stats/match/:matchId/game/:gameNumber"
|
||||
element={<MatchGameDetailPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/communities/:cid/matches"
|
||||
element={<MatchAdminPage />}
|
||||
|
||||
@@ -310,6 +310,101 @@ export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useReshuffleDoubleEliminationSeeds(
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useMutation({
|
||||
mutationFn: (matchId: string) =>
|
||||
apiFetch<ApiMatch>(
|
||||
`/communities/${communityId}/matches/${matchId}/double-elimination/seeds/reshuffle`,
|
||||
{ method: 'POST' },
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSwapDoubleEliminationSeeds(
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useMutation({
|
||||
mutationFn: (params: {
|
||||
matchId: string;
|
||||
leftSeedNumber: number;
|
||||
rightSeedNumber: number;
|
||||
}) =>
|
||||
apiFetch<ApiMatch>(
|
||||
`/communities/${communityId}/matches/${params.matchId}/double-elimination/seeds/swap`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
leftSeedNumber: params.leftSeedNumber,
|
||||
rightSeedNumber: params.rightSeedNumber,
|
||||
}),
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useApplyDoubleEliminationWalkover(
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useMutation({
|
||||
mutationFn: (params: {
|
||||
matchId: string;
|
||||
bracketMatchId: string;
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
}) =>
|
||||
apiFetch<ApiMatch>(
|
||||
`/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/walkover`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
winnerTeamIndex: params.winnerTeamIndex,
|
||||
reason: params.reason,
|
||||
}),
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCancelDoubleEliminationWalkover(
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useMutation({
|
||||
mutationFn: (params: {
|
||||
matchId: string;
|
||||
bracketMatchId: string;
|
||||
reason?: string;
|
||||
}) =>
|
||||
apiFetch<ApiMatch>(
|
||||
`/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/walkover/cancel`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason: params.reason }),
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCancelDoubleEliminationRiotResult(
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useMutation({
|
||||
mutationFn: (params: {
|
||||
matchId: string;
|
||||
bracketMatchId: string;
|
||||
reason?: string;
|
||||
}) =>
|
||||
apiFetch<ApiMatch>(
|
||||
`/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/result/cancel`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason: params.reason }),
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
function createUserHistoryPath(
|
||||
communityId: string,
|
||||
userId: string,
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
ApiRiotRecentStatsSummary,
|
||||
ApiTierHistoryEntry,
|
||||
ApiTierInfo,
|
||||
ApiDoubleEliminationBracket,
|
||||
MatchStatus,
|
||||
Position,
|
||||
RiotLane,
|
||||
@@ -53,6 +54,7 @@ export interface MatchDetailView {
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
gameMode: ApiMatch["gameMode"];
|
||||
doubleElimination?: ApiDoubleEliminationBracket;
|
||||
tournamentCodes: TournamentCodeSlotView[];
|
||||
joined: boolean;
|
||||
participants: ParticipantView[];
|
||||
@@ -63,6 +65,7 @@ export interface MatchDetailView {
|
||||
riotMatchIds: string[];
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
riotMatchId: string;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
@@ -462,6 +465,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
maxParticipants: match.maxParticipants,
|
||||
gameCount: match.gameCount ?? 3,
|
||||
gameMode: match.gameMode ?? "pair",
|
||||
doubleElimination: match.doubleElimination,
|
||||
tournamentCodes: match.tournamentCodes ?? [],
|
||||
joined: Boolean(match.joined),
|
||||
participants,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
||||
export type MatchGameMode =
|
||||
| 'pair'
|
||||
| 'bracket'
|
||||
| 'round-robin'
|
||||
| 'double-elimination';
|
||||
export type MatchStatus =
|
||||
| 'recruiting'
|
||||
| 'team-built'
|
||||
@@ -136,15 +140,22 @@ export type TournamentCodeState =
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'expired'
|
||||
| 'released';
|
||||
| 'released'
|
||||
| 'voided';
|
||||
|
||||
export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
seriesGameNumber?: number;
|
||||
seriesGameCount?: number;
|
||||
seriesRequiredWins?: number;
|
||||
bracketMatchId?: string;
|
||||
bracketSide?: string;
|
||||
roundNumber?: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
matchNumber?: number;
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeSlotState;
|
||||
@@ -189,6 +200,7 @@ export interface ApiMatchGameResultParticipant {
|
||||
|
||||
export interface ApiMatchGameResult {
|
||||
gameNumber: number;
|
||||
bracketMatchId?: string;
|
||||
riotMatchId: string;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
@@ -205,6 +217,7 @@ export interface ApiMatchResult {
|
||||
riotMatchIds: string[];
|
||||
games: ApiMatchGameResult[];
|
||||
seriesResults?: Array<{
|
||||
bracketMatchId?: string;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
@@ -225,6 +238,58 @@ export interface ApiMatchGameAssignment {
|
||||
teamBIndex: number;
|
||||
}
|
||||
|
||||
export interface ApiDoubleEliminationSeed {
|
||||
seedNumber: number;
|
||||
teamIndex: number;
|
||||
}
|
||||
|
||||
export interface ApiDoubleEliminationBracketDestination {
|
||||
bracketMatchId: string;
|
||||
position: 'A' | 'B';
|
||||
}
|
||||
|
||||
export interface ApiDoubleEliminationWalkover {
|
||||
winnerTeamIndex: number;
|
||||
reason?: string;
|
||||
awardedAt: string;
|
||||
cancelledAt?: string;
|
||||
cancelReason?: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface ApiDoubleEliminationBracketMatch {
|
||||
bracketMatchId: string;
|
||||
gameNumber: number;
|
||||
gameCount: number;
|
||||
requiredWins: number;
|
||||
bracketSide: 'winner' | 'loser' | 'grand-final' | 'reset-final';
|
||||
roundNumber: number;
|
||||
matchNumber: number;
|
||||
state: 'pending' | 'ready' | 'completed';
|
||||
teamAIndex?: number;
|
||||
teamBIndex?: number;
|
||||
winnerAdvancesTo?: ApiDoubleEliminationBracketDestination;
|
||||
loserAdvancesTo?: ApiDoubleEliminationBracketDestination;
|
||||
winnerTeamIndex?: number;
|
||||
loserTeamIndex?: number;
|
||||
completedBy?: 'riot-result' | 'walkover';
|
||||
completedAt?: string;
|
||||
walkover?: ApiDoubleEliminationWalkover;
|
||||
}
|
||||
|
||||
export interface ApiDoubleEliminationBracket {
|
||||
teamCount: 4 | 8;
|
||||
resetFinalEnabled: boolean;
|
||||
resetFinalCreated: boolean;
|
||||
seeds: ApiDoubleEliminationSeed[];
|
||||
bracketMatches: ApiDoubleEliminationBracketMatch[];
|
||||
placements: {
|
||||
firstTeamIndex?: number;
|
||||
secondTeamIndex?: number;
|
||||
thirdTeamIndex?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ManualTournamentResultCollectResponse {
|
||||
scanned: number;
|
||||
matched: number;
|
||||
@@ -247,6 +312,7 @@ export interface ApiMatch {
|
||||
gameMode: MatchGameMode;
|
||||
roundRobinMaxRounds?: number;
|
||||
gameSchedule?: ApiMatchGameAssignment[];
|
||||
doubleElimination?: ApiDoubleEliminationBracket;
|
||||
tournamentCodes?: TournamentCodeSlotView[];
|
||||
hostUserId?: string;
|
||||
participants: ApiMatchParticipant[];
|
||||
@@ -407,6 +473,7 @@ export interface MatchMutationRequest {
|
||||
gameCount?: number;
|
||||
gameMode?: MatchGameMode;
|
||||
roundRobinMaxRounds?: number;
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
prizes?: string[];
|
||||
notices?: string[];
|
||||
schedule?: ApiMatchScheduleItem[];
|
||||
@@ -420,6 +487,8 @@ export interface DdragonChampionEntry {
|
||||
export interface DdragonSummonerSpellEntry {
|
||||
key: string;
|
||||
name: string;
|
||||
description: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneEntry {
|
||||
@@ -427,12 +496,26 @@ export interface DdragonRuneEntry {
|
||||
key: string;
|
||||
icon: string;
|
||||
name: string;
|
||||
shortDesc: string;
|
||||
longDesc: string;
|
||||
}
|
||||
|
||||
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
||||
slots: Array<{ runes: DdragonRuneEntry[] }>;
|
||||
}
|
||||
|
||||
export interface DdragonItemEntry {
|
||||
name: string;
|
||||
description: string;
|
||||
plaintext: string;
|
||||
gold: {
|
||||
base: number;
|
||||
total: number;
|
||||
sell: number;
|
||||
purchasable: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DdragonManifest {
|
||||
version: string;
|
||||
cdn: string;
|
||||
@@ -440,6 +523,7 @@ export interface DdragonManifest {
|
||||
champions: Record<string, DdragonChampionEntry>;
|
||||
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
||||
runesReforged: DdragonRuneStyleEntry[];
|
||||
items: Record<string, DdragonItemEntry>;
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
@@ -661,6 +745,8 @@ export interface ApiRecentMatchTeam {
|
||||
|
||||
export interface ApiRecentMatchView {
|
||||
matchId: string;
|
||||
internalMatchId?: string;
|
||||
gameNumber?: number;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
gameCreation: number;
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
resolveAuctionErrorMessage,
|
||||
resolveAuctionRejectionMessage,
|
||||
} from './auctionRejectionMessages';
|
||||
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상
|
||||
// (호출부는 전부 addNewRelicPageAction / describeAuctionForTelemetry 로 grep 가능).
|
||||
import { addNewRelicPageAction } from '../lib/observability/new-relic';
|
||||
|
||||
type ConnectionStatus =
|
||||
| 'idle'
|
||||
@@ -180,9 +183,36 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
resolveCurrentBidPointAmount(nextAuction);
|
||||
}
|
||||
|
||||
function commitAuctionState(nextAuction: ApiAuction): boolean {
|
||||
function commitAuctionState(
|
||||
nextAuction: ApiAuction,
|
||||
source = 'socket-state',
|
||||
): boolean {
|
||||
const currentAuction = latestAuctionRef.current;
|
||||
if (!shouldApplyIncomingAuctionState(currentAuction, nextAuction)) {
|
||||
const applied = shouldApplyIncomingAuctionState(currentAuction, nextAuction);
|
||||
const currentRevision =
|
||||
typeof currentAuction?.revision === 'number'
|
||||
? currentAuction.revision
|
||||
: -1;
|
||||
const incomingRevision =
|
||||
typeof nextAuction?.revision === 'number' ? nextAuction.revision : -1;
|
||||
// 단조성을 깨고 적용되는 경우(=revision이 같거나 뒤로 가는데도 반영됨).
|
||||
// force-resync/lifecycle 교체로만 발생하며, "2~3 버전 롤백"의 직접 증거가 된다.
|
||||
const isBackwardApply =
|
||||
applied &&
|
||||
currentRevision >= 0 &&
|
||||
incomingRevision >= 0 &&
|
||||
incomingRevision <= currentRevision;
|
||||
addNewRelicPageAction('AuctionClientStateApply', {
|
||||
matchId: matchId ?? 'none',
|
||||
source,
|
||||
applied,
|
||||
isBackwardApply,
|
||||
revisionDelta: incomingRevision - currentRevision,
|
||||
...describeAuctionForTelemetry('current', currentAuction),
|
||||
...describeAuctionForTelemetry('incoming', nextAuction),
|
||||
});
|
||||
|
||||
if (!applied) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -361,7 +391,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
const didApplyState = commitAuctionState(nextAuction);
|
||||
const didApplyState = commitAuctionState(nextAuction, 'socket-state');
|
||||
if (didApplyState) {
|
||||
clearPendingActionRequests();
|
||||
}
|
||||
@@ -384,7 +414,24 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
|
||||
socket.on('bid', (payload: BidDeltaPayload) => {
|
||||
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
|
||||
const beforeBid = latestAuctionRef.current;
|
||||
const didApplyBidDelta = commitBidDelta(payload);
|
||||
addNewRelicPageAction('AuctionClientBidDelta', {
|
||||
matchId: matchId ?? 'none',
|
||||
applied: didApplyBidDelta,
|
||||
deltaRevision:
|
||||
typeof payload?.revision === 'number' ? payload.revision : -1,
|
||||
deltaBidAmount: Number(payload?.currentHighestBidPointAmount ?? -1),
|
||||
deltaBidderTeamIndex: Number(
|
||||
payload?.currentHighestBidderTeamIndex ?? -1,
|
||||
),
|
||||
beforeRevision:
|
||||
typeof beforeBid?.revision === 'number' ? beforeBid.revision : -1,
|
||||
beforeBidAmount: beforeBid
|
||||
? resolveCurrentBidPointAmount(beforeBid)
|
||||
: -1,
|
||||
beforePlayerUserId: beforeBid?.currentBidRoundPlayerUserId ?? 'none',
|
||||
});
|
||||
if (payload?.bidRequestId) {
|
||||
if (
|
||||
didApplyBidDelta ||
|
||||
@@ -429,6 +476,12 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
};
|
||||
latestAuctionRef.current = nextAuction;
|
||||
setAuction(nextAuction);
|
||||
addNewRelicPageAction('AuctionClientSideEffect', {
|
||||
matchId: matchId ?? 'none',
|
||||
matchSideEffectStatus: matchSideEffectStatus ?? 'unknown',
|
||||
matchSideEffectRevision,
|
||||
...describeAuctionForTelemetry('current', currentAuction),
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('reset', (payload: ResetPayload) => {
|
||||
@@ -574,6 +627,23 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
clearPendingActionRequest(auctionActionRequestId);
|
||||
setError('경매 진행 응답이 지연되어 최신 상태를 다시 확인해주세요.');
|
||||
}, 10_000);
|
||||
addNewRelicPageAction('AuctionClientActionSent', {
|
||||
matchId: matchId ?? 'none',
|
||||
action: eventName,
|
||||
retryAttempt,
|
||||
sentRevision:
|
||||
typeof payload.clientObservedRevision === 'number'
|
||||
? payload.clientObservedRevision
|
||||
: -1,
|
||||
sentOrderIndex:
|
||||
typeof payload.clientObservedCurrentAuctionPlayerOrderIndex === 'number'
|
||||
? payload.clientObservedCurrentAuctionPlayerOrderIndex
|
||||
: -1,
|
||||
sentPlayerUserId:
|
||||
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
|
||||
sentPhase: payload.clientObservedPhase ?? 'none',
|
||||
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
|
||||
});
|
||||
socket.emit(
|
||||
eventName,
|
||||
actionPayload,
|
||||
@@ -590,14 +660,6 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
clearPendingActionRequest(
|
||||
ack?.auctionActionRequestId ?? auctionActionRequestId,
|
||||
);
|
||||
// 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청).
|
||||
// commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후
|
||||
// buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다.
|
||||
if (ack.state) {
|
||||
commitAuctionState(ack.state);
|
||||
} else if (isAuctionResyncRecommended(ack)) {
|
||||
resyncAuctionState();
|
||||
}
|
||||
// 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가
|
||||
// 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청
|
||||
// id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구).
|
||||
@@ -605,6 +667,41 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
Boolean(ack.state) &&
|
||||
isAuctionResyncRecommended(ack) &&
|
||||
retryAttempt < 1;
|
||||
// 거부 시 "클라가 보낸 관측 revision"과 "서버가 동봉한 진짜 state"를 함께
|
||||
// 기록한다. observedRevision < serverRevision 이면 stale-client CONFLICT 확정.
|
||||
addNewRelicPageAction('AuctionClientActionRejected', {
|
||||
matchId: matchId ?? 'none',
|
||||
action: eventName,
|
||||
retryAttempt,
|
||||
rejectionReason:
|
||||
ack?.auctionRejectionReason ?? ack?.code ?? 'unknown',
|
||||
rejectionCode: ack?.code ?? 'none',
|
||||
resyncRecommended: isAuctionResyncRecommended(ack),
|
||||
hasAckState: Boolean(ack?.state),
|
||||
willAutoRetry: canAutoRetry,
|
||||
sentRevision:
|
||||
typeof payload.clientObservedRevision === 'number'
|
||||
? payload.clientObservedRevision
|
||||
: -1,
|
||||
sentOrderIndex:
|
||||
typeof payload.clientObservedCurrentAuctionPlayerOrderIndex ===
|
||||
'number'
|
||||
? payload.clientObservedCurrentAuctionPlayerOrderIndex
|
||||
: -1,
|
||||
sentPlayerUserId:
|
||||
payload.clientObservedCurrentBidRoundPlayerUserId ?? 'none',
|
||||
sentPhase: payload.clientObservedPhase ?? 'none',
|
||||
...describeAuctionForTelemetry('observed', latestAuctionRef.current),
|
||||
...describeAuctionForTelemetry('server', ack?.state ?? null),
|
||||
});
|
||||
// 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청).
|
||||
// commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후
|
||||
// buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다.
|
||||
if (ack.state) {
|
||||
commitAuctionState(ack.state, 'action-reject-rebaseline');
|
||||
} else if (isAuctionResyncRecommended(ack)) {
|
||||
resyncAuctionState();
|
||||
}
|
||||
if (canAutoRetry) {
|
||||
emitAuctionAction(
|
||||
eventName,
|
||||
@@ -621,7 +718,17 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
clearPendingActionRequest(
|
||||
ack.auctionActionRequestId ?? auctionActionRequestId,
|
||||
);
|
||||
commitAuctionState(ackState);
|
||||
addNewRelicPageAction('AuctionClientActionAck', {
|
||||
matchId: matchId ?? 'none',
|
||||
action: eventName,
|
||||
retryAttempt,
|
||||
sentRevision:
|
||||
typeof payload.clientObservedRevision === 'number'
|
||||
? payload.clientObservedRevision
|
||||
: -1,
|
||||
...describeAuctionForTelemetry('server', ackState),
|
||||
});
|
||||
commitAuctionState(ackState, 'action-ack');
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -754,6 +861,59 @@ function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
return Number.isFinite(bidPointAmount) ? bidPointAmount : 0;
|
||||
}
|
||||
|
||||
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
|
||||
type AuctionTelemetryAttributes = Record<string, string | number | boolean | null>;
|
||||
|
||||
function readAuctionHistorySequence(auction: ApiAuction | null | undefined) {
|
||||
const value = (auction as { currentAuctionHistorySequence?: unknown } | null)
|
||||
?.currentAuctionHistorySequence;
|
||||
return typeof value === 'number' ? value : -1;
|
||||
}
|
||||
|
||||
function summarizeAuctionTeams(auction: ApiAuction | null | undefined) {
|
||||
const teams = Array.isArray(auction?.auctionTeams) ? auction.auctionTeams : [];
|
||||
let assignedMemberCount = 0;
|
||||
for (const team of teams) {
|
||||
const members = (team as { members?: unknown[] }).members;
|
||||
if (Array.isArray(members)) assignedMemberCount += members.length;
|
||||
}
|
||||
return { teamCount: teams.length, assignedMemberCount };
|
||||
}
|
||||
|
||||
// New Relic로 보내기 위해 경매 상태를 평탄한 속성 집합으로 요약한다.
|
||||
// prefix로 두 상태(예: 현재 vs 수신)를 한 이벤트에 같이 실어 revision 어긋남을
|
||||
// 한눈에 비교할 수 있게 한다.
|
||||
function describeAuctionForTelemetry(
|
||||
prefix: string,
|
||||
auction: ApiAuction | null | undefined,
|
||||
): AuctionTelemetryAttributes {
|
||||
const teamSummary = summarizeAuctionTeams(auction);
|
||||
return {
|
||||
[`${prefix}Revision`]:
|
||||
typeof auction?.revision === 'number' ? auction.revision : -1,
|
||||
[`${prefix}HistorySequence`]: readAuctionHistorySequence(auction),
|
||||
[`${prefix}Phase`]: auction?.phase ?? 'unknown',
|
||||
[`${prefix}LifecycleId`]: auction?.auctionLifecycleId ?? 'none',
|
||||
[`${prefix}OrderIndex`]:
|
||||
typeof auction?.currentAuctionPlayerOrderIndex === 'number'
|
||||
? auction.currentAuctionPlayerOrderIndex
|
||||
: -1,
|
||||
[`${prefix}PlayerUserId`]: auction?.currentBidRoundPlayerUserId ?? 'none',
|
||||
[`${prefix}BidAmount`]: auction
|
||||
? resolveCurrentBidPointAmount(auction)
|
||||
: -1,
|
||||
[`${prefix}BidderTeamIndex`]:
|
||||
typeof auction?.currentHighestBidderTeamIndex === 'number'
|
||||
? auction.currentHighestBidderTeamIndex
|
||||
: typeof auction?.currentBidderTeamIndex === 'number'
|
||||
? auction.currentBidderTeamIndex
|
||||
: -1,
|
||||
[`${prefix}TeamCount`]: teamSummary.teamCount,
|
||||
[`${prefix}AssignedMemberCount`]: teamSummary.assignedMemberCount,
|
||||
[`${prefix}ForceResync`]: Boolean(auction?.shouldForceAuctionStateResync),
|
||||
};
|
||||
}
|
||||
|
||||
function shouldApplyIncomingAuctionState(
|
||||
current: ApiAuction | null,
|
||||
incoming: ApiAuction,
|
||||
|
||||
@@ -0,0 +1,910 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import type { ApiInternalMatchDetailResponse, DdragonManifest, TeamSide } from "../api/types";
|
||||
import {
|
||||
championDisplayName,
|
||||
championIconUrl,
|
||||
} from "../lib/ddragon";
|
||||
import { teamIndexLabel } from "../lib/league";
|
||||
import { LANE_LABELS } from "../lib/riot-history";
|
||||
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
|
||||
|
||||
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
||||
|
||||
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
|
||||
type InternalGameTeam = InternalGameDetail["teams"][number];
|
||||
type InternalGameParticipant = InternalGameTeam["participants"][number];
|
||||
type DdragonManifestData = DdragonManifest | null | undefined;
|
||||
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
|
||||
|
||||
const DETAIL_TABS: Array<{ id: InternalGameDetailTab; label: string }> = [
|
||||
{ id: "scoreboard", label: "스코어보드" },
|
||||
{ id: "matchup", label: "라인전" },
|
||||
{ id: "build", label: "룬 / 빌드" },
|
||||
];
|
||||
|
||||
const SKILL_ROWS: Array<{
|
||||
slot: 1 | 2 | 3 | 4;
|
||||
label: string;
|
||||
className: string;
|
||||
}> = [
|
||||
{ slot: 1, label: "Q", className: "bg-blue-500 text-white" },
|
||||
{ slot: 2, label: "W", className: "bg-cyan-500 text-white" },
|
||||
{ slot: 3, label: "E", className: "bg-amber-500 text-black" },
|
||||
{ slot: 4, label: "R", className: "bg-red-500 text-white" },
|
||||
];
|
||||
|
||||
const STAT_PERK_LABELS: Record<number, string> = {
|
||||
5001: "체력",
|
||||
5002: "방어",
|
||||
5003: "마저",
|
||||
5005: "공속",
|
||||
5007: "가속",
|
||||
5008: "적응",
|
||||
5010: "이속",
|
||||
5011: "체력",
|
||||
};
|
||||
|
||||
const LANE_SORT_ORDER = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"];
|
||||
|
||||
function formatDuration(seconds: number) {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const rest = seconds % 60;
|
||||
return `${minutes}:${String(rest).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function formatNumber(value: number) {
|
||||
return new Intl.NumberFormat("ko-KR").format(value);
|
||||
}
|
||||
|
||||
function sideTone(side: TeamSide) {
|
||||
return side === "blue"
|
||||
? {
|
||||
border: "border-blue-500/20",
|
||||
bg: "bg-blue-500/5",
|
||||
text: "text-blue-400",
|
||||
bar: "bg-blue-500",
|
||||
}
|
||||
: {
|
||||
border: "border-red-500/20",
|
||||
bg: "bg-red-500/5",
|
||||
text: "text-red-400",
|
||||
bar: "bg-red-500",
|
||||
};
|
||||
}
|
||||
|
||||
function getTeamName(
|
||||
detail: ApiInternalMatchDetailResponse,
|
||||
teamIndex: number,
|
||||
) {
|
||||
return teamIndexLabel(
|
||||
teamIndex,
|
||||
detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name,
|
||||
);
|
||||
}
|
||||
|
||||
function participantBuildKey(participant: InternalGameParticipant) {
|
||||
return `${participant.side}-${participant.userId ?? participant.summonerName}-${participant.championId}`;
|
||||
}
|
||||
|
||||
function findRuneStyle(
|
||||
manifest: DdragonManifestData,
|
||||
styleId: number | undefined,
|
||||
) {
|
||||
return manifest?.runesReforged.find((style) => style.id === styleId) ?? null;
|
||||
}
|
||||
|
||||
function selectedRuneIds(participant: InternalGameParticipant) {
|
||||
const explicit = participant.perks.selectedPerkIds ?? [];
|
||||
const fromStyles =
|
||||
participant.perks.styles?.flatMap((style) => style.perkIds) ?? [];
|
||||
return new Set([
|
||||
...explicit,
|
||||
...fromStyles,
|
||||
...(participant.perks.keystone ? [participant.perks.keystone] : []),
|
||||
]);
|
||||
}
|
||||
|
||||
function runeStyleSelection(
|
||||
participant: InternalGameParticipant,
|
||||
styleId: number | undefined,
|
||||
) {
|
||||
return participant.perks.styles?.find((style) => style.styleId === styleId);
|
||||
}
|
||||
|
||||
function laneSortValue(position: string) {
|
||||
const index = LANE_SORT_ORDER.indexOf(position);
|
||||
return index === -1 ? 99 : index;
|
||||
}
|
||||
|
||||
function ChampionCell({
|
||||
participant,
|
||||
manifest,
|
||||
}: {
|
||||
participant: InternalGameParticipant;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
const icon = championIconUrl(manifest, participant.championId);
|
||||
const name =
|
||||
championDisplayName(manifest, participant.championId) ??
|
||||
String(participant.championId);
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="relative h-10 w-10 shrink-0 overflow-hidden bg-base-content/10">
|
||||
{icon ? (
|
||||
<img src={icon} alt={name} className="h-full w-full object-cover scale-[1.18]" />
|
||||
) : null}
|
||||
{participant.championLevel > 0 && (
|
||||
<span className="absolute bottom-0 right-0 min-w-4 bg-base-300 px-1 text-center text-[10px] font-bold leading-4 text-base-content">
|
||||
{participant.championLevel}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<span className="block truncate text-sm font-bold text-base-content">
|
||||
{name}
|
||||
</span>
|
||||
<span className="text-xs text-base-content/35">
|
||||
{LANE_LABELS[participant.teamPosition] ??
|
||||
participant.teamPosition ??
|
||||
"-"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChampionAvatar({
|
||||
participant,
|
||||
manifest,
|
||||
size = "h-9 w-9",
|
||||
}: {
|
||||
participant: InternalGameParticipant;
|
||||
manifest: DdragonManifestData;
|
||||
size?: string;
|
||||
}) {
|
||||
const icon = championIconUrl(manifest, participant.championId);
|
||||
const name =
|
||||
championDisplayName(manifest, participant.championId) ??
|
||||
String(participant.championId);
|
||||
return (
|
||||
<span
|
||||
className={`relative ${size} shrink-0 overflow-hidden bg-base-content/10`}
|
||||
title={name}
|
||||
>
|
||||
{icon ? (
|
||||
<img src={icon} alt={name} className="h-full w-full object-cover scale-[1.18]" />
|
||||
) : null}
|
||||
{participant.championLevel > 0 ? (
|
||||
<span className="absolute bottom-0 right-0 min-w-4 bg-base-300 px-1 text-center text-[10px] font-bold leading-4 text-base-content">
|
||||
{participant.championLevel}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function RuneBuildPanel({
|
||||
selectedGame,
|
||||
detail,
|
||||
manifest,
|
||||
}: {
|
||||
selectedGame: InternalGameDetail;
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
const orderedTeams = [...selectedGame.teams].sort((left, right) =>
|
||||
left.side === right.side ? 0 : left.side === "blue" ? -1 : 1,
|
||||
);
|
||||
const participants = orderedTeams.flatMap((team) => team.participants);
|
||||
const defaultKey = participants[0]
|
||||
? participantBuildKey(participants[0])
|
||||
: "";
|
||||
const [selectedKey, setSelectedKey] = useState(defaultKey);
|
||||
const effectiveSelectedKey = participants.some(
|
||||
(participant) => participantBuildKey(participant) === selectedKey,
|
||||
)
|
||||
? selectedKey
|
||||
: defaultKey;
|
||||
const selectedParticipant =
|
||||
participants.find(
|
||||
(participant) =>
|
||||
participantBuildKey(participant) === effectiveSelectedKey,
|
||||
) ?? participants[0];
|
||||
|
||||
if (!selectedParticipant) {
|
||||
return (
|
||||
<section className="border border-base-content/10 bg-base-100 px-4 py-12 text-center text-sm font-bold text-base-content/35">
|
||||
빌드 데이터가 없습니다
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="overflow-hidden border border-base-content/10 bg-base-100">
|
||||
<BuildChampionSelector
|
||||
selectedGame={selectedGame}
|
||||
detail={detail}
|
||||
manifest={manifest}
|
||||
selectedKey={participantBuildKey(selectedParticipant)}
|
||||
onSelect={setSelectedKey}
|
||||
/>
|
||||
<div className="grid border-t border-base-content/8 lg:grid-cols-[minmax(0,1.05fr)_minmax(0,1fr)]">
|
||||
<RunesPanel participant={selectedParticipant} manifest={manifest} />
|
||||
<div className="border-t border-base-content/8 lg:border-l lg:border-t-0">
|
||||
<ItemBuildPanel
|
||||
participant={selectedParticipant}
|
||||
manifest={manifest}
|
||||
/>
|
||||
<SkillBuildPanel participant={selectedParticipant} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function BuildChampionSelector({
|
||||
selectedGame,
|
||||
detail,
|
||||
manifest,
|
||||
selectedKey,
|
||||
onSelect,
|
||||
}: {
|
||||
selectedGame: InternalGameDetail;
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
manifest: DdragonManifestData;
|
||||
selectedKey: string;
|
||||
onSelect: (key: string) => void;
|
||||
}) {
|
||||
const orderedTeams = [...selectedGame.teams].sort((left, right) =>
|
||||
left.side === right.side ? 0 : left.side === "blue" ? -1 : 1,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="grid gap-4 bg-base-content/[0.015] p-3 lg:grid-cols-2">
|
||||
{orderedTeams.map((team) => {
|
||||
const tone = sideTone(team.side);
|
||||
return (
|
||||
<div key={`build-selector-${team.side}`} className="min-w-0">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className={`text-sm font-bold ${tone.text}`}>
|
||||
{team.side === "blue" ? "블루" : "레드"}
|
||||
</div>
|
||||
<div className="truncate text-xs font-bold text-base-content/40">
|
||||
{getTeamName(detail, team.teamIndex)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
{team.participants.map((participant) => (
|
||||
<BuildChampionButton
|
||||
key={`build-select-${participantBuildKey(participant)}`}
|
||||
participant={participant}
|
||||
manifest={manifest}
|
||||
selected={participantBuildKey(participant) === selectedKey}
|
||||
onClick={() => onSelect(participantBuildKey(participant))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BuildChampionButton({
|
||||
participant,
|
||||
manifest,
|
||||
selected,
|
||||
onClick,
|
||||
}: {
|
||||
participant: InternalGameParticipant;
|
||||
manifest: DdragonManifestData;
|
||||
selected: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const icon = championIconUrl(manifest, participant.championId);
|
||||
const championName =
|
||||
championDisplayName(manifest, participant.championId) ??
|
||||
String(participant.championId);
|
||||
const tone = sideTone(participant.side);
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
title={`${participant.summonerName} · ${championName}`}
|
||||
className={`relative h-11 w-11 overflow-hidden border bg-base-content/10 transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
|
||||
selected
|
||||
? `border-transparent opacity-100 ring-1 ring-current ${tone.text}`
|
||||
: "border-base-content/5 opacity-35 hover:opacity-75"
|
||||
}`}
|
||||
>
|
||||
{icon ? (
|
||||
<img src={icon} alt="" className="h-full w-full object-cover scale-[1.18]" />
|
||||
) : null}
|
||||
{participant.championLevel > 0 ? (
|
||||
<span className="absolute bottom-0 right-0 min-w-4 bg-base-300 px-1 text-center text-[10px] font-bold leading-4 text-base-content">
|
||||
{participant.championLevel}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function RunesPanel({
|
||||
participant,
|
||||
manifest,
|
||||
}: {
|
||||
participant: InternalGameParticipant;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
const selectedIds = selectedRuneIds(participant);
|
||||
const primaryStyleId =
|
||||
participant.perks.primaryStyle ?? participant.perks.styles?.[0]?.styleId;
|
||||
const subStyleId =
|
||||
participant.perks.subStyle ?? participant.perks.styles?.[1]?.styleId;
|
||||
const primaryStyle = findRuneStyle(manifest, primaryStyleId);
|
||||
const subStyle = findRuneStyle(manifest, subStyleId);
|
||||
|
||||
return (
|
||||
<div className="p-3">
|
||||
<div className="mb-3 flex min-w-0 items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
|
||||
룬
|
||||
</div>
|
||||
<div className="mt-0.5 truncate text-xs text-base-content/40">
|
||||
{participant.summonerName}
|
||||
</div>
|
||||
</div>
|
||||
<ChampionCell participant={participant} manifest={manifest} />
|
||||
</div>
|
||||
<div className="grid gap-x-6 gap-y-4 md:grid-cols-2">
|
||||
<RuneTreeColumn
|
||||
label="주 룬"
|
||||
isPrimary
|
||||
runeStyle={primaryStyle}
|
||||
selection={runeStyleSelection(participant, primaryStyleId)}
|
||||
selectedIds={selectedIds}
|
||||
manifest={manifest}
|
||||
/>
|
||||
<RuneTreeColumn
|
||||
label="보조 룬"
|
||||
isPrimary={false}
|
||||
runeStyle={subStyle}
|
||||
selection={runeStyleSelection(participant, subStyleId)}
|
||||
selectedIds={selectedIds}
|
||||
manifest={manifest}
|
||||
/>
|
||||
</div>
|
||||
<RuneShardRows participant={participant} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuneTreeColumn({
|
||||
label,
|
||||
isPrimary,
|
||||
runeStyle,
|
||||
selection,
|
||||
selectedIds,
|
||||
manifest,
|
||||
}: {
|
||||
label: string;
|
||||
isPrimary: boolean;
|
||||
runeStyle: RuneStyleEntry | null;
|
||||
selection: ReturnType<typeof runeStyleSelection>;
|
||||
selectedIds: Set<number>;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
if (!runeStyle) {
|
||||
return (
|
||||
<div>
|
||||
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
|
||||
{label}
|
||||
</div>
|
||||
<div className="mt-8 text-center text-xs font-bold text-base-content/35">
|
||||
룬 데이터 없음
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectionIds = new Set(selection?.perkIds ?? []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<RuneStyleIcon
|
||||
styleId={runeStyle.id}
|
||||
manifest={manifest}
|
||||
className="h-6 w-6"
|
||||
slotClassName="bg-base-content/10"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
|
||||
{label}
|
||||
</div>
|
||||
<div className="truncate text-xs font-bold text-base-content">
|
||||
{runeStyle.name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 space-y-2.5">
|
||||
{runeStyle.slots.map((slot, slotIndex) => {
|
||||
// 보조 룬 트리는 핵심 룬(0번 행)을 선택하지 않으므로 숨긴다.
|
||||
if (!isPrimary && slotIndex === 0) return null;
|
||||
const isKeystoneRow = isPrimary && slotIndex === 0;
|
||||
const cell = isKeystoneRow ? "2.5rem" : "2.25rem";
|
||||
const iconSize = isKeystoneRow ? "h-10 w-10" : "h-9 w-9";
|
||||
return (
|
||||
<div
|
||||
key={`${runeStyle.id}-${slotIndex}`}
|
||||
className="grid justify-start gap-2 border-b border-base-content/8 pb-3 last:border-b-0 last:pb-0"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${slot.runes.length}, minmax(0, ${cell}))`,
|
||||
}}
|
||||
>
|
||||
{slot.runes.map((rune) => {
|
||||
const selected =
|
||||
selectedIds.has(rune.id) || selectionIds.has(rune.id);
|
||||
return (
|
||||
<RuneIcon
|
||||
key={rune.id}
|
||||
runeId={rune.id}
|
||||
manifest={manifest}
|
||||
className={iconSize}
|
||||
slotClassName={`border bg-base-content/10 transition ${
|
||||
selected
|
||||
? "border-transparent opacity-100 ring-1 ring-primary/60"
|
||||
: "border-transparent opacity-20 grayscale"
|
||||
}`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuneShardRows({ participant }: { participant: InternalGameParticipant }) {
|
||||
const statPerks = participant.perks.statPerks;
|
||||
const shards = [
|
||||
{ label: "공격", value: statPerks?.offense },
|
||||
{ label: "보조", value: statPerks?.flex },
|
||||
{ label: "방어", value: statPerks?.defense },
|
||||
].filter((shard) => typeof shard.value === "number" && shard.value > 0);
|
||||
|
||||
if (shards.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-base-content/8 pt-3 text-xs">
|
||||
<span className="font-bold uppercase tracking-wider text-base-content/35">
|
||||
스탯 파편
|
||||
</span>
|
||||
{shards.map((shard) => (
|
||||
<span key={`${shard.label}-${shard.value}`} className="text-base-content/60">
|
||||
<span className="text-base-content/35">{shard.label} </span>
|
||||
<span className="font-bold">
|
||||
{STAT_PERK_LABELS[shard.value ?? 0] ?? shard.value}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemBuildPanel({
|
||||
participant,
|
||||
manifest,
|
||||
}: {
|
||||
participant: InternalGameParticipant;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
const buildEvents = (participant.itemBuild ?? []).filter(
|
||||
(event) => event.itemId > 0 && event.type === "purchased",
|
||||
);
|
||||
const fallbackItems = [
|
||||
...participant.items
|
||||
.filter((itemId) => itemId > 0)
|
||||
.map((itemId) => ({ itemId, trinket: false })),
|
||||
...(participant.trinket > 0
|
||||
? [{ itemId: participant.trinket, trinket: true }]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-3">
|
||||
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
|
||||
아이템 빌드
|
||||
</div>
|
||||
{buildEvents.length > 0 ? (
|
||||
<div className="mt-3 flex flex-wrap items-start gap-x-2 gap-y-4">
|
||||
{buildEvents.map((event, index) => (
|
||||
<div
|
||||
key={`${event.timestamp}-${event.itemId}-${event.type}-${index}`}
|
||||
className="flex items-start gap-2"
|
||||
>
|
||||
<ItemBuildNode
|
||||
itemId={event.itemId}
|
||||
timestamp={event.timestamp}
|
||||
manifest={manifest}
|
||||
/>
|
||||
{index < buildEvents.length - 1 ? (
|
||||
<span className="pt-2 text-xs font-bold text-base-content/25">
|
||||
>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : fallbackItems.length > 0 ? (
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
{fallbackItems.map((item, index) => (
|
||||
<ItemIcon
|
||||
key={`fallback-item-${item.itemId}-${index}`}
|
||||
itemId={item.itemId}
|
||||
manifest={manifest}
|
||||
trinket={item.trinket}
|
||||
className="h-9 w-9"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-6 text-center text-xs font-bold text-base-content/35">
|
||||
아이템 빌드 데이터 없음
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemBuildNode({
|
||||
itemId,
|
||||
timestamp,
|
||||
manifest,
|
||||
}: {
|
||||
itemId: number;
|
||||
timestamp: number;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
return (
|
||||
<div className="w-11 text-center">
|
||||
<ItemIcon itemId={itemId} manifest={manifest} className="h-9 w-9" />
|
||||
<span className="mt-1 block text-[11px] font-bold tabular-nums text-base-content/35">
|
||||
{formatDuration(timestamp)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SkillBuildPanel({
|
||||
participant,
|
||||
}: {
|
||||
participant: InternalGameParticipant;
|
||||
}) {
|
||||
const skillEvents = participant.skillBuild ?? [];
|
||||
const skillByLevel = new Map(
|
||||
skillEvents.map((event) => [event.level, event]),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="border-t border-base-content/8 p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="text-xs font-bold uppercase tracking-wider text-base-content/35">
|
||||
스킬 빌드
|
||||
</div>
|
||||
<div className="text-xs font-bold text-base-content/35">
|
||||
Lv. {skillEvents.length || participant.championLevel || "-"}
|
||||
</div>
|
||||
</div>
|
||||
{skillEvents.length > 0 ? (
|
||||
<div className="mt-3 overflow-x-auto">
|
||||
<div className="min-w-[610px] space-y-1">
|
||||
{SKILL_ROWS.map((row) => (
|
||||
<div
|
||||
key={`skill-row-${row.slot}`}
|
||||
className="grid grid-cols-[2rem_repeat(18,minmax(1.45rem,1fr))] gap-1"
|
||||
>
|
||||
<div
|
||||
className={`flex h-7 items-center justify-center text-xs font-bold ${row.className}`}
|
||||
>
|
||||
{row.label}
|
||||
</div>
|
||||
{Array.from({ length: 18 }, (_, index) => index + 1).map(
|
||||
(level) => {
|
||||
const event = skillByLevel.get(level);
|
||||
const active = event?.skillSlot === row.slot;
|
||||
return (
|
||||
<div
|
||||
key={`${row.slot}-${level}`}
|
||||
className={`flex h-7 items-center justify-center text-[11px] font-bold tabular-nums ${
|
||||
active
|
||||
? row.className
|
||||
: "bg-base-content/[0.045] text-transparent"
|
||||
}`}
|
||||
>
|
||||
{active ? level : ""}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-6 text-center text-xs font-bold text-base-content/35">
|
||||
스킬 빌드 데이터 없음
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MatchupMetricRow({
|
||||
label,
|
||||
blueLead,
|
||||
redLead,
|
||||
blueText,
|
||||
redText,
|
||||
}: {
|
||||
label: string;
|
||||
blueLead: boolean;
|
||||
redLead: boolean;
|
||||
blueText: string;
|
||||
redText: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 px-3 py-1.5 text-xs">
|
||||
<span
|
||||
className={`text-right tabular-nums ${
|
||||
blueLead ? "font-bold text-blue-400" : "text-base-content/55"
|
||||
}`}
|
||||
>
|
||||
{blueText}
|
||||
</span>
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
className={`tabular-nums ${
|
||||
redLead ? "font-bold text-red-400" : "text-base-content/55"
|
||||
}`}
|
||||
>
|
||||
{redText}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LaneMatchupCard({
|
||||
blue,
|
||||
red,
|
||||
detail,
|
||||
manifest,
|
||||
}: {
|
||||
blue: InternalGameParticipant;
|
||||
red: InternalGameParticipant;
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
const laneLabel =
|
||||
LANE_LABELS[blue.teamPosition] ??
|
||||
LANE_LABELS[red.teamPosition] ??
|
||||
blue.teamPosition ??
|
||||
"-";
|
||||
|
||||
const metrics = [
|
||||
{
|
||||
key: "kda",
|
||||
label: "KDA",
|
||||
blueValue:
|
||||
blue.deaths === 0
|
||||
? blue.kills + blue.assists
|
||||
: (blue.kills + blue.assists) / blue.deaths,
|
||||
redValue:
|
||||
red.deaths === 0
|
||||
? red.kills + red.assists
|
||||
: (red.kills + red.assists) / red.deaths,
|
||||
blueText: `${blue.kills}/${blue.deaths}/${blue.assists}`,
|
||||
redText: `${red.kills}/${red.deaths}/${red.assists}`,
|
||||
},
|
||||
{
|
||||
key: "gold",
|
||||
label: "골드",
|
||||
blueValue: blue.gold,
|
||||
redValue: red.gold,
|
||||
blueText: formatNumber(blue.gold),
|
||||
redText: formatNumber(red.gold),
|
||||
},
|
||||
{
|
||||
key: "cs",
|
||||
label: "CS",
|
||||
blueValue: blue.cs,
|
||||
redValue: red.cs,
|
||||
blueText: `${blue.cs} (${blue.csPerMin}/m)`,
|
||||
redText: `${red.cs} (${red.csPerMin}/m)`,
|
||||
},
|
||||
];
|
||||
|
||||
const championName = (participant: InternalGameParticipant) =>
|
||||
championDisplayName(manifest, participant.championId) ??
|
||||
String(participant.championId);
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden border border-base-content/10 bg-base-100">
|
||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 border-b border-base-content/8 bg-base-content/[0.015] px-3 py-2">
|
||||
<div className="flex min-w-0 items-center justify-end gap-2">
|
||||
<div className="min-w-0 text-right">
|
||||
<div className="truncate text-xs font-bold text-base-content">
|
||||
{blue.summonerName}
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-base-content/40">
|
||||
{championName(blue)}
|
||||
</div>
|
||||
</div>
|
||||
<ChampionAvatar participant={blue} manifest={manifest} />
|
||||
</div>
|
||||
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
|
||||
{laneLabel}
|
||||
</span>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ChampionAvatar participant={red} manifest={manifest} />
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-xs font-bold text-base-content">
|
||||
{red.summonerName}
|
||||
</div>
|
||||
<div className="truncate text-[11px] text-base-content/40">
|
||||
{championName(red)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y divide-base-content/5">
|
||||
{metrics.map((metric) => (
|
||||
<MatchupMetricRow
|
||||
key={`${detail.match.matchId}-${blue.teamPosition}-${metric.key}`}
|
||||
label={metric.label}
|
||||
blueLead={metric.blueValue > metric.redValue}
|
||||
redLead={metric.redValue > metric.blueValue}
|
||||
blueText={metric.blueText}
|
||||
redText={metric.redText}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LaneMatchupPanel({
|
||||
selectedGame,
|
||||
detail,
|
||||
manifest,
|
||||
}: {
|
||||
selectedGame: InternalGameDetail;
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
manifest: DdragonManifestData;
|
||||
}) {
|
||||
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
||||
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
||||
|
||||
if (!blueTeam || !redTeam) {
|
||||
return (
|
||||
<section className="border border-base-content/10 bg-base-100 px-4 py-12 text-center text-sm font-bold text-base-content/35">
|
||||
라인전 비교 데이터가 없습니다
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const blueSorted = [...blueTeam.participants].sort(
|
||||
(left, right) =>
|
||||
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
|
||||
);
|
||||
const redSorted = [...redTeam.participants].sort(
|
||||
(left, right) =>
|
||||
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
|
||||
);
|
||||
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
|
||||
const redTeamName = getTeamName(detail, redTeam.teamIndex);
|
||||
|
||||
return (
|
||||
<section className="overflow-hidden border border-base-content/10 bg-base-100">
|
||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 border-b border-base-content/8 px-4 py-3 text-xs font-bold">
|
||||
<span className="truncate text-right text-blue-400">
|
||||
{blueTeamName}
|
||||
</span>
|
||||
<span className="text-base-content/20">VS</span>
|
||||
<span className="truncate text-red-400">{redTeamName}</span>
|
||||
</div>
|
||||
<div className="grid gap-3 p-4 lg:grid-cols-2">
|
||||
{blueSorted.map((blue, index) => {
|
||||
const red = redSorted[index];
|
||||
if (!red) return null;
|
||||
return (
|
||||
<LaneMatchupCard
|
||||
key={`matchup-${blue.teamPosition}-${blue.summonerName}`}
|
||||
blue={blue}
|
||||
red={red}
|
||||
detail={detail}
|
||||
manifest={manifest}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function InternalGameDetailTabBar({
|
||||
activeTab,
|
||||
onChange,
|
||||
}: {
|
||||
activeTab: InternalGameDetailTab;
|
||||
onChange: (tab: InternalGameDetailTab) => void;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="flex flex-wrap border-b border-base-content/8"
|
||||
role="tablist"
|
||||
aria-label="상세 분석"
|
||||
>
|
||||
{DETAIL_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === tab.id}
|
||||
onClick={() => onChange(tab.id)}
|
||||
className={`border-b-2 px-3 py-2 text-xs font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
|
||||
activeTab === tab.id
|
||||
? "border-primary bg-primary/5 text-primary"
|
||||
: "border-transparent text-base-content/45 hover:text-base-content"
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function InternalGameAnalysisPanel({
|
||||
activeTab,
|
||||
selectedGame,
|
||||
detail,
|
||||
manifest,
|
||||
scoreboard,
|
||||
}: {
|
||||
activeTab: InternalGameDetailTab;
|
||||
selectedGame: InternalGameDetail;
|
||||
detail: ApiInternalMatchDetailResponse;
|
||||
manifest: DdragonManifestData;
|
||||
scoreboard: ReactNode;
|
||||
}) {
|
||||
if (activeTab === "scoreboard") {
|
||||
return <>{scoreboard}</>;
|
||||
}
|
||||
|
||||
if (activeTab === "build") {
|
||||
return (
|
||||
<RuneBuildPanel
|
||||
selectedGame={selectedGame}
|
||||
detail={detail}
|
||||
manifest={manifest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<LaneMatchupPanel
|
||||
selectedGame={selectedGame}
|
||||
detail={detail}
|
||||
manifest={manifest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import type { CSSProperties, ReactNode, RefObject } from "react";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import type { DdragonManifest } from "../api/types";
|
||||
import {
|
||||
itemDetails,
|
||||
itemDisplayName,
|
||||
itemIconUrl,
|
||||
runeDetails,
|
||||
runeIconUrl,
|
||||
runeStyleDetails,
|
||||
runeStyleIconUrl,
|
||||
safeDdragonDescriptionHtml,
|
||||
summonerSpellDetails,
|
||||
summonerSpellIconUrl,
|
||||
} from "../lib/ddragon";
|
||||
|
||||
type TooltipPosition = {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
placement: "top" | "bottom";
|
||||
};
|
||||
|
||||
type ItemIconProps = {
|
||||
itemId: number;
|
||||
manifest: DdragonManifest | null | undefined;
|
||||
className?: string;
|
||||
imageClassName?: string;
|
||||
trinket?: boolean;
|
||||
};
|
||||
|
||||
type TooltipIconProps = {
|
||||
active: boolean;
|
||||
label: string;
|
||||
emptyLabel: string;
|
||||
icon: string | null;
|
||||
className: string;
|
||||
imageClassName: string;
|
||||
slotClassName: string;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
type ManifestIconProps = {
|
||||
manifest: DdragonManifest | null | undefined;
|
||||
className?: string;
|
||||
imageClassName?: string;
|
||||
slotClassName?: string;
|
||||
};
|
||||
|
||||
const VIEWPORT_MARGIN = 8;
|
||||
const TOOLTIP_GAP = 8;
|
||||
const TOOLTIP_WIDTH = 320;
|
||||
|
||||
export function ItemIcon({
|
||||
itemId,
|
||||
manifest,
|
||||
className = "h-6 w-6",
|
||||
imageClassName = "scale-[1.18]",
|
||||
trinket = false,
|
||||
}: ItemIconProps) {
|
||||
const icon = itemIconUrl(manifest, itemId);
|
||||
const hasItem = itemId > 0;
|
||||
const itemName = itemDisplayName(manifest, itemId) ?? `아이템 ${itemId}`;
|
||||
const slotTone = trinket
|
||||
? "border-primary/25 bg-base-content/[0.04]"
|
||||
: "border-base-content/5 bg-base-content/8";
|
||||
|
||||
return (
|
||||
<TooltipIcon
|
||||
active={hasItem}
|
||||
label={itemName}
|
||||
emptyLabel="빈 아이템 슬롯"
|
||||
icon={icon}
|
||||
className={className}
|
||||
imageClassName={imageClassName}
|
||||
slotClassName={`border ${slotTone}`}
|
||||
>
|
||||
<ItemTooltipContent itemId={itemId} manifest={manifest} />
|
||||
</TooltipIcon>
|
||||
);
|
||||
}
|
||||
|
||||
export function SummonerSpellIcon({
|
||||
spellId,
|
||||
manifest,
|
||||
className = "h-5 w-5",
|
||||
imageClassName = "",
|
||||
slotClassName = "border border-base-content/5 bg-base-content/10",
|
||||
}: ManifestIconProps & { spellId: number }) {
|
||||
const spell = summonerSpellDetails(manifest, spellId);
|
||||
const spellName = spell?.name ?? `스펠 ${spellId}`;
|
||||
|
||||
return (
|
||||
<TooltipIcon
|
||||
active={spellId > 0}
|
||||
label={spellName}
|
||||
emptyLabel="빈 스펠 슬롯"
|
||||
icon={summonerSpellIconUrl(manifest, spellId)}
|
||||
className={className}
|
||||
imageClassName={imageClassName}
|
||||
slotClassName={slotClassName}
|
||||
>
|
||||
<SummonerSpellTooltipContent spellId={spellId} manifest={manifest} />
|
||||
</TooltipIcon>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuneIcon({
|
||||
runeId,
|
||||
manifest,
|
||||
className = "h-5 w-5",
|
||||
imageClassName = "",
|
||||
slotClassName = "border border-base-content/5 bg-base-content/10",
|
||||
}: ManifestIconProps & { runeId: number | undefined }) {
|
||||
const rune = runeDetails(manifest, runeId);
|
||||
const runeName = rune?.name ?? (runeId ? `룬 ${runeId}` : "룬");
|
||||
|
||||
return (
|
||||
<TooltipIcon
|
||||
active={Boolean(runeId)}
|
||||
label={runeName}
|
||||
emptyLabel="빈 룬 슬롯"
|
||||
icon={runeIconUrl(manifest, runeId)}
|
||||
className={className}
|
||||
imageClassName={imageClassName}
|
||||
slotClassName={slotClassName}
|
||||
>
|
||||
<RuneTooltipContent runeId={runeId} manifest={manifest} />
|
||||
</TooltipIcon>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuneStyleIcon({
|
||||
styleId,
|
||||
manifest,
|
||||
className = "h-5 w-5",
|
||||
imageClassName = "",
|
||||
slotClassName = "border border-base-content/5 bg-base-content/10",
|
||||
}: ManifestIconProps & { styleId: number | undefined }) {
|
||||
const style = runeStyleDetails(manifest, styleId);
|
||||
const styleName = style?.name ?? (styleId ? `룬 ${styleId}` : "룬");
|
||||
|
||||
return (
|
||||
<TooltipIcon
|
||||
active={Boolean(styleId)}
|
||||
label={styleName}
|
||||
emptyLabel="빈 룬 슬롯"
|
||||
icon={runeStyleIconUrl(manifest, styleId)}
|
||||
className={className}
|
||||
imageClassName={imageClassName}
|
||||
slotClassName={slotClassName}
|
||||
>
|
||||
<RuneStyleTooltipContent styleId={styleId} manifest={manifest} />
|
||||
</TooltipIcon>
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipIcon({
|
||||
active,
|
||||
label,
|
||||
emptyLabel,
|
||||
icon,
|
||||
className,
|
||||
imageClassName,
|
||||
slotClassName,
|
||||
children,
|
||||
}: TooltipIconProps) {
|
||||
const anchorRef = useRef<HTMLSpanElement>(null);
|
||||
const tooltipId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<span
|
||||
ref={anchorRef}
|
||||
className={`relative inline-flex shrink-0 ${className}`}
|
||||
role={active ? "img" : undefined}
|
||||
tabIndex={active ? 0 : undefined}
|
||||
aria-label={active ? label : emptyLabel}
|
||||
aria-describedby={active && open ? tooltipId : undefined}
|
||||
onBlur={() => setOpen(false)}
|
||||
onFocus={() => active && setOpen(true)}
|
||||
onMouseEnter={() => active && setOpen(true)}
|
||||
onMouseLeave={() => setOpen(false)}
|
||||
>
|
||||
<span
|
||||
className={`block h-full w-full overflow-hidden ${slotClassName}`}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{icon ? (
|
||||
<img
|
||||
src={icon}
|
||||
alt=""
|
||||
className={`h-full w-full object-cover ${imageClassName}`}
|
||||
loading="lazy"
|
||||
/>
|
||||
) : null}
|
||||
</span>
|
||||
{active && open ? (
|
||||
<TooltipPortal id={tooltipId} anchorRef={anchorRef}>
|
||||
{children}
|
||||
</TooltipPortal>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipPortal({
|
||||
id,
|
||||
anchorRef,
|
||||
children,
|
||||
}: {
|
||||
id: string;
|
||||
anchorRef: RefObject<HTMLElement | null>;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [position, setPosition] = useState<TooltipPosition | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function updatePosition() {
|
||||
const anchor = anchorRef.current;
|
||||
if (!anchor) return;
|
||||
|
||||
const rect = anchor.getBoundingClientRect();
|
||||
const width = Math.min(
|
||||
TOOLTIP_WIDTH,
|
||||
window.innerWidth - VIEWPORT_MARGIN * 2,
|
||||
);
|
||||
const left = clamp(
|
||||
rect.left + rect.width / 2 - width / 2,
|
||||
VIEWPORT_MARGIN,
|
||||
window.innerWidth - width - VIEWPORT_MARGIN,
|
||||
);
|
||||
const placement = rect.top > 260 ? "top" : "bottom";
|
||||
setPosition({
|
||||
left,
|
||||
top:
|
||||
placement === "top"
|
||||
? rect.top - TOOLTIP_GAP
|
||||
: rect.bottom + TOOLTIP_GAP,
|
||||
width,
|
||||
placement,
|
||||
});
|
||||
}
|
||||
|
||||
updatePosition();
|
||||
window.addEventListener("resize", updatePosition);
|
||||
window.addEventListener("scroll", updatePosition, true);
|
||||
return () => {
|
||||
window.removeEventListener("resize", updatePosition);
|
||||
window.removeEventListener("scroll", updatePosition, true);
|
||||
};
|
||||
}, [anchorRef]);
|
||||
|
||||
if (typeof document === "undefined" || !position) return null;
|
||||
|
||||
const style: CSSProperties = {
|
||||
left: position.left,
|
||||
top: position.top,
|
||||
width: position.width,
|
||||
transform:
|
||||
position.placement === "top" ? "translateY(-100%)" : undefined,
|
||||
};
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
id={id}
|
||||
role="tooltip"
|
||||
style={style}
|
||||
className="pointer-events-none fixed z-[1000] border border-base-content/20 bg-black px-3 py-3 text-xs leading-relaxed text-white shadow-2xl"
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
function SummonerSpellTooltipContent({
|
||||
spellId,
|
||||
manifest,
|
||||
}: {
|
||||
spellId: number;
|
||||
manifest: DdragonManifest | null | undefined;
|
||||
}) {
|
||||
const spell = summonerSpellDetails(manifest, spellId);
|
||||
const descriptionHtml = spell?.description
|
||||
? safeDdragonDescriptionHtml(spell.description)
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="font-black text-[#f0d878]">
|
||||
{spell?.name ?? `스펠 ${spellId}`}
|
||||
</div>
|
||||
{descriptionHtml ? (
|
||||
<div
|
||||
className="text-white/80 [&_br]:block [&_br]:content-['']"
|
||||
dangerouslySetInnerHTML={{ __html: descriptionHtml }}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-white/55">
|
||||
스펠 상세 정보를 불러오는 중입니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuneTooltipContent({
|
||||
runeId,
|
||||
manifest,
|
||||
}: {
|
||||
runeId: number | undefined;
|
||||
manifest: DdragonManifest | null | undefined;
|
||||
}) {
|
||||
const rune = runeDetails(manifest, runeId);
|
||||
const descriptionHtml = rune?.longDesc
|
||||
? safeDdragonDescriptionHtml(rune.longDesc)
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="font-black text-[#f0d878]">
|
||||
{rune?.name ?? (runeId ? `룬 ${runeId}` : "룬")}
|
||||
</div>
|
||||
{rune?.shortDesc ? (
|
||||
<div className="font-bold text-white">{rune.shortDesc}</div>
|
||||
) : null}
|
||||
{descriptionHtml ? (
|
||||
<div
|
||||
className="text-white/80 [&_br]:block [&_br]:content-['']"
|
||||
dangerouslySetInnerHTML={{ __html: descriptionHtml }}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-white/55">룬 상세 정보를 불러오는 중입니다.</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RuneStyleTooltipContent({
|
||||
styleId,
|
||||
manifest,
|
||||
}: {
|
||||
styleId: number | undefined;
|
||||
manifest: DdragonManifest | null | undefined;
|
||||
}) {
|
||||
const style = runeStyleDetails(manifest, styleId);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="font-black text-[#f0d878]">
|
||||
{style?.name ?? (styleId ? `룬 ${styleId}` : "룬")}
|
||||
</div>
|
||||
<div className="text-white/55">룬 스타일</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemTooltipContent({
|
||||
itemId,
|
||||
manifest,
|
||||
}: {
|
||||
itemId: number;
|
||||
manifest: DdragonManifest | null | undefined;
|
||||
}) {
|
||||
const item = itemDetails(manifest, itemId);
|
||||
const descriptionHtml = item?.description
|
||||
? safeDdragonDescriptionHtml(item.description)
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="font-black text-[#f0d878]">
|
||||
{item?.name ?? `아이템 ${itemId}`}
|
||||
</div>
|
||||
{item?.plaintext ? (
|
||||
<div className="font-bold text-white">{item.plaintext}</div>
|
||||
) : null}
|
||||
{descriptionHtml ? (
|
||||
<div
|
||||
className="space-y-1 text-white/80 [&_br]:block [&_br]:content-['']"
|
||||
dangerouslySetInnerHTML={{ __html: descriptionHtml }}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-white/55">
|
||||
아이템 상세 정보를 불러오는 중입니다.
|
||||
</div>
|
||||
)}
|
||||
{item?.gold.total ? (
|
||||
<div className="border-t border-white/10 pt-2 font-bold text-white">
|
||||
가격:
|
||||
<span className="text-[#f0d878]">{item.gold.total}</span>{" "}
|
||||
<span className="text-[#f0d878]">
|
||||
({item.gold.base || item.gold.total})
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number) {
|
||||
if (max < min) return min;
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
@@ -122,6 +122,51 @@ body {
|
||||
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */
|
||||
}
|
||||
|
||||
/* ── 실시간 입찰 피드백 모션 ──
|
||||
입찰가 갱신 시 pop(스케일 펄스), 내가 밀렸을 때 shake(주의 환기). */
|
||||
@keyframes lts-bid-pop {
|
||||
0% {
|
||||
transform: scale(1);
|
||||
}
|
||||
35% {
|
||||
transform: scale(1.14);
|
||||
}
|
||||
100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes lts-outbid-shake {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateX(0);
|
||||
}
|
||||
20% {
|
||||
transform: translateX(-3px);
|
||||
}
|
||||
40% {
|
||||
transform: translateX(3px);
|
||||
}
|
||||
60% {
|
||||
transform: translateX(-2px);
|
||||
}
|
||||
80% {
|
||||
transform: translateX(2px);
|
||||
}
|
||||
}
|
||||
.animate-bid-pop {
|
||||
animation: lts-bid-pop 0.45s cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
transform-origin: right center;
|
||||
}
|
||||
.animate-outbid-shake {
|
||||
animation: lts-outbid-shake 0.4s ease-in-out;
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.animate-bid-pop,
|
||||
.animate-outbid-shake {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* poro.gg style: 모든 모서리 각지게 */
|
||||
*,
|
||||
*::before,
|
||||
|
||||
@@ -2,6 +2,25 @@ import type { DdragonManifest } from '../api/types';
|
||||
|
||||
const FALLBACK_VERSION = '15.24.1';
|
||||
const FALLBACK_CDN = 'https://ddragon.leagueoflegends.com/cdn';
|
||||
const DDRAGON_DESCRIPTION_TAG_CLASSES: Record<string, string> = {
|
||||
active: 'text-[#f0d878] font-semibold',
|
||||
attention: 'text-[#f0d878] font-semibold',
|
||||
flavorText: 'text-white/45 italic',
|
||||
healing: 'text-emerald-300 font-semibold',
|
||||
keywordMajor: 'text-[#f0d878] font-semibold',
|
||||
keywordName: 'text-[#f0d878] font-semibold',
|
||||
keywordStealth: 'text-violet-300 font-semibold',
|
||||
mainText: 'text-white/80',
|
||||
ornnBonus: 'text-[#f0d878] font-semibold',
|
||||
passive: 'text-[#f0d878] font-semibold',
|
||||
rarityGeneric: 'text-white/55',
|
||||
rarityLegendary: 'text-[#f0d878] font-semibold',
|
||||
rarityMythic: 'text-violet-300 font-semibold',
|
||||
rules: 'text-white/45',
|
||||
shield: 'text-sky-300 font-semibold',
|
||||
stats: 'text-sky-200',
|
||||
status: 'text-sky-300 font-semibold',
|
||||
};
|
||||
|
||||
function cdn(manifest: DdragonManifest | null | undefined) {
|
||||
return manifest?.cdn ?? FALLBACK_CDN;
|
||||
@@ -42,6 +61,34 @@ export function itemIconUrl(
|
||||
return `${cdn(manifest)}/${version(manifest)}/img/item/${itemId}.png`;
|
||||
}
|
||||
|
||||
export function itemDetails(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
itemId: number,
|
||||
) {
|
||||
if (!itemId) return null;
|
||||
return manifest?.items?.[String(itemId)] ?? null;
|
||||
}
|
||||
|
||||
export function itemDisplayName(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
itemId: number,
|
||||
) {
|
||||
return itemDetails(manifest, itemId)?.name ?? null;
|
||||
}
|
||||
|
||||
export function safeDdragonDescriptionHtml(description: string) {
|
||||
const escaped = escapeHtml(description);
|
||||
return escaped
|
||||
.replace(/<br\s*\/?>/gi, '<br />')
|
||||
.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9]*)(?:\s[\s\S]*?)?>/g, (_match, closing, tag) => {
|
||||
const normalizedTag = String(tag);
|
||||
const className = DDRAGON_DESCRIPTION_TAG_CLASSES[normalizedTag];
|
||||
if (!className) return '';
|
||||
return closing ? '</span>' : `<span class="${className}">`;
|
||||
})
|
||||
.replace(/<\/?[a-zA-Z][\s\S]*?>/g, '');
|
||||
}
|
||||
|
||||
export function summonerSpellIconUrl(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
spellId: number,
|
||||
@@ -51,21 +98,44 @@ export function summonerSpellIconUrl(
|
||||
return `${cdn(manifest)}/${version(manifest)}/img/spell/${spell.key}.png`;
|
||||
}
|
||||
|
||||
export function summonerSpellDetails(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
spellId: number,
|
||||
) {
|
||||
if (!spellId) return null;
|
||||
return manifest?.summonerSpells[String(spellId)] ?? null;
|
||||
}
|
||||
|
||||
export function runeStyleDetails(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
styleId: number | undefined,
|
||||
) {
|
||||
return manifest?.runesReforged.find((entry) => entry.id === styleId) ?? null;
|
||||
}
|
||||
|
||||
export function runeStyleIconUrl(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
styleId: number | undefined,
|
||||
) {
|
||||
const style = manifest?.runesReforged.find((entry) => entry.id === styleId);
|
||||
const style = runeStyleDetails(manifest, styleId);
|
||||
return style ? `${cdn(manifest)}/img/${style.icon}` : null;
|
||||
}
|
||||
|
||||
export function runeDetails(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
runeId: number | undefined,
|
||||
) {
|
||||
if (!runeId) return null;
|
||||
return manifest?.runesReforged
|
||||
.flatMap((style) => style.slots.flatMap((slot) => slot.runes))
|
||||
.find((entry) => entry.id === runeId) ?? null;
|
||||
}
|
||||
|
||||
export function runeKeystoneIconUrl(
|
||||
manifest: DdragonManifest | null | undefined,
|
||||
runeId: number | undefined,
|
||||
) {
|
||||
const rune = manifest?.runesReforged
|
||||
.flatMap((style) => style.slots.flatMap((slot) => slot.runes))
|
||||
.find((entry) => entry.id === runeId);
|
||||
const rune = runeDetails(manifest, runeId);
|
||||
|
||||
return rune ? `${cdn(manifest)}/img/${rune.icon}` : null;
|
||||
}
|
||||
@@ -76,3 +146,12 @@ export function runeIconUrl(
|
||||
) {
|
||||
return runeKeystoneIconUrl(manifest, runeId);
|
||||
}
|
||||
|
||||
function escapeHtml(value: string) {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export function internalMatchDetailPath(communityId: string, matchId: string) {
|
||||
return `/communities/${communityId}/internal-stats/match/${matchId}`;
|
||||
}
|
||||
|
||||
export function internalMatchGamePath(
|
||||
communityId: string,
|
||||
matchId: string,
|
||||
gameNumber: string | number,
|
||||
) {
|
||||
return `${internalMatchDetailPath(communityId, matchId)}/game/${gameNumber}`;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { BrowserAgent } from '@newrelic/browser-agent/loaders/browser-agent';
|
||||
import type { AgentOptions } from '@newrelic/browser-agent/loaders/agent';
|
||||
|
||||
type NewRelicBrowserAgent = InstanceType<typeof BrowserAgent>;
|
||||
type NewRelicAttributeValue = string | number | boolean | null;
|
||||
type NewRelicAttributes = Record<string, NewRelicAttributeValue>;
|
||||
|
||||
const DEFAULT_BEACON = 'bam.nr-data.net';
|
||||
const DEFAULT_RELEASE_NAME = 'lolympus-web';
|
||||
|
||||
let browserAgent: NewRelicBrowserAgent | null = null;
|
||||
|
||||
function readEnvValue(name: string): string | undefined {
|
||||
const value = import.meta.env[name];
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function readEnvNumber(name: string): number | undefined {
|
||||
const value = Number(readEnvValue(name));
|
||||
return Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function isBrowserRuntime() {
|
||||
return typeof window !== 'undefined';
|
||||
}
|
||||
|
||||
export function isNewRelicBrowserMonitoringEnabled() {
|
||||
return readEnvValue('VITE_NEW_RELIC_ENABLED') !== 'false';
|
||||
}
|
||||
|
||||
export function createNewRelicBrowserAgentOptions(): AgentOptions | null {
|
||||
if (!isNewRelicBrowserMonitoringEnabled()) return null;
|
||||
|
||||
const applicationID = readEnvValue('VITE_NEW_RELIC_APPLICATION_ID');
|
||||
const accountID = readEnvNumber('VITE_NEW_RELIC_ACCOUNT_ID');
|
||||
const licenseKey = readEnvValue('VITE_NEW_RELIC_LICENSE_KEY');
|
||||
const beacon = readEnvValue('VITE_NEW_RELIC_BEACON') ?? DEFAULT_BEACON;
|
||||
const agentID = readEnvNumber('VITE_NEW_RELIC_AGENT_ID') ?? Number(applicationID);
|
||||
const applicationNumericID = Number(applicationID);
|
||||
const trustKey = readEnvNumber('VITE_NEW_RELIC_TRUST_KEY') ?? accountID;
|
||||
|
||||
if (
|
||||
!applicationID ||
|
||||
!accountID ||
|
||||
!licenseKey ||
|
||||
!Number.isFinite(agentID) ||
|
||||
!Number.isFinite(applicationNumericID)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
info: {
|
||||
applicationID,
|
||||
beacon,
|
||||
errorBeacon: beacon,
|
||||
licenseKey,
|
||||
sa: 1,
|
||||
},
|
||||
init: {
|
||||
ajax: {
|
||||
deny_list: [beacon],
|
||||
},
|
||||
browser_consent_mode: {
|
||||
enabled: false,
|
||||
},
|
||||
distributed_tracing: {
|
||||
enabled: true,
|
||||
},
|
||||
performance: {
|
||||
capture_detail: false,
|
||||
capture_marks: false,
|
||||
capture_measures: true,
|
||||
},
|
||||
privacy: {
|
||||
cookies_enabled: true,
|
||||
},
|
||||
session_replay: {
|
||||
enabled: false,
|
||||
autoStart: false,
|
||||
},
|
||||
},
|
||||
loader_config: {
|
||||
accountID,
|
||||
agentID,
|
||||
applicationID: applicationNumericID,
|
||||
licenseKey,
|
||||
trustKey,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function applyReleaseMetadata(agent: NewRelicBrowserAgent) {
|
||||
const applicationVersion =
|
||||
readEnvValue('VITE_NEW_RELIC_APPLICATION_VERSION') ??
|
||||
readEnvValue('VITE_APP_VERSION') ??
|
||||
readEnvValue('VITE_BUILD_NUMBER');
|
||||
if (!applicationVersion) return;
|
||||
|
||||
agent.setApplicationVersion(applicationVersion);
|
||||
agent.addRelease(
|
||||
readEnvValue('VITE_NEW_RELIC_RELEASE_NAME') ?? DEFAULT_RELEASE_NAME,
|
||||
readEnvValue('VITE_NEW_RELIC_RELEASE_ID') ?? applicationVersion,
|
||||
);
|
||||
}
|
||||
|
||||
export function initializeNewRelicBrowserAgent(
|
||||
options = createNewRelicBrowserAgentOptions(),
|
||||
) {
|
||||
if (!isBrowserRuntime() || !options) return null;
|
||||
if (browserAgent) return browserAgent;
|
||||
|
||||
// New Relic recommends instantiating the npm BrowserAgent from the earliest
|
||||
// browser entry point: https://docs.newrelic.com/docs/browser/browser-monitoring/installation/install-browser-monitoring-agent/
|
||||
browserAgent = new BrowserAgent(options);
|
||||
applyReleaseMetadata(browserAgent);
|
||||
|
||||
return browserAgent;
|
||||
}
|
||||
|
||||
export function getNewRelicBrowserAgent() {
|
||||
return browserAgent;
|
||||
}
|
||||
|
||||
export function setNewRelicUserId(userId: string | null, resetSession = false) {
|
||||
browserAgent?.setUserId(userId, resetSession);
|
||||
}
|
||||
|
||||
export function setNewRelicPageViewName(name: string, host?: string) {
|
||||
browserAgent?.setPageViewName(name, host);
|
||||
}
|
||||
|
||||
export function setNewRelicCustomAttribute(
|
||||
name: string,
|
||||
value: NewRelicAttributeValue,
|
||||
persist = false,
|
||||
) {
|
||||
browserAgent?.setCustomAttribute(name, value, persist);
|
||||
}
|
||||
|
||||
export function addNewRelicPageAction(
|
||||
name: string,
|
||||
attributes?: NewRelicAttributes,
|
||||
) {
|
||||
browserAgent?.addPageAction(name, attributes);
|
||||
}
|
||||
|
||||
export function recordNewRelicCustomEvent(
|
||||
eventType: string,
|
||||
attributes?: NewRelicAttributes,
|
||||
) {
|
||||
browserAgent?.recordCustomEvent(eventType, attributes);
|
||||
}
|
||||
|
||||
export function noticeNewRelicError(
|
||||
error: Error | string,
|
||||
attributes?: NewRelicAttributes,
|
||||
) {
|
||||
browserAgent?.noticeError(error, attributes);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { initializeNewRelicBrowserAgent } from './lib/observability/new-relic.ts';
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
@@ -6,6 +7,7 @@ import App from './App.tsx';
|
||||
import { MsalAppProvider } from './lib/auth/MsalAppProvider.tsx';
|
||||
import { initializeTheme } from './config.ts';
|
||||
|
||||
initializeNewRelicBrowserAgent();
|
||||
initializeTheme();
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
|
||||
+1375
-324
File diff suppressed because it is too large.
Load diff
@@ -5,14 +5,15 @@ import { DEFAULT_COMMUNITY_ID } from "../config";
|
||||
import {
|
||||
championDisplayName,
|
||||
championIconUrl,
|
||||
itemIconUrl,
|
||||
} from "../lib/ddragon";
|
||||
import {
|
||||
sideShortLabel,
|
||||
teamIndexColorClasses,
|
||||
teamIndexLabel,
|
||||
} from "../lib/league";
|
||||
import { internalMatchGamePath } from "../lib/internal-match-routes";
|
||||
import { LANE_LABELS } from "../lib/riot-history";
|
||||
import { ItemIcon } from "../components/ItemTooltip";
|
||||
|
||||
function formatDateTime(value: string | number) {
|
||||
return new Intl.DateTimeFormat("ko-KR", {
|
||||
@@ -71,27 +72,28 @@ function ItemStrip({
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{[...items, trinket].map((itemId, index) => {
|
||||
const icon = itemIconUrl(manifest, itemId);
|
||||
return (
|
||||
<span
|
||||
{[...items, trinket].map((itemId, index) => (
|
||||
<ItemIcon
|
||||
key={`${itemId}-${index}`}
|
||||
className="w-5 h-5 bg-base-content/10 border border-base-content/5 overflow-hidden"
|
||||
>
|
||||
{icon ? (
|
||||
<img src={icon} alt="" className="w-full h-full object-cover" />
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
itemId={itemId}
|
||||
manifest={manifest}
|
||||
trinket={index === items.length}
|
||||
className="h-5 w-5"
|
||||
imageClassName=""
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GamePanel({
|
||||
communityId,
|
||||
matchId,
|
||||
game,
|
||||
manifest,
|
||||
}: {
|
||||
communityId: string;
|
||||
matchId: string;
|
||||
game: ApiInternalMatchDetailResponse["games"][number];
|
||||
manifest: ReturnType<typeof useDdragonManifest>["data"];
|
||||
}) {
|
||||
@@ -112,6 +114,13 @@ function GamePanel({
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Link
|
||||
to={internalMatchGamePath(communityId, matchId, game.gameNumber)}
|
||||
state={{ backTo: historyBackTo }}
|
||||
className="border border-primary/20 px-2 py-1 text-xs font-black text-primary transition-colors hover:bg-primary/8"
|
||||
>
|
||||
상세 분석
|
||||
</Link>
|
||||
{game.teams.map((team) => (
|
||||
<span
|
||||
key={team.side}
|
||||
@@ -316,7 +325,13 @@ export default function InternalMatchDetailPage() {
|
||||
|
||||
<div className="space-y-4">
|
||||
{detail.games.map((game) => (
|
||||
<GamePanel key={game.riotMatchId} game={game} manifest={ddragon} />
|
||||
<GamePanel
|
||||
key={game.riotMatchId}
|
||||
communityId={communityId}
|
||||
matchId={detail.match.matchId}
|
||||
game={game}
|
||||
manifest={ddragon}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
+1171
-121
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -28,12 +28,13 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
|
||||
pair: "페어 매치",
|
||||
bracket: "토너먼트",
|
||||
"round-robin": "리그전",
|
||||
"double-elimination": "더블 엘리미네이션",
|
||||
};
|
||||
|
||||
function resultBadgeClass(won: boolean) {
|
||||
return won
|
||||
? "border-blue-500/20 bg-blue-500/10 text-blue-400"
|
||||
: "border-red-500/20 bg-red-500/10 text-red-400";
|
||||
? "border-info/20 bg-info/10 text-info"
|
||||
: "border-error/20 bg-error/10 text-error";
|
||||
}
|
||||
|
||||
function captainName(
|
||||
@@ -131,7 +132,7 @@ function ParticipantLine({
|
||||
{name}
|
||||
</span>
|
||||
{isCaptain && (
|
||||
<span className="shrink-0 border border-accent/20 bg-accent/10 px-1.5 py-0.5 text-xs font-bold text-amber-500">
|
||||
<span className="shrink-0 border border-accent/20 bg-accent/10 px-1.5 py-0.5 text-xs font-bold text-warning">
|
||||
팀장
|
||||
</span>
|
||||
)}
|
||||
@@ -191,9 +192,11 @@ function UpcomingGameCard({
|
||||
const opponentIndex =
|
||||
slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex;
|
||||
const ourTeam = teamByIndex.get(parsedTeamIndex);
|
||||
const opponentTeam = teamByIndex.get(opponentIndex);
|
||||
const opponentTeam = opponentIndex ? teamByIndex.get(opponentIndex) : undefined;
|
||||
const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name);
|
||||
const opponentTeamName = teamIndexLabel(opponentIndex, opponentTeam?.name);
|
||||
const opponentTeamName = opponentIndex
|
||||
? teamIndexLabel(opponentIndex, opponentTeam?.name)
|
||||
: "상대 미정";
|
||||
const ourCaptainName = captainName(ourTeam, participantByUserId);
|
||||
const opponentCaptainName = captainName(opponentTeam, participantByUserId);
|
||||
const opponentMembers = opponentTeam?.members ?? [];
|
||||
@@ -433,7 +436,7 @@ function TeamGameCardsSection({
|
||||
|
||||
<div className="p-4">
|
||||
{replaceError && (
|
||||
<div className="mb-3 border border-red-500/20 bg-red-500/8 px-3 py-2 text-xs text-red-300">
|
||||
<div className="mb-3 border border-error/20 bg-error/8 px-3 py-2 text-xs text-error">
|
||||
{replaceError}
|
||||
</div>
|
||||
)}
|
||||
@@ -531,7 +534,7 @@ export default function MatchTeamProgressPage() {
|
||||
|
||||
if (!DEFAULT_COMMUNITY_ID) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 text-center text-sm text-amber-600">
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 text-center text-sm text-warning">
|
||||
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
|
||||
</main>
|
||||
);
|
||||
@@ -701,9 +704,9 @@ export default function MatchTeamProgressPage() {
|
||||
aria-modal="true"
|
||||
aria-labelledby="team-tournament-code-replace-title"
|
||||
>
|
||||
<div className="w-full max-w-md border border-amber-500/25 bg-base-100 p-5 shadow-2xl">
|
||||
<div className="w-full max-w-md border border-warning/25 bg-base-100 p-5 shadow-2xl">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="inline-flex h-9 w-9 shrink-0 items-center justify-center border border-amber-500/25 bg-amber-500/10 text-amber-400">
|
||||
<span className="inline-flex h-9 w-9 shrink-0 items-center justify-center border border-warning/25 bg-warning/10 text-warning">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
@@ -743,7 +746,7 @@ export default function MatchTeamProgressPage() {
|
||||
handleConfirmReplaceTournamentCode();
|
||||
}
|
||||
}}
|
||||
className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-amber-400/60"
|
||||
className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-warning/60"
|
||||
placeholder="예"
|
||||
/>
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,6 +24,7 @@ const DEFAULT_FORM: MatchMutationRequest = {
|
||||
maxParticipants: 10,
|
||||
gameCount: 3,
|
||||
gameMode: 'pair',
|
||||
doubleEliminationResetFinalEnabled: true,
|
||||
prizes: [],
|
||||
notices: [],
|
||||
schedule: [],
|
||||
@@ -33,6 +34,7 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
|
||||
pair: '페어',
|
||||
bracket: '브래킷',
|
||||
'round-robin': '라운드 로빈',
|
||||
'double-elimination': '더블 엘리미네이션',
|
||||
};
|
||||
|
||||
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
|
||||
@@ -50,6 +52,12 @@ function normalizeRoundRobinMaxRounds(
|
||||
return Math.max(1, Math.min(fullRoundCount, Math.floor(value)));
|
||||
}
|
||||
|
||||
function normalizeSeriesGameCount(value: number | undefined) {
|
||||
if (!value || !Number.isFinite(value) || value < 1) return 3;
|
||||
const integer = Math.floor(value);
|
||||
return integer % 2 === 0 ? integer + 1 : integer;
|
||||
}
|
||||
|
||||
function RequiredBadge() {
|
||||
return (
|
||||
<span className="ml-1 inline-flex items-center border border-primary/20 bg-primary/5 px-1.5 py-0.5 text-xs font-bold text-primary">
|
||||
@@ -122,6 +130,8 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & {
|
||||
gameCount: match.gameCount,
|
||||
gameMode: match.gameMode ?? 'pair',
|
||||
roundRobinMaxRounds: match.roundRobinMaxRounds,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
match.doubleElimination?.resetFinalEnabled ?? true,
|
||||
prizes: match.prizes,
|
||||
notices: match.notices,
|
||||
schedule: match.schedule,
|
||||
@@ -188,6 +198,10 @@ export default function MatchAdminPage() {
|
||||
maxParticipants: Number(form.maxParticipants ?? 10),
|
||||
gameCount: Number(form.gameCount ?? 3),
|
||||
gameMode: form.gameMode,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
form.gameMode === 'double-elimination'
|
||||
? Boolean(form.doubleEliminationResetFinalEnabled)
|
||||
: undefined,
|
||||
roundRobinMaxRounds:
|
||||
form.gameMode === 'round-robin'
|
||||
? normalizeRoundRobinMaxRounds(
|
||||
@@ -329,7 +343,10 @@ export default function MatchAdminPage() {
|
||||
}}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
>
|
||||
{[10, 20, 30, 40, 50, 60].map((value) => (
|
||||
{(form.gameMode === 'double-elimination'
|
||||
? [20, 40]
|
||||
: [10, 20, 30, 40, 50, 60]
|
||||
).map((value) => (
|
||||
<option key={value} value={value}>{value}명</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -339,16 +356,39 @@ export default function MatchAdminPage() {
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
step={form.gameMode === 'double-elimination' ? 2 : 1}
|
||||
value={form.gameCount}
|
||||
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
/>
|
||||
{form.gameMode === 'double-elimination' && (
|
||||
<span className="mt-1 block text-xs text-base-content/30">
|
||||
승자조는 현재 3판 2선승으로 진행됩니다. 추후 5판 3선승도 같은
|
||||
구조로 지원합니다.
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
<label className="text-xs text-base-content/45">
|
||||
게임 모드
|
||||
<select
|
||||
value={form.gameMode}
|
||||
onChange={(event) => setForm((current) => ({ ...current, gameMode: event.target.value as MatchGameMode }))}
|
||||
onChange={(event) => {
|
||||
const gameMode = event.target.value as MatchGameMode;
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
gameMode,
|
||||
maxParticipants:
|
||||
gameMode === 'double-elimination' &&
|
||||
current.maxParticipants !== 20 &&
|
||||
current.maxParticipants !== 40
|
||||
? 20
|
||||
: current.maxParticipants,
|
||||
gameCount:
|
||||
gameMode === 'double-elimination'
|
||||
? normalizeSeriesGameCount(current.gameCount)
|
||||
: current.gameCount,
|
||||
}));
|
||||
}}
|
||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
||||
>
|
||||
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
|
||||
@@ -385,6 +425,22 @@ export default function MatchAdminPage() {
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
{form.gameMode === 'double-elimination' && (
|
||||
<label className="flex items-center gap-2 border border-base-content/10 px-3 py-2 text-xs text-base-content/55">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(form.doubleEliminationResetFinalEnabled)}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
doubleEliminationResetFinalEnabled:
|
||||
event.target.checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
그랜드 파이널 리셋 허용
|
||||
</label>
|
||||
)}
|
||||
<label className="text-xs text-base-content/45">
|
||||
상품 (줄바꿈 구분)
|
||||
<textarea
|
||||
@@ -474,6 +530,14 @@ export default function MatchAdminPage() {
|
||||
최대 {match.roundRobinMaxRounds}R
|
||||
</span>
|
||||
)}
|
||||
{match.gameMode === 'double-elimination' && (
|
||||
<span className="block text-xs text-base-content/30">
|
||||
GF 리셋{' '}
|
||||
{match.doubleElimination?.resetFinalEnabled
|
||||
? '허용'
|
||||
: '없음'}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">
|
||||
<div className="inline-flex gap-2">
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
# API Performance Observability Runbook
|
||||
|
||||
이 문서는 API p95 latency, Mongoose query count, returned document count,
|
||||
hydrated document count를 기준으로 전체 API 성능 리포트를 생성하는 운영 절차를
|
||||
정리한다.
|
||||
|
||||
## 목적
|
||||
|
||||
- 특정 top 10 API만 보는 것이 아니라, controller에 정의된 모든 API를 대상으로
|
||||
리포트를 만든다.
|
||||
- 운영 New Relic 실측 Transaction duration 데이터를 우선 활용한다.
|
||||
- `ApiRequestPerformance` custom event가 쌓인 환경에서는 Mongoose document 반환량까지
|
||||
함께 분석한다.
|
||||
- 로컬/staging 리허설에서는 NDJSON 파일로 동일한 리포트를 만든다.
|
||||
|
||||
## 데이터 소스
|
||||
|
||||
| Source | 명령 옵션 | 용도 | 포함 지표 |
|
||||
|---|---|---|---|
|
||||
| Local NDJSON | `--source=local` | staging/local 재현 테스트 | latency, query count, Mongoose duration, docs returned, hydrated docs |
|
||||
| New Relic custom event | `--source=newrelic-custom` | 운영/staging 상세 실측 분석 | latency, query count, Mongoose duration, docs returned, hydrated docs |
|
||||
| New Relic Transaction | `--source=newrelic-transaction` | 기존 New Relic latency 확인 | latency, error rate |
|
||||
|
||||
## 환경변수
|
||||
|
||||
### API 서버 계측
|
||||
|
||||
| 환경변수 | 기본값 | 설명 |
|
||||
|---|---:|---|
|
||||
| `API_PERF_OBSERVABILITY_ENABLED` | `false` | API/Mongoose 성능 계측 전체 활성화 |
|
||||
| `API_PERF_LOCAL_EVENTS_ENABLED` | `API_PERF_OBSERVABILITY_ENABLED` 값 | 로컬 NDJSON 파일 기록 여부 |
|
||||
| `API_PERF_LOCAL_EVENT_FILE` | `/tmp/lolympus-api-performance.ndjson` | 로컬 이벤트 파일 경로 |
|
||||
| `API_PERF_NEW_RELIC_REQUEST_EVENTS_ENABLED` | `API_PERF_OBSERVABILITY_ENABLED` 값 | `ApiRequestPerformance` custom event 기록 여부 |
|
||||
| `API_PERF_NEW_RELIC_QUERY_EVENTS_ENABLED` | `false` | query별 `MongooseQueryPerformance` custom event 기록 여부 |
|
||||
|
||||
`API_PERF_NEW_RELIC_QUERY_EVENTS_ENABLED`는 이벤트 수가 많을 수 있으므로 기본값을
|
||||
`false`로 유지한다. request 단위 지표만으로도 route별 문서 반환량은 확인할 수 있다.
|
||||
|
||||
### New Relic 리포트 조회
|
||||
|
||||
| 환경변수 | 설명 |
|
||||
|---|---|
|
||||
| `NEW_RELIC_ACCOUNT_ID` | New Relic account id |
|
||||
| `NEW_RELIC_USER_API_KEY` 또는 `NEW_RELIC_API_KEY` | NerdGraph 조회용 API key |
|
||||
| `NEW_RELIC_APP_NAME` | API app name. 기본값은 `lolympus` |
|
||||
|
||||
## 기본 운영 흐름
|
||||
|
||||
### 1. 전체 API 목록 확인
|
||||
|
||||
```bash
|
||||
pnpm --filter api perf:routes
|
||||
```
|
||||
|
||||
이 명령은 `*.controller.ts` 파일을 읽어 전체 route manifest를 출력한다. 리포트는
|
||||
이 manifest를 기준으로 모든 API를 출력한다. 트래픽이 없었던 API는 `no-samples`로
|
||||
표시된다.
|
||||
|
||||
### 2. New Relic Transaction 기반 전체 latency 리포트
|
||||
|
||||
```bash
|
||||
NEW_RELIC_ACCOUNT_ID=... \
|
||||
NEW_RELIC_USER_API_KEY=... \
|
||||
NEW_RELIC_APP_NAME=lolympus \
|
||||
pnpm --filter api perf:report -- --source=newrelic-transaction --since="1 day ago"
|
||||
```
|
||||
|
||||
이미 New Relic에 쌓인 Transaction duration을 사용한다. 가장 먼저 실행해 전체 API의
|
||||
p95/p99 latency와 error rate를 확인한다.
|
||||
|
||||
제한사항:
|
||||
|
||||
- Mongoose docs returned, hydrated docs returned는 나오지 않는다.
|
||||
- 이번 계측 배포 이후에는 transaction name이 `METHOD /route-template` 형태로 잡혀
|
||||
route별 집계 정확도가 올라간다.
|
||||
|
||||
### 3. New Relic custom event 기반 상세 리포트
|
||||
|
||||
API 서버가 아래 환경변수로 실행된 뒤 트래픽이 쌓여야 한다.
|
||||
|
||||
```bash
|
||||
API_PERF_OBSERVABILITY_ENABLED=true
|
||||
API_PERF_NEW_RELIC_REQUEST_EVENTS_ENABLED=true
|
||||
```
|
||||
|
||||
중요: custom event는 소급 생성되지 않는다. 계측 코드가 배포되고 위 환경변수로
|
||||
서버가 재시작된 이후의 요청부터 `ApiRequestPerformance`가 쌓인다. 기존 New Relic
|
||||
Transaction 데이터가 있어도 custom event 리포트는 0건일 수 있다.
|
||||
|
||||
리포트 생성:
|
||||
|
||||
```bash
|
||||
NEW_RELIC_ACCOUNT_ID=... \
|
||||
NEW_RELIC_USER_API_KEY=... \
|
||||
NEW_RELIC_APP_NAME=lolympus \
|
||||
pnpm --filter api perf:report -- --source=newrelic-custom --since="1 day ago"
|
||||
```
|
||||
|
||||
이 리포트는 route별로 다음 지표를 포함한다.
|
||||
|
||||
- `samples`
|
||||
- `avgMs`, `p50Ms`, `p95Ms`, `p99Ms`, `maxMs`
|
||||
- `errorRatePercentage`
|
||||
- `queryCountP95`
|
||||
- `mongooseDurationP95Ms`
|
||||
- `docsReturnedP95`
|
||||
- `hydratedDocsReturnedP95`
|
||||
|
||||
### 4. Local NDJSON 기반 재현 테스트
|
||||
|
||||
staging/local API 서버를 계측 모드로 실행한다.
|
||||
|
||||
```bash
|
||||
API_PERF_OBSERVABILITY_ENABLED=true \
|
||||
API_PERF_LOCAL_EVENTS_ENABLED=true \
|
||||
API_PERF_LOCAL_EVENT_FILE=/tmp/lolympus-api-performance.ndjson \
|
||||
pnpm --filter api start:staging
|
||||
```
|
||||
|
||||
브라우저, curl, Postman, k6 등으로 테스트 대상 API를 호출한다. 호출하지 않은 API는
|
||||
리포트에서 `no-samples`로 남는다.
|
||||
|
||||
리포트 생성:
|
||||
|
||||
```bash
|
||||
pnpm --filter api perf:report -- \
|
||||
--source=local \
|
||||
--input=/tmp/lolympus-api-performance.ndjson
|
||||
```
|
||||
|
||||
JSON 출력:
|
||||
|
||||
```bash
|
||||
pnpm --filter api perf:report -- \
|
||||
--source=local \
|
||||
--input=/tmp/lolympus-api-performance.ndjson \
|
||||
--format=json
|
||||
```
|
||||
|
||||
파일 저장:
|
||||
|
||||
```bash
|
||||
pnpm --filter api perf:report -- \
|
||||
--source=local \
|
||||
--input=/tmp/lolympus-api-performance.ndjson \
|
||||
--output=/tmp/api-performance-report.md
|
||||
```
|
||||
|
||||
## 예산값 조정
|
||||
|
||||
기본 기준:
|
||||
|
||||
- p95 latency budget: `300ms`
|
||||
- docs returned p95 budget: `500`
|
||||
- hydrated docs returned p95 budget: `0`
|
||||
|
||||
명령에서 덮어쓸 수 있다.
|
||||
|
||||
```bash
|
||||
pnpm --filter api perf:report -- \
|
||||
--source=newrelic-custom \
|
||||
--since="1 day ago" \
|
||||
--p95-budget-ms=500 \
|
||||
--docs-returned-p95-budget=300 \
|
||||
--hydrated-docs-returned-p95-budget=0
|
||||
```
|
||||
|
||||
## 리포트 해석
|
||||
|
||||
| Status | 의미 | 다음 작업 |
|
||||
|---|---|---|
|
||||
| `ok` | 현재 budget 안에 있음 | 유지 관찰 |
|
||||
| `slow` | p95 latency가 budget 초과 | New Relic trace, Mongoose duration, 외부 호출 확인 |
|
||||
| `document-heavy` | docs returned 또는 hydrated docs returned가 budget 초과 | `.lean()`, `.select()`, pagination, aggregation/materialized view 검토 |
|
||||
| `no-samples` | route manifest에는 있으나 측정 기간에 호출 샘플 없음 | 테스트 커버리지/운영 트래픽 여부 확인 |
|
||||
|
||||
`document-heavy`가 뜨는 API는 latency가 아직 괜찮아도 우선 조사 대상이다. 데이터가
|
||||
늘어나면 p95 latency가 악화될 가능성이 높다.
|
||||
|
||||
## 권장 분석 순서
|
||||
|
||||
1. `newrelic-transaction`으로 전체 route의 p95/p99 latency를 확인한다.
|
||||
2. `newrelic-custom`으로 `slow` 또는 `document-heavy` route를 확인한다.
|
||||
3. `docsReturnedP95`가 크면 projection, pagination, aggregate result 축소를 본다.
|
||||
4. `hydratedDocsReturnedP95`가 0보다 크면 읽기 전용 경로에 `.lean()` 적용을 검토한다.
|
||||
5. `queryCountP95`가 크면 N+1 query 또는 반복 조회를 찾는다.
|
||||
6. `mongooseDurationP95Ms`가 낮은데 `p95Ms`만 높으면 외부 API, CPU work, serialization,
|
||||
payload size를 본다.
|
||||
|
||||
## 전체 API 테스트 체크리스트
|
||||
|
||||
- [ ] `pnpm --filter api perf:routes`로 route 목록을 확인했다.
|
||||
- [ ] 주요 화면/운영 기능을 실제로 한 번 이상 호출했다.
|
||||
- [ ] 리포트의 `no-samples` route를 확인했다.
|
||||
- [ ] intentionally unused/admin-only API와 테스트 누락 API를 구분했다.
|
||||
- [ ] `slow` route의 New Relic trace를 확인했다.
|
||||
- [ ] `document-heavy` route의 Mongoose 반환량과 hydration 여부를 확인했다.
|
||||
- [ ] 개선 전 리포트를 저장했다.
|
||||
- [ ] 개선 후 같은 window/traffic 조건으로 리포트를 다시 생성했다.
|
||||
|
||||
## 운영 주의사항
|
||||
|
||||
- 계측은 기본 비활성화다. 운영에서 켤 때는 배포 환경변수로 명시한다.
|
||||
- request body, auth header, cookie, raw Mongo filter/result는 기록하지 않는다.
|
||||
- query별 custom event는 cardinality와 event volume이 커질 수 있어 필요할 때만 켠다.
|
||||
- local NDJSON 파일은 장시간 부하 테스트 시 커질 수 있다. 테스트 전 파일을 지우거나
|
||||
새 경로를 사용한다.
|
||||
- New Relic custom event 기반 리포트는 계측 활성화 이후 쌓인 데이터만 포함한다.
|
||||
- Transaction 기반 리포트는 기존 실측 latency를 볼 수 있지만 Mongoose 문서 반환량은
|
||||
포함하지 않는다.
|
||||
|
||||
## 문제 해결
|
||||
|
||||
### 리포트가 전부 `no-samples`로 나온다
|
||||
|
||||
- local source라면 `--input` 경로가 `API_PERF_LOCAL_EVENT_FILE`과 같은지 확인한다.
|
||||
- API 서버가 `API_PERF_OBSERVABILITY_ENABLED=true`로 실행됐는지 확인한다.
|
||||
- API를 실제로 호출했는지 확인한다.
|
||||
- New Relic source라면 `--since` window 안에 데이터가 있는지 확인한다.
|
||||
- `newrelic-custom` source라면 계측 배포/환경변수 활성화 이후의 요청인지 확인한다.
|
||||
|
||||
New Relic에서 custom event 존재 여부를 먼저 확인한다.
|
||||
|
||||
```sql
|
||||
FROM ApiRequestPerformance SELECT count(*) SINCE 1 day ago
|
||||
```
|
||||
|
||||
app name 필터까지 확인한다.
|
||||
|
||||
```sql
|
||||
FROM ApiRequestPerformance
|
||||
SELECT count(*)
|
||||
WHERE appName = 'lolympus'
|
||||
SINCE 1 day ago
|
||||
```
|
||||
|
||||
위 값이 0이면 `pnpm --filter api perf:report -- --source=newrelic-custom`도 전부
|
||||
`no-samples`가 맞다. 이 경우 historical latency는 `newrelic-transaction` source로
|
||||
보고, 상세 Mongoose 지표는 계측 활성화 후 다시 수집한다.
|
||||
|
||||
### New Relic 조회가 실패한다
|
||||
|
||||
- `NEW_RELIC_ACCOUNT_ID`가 숫자인지 확인한다.
|
||||
- `NEW_RELIC_USER_API_KEY` 또는 `NEW_RELIC_API_KEY`가 NerdGraph 조회 권한을 갖는지 확인한다.
|
||||
- `NEW_RELIC_APP_NAME`이 New Relic app name과 일치하는지 확인한다.
|
||||
|
||||
### Mongoose 지표가 비어 있다
|
||||
|
||||
- `newrelic-transaction` source는 Mongoose 지표를 제공하지 않는다.
|
||||
- `newrelic-custom` 또는 `local` source를 사용한다.
|
||||
- 계측 활성화 이후 발생한 request인지 확인한다.
|
||||
|
||||
## 관련 파일
|
||||
|
||||
- `apps/api/src/modules/global/observability/api-performance.interceptor.ts`
|
||||
- `apps/api/src/modules/global/observability/performance-observer.ts`
|
||||
- `apps/api/src/modules/global/observability/mongoose-performance.plugin.ts`
|
||||
- `apps/api/src/scripts/api-performance-report.ts`
|
||||
- `docs/specs/api-performance-observability.md`
|
||||
@@ -0,0 +1,80 @@
|
||||
# Spec: API Performance Observability And Full Route Report
|
||||
|
||||
## Objective
|
||||
|
||||
Add Phase 1 and Phase 2 support for API performance work:
|
||||
|
||||
- Phase 1 records request latency and Mongoose document-return metrics.
|
||||
- Phase 2 generates a report for every API route, not only the slowest routes.
|
||||
- New Relic Transaction or custom event data is the preferred production source.
|
||||
- Local NDJSON files provide a staging/local fallback with query-level detail.
|
||||
|
||||
Success means an engineer can run representative traffic against the API and produce
|
||||
a route-complete report that includes routes with no samples.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- NestJS API in `apps/api`
|
||||
- Mongoose models created through `ConnectionService`
|
||||
- New Relic Node agent, already configured by `apps/api/newrelic.cjs`
|
||||
- Jest for unit tests
|
||||
- `ts-node` for API maintenance scripts
|
||||
|
||||
## Commands
|
||||
|
||||
- Build: `pnpm --filter api build`
|
||||
- Test: `pnpm --filter api test`
|
||||
- Generate local/New Relic report: `pnpm --filter api perf:report`
|
||||
- Generate route manifest only: `pnpm --filter api perf:routes`
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `apps/api/src/modules/global/observability/` contains request/query instrumentation.
|
||||
- `apps/api/src/scripts/api-performance-report.ts` generates full API reports.
|
||||
- `docs/specs/api-performance-observability.md` defines this behavior.
|
||||
|
||||
## Code Style
|
||||
|
||||
Instrumentation must be opt-in and defensive:
|
||||
|
||||
```ts
|
||||
if (!isPerformanceObservabilityEnabled()) return;
|
||||
recordApiPerformanceEvent({
|
||||
type: 'api-request',
|
||||
method,
|
||||
route,
|
||||
durationMs,
|
||||
});
|
||||
```
|
||||
|
||||
Do not record raw request bodies, authorization headers, cookies, raw Mongo filters,
|
||||
or raw query results.
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Unit test pure metric aggregation and route discovery logic.
|
||||
- Unit test request context aggregation without a database.
|
||||
- Build the API to catch Nest and TypeScript integration issues.
|
||||
- Production/staging validation uses New Relic Transaction data and optional local
|
||||
NDJSON from representative traffic.
|
||||
|
||||
## Boundaries
|
||||
|
||||
- Always: keep instrumentation disabled unless explicitly enabled.
|
||||
- Always: include all discovered controller routes in the report.
|
||||
- Always: report `no-samples` for routes that did not receive traffic.
|
||||
- Ask first: adding external load-test dependencies or CI performance gates.
|
||||
- Never: log secrets, request bodies, auth headers, cookies, or raw Mongo filters.
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- API request events include duration, status, route, query count, Mongoose duration,
|
||||
returned document count, and hydrated document count.
|
||||
- Mongoose query events include model, collection, operation, duration, returned
|
||||
documents, hydrated documents, and lean status.
|
||||
- New Relic receives route-level custom events when instrumentation is enabled.
|
||||
- New Relic Transaction traces can be grouped by route through custom transaction names
|
||||
and attributes.
|
||||
- The report generator can use local NDJSON, New Relic custom events, or New Relic
|
||||
Transaction duration data.
|
||||
- The report lists every API route from controller source files.
|
||||
Generated
+890
-17
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user