Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ee8c3807b | ||
|
|
88de2148ae | ||
|
|
871a5fe78a | ||
|
|
60a006008a | ||
|
|
df7dcd3a9c | ||
|
|
292e37aaac | ||
|
|
4906f665fd | ||
|
|
68afaf0cb8 | ||
|
|
38c2d1f1b4 | ||
|
|
4ab5722759 | ||
|
|
51ea9c42d3 | ||
|
|
d6e0bbf0e8 | ||
|
|
e80313e459 | ||
|
|
9decc6866f | ||
|
|
e12f182e7f | ||
|
|
b9aaf55193 |
No files matched your search
@@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
|
|||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<video
|
<video
|
||||||
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/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"
|
poster="docs/screenshots/lolympus-auction.png"
|
||||||
width="960"
|
width="960"
|
||||||
autoplay="autoplay"
|
autoplay="autoplay"
|
||||||
@@ -13,20 +13,20 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
|
|||||||
playsinline="playsinline"
|
playsinline="playsinline"
|
||||||
controls
|
controls
|
||||||
>
|
>
|
||||||
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/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>
|
</video>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/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>
|
</p>
|
||||||
|
|
||||||
## 배포 주소
|
## 배포 주소
|
||||||
|
|
||||||
| Environment | Version | URL |
|
| Environment | Version | URL |
|
||||||
| ----------- | ------- | -------------------------------------- |
|
| ----------- | ------- | -------------------------------------- |
|
||||||
| Production | v83 | <https://lolympus.dahyeon.us/> |
|
| Production | v84 | <https://lolympus.dahyeon.us/> |
|
||||||
| Staging | v83 | <https://release-83.lolympus.pages.dev/> |
|
| Staging | v84 | <https://release-84.lolympus.pages.dev/> |
|
||||||
|
|
||||||
## 개요
|
## 개요
|
||||||
|
|
||||||
@@ -48,7 +48,10 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
|
|||||||
4. **팀별 진행 페이지**
|
4. **팀별 진행 페이지**
|
||||||
각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다.
|
각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다.
|
||||||
|
|
||||||
5. **결과 수집과 통계**
|
5. **더블 엘리미네이션 운영**
|
||||||
|
4팀/8팀 더블 엘리미네이션 대진표를 생성하고, 시드 교체, 부전승, 제한적 결과 취소, 그랜드 파이널 리셋을 관리합니다.
|
||||||
|
|
||||||
|
6. **결과 수집과 통계**
|
||||||
Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다.
|
Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다.
|
||||||
|
|
||||||
## 스크린샷
|
## 스크린샷
|
||||||
@@ -78,6 +81,7 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
|
|||||||
- Riot 계정 기반 참가자 프로필, 티어, 포지션 확인
|
- Riot 계정 기반 참가자 프로필, 티어, 포지션 확인
|
||||||
- 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원
|
- 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원
|
||||||
- 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리
|
- 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리
|
||||||
|
- 4팀/8팀 더블 엘리미네이션 대진표, 시드 관리, 부전승, 제한적 취소, 그랜드 파이널 리셋 지원
|
||||||
- 경기별 토너먼트 코드 배정과 팀별 복사 UI
|
- 경기별 토너먼트 코드 배정과 팀별 복사 UI
|
||||||
- 팀별 경기 일정, 상대 팀, 라인업, 결과 확인
|
- 팀별 경기 일정, 상대 팀, 라인업, 결과 확인
|
||||||
- Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공
|
- Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공
|
||||||
@@ -145,6 +149,12 @@ NEW_RELIC_SPAN_EVENTS_MAX_SAMPLES_STORED=10000
|
|||||||
|
|
||||||
New Relic Node agent의 정수 환경변수는 `100k` 같은 축약형 대신 `100000`처럼 숫자 문자열을 사용합니다.
|
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 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
|
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
|
||||||
|
|
||||||
## 커맨드
|
## 커맨드
|
||||||
@@ -154,6 +164,8 @@ New Relic Node agent의 정수 환경변수는 `100k` 같은 축약형 대신 `1
|
|||||||
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
|
| `pnpm start:web:dev` | 웹 앱 개발 서버 실행 |
|
||||||
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
|
| `pnpm start:api:dev` | API 서버 dev 환경 실행 |
|
||||||
| `pnpm --filter api test` | API 테스트 실행 |
|
| `pnpm --filter api test` | API 테스트 실행 |
|
||||||
|
| `pnpm --filter api perf:routes` | API 성능 리포트 대상 route 출력 |
|
||||||
|
| `pnpm --filter api perf:report` | API 성능 리포트 생성 |
|
||||||
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
|
| `pnpm --filter web build:staging` | 웹 staging 빌드 검증 |
|
||||||
| `pnpm deploy:web:staging` | Cloudflare Pages staging 배포 |
|
| `pnpm deploy:web:staging` | Cloudflare Pages staging 배포 |
|
||||||
| `pnpm deploy:web:prod` | Cloudflare Pages production 배포 |
|
| `pnpm deploy:web:prod` | Cloudflare Pages production 배포 |
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
"pm2:dev": "pm2 start npm --name lolympus-tournament-support --update-env -- run start:dev",
|
"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: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",
|
"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",
|
"start:debug": "nest start --debug --watch",
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
"test": "jest",
|
"test": "jest",
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { APP_INTERCEPTOR } from '@nestjs/core';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
|
import { ApiPerformanceInterceptor } from './modules/global/observability/api-performance.interceptor';
|
||||||
import { AuctionModule } from './modules/auction/auction.module';
|
import { AuctionModule } from './modules/auction/auction.module';
|
||||||
import { AuthModule } from './modules/auth/auth.module';
|
import { AuthModule } from './modules/auth/auth.module';
|
||||||
import { CommunityModule } from './modules/community/community.module';
|
import { CommunityModule } from './modules/community/community.module';
|
||||||
@@ -39,6 +41,12 @@ import { UserModule } from './modules/user/user.module';
|
|||||||
DakaoModule,
|
DakaoModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [
|
||||||
|
AppService,
|
||||||
|
{
|
||||||
|
provide: APP_INTERCEPTOR,
|
||||||
|
useClass: ApiPerformanceInterceptor,
|
||||||
|
},
|
||||||
|
],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
@@ -183,6 +183,77 @@ describe('AuctionService', () => {
|
|||||||
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('lists auction history with a summary projection and short local cache', async () => {
|
||||||
|
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const match = {
|
||||||
|
communityId: {
|
||||||
|
equals: jest.fn((value) => value.toString() === communityId.toString()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const historyRows = [
|
||||||
|
{
|
||||||
|
action: 'sold',
|
||||||
|
sequence: 4,
|
||||||
|
takenAt: new Date('2026-06-26T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
action: 'open-bidding',
|
||||||
|
sequence: 3,
|
||||||
|
takenAt: new Date('2026-06-26T00:00:01.000Z'),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const historyExec = jest.fn().mockResolvedValue(historyRows);
|
||||||
|
const historyLean = jest.fn().mockReturnValue({ exec: historyExec });
|
||||||
|
const historyLimit = jest.fn().mockReturnValue({ lean: historyLean });
|
||||||
|
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
|
||||||
|
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
|
||||||
|
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
|
||||||
|
const { service } = createService({
|
||||||
|
auctionHistory: {
|
||||||
|
find: historyFind,
|
||||||
|
},
|
||||||
|
match: {
|
||||||
|
findById: jest.fn().mockReturnValue({
|
||||||
|
select: jest.fn().mockResolvedValue(match),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.listHistory({ matchId, communityId }),
|
||||||
|
).resolves.toEqual([
|
||||||
|
{
|
||||||
|
action: 'sold',
|
||||||
|
actionLabel: '낙찰 처리',
|
||||||
|
sequence: 4,
|
||||||
|
takenAt: historyRows[0].takenAt,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
action: 'open-bidding',
|
||||||
|
actionLabel: '입찰 열기',
|
||||||
|
sequence: 3,
|
||||||
|
takenAt: historyRows[1].takenAt,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await service.listHistory({ matchId, communityId });
|
||||||
|
|
||||||
|
expect(historyFind).toHaveBeenCalledTimes(1);
|
||||||
|
expect(historySelect).toHaveBeenCalledWith({
|
||||||
|
_id: 0,
|
||||||
|
action: 1,
|
||||||
|
sequence: 1,
|
||||||
|
takenAt: 1,
|
||||||
|
});
|
||||||
|
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
|
||||||
|
expect(historyLimit).toHaveBeenCalledWith(100);
|
||||||
|
|
||||||
|
nowSpy.mockReturnValue(3101);
|
||||||
|
await service.listHistory({ matchId, communityId });
|
||||||
|
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
|||||||
@@ -58,6 +58,9 @@ const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
|||||||
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
||||||
const AUCTION_REHYDRATE_LOCK_TTL_MS = 5 * 1000;
|
const AUCTION_REHYDRATE_LOCK_TTL_MS = 5 * 1000;
|
||||||
const AUCTION_REHYDRATE_LOCK_WAIT_MS = 50;
|
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 {
|
interface StartAuctionParams {
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
@@ -141,6 +144,17 @@ export interface AuctionHistoryView {
|
|||||||
takenAt: Date;
|
takenAt: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface AuctionHistorySummaryRecord {
|
||||||
|
sequence: number;
|
||||||
|
action: AuctionActionType;
|
||||||
|
takenAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuctionHistoryListCacheEntry {
|
||||||
|
entries: AuctionHistoryView[];
|
||||||
|
expiresAtTimestampMS: number;
|
||||||
|
}
|
||||||
|
|
||||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||||
|
|
||||||
export interface AuctionBidDeltaResponse {
|
export interface AuctionBidDeltaResponse {
|
||||||
@@ -183,6 +197,10 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuctionService {
|
export class AuctionService {
|
||||||
private readonly logger = new Logger(AuctionService.name);
|
private readonly logger = new Logger(AuctionService.name);
|
||||||
|
private readonly auctionHistoryListCache = new Map<
|
||||||
|
string,
|
||||||
|
AuctionHistoryListCacheEntry
|
||||||
|
>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
@@ -551,18 +569,64 @@ export class AuctionService {
|
|||||||
throw new BadRequestException('Match does not belong to this community.');
|
throw new BadRequestException('Match does not belong to this community.');
|
||||||
}
|
}
|
||||||
|
|
||||||
const entries = await AuctionHistoryModel.find({ matchId: params.matchId })
|
const cacheKey = this.buildAuctionHistoryListCacheKey(params);
|
||||||
.sort({ sequence: -1 })
|
const cachedHistory = this.getCachedAuctionHistoryList(cacheKey);
|
||||||
.limit(100)
|
if (cachedHistory) return cachedHistory;
|
||||||
.lean()
|
|
||||||
.exec();
|
|
||||||
|
|
||||||
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,
|
sequence: entry.sequence,
|
||||||
action: entry.action,
|
action: entry.action,
|
||||||
actionLabel: this.formatHistoryActionLabel(entry.action),
|
actionLabel: this.formatHistoryActionLabel(entry.action),
|
||||||
takenAt: entry.takenAt,
|
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(
|
public async openBidding(
|
||||||
|
|||||||
@@ -205,24 +205,36 @@ describe('CommunityStatsService', () => {
|
|||||||
get: jest.fn().mockResolvedValue(null),
|
get: jest.fn().mockResolvedValue(null),
|
||||||
set: jest.fn().mockResolvedValue(undefined),
|
set: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
} 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(
|
const service = new CommunityStatsService(
|
||||||
{} as ConnectionService,
|
{} as ConnectionService,
|
||||||
cacheService,
|
cacheService,
|
||||||
{} as MatchStatsRepository,
|
matchStatsRepository,
|
||||||
{} as MatchStatsService,
|
{} as MatchStatsService,
|
||||||
);
|
);
|
||||||
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
|
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
|
||||||
jest.fn().mockResolvedValue({
|
jest.fn().mockResolvedValue({
|
||||||
|
community: {},
|
||||||
season: {
|
season: {
|
||||||
id: 'all',
|
id: 'all',
|
||||||
label: '전체',
|
label: '전체',
|
||||||
startTime: null,
|
startedAt: null,
|
||||||
endTime: null,
|
endedAt: null,
|
||||||
},
|
},
|
||||||
matches: [],
|
from: null,
|
||||||
records: [participant],
|
to: null,
|
||||||
detailsByMatchId: new Map(),
|
|
||||||
});
|
});
|
||||||
|
const buildBaseDataset = jest.spyOn(
|
||||||
|
service as unknown as { buildBaseDataset: jest.Mock },
|
||||||
|
'buildBaseDataset',
|
||||||
|
);
|
||||||
|
|
||||||
const response = await service.getUserInternalHistory({
|
const response = await service.getUserInternalHistory({
|
||||||
communityId,
|
communityId,
|
||||||
@@ -236,9 +248,85 @@ describe('CommunityStatsService', () => {
|
|||||||
gameNumber: 2,
|
gameNumber: 2,
|
||||||
queueLabel: '내전',
|
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(cacheService.set).toHaveBeenCalledWith(
|
||||||
expect.stringContaining(`userInternal:v2:${userId.toString()}`),
|
expect.stringContaining(`userInternal:v3:${userId.toString()}`),
|
||||||
response,
|
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,
|
TeamInsightsResponse,
|
||||||
UserInternalHistoryResponse,
|
UserInternalHistoryResponse,
|
||||||
} from './community-stats.types';
|
} 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 { MatchStatsService } from './match-stats.service';
|
||||||
import {
|
import {
|
||||||
InternalGameDetail,
|
InternalGameDetail,
|
||||||
@@ -55,6 +59,10 @@ interface BaseDataset {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommunityStatsService {
|
export class CommunityStatsService {
|
||||||
private readonly logger = new Logger(CommunityStatsService.name);
|
private readonly logger = new Logger(CommunityStatsService.name);
|
||||||
|
private readonly userInternalHistoryInFlight = new Map<
|
||||||
|
string,
|
||||||
|
Promise<UserInternalHistoryResponse>
|
||||||
|
>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
@@ -293,7 +301,7 @@ export class CommunityStatsService {
|
|||||||
filters: CommunityStatsFilters;
|
filters: CommunityStatsFilters;
|
||||||
}): Promise<UserInternalHistoryResponse> {
|
}): Promise<UserInternalHistoryResponse> {
|
||||||
const key = this.cacheKey(
|
const key = this.cacheKey(
|
||||||
`userInternal:v2:${params.userId.toString()}`,
|
`userInternal:v3:${params.userId.toString()}`,
|
||||||
params.communityId,
|
params.communityId,
|
||||||
params.filters,
|
params.filters,
|
||||||
);
|
);
|
||||||
@@ -301,38 +309,20 @@ export class CommunityStatsService {
|
|||||||
await this.cacheService.get<UserInternalHistoryResponse>(key);
|
await this.cacheService.get<UserInternalHistoryResponse>(key);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
|
|
||||||
const dataset = await this.buildBaseDataset(
|
// Auction viewers can all request the same next player's internal history
|
||||||
params.communityId,
|
// at once. Coalesce local cache misses so one player change does one DB read.
|
||||||
params.filters,
|
const inFlight = this.userInternalHistoryInFlight.get(key);
|
||||||
);
|
if (inFlight) return inFlight;
|
||||||
const allUserRecords = dataset.records
|
|
||||||
.filter((record) => record.userId === params.userId.toString())
|
const promise = this.buildUserInternalHistoryResponse(params, key);
|
||||||
.sort((left, right) => right.gameCreation - left.gameCreation);
|
this.userInternalHistoryInFlight.set(key, promise);
|
||||||
const records = this.applyChampionFilter(allUserRecords, params.filters);
|
try {
|
||||||
const limit = this.clampLimit(params.filters.limit, 30, 50);
|
return await promise;
|
||||||
const cursor = params.filters.cursor;
|
} finally {
|
||||||
const page = records
|
if (this.userInternalHistoryInFlight.get(key) === promise) {
|
||||||
.filter((record) => !cursor || record.gameCreation < cursor)
|
this.userInternalHistoryInFlight.delete(key);
|
||||||
.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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public invalidateCommunity(
|
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(
|
private async rebuildMissingOrStaleFragments(
|
||||||
communityId: mongoose.Types.ObjectId,
|
communityId: mongoose.Types.ObjectId,
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
|
|||||||
@@ -3,6 +3,16 @@ import mongoose from 'mongoose';
|
|||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||||
|
|
||||||
|
export type MatchStatsUserRecordFragment = Pick<
|
||||||
|
MatchStats,
|
||||||
|
'matchId' | 'records'
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type MatchStatsDetailFragment = Pick<
|
||||||
|
MatchStats,
|
||||||
|
'matchId' | 'gameDetails'
|
||||||
|
>;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MatchStatsRepository {
|
export class MatchStatsRepository {
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
@@ -68,6 +78,53 @@ export class MatchStatsRepository {
|
|||||||
toGameCreation?: number;
|
toGameCreation?: number;
|
||||||
}): Promise<MatchStatsDocument[]> {
|
}): Promise<MatchStatsDocument[]> {
|
||||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
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> = {
|
const filter: Record<string, unknown> = {
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
userIds: params.userId,
|
userIds: params.userId,
|
||||||
@@ -78,7 +135,6 @@ export class MatchStatsRepository {
|
|||||||
if (params.toGameCreation !== undefined) {
|
if (params.toGameCreation !== undefined) {
|
||||||
filter.gameCreationMin = { $lte: params.toGameCreation };
|
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||||
}
|
}
|
||||||
|
return filter;
|
||||||
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,10 +4,13 @@ import {
|
|||||||
OnModuleDestroy,
|
OnModuleDestroy,
|
||||||
OnModuleInit,
|
OnModuleInit,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import { DakaoOutboxService } from './dakao-outbox.service';
|
import { DakaoOutboxService } from './dakao-outbox.service';
|
||||||
|
|
||||||
const SWEEP_INTERVAL_MS = 60 * 1000;
|
const SWEEP_INTERVAL_MS = 60 * 1000;
|
||||||
const STALE_OUTBOX_MS = 5 * 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()
|
@Injectable()
|
||||||
export class DakaoOutboxSweeperService
|
export class DakaoOutboxSweeperService
|
||||||
@@ -16,7 +19,10 @@ export class DakaoOutboxSweeperService
|
|||||||
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
|
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
|
||||||
private timer: NodeJS.Timeout | undefined;
|
private timer: NodeJS.Timeout | undefined;
|
||||||
|
|
||||||
constructor(private readonly outboxService: DakaoOutboxService) {}
|
constructor(
|
||||||
|
private readonly outboxService: DakaoOutboxService,
|
||||||
|
private readonly distributedLockService: DistributedLockService,
|
||||||
|
) {}
|
||||||
|
|
||||||
onModuleInit() {
|
onModuleInit() {
|
||||||
this.timer = setInterval(() => {
|
this.timer = setInterval(() => {
|
||||||
@@ -31,12 +37,23 @@ export class DakaoOutboxSweeperService
|
|||||||
|
|
||||||
private async sweep(): Promise<void> {
|
private async sweep(): Promise<void> {
|
||||||
try {
|
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,
|
staleMs: STALE_OUTBOX_MS,
|
||||||
limit: 20,
|
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) {
|
} catch (err) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
|
|||||||
@@ -70,8 +70,7 @@ describe('DakaoOutboxService', () => {
|
|||||||
process.env.NODE_ENV = 'staging';
|
process.env.NODE_ENV = 'staging';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const exec = jest.fn().mockResolvedValue([
|
const staleRow = {
|
||||||
{
|
|
||||||
eventId: 'lolympus:chat.send-message:chat-log-1',
|
eventId: 'lolympus:chat.send-message:chat-log-1',
|
||||||
type: 'chat.send-message',
|
type: 'chat.send-message',
|
||||||
eventSource: 'lolympus',
|
eventSource: 'lolympus',
|
||||||
@@ -81,33 +80,45 @@ describe('DakaoOutboxService', () => {
|
|||||||
chatroomId: '18474390111480678',
|
chatroomId: '18474390111480678',
|
||||||
segments: [{ kind: 'text', text: 'done' }],
|
segments: [{ kind: 'text', text: 'done' }],
|
||||||
},
|
},
|
||||||
},
|
};
|
||||||
]);
|
const exec = jest.fn().mockResolvedValue([staleRow]);
|
||||||
const lean = jest.fn().mockReturnValue({ exec });
|
const lean = jest.fn().mockReturnValue({ exec });
|
||||||
const limit = jest.fn().mockReturnValue({ lean });
|
const limit = jest.fn().mockReturnValue({ lean });
|
||||||
const sort = jest.fn().mockReturnValue({ limit });
|
const sort = jest.fn().mockReturnValue({ limit });
|
||||||
|
const claimExec = jest.fn().mockResolvedValue(staleRow);
|
||||||
|
const claimLean = jest.fn().mockReturnValue({ exec: claimExec });
|
||||||
const outboxModel = {
|
const outboxModel = {
|
||||||
find: jest.fn().mockReturnValue({ sort }),
|
find: jest.fn().mockReturnValue({ sort }),
|
||||||
|
findOneAndUpdate: jest.fn().mockReturnValue({ lean: claimLean }),
|
||||||
|
updateOne: jest.fn().mockReturnValue(execResult({ modifiedCount: 1 })),
|
||||||
};
|
};
|
||||||
const { service } = makeService(outboxModel);
|
const { service, natsService } = makeService(outboxModel);
|
||||||
const enqueue = jest
|
|
||||||
.spyOn(service, 'enqueueAndPublish')
|
|
||||||
.mockResolvedValue(undefined);
|
|
||||||
|
|
||||||
await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe(
|
await expect(service.sweepStale({ staleMs: 1, limit: 1 })).resolves.toBe(
|
||||||
1,
|
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({
|
expect.objectContaining({
|
||||||
envelope: expect.objectContaining({
|
|
||||||
resultSubjects: {
|
resultSubjects: {
|
||||||
succeeded:
|
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||||
'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
|
||||||
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
}),
|
{ messageId: 'lolympus:chat.send-message:chat-log-1' },
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
process.env.NODE_ENV = previousNodeEnv;
|
process.env.NODE_ENV = previousNodeEnv;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import { NatsService } from '../global/nats/nats.service';
|
import { NatsService } from '../global/nats/nats.service';
|
||||||
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
import { resolveDakaoNatsNames } from './dakao.nats-names';
|
||||||
@@ -10,6 +11,7 @@ import {
|
|||||||
|
|
||||||
const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message';
|
const CHAT_SEND_MESSAGE_TYPE = 'chat.send-message';
|
||||||
const TERMINAL_STATES = ['sent', 'failed'] as const;
|
const TERMINAL_STATES = ['sent', 'failed'] as const;
|
||||||
|
const DEFAULT_PUBLISH_LEASE_DURATION_MILLISECONDS = 60_000;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DakaoOutboxService {
|
export class DakaoOutboxService {
|
||||||
@@ -50,35 +52,59 @@ export class DakaoOutboxService {
|
|||||||
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
||||||
).exec();
|
).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 {
|
try {
|
||||||
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
await this.natsService.publishJetStream(params.subject, params.envelope, {
|
||||||
messageId: params.eventId,
|
messageId: params.eventId,
|
||||||
});
|
});
|
||||||
await OutboxModel.updateOne(
|
await OutboxModel.updateOne(
|
||||||
{
|
updateFilter,
|
||||||
eventId: params.eventId,
|
|
||||||
state: { $nin: TERMINAL_STATES },
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
state: 'published',
|
state: 'published',
|
||||||
publishedAt: new Date(),
|
publishedAt: new Date(),
|
||||||
},
|
},
|
||||||
$inc: { publishAttempts: 1 },
|
$inc: { publishAttempts: 1 },
|
||||||
$unset: { lastPublishError: '' },
|
$unset: {
|
||||||
|
lastPublishError: '',
|
||||||
|
publishLeaseOwnerIdentifier: '',
|
||||||
|
publishLeaseExpiresAt: '',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
).exec();
|
).exec();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await OutboxModel.updateOne(
|
await OutboxModel.updateOne(
|
||||||
{
|
updateFilter,
|
||||||
eventId: params.eventId,
|
|
||||||
state: { $nin: TERMINAL_STATES },
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
$inc: { publishAttempts: 1 },
|
$inc: { publishAttempts: 1 },
|
||||||
$set: {
|
$set: {
|
||||||
lastPublishError: (err as Error)?.message ?? String(err),
|
lastPublishError: (err as Error)?.message ?? String(err),
|
||||||
},
|
},
|
||||||
|
$unset: {
|
||||||
|
publishLeaseOwnerIdentifier: '',
|
||||||
|
publishLeaseExpiresAt: '',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
).exec();
|
).exec();
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
@@ -146,40 +172,77 @@ export class DakaoOutboxService {
|
|||||||
|
|
||||||
public async sweepStale(params?: {
|
public async sweepStale(params?: {
|
||||||
staleMs?: number;
|
staleMs?: number;
|
||||||
|
publishLeaseDurationMilliseconds?: number;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
}): Promise<number> {
|
}): Promise<number> {
|
||||||
const OutboxModel =
|
const OutboxModel =
|
||||||
await this.connectionService.getModel('dakaoOutboxMessage');
|
await this.connectionService.getModel('dakaoOutboxMessage');
|
||||||
|
const currentTimestamp = new Date();
|
||||||
const staleBefore = 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({
|
const rows = await OutboxModel.find({
|
||||||
state: { $in: ['pending', 'published'] },
|
state: { $in: ['pending', 'published'] },
|
||||||
updatedAt: { $lte: staleBefore },
|
updatedAt: { $lte: staleBefore },
|
||||||
|
$or: [
|
||||||
|
{ publishLeaseExpiresAt: { $exists: false } },
|
||||||
|
{ publishLeaseExpiresAt: { $lte: currentTimestamp } },
|
||||||
|
],
|
||||||
})
|
})
|
||||||
.sort({ updatedAt: 1 })
|
.sort({ updatedAt: 1 })
|
||||||
.limit(params?.limit ?? 20)
|
.limit(params?.limit ?? 20)
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
|
|
||||||
|
let swept = 0;
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
await this.enqueueAndPublish({
|
const claimedRow = await OutboxModel.findOneAndUpdate(
|
||||||
subject: row.subject,
|
{
|
||||||
eventId: row.eventId,
|
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: {
|
envelope: {
|
||||||
schema: 'dakao.command.v1',
|
schema: 'dakao.command.v1',
|
||||||
eventId: row.eventId,
|
eventId: claimedRow.eventId,
|
||||||
type: row.type,
|
type: claimedRow.type,
|
||||||
eventSource: row.eventSource,
|
eventSource: claimedRow.eventSource,
|
||||||
correlationId: row.correlationId,
|
correlationId: claimedRow.correlationId,
|
||||||
resultSubjects:
|
resultSubjects:
|
||||||
row.resultSubjects ?? this.resolveDefaultResultSubjects(row.type),
|
claimedRow.resultSubjects ??
|
||||||
payload: row.payload,
|
this.resolveDefaultResultSubjects(claimedRow.type),
|
||||||
|
payload: claimedRow.payload,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
swept += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
return rows.length;
|
return swept;
|
||||||
}
|
}
|
||||||
|
|
||||||
private resolveDefaultResultSubjects(
|
private resolveDefaultResultSubjects(
|
||||||
|
|||||||
@@ -56,20 +56,20 @@ describe('DakaoSubscriber', () => {
|
|||||||
|
|
||||||
expect(segments).toEqual([
|
expect(segments).toEqual([
|
||||||
{ kind: 'mention', userId: '12345', displayText: '프리리' },
|
{ kind: 'mention', userId: '12345', displayText: '프리리' },
|
||||||
{ kind: 'text', text: ' 사용법\n' },
|
{ kind: 'text', text: ' 내전 명령어 사용법\n' },
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{ kind: 'text', text: ' !내전 일정\n' },
|
{ kind: 'text', text: ' !내전 일정\u3000\n' },
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
kind: 'text',
|
kind: 'text',
|
||||||
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\n',
|
text: ' !내전 신청 코드 소환사이름#태그 포지션1,포지션2\u3000\n',
|
||||||
},
|
},
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\n' },
|
{ kind: 'text', text: ' !내전 계정등록 소환사이름#태그\u3000\n' },
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
kind: 'text',
|
kind: 'text',
|
||||||
text: ' !내전 선호포지션등록 포지션1,포지션2\n',
|
text: ' !내전 선호포지션등록 포지션1,포지션2\u3000\n',
|
||||||
},
|
},
|
||||||
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import {
|
||||||
|
buildDoubleEliminationBracket,
|
||||||
|
cancelDoubleEliminationBracketMatch,
|
||||||
|
completeDoubleEliminationBracketMatch,
|
||||||
|
reshuffleDoubleEliminationSeeds,
|
||||||
|
swapDoubleEliminationSeeds,
|
||||||
|
} from './double-elimination.util';
|
||||||
|
|
||||||
|
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('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,672 @@
|
|||||||
|
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;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
: buildEightTeamBracketMatches(),
|
||||||
|
placements: {},
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'bracket-created',
|
||||||
|
createdAt: new Date(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
applySeedTeams(bracket);
|
||||||
|
refreshBracketMatchStates(bracket);
|
||||||
|
return bracket;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
bracket.bracketMatches.push({
|
||||||
|
bracketMatchId: 'GF_RESET',
|
||||||
|
gameNumber: nextGameNumber(bracket),
|
||||||
|
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(): DoubleEliminationBracketMatch[] {
|
||||||
|
return [
|
||||||
|
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
|
||||||
|
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, {
|
||||||
|
teamASource: seedSource(2),
|
||||||
|
teamBSource: seedSource(3),
|
||||||
|
winnerAdvancesTo: destination('WB_FINAL', 'B'),
|
||||||
|
loserAdvancesTo: destination('LB_R1_M1', 'B'),
|
||||||
|
}),
|
||||||
|
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, {
|
||||||
|
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, {
|
||||||
|
teamASource: loserSource('WB_R1_M1'),
|
||||||
|
teamBSource: loserSource('WB_R1_M2'),
|
||||||
|
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||||
|
}),
|
||||||
|
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, {
|
||||||
|
teamASource: winnerSource('LB_R1_M1'),
|
||||||
|
teamBSource: loserSource('WB_FINAL'),
|
||||||
|
winnerAdvancesTo: destination('GF', 'B'),
|
||||||
|
}),
|
||||||
|
bracketMatch('GF', 6, 'grand-final', 1, 1, {
|
||||||
|
teamASource: winnerSource('WB_FINAL'),
|
||||||
|
teamBSource: winnerSource('LB_FINAL'),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEightTeamBracketMatches(): DoubleEliminationBracketMatch[] {
|
||||||
|
return [
|
||||||
|
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
|
||||||
|
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, {
|
||||||
|
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, {
|
||||||
|
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, {
|
||||||
|
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, {
|
||||||
|
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, {
|
||||||
|
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, {
|
||||||
|
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, {
|
||||||
|
teamASource: loserSource('WB_R1_M1'),
|
||||||
|
teamBSource: loserSource('WB_R1_M2'),
|
||||||
|
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
|
||||||
|
}),
|
||||||
|
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, {
|
||||||
|
teamASource: loserSource('WB_R1_M3'),
|
||||||
|
teamBSource: loserSource('WB_R1_M4'),
|
||||||
|
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
|
||||||
|
}),
|
||||||
|
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, {
|
||||||
|
teamASource: winnerSource('LB_R1_M1'),
|
||||||
|
teamBSource: loserSource('WB_R2_M2'),
|
||||||
|
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
|
||||||
|
}),
|
||||||
|
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, {
|
||||||
|
teamASource: winnerSource('LB_R1_M2'),
|
||||||
|
teamBSource: loserSource('WB_R2_M1'),
|
||||||
|
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
|
||||||
|
}),
|
||||||
|
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, {
|
||||||
|
teamASource: winnerSource('LB_R2_M1'),
|
||||||
|
teamBSource: winnerSource('LB_R2_M2'),
|
||||||
|
winnerAdvancesTo: destination('LB_FINAL', 'A'),
|
||||||
|
}),
|
||||||
|
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, {
|
||||||
|
teamASource: winnerSource('LB_R3_M1'),
|
||||||
|
teamBSource: loserSource('WB_FINAL'),
|
||||||
|
winnerAdvancesTo: destination('GF', 'B'),
|
||||||
|
}),
|
||||||
|
bracketMatch('GF', 14, 'grand-final', 1, 1, {
|
||||||
|
teamASource: winnerSource('WB_FINAL'),
|
||||||
|
teamBSource: winnerSource('LB_FINAL'),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
function bracketMatch(
|
||||||
|
bracketMatchId: string,
|
||||||
|
gameNumber: number,
|
||||||
|
bracketSide: DoubleEliminationBracketSide,
|
||||||
|
roundNumber: number,
|
||||||
|
matchNumber: number,
|
||||||
|
params: Partial<DoubleEliminationBracketMatch>,
|
||||||
|
): DoubleEliminationBracketMatch {
|
||||||
|
return {
|
||||||
|
bracketMatchId,
|
||||||
|
gameNumber,
|
||||||
|
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.');
|
||||||
|
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 cloneBracket(
|
||||||
|
bracket: DoubleEliminationBracket,
|
||||||
|
): DoubleEliminationBracket {
|
||||||
|
return {
|
||||||
|
...bracket,
|
||||||
|
seeds: bracket.seeds.map((seed) => ({ ...seed })),
|
||||||
|
bracketMatches: bracket.bracketMatches.map((match) => ({
|
||||||
|
...match,
|
||||||
|
teamASource: match.teamASource ? { ...match.teamASource } : undefined,
|
||||||
|
teamBSource: match.teamBSource ? { ...match.teamBSource } : undefined,
|
||||||
|
winnerAdvancesTo: match.winnerAdvancesTo
|
||||||
|
? { ...match.winnerAdvancesTo }
|
||||||
|
: undefined,
|
||||||
|
loserAdvancesTo: match.loserAdvancesTo
|
||||||
|
? { ...match.loserAdvancesTo }
|
||||||
|
: undefined,
|
||||||
|
walkover: match.walkover ? { ...match.walkover } : undefined,
|
||||||
|
})),
|
||||||
|
placements: { ...bracket.placements },
|
||||||
|
events: bracket.events.map((event) => ({ ...event })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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', () => {
|
describe('resolveMongoDbName', () => {
|
||||||
it('uses production database only for prod', () => {
|
it('uses production database only for prod', () => {
|
||||||
@@ -12,3 +16,47 @@ describe('resolveMongoDbName', () => {
|
|||||||
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
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 mongoose from 'mongoose';
|
||||||
|
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin';
|
||||||
import { SecretService } from '../secret/secret.service';
|
import { SecretService } from '../secret/secret.service';
|
||||||
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
import { tournamentModelDefinitions, TournamentModelTypes } from './schema';
|
||||||
|
|
||||||
@@ -9,15 +10,44 @@ export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
|
|||||||
return 'lolympus-dev';
|
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 })
|
@Injectable({ scope: Scope.DEFAULT })
|
||||||
export class ConnectionService implements OnModuleInit {
|
export class ConnectionService implements OnModuleInit {
|
||||||
|
private readonly logger = new Logger(ConnectionService.name);
|
||||||
private connection: mongoose.Connection | null = null;
|
private connection: mongoose.Connection | null = null;
|
||||||
constructor(private readonly secretService: SecretService) {}
|
constructor(private readonly secretService: SecretService) {}
|
||||||
|
|
||||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
||||||
|
|
||||||
public async getConnection(): Promise<mongoose.Connection> {
|
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;
|
return this.connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,15 +55,17 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
'MONGODB_CONNECTION_STRING',
|
'MONGODB_CONNECTION_STRING',
|
||||||
);
|
);
|
||||||
const dbName = resolveMongoDbName();
|
const dbName = resolveMongoDbName();
|
||||||
|
const appName = resolveMongoAppName();
|
||||||
|
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
|
||||||
const defaultConnection = await mongoose
|
const defaultConnection = await mongoose
|
||||||
.createConnection(connectionString, {
|
.createConnection(connectionString, connectionOptions)
|
||||||
dbName,
|
|
||||||
minPoolSize: 10,
|
|
||||||
maxPoolSize: 20,
|
|
||||||
})
|
|
||||||
.asPromise();
|
.asPromise();
|
||||||
this.connection = defaultConnection;
|
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;
|
return this.connection;
|
||||||
}
|
}
|
||||||
@@ -50,6 +82,7 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
const connection = await this.getConnection();
|
const connection = await this.getConnection();
|
||||||
|
|
||||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||||
|
applyMongoosePerformancePlugin(modelDefinition.schema);
|
||||||
// 이미 생성된 경우 컴파일 스킵.
|
// 이미 생성된 경우 컴파일 스킵.
|
||||||
if (
|
if (
|
||||||
Object.prototype.hasOwnProperty.call(
|
Object.prototype.hasOwnProperty.call(
|
||||||
@@ -86,15 +119,24 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
const session = await connection.startSession(options);
|
const session = await connection.startSession(options);
|
||||||
return session as unknown as mongoose.ClientSession;
|
return session as unknown as mongoose.ClientSession;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
this.logError('Failed to start MongoDB session', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async onModuleInit() {
|
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() {
|
public async onModuleDestroy() {
|
||||||
await this.connection?.close();
|
await this.connection?.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private logError(message: string, error: unknown): void {
|
||||||
|
this.logger.error(
|
||||||
|
`${message}: ${error instanceof Error ? error.message : String(error)}`,
|
||||||
|
error instanceof Error ? error.stack : undefined,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+572
@@ -0,0 +1,572 @@
|
|||||||
|
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',
|
||||||
|
unique: true,
|
||||||
|
}),
|
||||||
|
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',
|
||||||
|
unique: true,
|
||||||
|
}),
|
||||||
|
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('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']);
|
||||||
|
});
|
||||||
|
});
|
||||||
+757
@@ -0,0 +1,757 @@
|
|||||||
|
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',
|
||||||
|
unique: true,
|
||||||
|
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, 'bracketMatchId'),
|
||||||
|
...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);
|
||||||
|
}
|
||||||
+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 type TeamSide = 'blue' | 'red';
|
||||||
export const TEAM_SIDES: 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[] = [
|
export const MATCH_GAME_MODES: MatchGameMode[] = [
|
||||||
'pair',
|
'pair',
|
||||||
'bracket',
|
'bracket',
|
||||||
'round-robin',
|
'round-robin',
|
||||||
|
'double-elimination',
|
||||||
];
|
];
|
||||||
|
|
||||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||||
@@ -47,13 +52,15 @@ export type TournamentCodeState =
|
|||||||
| 'reserved'
|
| 'reserved'
|
||||||
| 'used'
|
| 'used'
|
||||||
| 'expired'
|
| 'expired'
|
||||||
| 'released';
|
| 'released'
|
||||||
|
| 'voided';
|
||||||
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
|
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
|
||||||
'available',
|
'available',
|
||||||
'reserved',
|
'reserved',
|
||||||
'used',
|
'used',
|
||||||
'expired',
|
'expired',
|
||||||
'released',
|
'released',
|
||||||
|
'voided',
|
||||||
];
|
];
|
||||||
export type TournamentMapType = 'SUMMONERS_RIFT';
|
export type TournamentMapType = 'SUMMONERS_RIFT';
|
||||||
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
|
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
|
||||||
@@ -385,6 +392,8 @@ export interface DakaoOutboxMessage extends MongooseTimestamps {
|
|||||||
payload: Record<string, unknown>;
|
payload: Record<string, unknown>;
|
||||||
state: DakaoOutboxMessageState;
|
state: DakaoOutboxMessageState;
|
||||||
publishAttempts: number;
|
publishAttempts: number;
|
||||||
|
publishLeaseOwnerIdentifier?: string;
|
||||||
|
publishLeaseExpiresAt?: Date;
|
||||||
publishedAt?: Date;
|
publishedAt?: Date;
|
||||||
terminalAt?: Date;
|
terminalAt?: Date;
|
||||||
resultEventId?: string;
|
resultEventId?: string;
|
||||||
@@ -445,6 +454,7 @@ export interface TournamentCode extends MongooseTimestamps {
|
|||||||
state: TournamentCodeState;
|
state: TournamentCodeState;
|
||||||
matchId?: mongoose.Types.ObjectId;
|
matchId?: mongoose.Types.ObjectId;
|
||||||
gameNumber?: number;
|
gameNumber?: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
reservedAt?: Date;
|
reservedAt?: Date;
|
||||||
usedAt?: Date;
|
usedAt?: Date;
|
||||||
releasedAt?: Date;
|
releasedAt?: Date;
|
||||||
@@ -497,6 +507,7 @@ export interface MatchGameResultParticipant {
|
|||||||
|
|
||||||
export interface MatchGameResult {
|
export interface MatchGameResult {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
blueTeamIndex: number;
|
blueTeamIndex: number;
|
||||||
redTeamIndex: number;
|
redTeamIndex: number;
|
||||||
@@ -508,6 +519,7 @@ export interface MatchGameResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface MatchSeriesResult {
|
export interface MatchSeriesResult {
|
||||||
|
bracketMatchId?: string;
|
||||||
teamAIndex: number;
|
teamAIndex: number;
|
||||||
teamBIndex: number;
|
teamBIndex: number;
|
||||||
teamAWins: number;
|
teamAWins: number;
|
||||||
@@ -515,6 +527,118 @@ export interface MatchSeriesResult {
|
|||||||
winnerTeamIndex?: number;
|
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;
|
||||||
|
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 {
|
export interface MatchGameAssignment {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
@@ -564,6 +688,7 @@ export interface Match extends MongooseTimestamps {
|
|||||||
teams: MatchTeam[];
|
teams: MatchTeam[];
|
||||||
result?: MatchResult;
|
result?: MatchResult;
|
||||||
resultPollState?: MatchResultPollState;
|
resultPollState?: MatchResultPollState;
|
||||||
|
doubleElimination?: DoubleEliminationBracket;
|
||||||
legacyImported?: boolean;
|
legacyImported?: boolean;
|
||||||
legacyImportSource?: {
|
legacyImportSource?: {
|
||||||
importedAt: Date;
|
importedAt: Date;
|
||||||
@@ -610,6 +735,7 @@ export interface LegacyImportJob extends MongooseTimestamps {
|
|||||||
totalSkippedDuplicate: number;
|
totalSkippedDuplicate: number;
|
||||||
totalErrors: number;
|
totalErrors: number;
|
||||||
averageMemberSeconds?: number;
|
averageMemberSeconds?: number;
|
||||||
|
completedMemberJobIds: string[];
|
||||||
errors?: LegacyImportJobError[];
|
errors?: LegacyImportJobError[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1159,6 +1285,8 @@ export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
|
|||||||
default: 'pending',
|
default: 'pending',
|
||||||
},
|
},
|
||||||
publishAttempts: { type: Number, required: true, default: 0 },
|
publishAttempts: { type: Number, required: true, default: 0 },
|
||||||
|
publishLeaseOwnerIdentifier: { type: String },
|
||||||
|
publishLeaseExpiresAt: { type: Date },
|
||||||
publishedAt: { type: Date },
|
publishedAt: { type: Date },
|
||||||
terminalAt: { type: Date },
|
terminalAt: { type: Date },
|
||||||
resultEventId: { type: String },
|
resultEventId: { type: String },
|
||||||
@@ -1179,6 +1307,11 @@ export const DakaoOutboxMessageSchema = new Schema<DakaoOutboxMessage>(
|
|||||||
);
|
);
|
||||||
|
|
||||||
DakaoOutboxMessageSchema.index({ state: 1, updatedAt: 1 });
|
DakaoOutboxMessageSchema.index({ state: 1, updatedAt: 1 });
|
||||||
|
DakaoOutboxMessageSchema.index({
|
||||||
|
state: 1,
|
||||||
|
publishLeaseExpiresAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
});
|
||||||
DakaoOutboxMessageSchema.index({ correlationId: 1 }, { sparse: true });
|
DakaoOutboxMessageSchema.index({ correlationId: 1 }, { sparse: true });
|
||||||
|
|
||||||
export const DakaoSendResultEventSchema = new Schema<DakaoSendResultEvent>(
|
export const DakaoSendResultEventSchema = new Schema<DakaoSendResultEvent>(
|
||||||
@@ -1351,6 +1484,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
|||||||
},
|
},
|
||||||
matchId: { type: Schema.Types.ObjectId, ref: 'match' },
|
matchId: { type: Schema.Types.ObjectId, ref: 'match' },
|
||||||
gameNumber: { type: Number },
|
gameNumber: { type: Number },
|
||||||
|
bracketMatchId: { type: String },
|
||||||
reservedAt: { type: Date },
|
reservedAt: { type: Date },
|
||||||
usedAt: { type: Date },
|
usedAt: { type: Date },
|
||||||
releasedAt: { type: Date },
|
releasedAt: { type: Date },
|
||||||
@@ -1368,9 +1502,36 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
|
|||||||
|
|
||||||
TournamentCodeSchema.index({ code: 1 }, { unique: true });
|
TournamentCodeSchema.index({ code: 1 }, { unique: true });
|
||||||
TournamentCodeSchema.index({ state: 1, expiresAt: 1 });
|
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 },
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
partialFilterExpression: {
|
||||||
|
matchId: { $exists: true },
|
||||||
|
bracketMatchId: { $exists: true },
|
||||||
|
state: { $in: ['reserved', 'used'] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 });
|
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>(
|
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||||
{
|
{
|
||||||
@@ -1428,6 +1589,7 @@ const MatchGameResultParticipantSubSchema =
|
|||||||
const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||||
{
|
{
|
||||||
gameNumber: { type: Number, required: true },
|
gameNumber: { type: Number, required: true },
|
||||||
|
bracketMatchId: { type: String, required: false },
|
||||||
riotMatchId: { type: String, required: true },
|
riotMatchId: { type: String, required: true },
|
||||||
blueTeamIndex: { type: Number, required: true, min: 1 },
|
blueTeamIndex: { type: Number, required: true, min: 1 },
|
||||||
redTeamIndex: { type: Number, required: true, min: 1 },
|
redTeamIndex: { type: Number, required: true, min: 1 },
|
||||||
@@ -1446,6 +1608,7 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
|||||||
|
|
||||||
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
|
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
|
||||||
{
|
{
|
||||||
|
bracketMatchId: { type: String, required: false },
|
||||||
teamAIndex: { type: Number, required: true, min: 1 },
|
teamAIndex: { type: Number, required: true, min: 1 },
|
||||||
teamBIndex: { type: Number, required: true, min: 1 },
|
teamBIndex: { type: Number, required: true, min: 1 },
|
||||||
teamAWins: { type: Number, required: true, default: 0 },
|
teamAWins: { type: Number, required: true, default: 0 },
|
||||||
@@ -1465,6 +1628,158 @@ const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
|
|||||||
{ _id: false },
|
{ _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 },
|
||||||
|
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>(
|
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||||
{
|
{
|
||||||
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
winnerTeamIndex: { type: Number, required: false, min: 1 },
|
||||||
@@ -1595,6 +1910,10 @@ export const MatchSchema = new Schema<Match>(
|
|||||||
type: MatchResultPollStateSubSchema,
|
type: MatchResultPollStateSubSchema,
|
||||||
required: false,
|
required: false,
|
||||||
},
|
},
|
||||||
|
doubleElimination: {
|
||||||
|
type: DoubleEliminationBracketSubSchema,
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
legacyImported: { type: Boolean, required: false, default: false },
|
legacyImported: { type: Boolean, required: false, default: false },
|
||||||
legacyImportSource: {
|
legacyImportSource: {
|
||||||
type: MatchLegacyImportSourceSubSchema,
|
type: MatchLegacyImportSourceSubSchema,
|
||||||
@@ -1679,6 +1998,11 @@ export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
|
|||||||
totalSkippedDuplicate: { type: Number, required: true, default: 0 },
|
totalSkippedDuplicate: { type: Number, required: true, default: 0 },
|
||||||
totalErrors: { type: Number, required: true, default: 0 },
|
totalErrors: { type: Number, required: true, default: 0 },
|
||||||
averageMemberSeconds: { type: Number },
|
averageMemberSeconds: { type: Number },
|
||||||
|
completedMemberJobIds: {
|
||||||
|
type: [String],
|
||||||
|
required: true,
|
||||||
|
default: [],
|
||||||
|
},
|
||||||
errors: {
|
errors: {
|
||||||
type: [LegacyImportJobErrorSubSchema],
|
type: [LegacyImportJobErrorSubSchema],
|
||||||
required: true,
|
required: true,
|
||||||
@@ -1694,6 +2018,7 @@ export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
|
|||||||
|
|
||||||
LegacyImportJobSchema.index({ communityId: 1, startedAt: -1 });
|
LegacyImportJobSchema.index({ communityId: 1, startedAt: -1 });
|
||||||
LegacyImportJobSchema.index({ communityId: 1, state: 1 });
|
LegacyImportJobSchema.index({ communityId: 1, state: 1 });
|
||||||
|
LegacyImportJobSchema.index({ jobId: 1, completedMemberJobIds: 1 });
|
||||||
|
|
||||||
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
|
||||||
{
|
{
|
||||||
@@ -2088,6 +2413,7 @@ MatchStatsSchema.index({
|
|||||||
gameCreationMax: 1,
|
gameCreationMax: 1,
|
||||||
});
|
});
|
||||||
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
|
||||||
|
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
|
||||||
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
|
||||||
|
|
||||||
export const tournamentModelDefinitions: ModelDefinition[] = [
|
export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||||
|
|||||||
@@ -56,20 +56,25 @@ export interface JetStreamConsumeOptions {
|
|||||||
maxMessages?: number;
|
maxMessages?: number;
|
||||||
expiresMs?: number;
|
expiresMs?: number;
|
||||||
nakDelayMs?: number;
|
nakDelayMs?: number;
|
||||||
|
restartDelayMilliseconds?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS = 1_000;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class NatsService implements OnModuleDestroy {
|
export class NatsService implements OnModuleDestroy {
|
||||||
private readonly logger = new Logger(NatsService.name);
|
private readonly logger = new Logger(NatsService.name);
|
||||||
private readonly stringCodec = StringCodec();
|
private readonly stringCodec = StringCodec();
|
||||||
private readonly subscriptions = new Set<Subscription>();
|
private readonly subscriptions = new Set<Subscription>();
|
||||||
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
|
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
|
||||||
|
private isDestroying = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
|
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async onModuleDestroy() {
|
async onModuleDestroy() {
|
||||||
|
this.isDestroying = true;
|
||||||
for (const consumer of this.jetStreamConsumers) {
|
for (const consumer of this.jetStreamConsumers) {
|
||||||
try {
|
try {
|
||||||
await consumer.close();
|
await consumer.close();
|
||||||
@@ -199,6 +204,7 @@ export class NatsService implements OnModuleDestroy {
|
|||||||
options: JetStreamConsumeOptions,
|
options: JetStreamConsumeOptions,
|
||||||
handler: JetStreamMessageHandler<T>,
|
handler: JetStreamMessageHandler<T>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
while (!this.isDestroying) {
|
||||||
try {
|
try {
|
||||||
const consumer = await this.natsClient
|
const consumer = await this.natsClient
|
||||||
.jetstream()
|
.jetstream()
|
||||||
@@ -217,12 +223,19 @@ export class NatsService implements OnModuleDestroy {
|
|||||||
this.jetStreamConsumers.delete(messages);
|
this.jetStreamConsumers.delete(messages);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (this.isDestroying) return;
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
|
`JetStream consumer stream="${options.stream}" durable="${options.durable}" terminated: ${
|
||||||
(err as Error)?.stack ?? err
|
(err as Error)?.stack ?? err
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await this.sleep(
|
||||||
|
options.restartDelayMilliseconds ??
|
||||||
|
JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async consumeSubscription<T>(
|
private async consumeSubscription<T>(
|
||||||
@@ -313,4 +326,8 @@ export class NatsService implements OnModuleDestroy {
|
|||||||
? RetentionPolicy.Workqueue
|
? RetentionPolicy.Workqueue
|
||||||
: RetentionPolicy.Limits;
|
: 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;
|
||||||
|
}
|
||||||
@@ -11,6 +11,10 @@ interface NewRelicCustomEventApi {
|
|||||||
eventType: string,
|
eventType: string,
|
||||||
attributes: Record<string, NewRelicAttributeValue>,
|
attributes: Record<string, NewRelicAttributeValue>,
|
||||||
): void;
|
): void;
|
||||||
|
addCustomAttributes(
|
||||||
|
attributes: Record<string, NewRelicAttributeValue>,
|
||||||
|
): void;
|
||||||
|
setTransactionName(name: string): void;
|
||||||
}
|
}
|
||||||
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
|
||||||
|
|
||||||
@@ -37,3 +41,25 @@ export function recordNewRelicCustomEvent(
|
|||||||
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
|
// 관측성 실패가 비즈니스 로직을 막아선 안 된다.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 { SecretService } from '../secret/secret.service';
|
||||||
import { REDIS_CLIENT } from './redis.constants';
|
import { REDIS_CLIENT } from './redis.constants';
|
||||||
import { resolveRedisClientOptions } from './redis.config';
|
import { resolveRedisClientOptions } from './redis.config';
|
||||||
|
import { DistributedLockService } from './distributed-lock.service';
|
||||||
import { RedisService, type RedisClient } from './redis.service';
|
import { RedisService, type RedisClient } from './redis.service';
|
||||||
|
|
||||||
async function readFirstSecret(
|
async function readFirstSecret(
|
||||||
@@ -62,7 +63,8 @@ async function readFirstSecret(
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
RedisService,
|
RedisService,
|
||||||
|
DistributedLockService,
|
||||||
],
|
],
|
||||||
exports: [RedisService, REDIS_CLIENT],
|
exports: [RedisService, DistributedLockService, REDIS_CLIENT],
|
||||||
})
|
})
|
||||||
export class RedisModule {}
|
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;
|
name: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ClaimStalePendingStreamMessagesResult {
|
||||||
|
messages: StreamEntry[];
|
||||||
|
nextStartId: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface RawStreamMessage {
|
interface RawStreamMessage {
|
||||||
deliveriesCounter?: number;
|
deliveriesCounter?: number;
|
||||||
id: string;
|
id: string;
|
||||||
@@ -29,6 +34,16 @@ interface RawStreamReadResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function normalizeStreamFields(fields: unknown): Record<string, string> {
|
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) {
|
if (fields instanceof Map) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
[...fields.entries()].map(([key, value]) => [String(key), String(value)]),
|
[...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(
|
public async acknowledgeStream(
|
||||||
key: string,
|
key: string,
|
||||||
group: string,
|
group: string,
|
||||||
@@ -210,4 +257,37 @@ export class RedisService implements OnModuleDestroy {
|
|||||||
public async publish(channel: string, message: string): Promise<number> {
|
public async publish(channel: string, message: string): Promise<number> {
|
||||||
return this.client.publish(channel, message);
|
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 { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import {
|
||||||
|
type DistributedLockOwnership,
|
||||||
|
DistributedLockService,
|
||||||
|
} from '../global/redis/distributed-lock.service';
|
||||||
import type {
|
import type {
|
||||||
LegacyImportJobDocument,
|
LegacyImportJobDocument,
|
||||||
Match,
|
Match,
|
||||||
@@ -57,6 +61,7 @@ export class LegacyImportService {
|
|||||||
private readonly riotMatchService: RiotMatchService,
|
private readonly riotMatchService: RiotMatchService,
|
||||||
private readonly communityStatsService: CommunityStatsService,
|
private readonly communityStatsService: CommunityStatsService,
|
||||||
private readonly matchStatsService: MatchStatsService,
|
private readonly matchStatsService: MatchStatsService,
|
||||||
|
private readonly distributedLockService: DistributedLockService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async previewMembers(params: {
|
public async previewMembers(params: {
|
||||||
@@ -80,12 +85,14 @@ export class LegacyImportService {
|
|||||||
}): Promise<StartLegacyImportResponse> {
|
}): Promise<StartLegacyImportResponse> {
|
||||||
const lockKey = this.communityLockKey(params.communityId);
|
const lockKey = this.communityLockKey(params.communityId);
|
||||||
const jobId = randomUUID();
|
const jobId = randomUUID();
|
||||||
const acquired = await this.redisService.setStringIfAbsent(
|
const communityImportLockOwnership =
|
||||||
|
await this.distributedLockService.acquireLock({
|
||||||
lockKey,
|
lockKey,
|
||||||
jobId,
|
lockOwnershipToken: jobId,
|
||||||
LEGACY_IMPORT_LOCK_TTL_SECONDS,
|
lockExpirationDurationMilliseconds:
|
||||||
);
|
LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||||
if (!acquired) {
|
});
|
||||||
|
if (!communityImportLockOwnership) {
|
||||||
throw new ConflictException('Legacy import is already running.');
|
throw new ConflictException('Legacy import is already running.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,6 +140,7 @@ export class LegacyImportService {
|
|||||||
totalSkippedDuplicate: 0,
|
totalSkippedDuplicate: 0,
|
||||||
totalErrors: 0,
|
totalErrors: 0,
|
||||||
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||||
|
completedMemberJobIds: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const window of windows) {
|
for (const window of windows) {
|
||||||
@@ -160,7 +168,7 @@ export class LegacyImportService {
|
|||||||
{ jobId },
|
{ jobId },
|
||||||
{ $set: { state: 'completed', completedAt: new Date() } },
|
{ $set: { state: 'completed', completedAt: new Date() } },
|
||||||
).exec();
|
).exec();
|
||||||
await this.redisService.delete(lockKey);
|
await this.releaseDistributedLockSafely(communityImportLockOwnership);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -169,7 +177,7 @@ export class LegacyImportService {
|
|||||||
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await this.redisService.delete(lockKey);
|
await this.releaseDistributedLockSafely(communityImportLockOwnership);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -220,7 +228,11 @@ export class LegacyImportService {
|
|||||||
).exec();
|
).exec();
|
||||||
if (!job)
|
if (!job)
|
||||||
throw new NotFoundException('Running legacy import job not found.');
|
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;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,6 +240,7 @@ export class LegacyImportService {
|
|||||||
const started = Date.now();
|
const started = Date.now();
|
||||||
const legacyJob = await this.getRunnableJob(job);
|
const legacyJob = await this.getRunnableJob(job);
|
||||||
if (!legacyJob) return;
|
if (!legacyJob) return;
|
||||||
|
if (legacyJob.completedMemberJobIds?.includes(job.jobId)) return;
|
||||||
|
|
||||||
let discovered = 0;
|
let discovered = 0;
|
||||||
let imported = 0;
|
let imported = 0;
|
||||||
@@ -500,14 +513,14 @@ export class LegacyImportService {
|
|||||||
userByPuuid: UserByPuuidMap,
|
userByPuuid: UserByPuuidMap,
|
||||||
): Promise<ImportOutcome> {
|
): Promise<ImportOutcome> {
|
||||||
const lockKey = `legacy-import:match:${riotMatchId}`;
|
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 {
|
try {
|
||||||
|
const importOutcome = await this.distributedLockService.runWithLock(
|
||||||
|
{
|
||||||
|
lockKey,
|
||||||
|
lockExpirationDurationMilliseconds:
|
||||||
|
MATCH_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||||
|
},
|
||||||
|
async () => {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const existing = await MatchModel.exists({
|
const existing = await MatchModel.exists({
|
||||||
'result.games.riotMatchId': riotMatchId,
|
'result.games.riotMatchId': riotMatchId,
|
||||||
@@ -523,7 +536,9 @@ export class LegacyImportService {
|
|||||||
if (counts.total === 0) return 'skipped';
|
if (counts.total === 0) return 'skipped';
|
||||||
|
|
||||||
const gameResult = buildGameResult(detail, userByPuuid, 1);
|
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 winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||||
const matchPayload: Partial<Match> = {
|
const matchPayload: Partial<Match> = {
|
||||||
@@ -569,6 +584,10 @@ export class LegacyImportService {
|
|||||||
const match = await MatchModel.create(matchPayload);
|
const match = await MatchModel.create(matchPayload);
|
||||||
await this.matchStatsService.buildAndUpsert(match._id);
|
await this.matchStatsService.buildAndUpsert(match._id);
|
||||||
return 'imported';
|
return 'imported';
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (importOutcome === null) return 'duplicate';
|
||||||
|
return importOutcome;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await this.recordError(job.parentJobId, {
|
await this.recordError(job.parentJobId, {
|
||||||
puuid: job.puuid,
|
puuid: job.puuid,
|
||||||
@@ -576,8 +595,6 @@ export class LegacyImportService {
|
|||||||
reason: error instanceof Error ? error.message : String(error),
|
reason: error instanceof Error ? error.message : String(error),
|
||||||
});
|
});
|
||||||
return 'error';
|
return 'error';
|
||||||
} finally {
|
|
||||||
await this.redisService.delete(lockKey);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -626,6 +643,7 @@ export class LegacyImportService {
|
|||||||
jobId: job.parentJobId,
|
jobId: job.parentJobId,
|
||||||
}).exec();
|
}).exec();
|
||||||
if (!current || current.state === 'cancelled') return;
|
if (!current || current.state === 'cancelled') return;
|
||||||
|
if (current.completedMemberJobIds?.includes(job.jobId)) return;
|
||||||
|
|
||||||
const average =
|
const average =
|
||||||
current.averageMemberSeconds === undefined
|
current.averageMemberSeconds === undefined
|
||||||
@@ -634,14 +652,14 @@ export class LegacyImportService {
|
|||||||
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
|
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
|
||||||
);
|
);
|
||||||
|
|
||||||
const nextProcessed = current.processedMembers + 1;
|
const updateResult = await LegacyImportJobModel.updateOne(
|
||||||
const completed = nextProcessed >= current.totalMembers;
|
{
|
||||||
await LegacyImportJobModel.updateOne(
|
jobId: job.parentJobId,
|
||||||
{ jobId: job.parentJobId },
|
completedMemberJobIds: { $ne: job.jobId },
|
||||||
|
state: { $ne: 'cancelled' },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
state: completed ? 'completed' : current.state,
|
|
||||||
completedAt: completed ? new Date() : current.completedAt,
|
|
||||||
averageMemberSeconds: average,
|
averageMemberSeconds: average,
|
||||||
},
|
},
|
||||||
$inc: {
|
$inc: {
|
||||||
@@ -651,14 +669,49 @@ export class LegacyImportService {
|
|||||||
totalSkippedDuplicate: stats.duplicates,
|
totalSkippedDuplicate: stats.duplicates,
|
||||||
totalErrors: stats.errors,
|
totalErrors: stats.errors,
|
||||||
},
|
},
|
||||||
|
$addToSet: {
|
||||||
|
completedMemberJobIds: job.jobId,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
).exec();
|
).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) {
|
if (completed) {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
this.redisService.delete(
|
this.distributedLockService.releaseLockIfOwned({
|
||||||
this.communityLockKey(new mongoose.Types.ObjectId(job.communityId)),
|
lockKey: this.communityLockKey(
|
||||||
|
new mongoose.Types.ObjectId(job.communityId),
|
||||||
),
|
),
|
||||||
|
lockOwnershipToken: job.parentJobId,
|
||||||
|
lockExpirationDurationMilliseconds:
|
||||||
|
LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
|
||||||
|
}),
|
||||||
this.communityStatsService.invalidateCommunity(
|
this.communityStatsService.invalidateCommunity(
|
||||||
new mongoose.Types.ObjectId(job.communityId),
|
new mongoose.Types.ObjectId(job.communityId),
|
||||||
),
|
),
|
||||||
@@ -680,6 +733,20 @@ export class LegacyImportService {
|
|||||||
return legacyJob;
|
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> {
|
private async isCancelled(parentJobId: string): Promise<boolean> {
|
||||||
const LegacyImportJobModel =
|
const LegacyImportJobModel =
|
||||||
await this.connectionService.getModel('legacyImportJob');
|
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;
|
pentaKills: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ChampionAggregateRow extends AggregatedChampion {
|
||||||
|
lastFetchedAt?: Date;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MatchHistoryService {
|
export class MatchHistoryService {
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
@@ -129,29 +133,17 @@ export class MatchHistoryService {
|
|||||||
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
|
const { queueGroup, rank, queueIds } = this.resolveQueueFilters(
|
||||||
params.filters,
|
params.filters,
|
||||||
);
|
);
|
||||||
const docs = await this.findStoredMatches({
|
const aggregates = await this.aggregateChampionStats({
|
||||||
context,
|
context,
|
||||||
queueIds,
|
queueIds,
|
||||||
limit: MAX_AGGREGATE_MATCHES,
|
limit: MAX_AGGREGATE_MATCHES,
|
||||||
});
|
});
|
||||||
const aggregates = new Map<number, AggregatedChampion>();
|
|
||||||
|
|
||||||
for (const doc of docs) {
|
const champions = aggregates
|
||||||
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()]
|
|
||||||
.map((aggregate) => this.toChampionStatsRow(aggregate))
|
.map((aggregate) => this.toChampionStatsRow(aggregate))
|
||||||
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
|
.sort((a, b) => b.games - a.games || b.winRate - a.winRate);
|
||||||
const totals = this.toChampionStatsRow(
|
const totals = this.toChampionStatsRow(
|
||||||
[...aggregates.values()].reduce(
|
aggregates.reduce(
|
||||||
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
|
(acc, aggregate) => this.mergeChampionAggregate(acc, aggregate),
|
||||||
this.createChampionAggregate(0),
|
this.createChampionAggregate(0),
|
||||||
),
|
),
|
||||||
@@ -162,7 +154,7 @@ export class MatchHistoryService {
|
|||||||
rank,
|
rank,
|
||||||
queueIds,
|
queueIds,
|
||||||
season: context.season,
|
season: context.season,
|
||||||
lastFetchedAt: this.resolveLastFetchedAt(docs, context),
|
lastFetchedAt: this.resolveAggregateLastFetchedAt(aggregates, context),
|
||||||
champions,
|
champions,
|
||||||
totals,
|
totals,
|
||||||
};
|
};
|
||||||
@@ -363,6 +355,101 @@ export class MatchHistoryService {
|
|||||||
.slice(0, params.limit);
|
.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(
|
private findParticipant(
|
||||||
match: RiotMatchDto,
|
match: RiotMatchDto,
|
||||||
puuid: string,
|
puuid: string,
|
||||||
@@ -760,6 +847,24 @@ export class MatchHistoryService {
|
|||||||
return oldest.toISOString();
|
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 {
|
private clampLimit(value: number | undefined, fallback: number, max: number): number {
|
||||||
if (!value || !Number.isFinite(value)) return fallback;
|
if (!value || !Number.isFinite(value)) return fallback;
|
||||||
return Math.max(1, Math.min(Math.floor(value), max));
|
return Math.max(1, Math.min(Math.floor(value), max));
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
ArrayMinSize,
|
ArrayMinSize,
|
||||||
registerDecorator,
|
registerDecorator,
|
||||||
IsArray,
|
IsArray,
|
||||||
|
IsBoolean,
|
||||||
IsDate,
|
IsDate,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsInt,
|
IsInt,
|
||||||
@@ -106,6 +107,10 @@ export class CreateMatchDto {
|
|||||||
@Min(1)
|
@Min(1)
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
@@ -166,6 +171,10 @@ export class UpdateMatchDto {
|
|||||||
@Min(1)
|
@Min(1)
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
@@ -217,3 +226,31 @@ export class AddParticipantDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
riotPuuid?: string;
|
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';
|
} from '../global/database/schema';
|
||||||
import {
|
import {
|
||||||
AddParticipantDto,
|
AddParticipantDto,
|
||||||
|
ApplyDoubleEliminationWalkoverDto,
|
||||||
|
CancelDoubleEliminationActionDto,
|
||||||
CreateMatchDto,
|
CreateMatchDto,
|
||||||
JoinMatchDto,
|
JoinMatchDto,
|
||||||
|
SwapDoubleEliminationSeedsDto,
|
||||||
UpdateMatchDto,
|
UpdateMatchDto,
|
||||||
UpdateParticipantDto,
|
UpdateParticipantDto,
|
||||||
} from './dto/create-match.dto';
|
} from './dto/create-match.dto';
|
||||||
@@ -58,6 +61,8 @@ export class MatchController {
|
|||||||
gameCount: body.gameCount,
|
gameCount: body.gameCount,
|
||||||
gameMode: body.gameMode ?? 'pair',
|
gameMode: body.gameMode ?? 'pair',
|
||||||
roundRobinMaxRounds: body.roundRobinMaxRounds,
|
roundRobinMaxRounds: body.roundRobinMaxRounds,
|
||||||
|
doubleEliminationResetFinalEnabled:
|
||||||
|
body.doubleEliminationResetFinalEnabled,
|
||||||
prizes: body.prizes ?? [],
|
prizes: body.prizes ?? [],
|
||||||
notices: body.notices ?? [],
|
notices: body.notices ?? [],
|
||||||
schedule: body.schedule ?? [],
|
schedule: body.schedule ?? [],
|
||||||
@@ -121,6 +126,116 @@ export class MatchController {
|
|||||||
return this.matchService.update({ matchId, communityId, patch: body });
|
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')
|
@Delete(':matchId')
|
||||||
@Roles('admin', 'owner')
|
@Roles('admin', 'owner')
|
||||||
@UseGuards(RolesGuard)
|
@UseGuards(RolesGuard)
|
||||||
|
|||||||
@@ -2,9 +2,62 @@ import mongoose from 'mongoose';
|
|||||||
import { MatchService } from './match.service';
|
import { MatchService } from './match.service';
|
||||||
|
|
||||||
describe('MatchService', () => {
|
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 = {
|
const MatchModel = {
|
||||||
findById: jest.fn().mockResolvedValue(match),
|
findById: jest.fn().mockResolvedValue(match),
|
||||||
|
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
|
||||||
};
|
};
|
||||||
const connectionService = {
|
const connectionService = {
|
||||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||||
@@ -31,6 +84,7 @@ describe('MatchService', () => {
|
|||||||
communityStatsService as never,
|
communityStatsService as never,
|
||||||
matchStatsService as never,
|
matchStatsService as never,
|
||||||
),
|
),
|
||||||
|
MatchModel,
|
||||||
tournamentCodeService,
|
tournamentCodeService,
|
||||||
matchStatsService,
|
matchStatsService,
|
||||||
};
|
};
|
||||||
@@ -83,12 +137,16 @@ describe('MatchService', () => {
|
|||||||
function createServiceWithJoinModels(params: {
|
function createServiceWithJoinModels(params: {
|
||||||
user: Record<string, unknown> | null;
|
user: Record<string, unknown> | null;
|
||||||
match: Record<string, unknown> | null;
|
match: Record<string, unknown> | null;
|
||||||
|
updatedMatch?: Record<string, unknown> | null;
|
||||||
}) {
|
}) {
|
||||||
const UserModel = {
|
const UserModel = {
|
||||||
findById: jest.fn().mockResolvedValue(params.user),
|
findById: jest.fn().mockResolvedValue(params.user),
|
||||||
};
|
};
|
||||||
const MatchModel = {
|
const MatchModel = {
|
||||||
findById: jest.fn().mockResolvedValue(params.match),
|
findById: jest.fn().mockResolvedValue(params.match),
|
||||||
|
findOneAndUpdate: jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValue(params.updatedMatch ?? params.match),
|
||||||
};
|
};
|
||||||
const connectionService = {
|
const connectionService = {
|
||||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||||
@@ -233,15 +291,43 @@ describe('MatchService', () => {
|
|||||||
participants: [],
|
participants: [],
|
||||||
save: jest.fn().mockResolvedValue(undefined),
|
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,
|
matchId,
|
||||||
userId,
|
userId,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(match.participants).toEqual([
|
expect(joined).toBe(updatedMatch);
|
||||||
|
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
|
_id: matchId,
|
||||||
|
communityId,
|
||||||
|
status: 'recruiting',
|
||||||
|
'participants.userId': { $ne: userId },
|
||||||
|
$expr: expect.any(Object),
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
$push: {
|
||||||
|
participants: expect.objectContaining({
|
||||||
userId,
|
userId,
|
||||||
puuid: 'puuid-1',
|
puuid: 'puuid-1',
|
||||||
gameName: 'Dahyeon',
|
gameName: 'Dahyeon',
|
||||||
@@ -250,8 +336,191 @@ describe('MatchService', () => {
|
|||||||
preferredPositions: [{ position: 'MID', priority: 1 }],
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
||||||
excluded: false,
|
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: 1,
|
||||||
|
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 () => {
|
it('clears game schedule when a built match returns to recruiting', async () => {
|
||||||
@@ -310,7 +579,7 @@ describe('MatchService', () => {
|
|||||||
patch: { roundRobinMaxRounds: 3 },
|
patch: { roundRobinMaxRounds: 3 },
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow(
|
).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();
|
expect(match.set).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,12 +5,19 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import {
|
||||||
|
cancelDoubleEliminationBracketMatch,
|
||||||
|
completeDoubleEliminationBracketMatch,
|
||||||
|
reshuffleDoubleEliminationSeeds,
|
||||||
|
swapDoubleEliminationSeeds,
|
||||||
|
} from '../double-elimination/double-elimination.util';
|
||||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import {
|
import {
|
||||||
Match,
|
Match,
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
|
MatchGameMode,
|
||||||
MatchSeriesResult,
|
MatchSeriesResult,
|
||||||
MatchStatus,
|
MatchStatus,
|
||||||
POSITIONS,
|
POSITIONS,
|
||||||
@@ -26,17 +33,24 @@ const MATCH_SHORT_CODE_LENGTH = 4;
|
|||||||
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
|
||||||
const DEFAULT_MATCH_LIST_LIMIT = 50;
|
const DEFAULT_MATCH_LIST_LIMIT = 50;
|
||||||
const MAX_MATCH_LIST_LIMIT = 200;
|
const MAX_MATCH_LIST_LIMIT = 200;
|
||||||
|
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
|
||||||
|
|
||||||
|
interface DoubleEliminationConfigInput {
|
||||||
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
interface CreateMatchParams {
|
interface CreateMatchParams {
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
hostUserId?: mongoose.Types.ObjectId;
|
hostUserId?: mongoose.Types.ObjectId;
|
||||||
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>;
|
data: Partial<Match> &
|
||||||
|
Pick<Match, 'title' | 'scheduledAt'> &
|
||||||
|
DoubleEliminationConfigInput;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface UpdateMatchParams {
|
interface UpdateMatchParams {
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
patch: Partial<Match>;
|
patch: Partial<Match> & DoubleEliminationConfigInput;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ListMatchesQuery {
|
interface ListMatchesQuery {
|
||||||
@@ -89,6 +103,31 @@ interface UpdateParticipantPositionsParams {
|
|||||||
subPosition: Position;
|
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()
|
@Injectable()
|
||||||
export class MatchService {
|
export class MatchService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -105,15 +144,18 @@ export class MatchService {
|
|||||||
.select({ matchGameCount: 1 })
|
.select({ matchGameCount: 1 })
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
return MatchModel.create({
|
const normalizedData = this.normalizeMatchConfig({
|
||||||
...params.data,
|
...params.data,
|
||||||
shortCode:
|
|
||||||
params.data.shortCode ??
|
|
||||||
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
|
||||||
gameCount:
|
gameCount:
|
||||||
params.data.gameCount ??
|
params.data.gameCount ??
|
||||||
community?.matchGameCount ??
|
community?.matchGameCount ??
|
||||||
DEFAULT_TOURNAMENT_GAME_COUNT,
|
DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||||
|
});
|
||||||
|
return MatchModel.create({
|
||||||
|
...normalizedData,
|
||||||
|
shortCode:
|
||||||
|
normalizedData.shortCode ??
|
||||||
|
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
hostUserId: params.hostUserId,
|
hostUserId: params.hostUserId,
|
||||||
});
|
});
|
||||||
@@ -216,13 +258,30 @@ export class MatchService {
|
|||||||
previousStatus !== 'recruiting' &&
|
previousStatus !== 'recruiting' &&
|
||||||
('maxParticipants' in params.patch ||
|
('maxParticipants' in params.patch ||
|
||||||
'gameMode' in params.patch ||
|
'gameMode' in params.patch ||
|
||||||
'roundRobinMaxRounds' in params.patch)
|
'roundRobinMaxRounds' in params.patch ||
|
||||||
|
'doubleEliminationResetFinalEnabled' in params.patch)
|
||||||
) {
|
) {
|
||||||
throw new BadRequestException(
|
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 (previousStatus !== 'recruiting' && match.status === 'recruiting') {
|
||||||
if (match.tournamentCodeIds.length > 0) {
|
if (match.tournamentCodeIds.length > 0) {
|
||||||
await this.tournamentCodeService.releaseFromMatch(match);
|
await this.tournamentCodeService.releaseFromMatch(match);
|
||||||
@@ -260,6 +319,174 @@ export class MatchService {
|
|||||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
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> {
|
public async join(params: JoinMatchParams): Promise<MatchDocument> {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const UserModel = await this.connectionService.getModel('user');
|
const UserModel = await this.connectionService.getModel('user');
|
||||||
@@ -267,29 +494,11 @@ export class MatchService {
|
|||||||
const user = await UserModel.findById(params.userId);
|
const user = await UserModel.findById(params.userId);
|
||||||
if (!user) throw new NotFoundException('User not found.');
|
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
|
const selectedRiot = params.riotPuuid
|
||||||
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
|
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
|
||||||
: user.riotAccounts.find((a) => a.isPrimary);
|
: user.riotAccounts.find((a) => a.isPrimary);
|
||||||
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
|
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
|
||||||
match.participants.push({
|
const participant = {
|
||||||
userId: user._id,
|
userId: user._id,
|
||||||
puuid: selectedRiot?.puuid,
|
puuid: selectedRiot?.puuid,
|
||||||
gameName: selectedRiot?.gameName,
|
gameName: selectedRiot?.gameName,
|
||||||
@@ -302,11 +511,210 @@ export class MatchService {
|
|||||||
),
|
),
|
||||||
joinedAt: new Date(),
|
joinedAt: new Date(),
|
||||||
excluded: false,
|
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: 1,
|
||||||
|
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 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;
|
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(
|
public async cancelJoin(
|
||||||
params: CancelMatchJoinParams,
|
params: CancelMatchJoinParams,
|
||||||
): Promise<MatchDocument> {
|
): Promise<MatchDocument> {
|
||||||
@@ -316,52 +724,57 @@ export class MatchService {
|
|||||||
const user = await UserModel.findById(params.userId);
|
const user = await UserModel.findById(params.userId);
|
||||||
if (!user) throw new NotFoundException('User not found.');
|
if (!user) throw new NotFoundException('User not found.');
|
||||||
|
|
||||||
const match = await MatchModel.findById(params.matchId);
|
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||||
if (!match) throw new NotFoundException('Match not found.');
|
{
|
||||||
if (!match.communityId.equals(user.communityId)) {
|
_id: params.matchId,
|
||||||
throw new BadRequestException(
|
communityId: user.communityId,
|
||||||
'User and match belong to different communities.',
|
status: 'recruiting',
|
||||||
|
'participants.userId': user._id,
|
||||||
|
},
|
||||||
|
{ $pull: { participants: { userId: user._id } } },
|
||||||
|
{ returnDocument: 'after', runValidators: true },
|
||||||
);
|
);
|
||||||
}
|
if (updatedMatch) return updatedMatch;
|
||||||
if (match.status !== 'recruiting') {
|
|
||||||
throw new BadRequestException('Match is not recruiting.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const participantIndex = match.participants.findIndex((participant) =>
|
return await this.throwCancelJoinFailure(MatchModel, params.matchId, user);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
|
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
|
||||||
public async removeParticipant(
|
public async removeParticipant(
|
||||||
params: RemoveParticipantParams,
|
params: RemoveParticipantParams,
|
||||||
): Promise<MatchDocument> {
|
): 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(
|
const match = await this.loadRecruitingMatch(
|
||||||
params.matchId,
|
params.matchId,
|
||||||
params.communityId,
|
params.communityId,
|
||||||
);
|
);
|
||||||
const participantIndex = match.participants.findIndex((participant) =>
|
if (
|
||||||
participant.userId.equals(params.targetUserId),
|
!match.participants.some((participant) =>
|
||||||
);
|
this.sameObjectId(participant.userId, params.targetUserId),
|
||||||
if (participantIndex === -1) {
|
)
|
||||||
|
) {
|
||||||
throw new NotFoundException('Participant not found.');
|
throw new NotFoundException('Participant not found.');
|
||||||
}
|
}
|
||||||
match.participants.splice(participantIndex, 1);
|
throw new BadRequestException('Participant could not be removed.');
|
||||||
await match.save();
|
|
||||||
return match;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
|
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
|
||||||
public async updateParticipantPositions(
|
public async updateParticipantPositions(
|
||||||
params: UpdateParticipantPositionsParams,
|
params: UpdateParticipantPositionsParams,
|
||||||
): Promise<MatchDocument> {
|
): Promise<MatchDocument> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const match = await this.loadRecruitingMatch(
|
const match = await this.loadRecruitingMatch(
|
||||||
params.matchId,
|
params.matchId,
|
||||||
params.communityId,
|
params.communityId,
|
||||||
@@ -372,14 +785,36 @@ export class MatchService {
|
|||||||
if (!participant) {
|
if (!participant) {
|
||||||
throw new NotFoundException('Participant not found.');
|
throw new NotFoundException('Participant not found.');
|
||||||
}
|
}
|
||||||
participant.preferredPositions = this.reorderPreferredPositions(
|
const preferredPositions = this.reorderPreferredPositions(
|
||||||
params.mainPosition,
|
params.mainPosition,
|
||||||
params.subPosition,
|
params.subPosition,
|
||||||
participant.preferredPositions,
|
participant.preferredPositions,
|
||||||
);
|
);
|
||||||
match.markModified('participants');
|
|
||||||
await match.save();
|
const updatedMatch = await MatchModel.findOneAndUpdate(
|
||||||
return match;
|
{
|
||||||
|
_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(
|
private async loadRecruitingMatch(
|
||||||
@@ -398,6 +833,69 @@ export class MatchService {
|
|||||||
return match;
|
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로 올리고 기존 나머지 선호는 뒤로 보존한다.
|
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
|
||||||
private reorderPreferredPositions(
|
private reorderPreferredPositions(
|
||||||
mainPosition: Position,
|
mainPosition: Position,
|
||||||
@@ -539,10 +1037,11 @@ export class MatchService {
|
|||||||
for (const game of games) {
|
for (const game of games) {
|
||||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||||
const key = `${teamAIndex}:${teamBIndex}`;
|
const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
|
||||||
const current =
|
const current =
|
||||||
bySeries.get(key) ??
|
bySeries.get(key) ??
|
||||||
({
|
({
|
||||||
|
bracketMatchId: game.bracketMatchId,
|
||||||
teamAIndex,
|
teamAIndex,
|
||||||
teamBIndex,
|
teamBIndex,
|
||||||
teamAWins: 0,
|
teamAWins: 0,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import { RedisService } from '../global/redis/redis.service';
|
import { RedisService } from '../global/redis/redis.service';
|
||||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||||
@@ -35,11 +36,18 @@ function makeScheduler() {
|
|||||||
};
|
};
|
||||||
const redis = {
|
const redis = {
|
||||||
getString: jest.fn().mockResolvedValue(null),
|
getString: jest.fn().mockResolvedValue(null),
|
||||||
setString: jest.fn().mockResolvedValue(undefined),
|
|
||||||
setStringIfAbsent: jest.fn().mockResolvedValue(true),
|
|
||||||
delete: jest.fn().mockResolvedValue(1),
|
delete: jest.fn().mockResolvedValue(1),
|
||||||
raw: jest.fn().mockReturnValue(rawClient),
|
raw: jest.fn().mockReturnValue(rawClient),
|
||||||
} as unknown as jest.Mocked<RedisService> & { raw: jest.Mock };
|
} 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 = {
|
const rateLimiter = {
|
||||||
isRefreshWindowOpen: jest.fn().mockResolvedValue(true),
|
isRefreshWindowOpen: jest.fn().mockResolvedValue(true),
|
||||||
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
||||||
@@ -52,6 +60,7 @@ function makeScheduler() {
|
|||||||
} as unknown as jest.Mocked<StaleAccountRepository>;
|
} as unknown as jest.Mocked<StaleAccountRepository>;
|
||||||
const scheduler = new BackgroundRefreshScheduler(
|
const scheduler = new BackgroundRefreshScheduler(
|
||||||
redis,
|
redis,
|
||||||
|
distributedLockService,
|
||||||
rateLimiter,
|
rateLimiter,
|
||||||
enrichmentService,
|
enrichmentService,
|
||||||
staleAccountRepository,
|
staleAccountRepository,
|
||||||
@@ -60,6 +69,7 @@ function makeScheduler() {
|
|||||||
return {
|
return {
|
||||||
scheduler,
|
scheduler,
|
||||||
redis,
|
redis,
|
||||||
|
distributedLockService,
|
||||||
rawClient,
|
rawClient,
|
||||||
rateLimiter,
|
rateLimiter,
|
||||||
enrichmentService,
|
enrichmentService,
|
||||||
@@ -115,8 +125,9 @@ describe('BackgroundRefreshScheduler', () => {
|
|||||||
|
|
||||||
it('does not query stale accounts when another leader holds the lock', async () => {
|
it('does not query stale accounts when another leader holds the lock', async () => {
|
||||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||||
const { scheduler, redis, staleAccountRepository } = makeScheduler();
|
const { scheduler, distributedLockService, staleAccountRepository } =
|
||||||
redis.getString.mockResolvedValue('another-consumer');
|
makeScheduler();
|
||||||
|
distributedLockService.acquireLock.mockResolvedValueOnce(null);
|
||||||
|
|
||||||
await scheduler.tick();
|
await scheduler.tick();
|
||||||
|
|
||||||
|
|||||||
@@ -9,13 +9,17 @@ import {
|
|||||||
RiotAccountEnrichmentService,
|
RiotAccountEnrichmentService,
|
||||||
} from '../riot/riot-account-enrichment.service';
|
} from '../riot/riot-account-enrichment.service';
|
||||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.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 { RedisService } from '../global/redis/redis.service';
|
||||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||||
import { StaleAccountRepository } from './stale-account.repository';
|
import { StaleAccountRepository } from './stale-account.repository';
|
||||||
|
|
||||||
const TICK_INTERVAL_MS = 60_000;
|
const TICK_INTERVAL_MS = 60_000;
|
||||||
const LEADER_KEY = 'riot:bg-refresh:leader';
|
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
|
||||||
const LEADER_TTL_SECONDS = 90;
|
const LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS = 90_000;
|
||||||
const LEADER_RENEW_INTERVAL_MS = 30_000;
|
const LEADER_RENEW_INTERVAL_MS = 30_000;
|
||||||
const STALE_THRESHOLD_MS = 6 * 60 * 60 * 1000;
|
const STALE_THRESHOLD_MS = 6 * 60 * 60 * 1000;
|
||||||
const PER_TICK_CANDIDATE_LIMIT = 20;
|
const PER_TICK_CANDIDATE_LIMIT = 20;
|
||||||
@@ -38,10 +42,11 @@ export class BackgroundRefreshScheduler
|
|||||||
private tickTimer?: NodeJS.Timeout;
|
private tickTimer?: NodeJS.Timeout;
|
||||||
private leaderRenewTimer?: NodeJS.Timeout;
|
private leaderRenewTimer?: NodeJS.Timeout;
|
||||||
private tickInProgress = false;
|
private tickInProgress = false;
|
||||||
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
private leaderLockOwnership: DistributedLockOwnership | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly redis: RedisService,
|
private readonly redis: RedisService,
|
||||||
|
private readonly distributedLockService: DistributedLockService,
|
||||||
private readonly rateLimiter: RiotRateLimiterService,
|
private readonly rateLimiter: RiotRateLimiterService,
|
||||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||||
private readonly staleAccountRepository: StaleAccountRepository,
|
private readonly staleAccountRepository: StaleAccountRepository,
|
||||||
@@ -59,9 +64,20 @@ export class BackgroundRefreshScheduler
|
|||||||
void this.safeTick();
|
void this.safeTick();
|
||||||
}
|
}
|
||||||
|
|
||||||
public onModuleDestroy(): void {
|
public async onModuleDestroy(): Promise<void> {
|
||||||
if (this.tickTimer) clearInterval(this.tickTimer);
|
if (this.tickTimer) clearInterval(this.tickTimer);
|
||||||
if (this.leaderRenewTimer) clearInterval(this.leaderRenewTimer);
|
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> {
|
private async safeTick(): Promise<void> {
|
||||||
@@ -158,33 +174,33 @@ export class BackgroundRefreshScheduler
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async tryBecomeLeader(): Promise<boolean> {
|
private async tryBecomeLeader(): Promise<boolean> {
|
||||||
const current = await this.redis.getString(LEADER_KEY);
|
if (this.leaderLockOwnership) {
|
||||||
if (current === this.consumer) {
|
const didExtendLeaderLock =
|
||||||
await this.redis.setString(
|
await this.distributedLockService.extendLockIfOwned(
|
||||||
LEADER_KEY,
|
this.leaderLockOwnership,
|
||||||
this.consumer,
|
|
||||||
LEADER_TTL_SECONDS,
|
|
||||||
);
|
);
|
||||||
return true;
|
if (didExtendLeaderLock) return true;
|
||||||
|
this.leaderLockOwnership = undefined;
|
||||||
}
|
}
|
||||||
if (current) return false;
|
|
||||||
|
|
||||||
return this.redis.setStringIfAbsent(
|
const leaderLockOwnership = await this.distributedLockService.acquireLock({
|
||||||
LEADER_KEY,
|
lockKey: LEADER_LOCK_KEY,
|
||||||
this.consumer,
|
lockExpirationDurationMilliseconds:
|
||||||
LEADER_TTL_SECONDS,
|
LEADER_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||||
);
|
});
|
||||||
|
this.leaderLockOwnership = leaderLockOwnership ?? undefined;
|
||||||
|
return Boolean(leaderLockOwnership);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async renewLeaderIfHeld(): Promise<void> {
|
private async renewLeaderIfHeld(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const current = await this.redis.getString(LEADER_KEY);
|
if (!this.leaderLockOwnership) return;
|
||||||
if (current !== this.consumer) return;
|
const didExtendLeaderLock =
|
||||||
await this.redis.setString(
|
await this.distributedLockService.extendLockIfOwned(
|
||||||
LEADER_KEY,
|
this.leaderLockOwnership,
|
||||||
this.consumer,
|
|
||||||
LEADER_TTL_SECONDS,
|
|
||||||
);
|
);
|
||||||
|
if (didExtendLeaderLock) return;
|
||||||
|
this.leaderLockOwnership = undefined;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Background refresh leader renew failed: ${
|
`Background refresh leader renew failed: ${
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import { RedisService } from '../global/redis/redis.service';
|
import { RedisService } from '../global/redis/redis.service';
|
||||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||||
@@ -19,6 +20,16 @@ function makeWorker() {
|
|||||||
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
|
acknowledgeStream: jest.fn().mockResolvedValue(undefined),
|
||||||
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
|
deleteStreamEntries: jest.fn().mockResolvedValue(undefined),
|
||||||
} as unknown as jest.Mocked<RedisService>;
|
} 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 = {
|
const jobQueueService = {
|
||||||
markProcessing: jest.fn().mockResolvedValue(undefined),
|
markProcessing: jest.fn().mockResolvedValue(undefined),
|
||||||
markCompleted: jest.fn().mockResolvedValue({
|
markCompleted: jest.fn().mockResolvedValue({
|
||||||
@@ -54,6 +65,7 @@ function makeWorker() {
|
|||||||
|
|
||||||
const worker = new RiotJobWorkerService(
|
const worker = new RiotJobWorkerService(
|
||||||
redisService,
|
redisService,
|
||||||
|
distributedLockService,
|
||||||
jobQueueService,
|
jobQueueService,
|
||||||
recentMatchesService,
|
recentMatchesService,
|
||||||
connectionService,
|
connectionService,
|
||||||
@@ -66,6 +78,7 @@ function makeWorker() {
|
|||||||
return {
|
return {
|
||||||
worker,
|
worker,
|
||||||
redisService,
|
redisService,
|
||||||
|
distributedLockService,
|
||||||
jobQueueService,
|
jobQueueService,
|
||||||
recentMatchesService,
|
recentMatchesService,
|
||||||
connectionService,
|
connectionService,
|
||||||
@@ -151,4 +164,37 @@ describe('RiotJobWorkerService', () => {
|
|||||||
redisService.deleteStreamEntries.mock.invocationCallOrder[0],
|
redisService.deleteStreamEntries.mock.invocationCallOrder[0],
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('leaves a stream entry pending when another worker owns the job processing lock', async () => {
|
||||||
|
const { worker, distributedLockService, redisService } = makeWorker();
|
||||||
|
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
|
||||||
|
const userId = new mongoose.Types.ObjectId().toString();
|
||||||
|
const job: RiotRefreshSubJob = {
|
||||||
|
jobId: 'job-1',
|
||||||
|
parentJobId: 'parent-1',
|
||||||
|
userId,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
region: 'asia',
|
||||||
|
platform: 'kr',
|
||||||
|
queueGroup: 'summoners-rift',
|
||||||
|
queueIds: [420],
|
||||||
|
requestedAt: Date.now(),
|
||||||
|
priority: 'high',
|
||||||
|
};
|
||||||
|
|
||||||
|
await (
|
||||||
|
worker as unknown as {
|
||||||
|
processEntry: (
|
||||||
|
stream: string,
|
||||||
|
entry: { id: string; message: Record<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';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
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 { RedisService, StreamEntry } from '../global/redis/redis.service';
|
||||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||||
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
||||||
@@ -23,17 +27,24 @@ import {
|
|||||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||||
|
|
||||||
const LEADER_KEY = 'riot:worker:leader';
|
const RIOT_JOB_WORKER_LEADER_LOCK_KEY =
|
||||||
const LEADER_TTL_SECONDS = 60;
|
'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()
|
@Injectable()
|
||||||
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||||
private readonly logger = new Logger(RiotJobWorkerService.name);
|
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;
|
private stopped = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly redisService: RedisService,
|
private readonly redisService: RedisService,
|
||||||
|
private readonly distributedLockService: DistributedLockService,
|
||||||
private readonly jobQueueService: RiotJobQueueService,
|
private readonly jobQueueService: RiotJobQueueService,
|
||||||
private readonly recentMatchesService: RiotRecentMatchesService,
|
private readonly recentMatchesService: RiotRecentMatchesService,
|
||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
@@ -48,8 +59,19 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
void this.loop();
|
void this.loop();
|
||||||
}
|
}
|
||||||
|
|
||||||
public onModuleDestroy() {
|
public async onModuleDestroy() {
|
||||||
this.stopped = true;
|
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> {
|
private async loop(): Promise<void> {
|
||||||
@@ -63,7 +85,9 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
|
|
||||||
await this.jobQueueService.promoteDueScheduledJobs();
|
await this.jobQueueService.promoteDueScheduledJobs();
|
||||||
const entry =
|
const entry =
|
||||||
|
(await this.readOneStalePendingMessage(RIOT_JOB_HIGH_STREAM)) ??
|
||||||
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
|
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
|
||||||
|
(await this.readOneStalePendingMessage(RIOT_JOB_LOW_STREAM)) ??
|
||||||
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
|
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
|
||||||
if (!entry) continue;
|
if (!entry) continue;
|
||||||
|
|
||||||
@@ -89,6 +113,31 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
return;
|
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 {
|
try {
|
||||||
if (this.isTournamentResultJob(job)) {
|
if (this.isTournamentResultJob(job)) {
|
||||||
await this.tournamentResultService.processPollJob(job);
|
await this.tournamentResultService.processPollJob(job);
|
||||||
@@ -136,8 +185,6 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
error instanceof Error ? error.message : error
|
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(
|
const result = await this.redisService.readGroup(
|
||||||
stream,
|
stream,
|
||||||
RIOT_JOB_GROUP,
|
RIOT_JOB_GROUP,
|
||||||
this.consumer,
|
this.consumerIdentifier,
|
||||||
'>',
|
'>',
|
||||||
{ count: 1, blockMs },
|
{ count: 1, blockMs },
|
||||||
);
|
);
|
||||||
@@ -237,6 +284,21 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
|||||||
return message ? { stream, message } : null;
|
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> {
|
private async ensureConsumerGroups(): Promise<void> {
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
[RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => {
|
[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> {
|
private async tryBecomeLeader(): Promise<boolean> {
|
||||||
const current = await this.redisService.getString(LEADER_KEY);
|
if (this.leaderLockOwnership) {
|
||||||
if (current === this.consumer) {
|
const didExtendLeaderLock =
|
||||||
await this.redisService.setString(
|
await this.distributedLockService.extendLockIfOwned(
|
||||||
LEADER_KEY,
|
this.leaderLockOwnership,
|
||||||
this.consumer,
|
|
||||||
LEADER_TTL_SECONDS,
|
|
||||||
);
|
);
|
||||||
return true;
|
if (didExtendLeaderLock) return true;
|
||||||
|
this.leaderLockOwnership = undefined;
|
||||||
}
|
}
|
||||||
if (current) return false;
|
|
||||||
return this.redisService.setStringIfAbsent(
|
const leaderLockOwnership = await this.distributedLockService.acquireLock({
|
||||||
LEADER_KEY,
|
lockKey: RIOT_JOB_WORKER_LEADER_LOCK_KEY,
|
||||||
this.consumer,
|
lockExpirationDurationMilliseconds:
|
||||||
LEADER_TTL_SECONDS,
|
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> {
|
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 DDRAGON_CDN = `${DDRAGON_BASE}/cdn`;
|
||||||
const DEFAULT_LOCALE = 'ko_KR';
|
const DEFAULT_LOCALE = 'ko_KR';
|
||||||
const CACHE_TTL_SECONDS = 24 * 60 * 60;
|
const CACHE_TTL_SECONDS = 24 * 60 * 60;
|
||||||
const CACHE_VERSION = 'v3';
|
const CACHE_VERSION = 'v5';
|
||||||
const FETCH_TIMEOUT_MS = 10_000;
|
const FETCH_TIMEOUT_MS = 10_000;
|
||||||
|
|
||||||
export interface DdragonChampionEntry {
|
export interface DdragonChampionEntry {
|
||||||
@@ -16,6 +16,8 @@ export interface DdragonChampionEntry {
|
|||||||
export interface DdragonSummonerSpellEntry {
|
export interface DdragonSummonerSpellEntry {
|
||||||
key: string;
|
key: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
description: string;
|
||||||
|
tooltip: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DdragonRuneEntry {
|
export interface DdragonRuneEntry {
|
||||||
@@ -23,12 +25,26 @@ export interface DdragonRuneEntry {
|
|||||||
key: string;
|
key: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
shortDesc: string;
|
||||||
|
longDesc: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
||||||
slots: Array<{ runes: 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 {
|
export interface DdragonManifest {
|
||||||
version: string;
|
version: string;
|
||||||
cdn: string;
|
cdn: string;
|
||||||
@@ -36,6 +52,7 @@ export interface DdragonManifest {
|
|||||||
champions: Record<string, DdragonChampionEntry>;
|
champions: Record<string, DdragonChampionEntry>;
|
||||||
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
||||||
runesReforged: DdragonRuneStyleEntry[];
|
runesReforged: DdragonRuneStyleEntry[];
|
||||||
|
items: Record<string, DdragonItemEntry>;
|
||||||
fetchedAt: string;
|
fetchedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,6 +70,8 @@ interface SummonerSpellDataEntry {
|
|||||||
key: string;
|
key: string;
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
tooltip?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SummonerSpellDataResponse {
|
interface SummonerSpellDataResponse {
|
||||||
@@ -64,12 +83,30 @@ interface RuneDataEntry {
|
|||||||
key: string;
|
key: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
shortDesc?: string;
|
||||||
|
longDesc?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RuneStyleDataEntry extends RuneDataEntry {
|
interface RuneStyleDataEntry extends RuneDataEntry {
|
||||||
slots?: Array<{ runes?: 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()
|
@Injectable()
|
||||||
export class RiotDdragonService {
|
export class RiotDdragonService {
|
||||||
private readonly logger = new Logger(RiotDdragonService.name);
|
private readonly logger = new Logger(RiotDdragonService.name);
|
||||||
@@ -102,10 +139,11 @@ export class RiotDdragonService {
|
|||||||
|
|
||||||
private async buildManifest(locale: string): Promise<DdragonManifest> {
|
private async buildManifest(locale: string): Promise<DdragonManifest> {
|
||||||
const version = await this.fetchLatestVersion();
|
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.fetchChampionMap(version, locale),
|
||||||
this.fetchSummonerSpellMap(version, locale),
|
this.fetchSummonerSpellMap(version, locale),
|
||||||
this.fetchRuneStyles(version, locale),
|
this.fetchRuneStyles(version, locale),
|
||||||
|
this.fetchItemMap(version, locale),
|
||||||
]);
|
]);
|
||||||
return {
|
return {
|
||||||
version,
|
version,
|
||||||
@@ -114,6 +152,7 @@ export class RiotDdragonService {
|
|||||||
champions,
|
champions,
|
||||||
summonerSpells,
|
summonerSpells,
|
||||||
runesReforged,
|
runesReforged,
|
||||||
|
items,
|
||||||
fetchedAt: new Date().toISOString(),
|
fetchedAt: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -164,6 +203,9 @@ export class RiotDdragonService {
|
|||||||
map[entry.key] = {
|
map[entry.key] = {
|
||||||
key: entry.id,
|
key: entry.id,
|
||||||
name: typeof entry.name === 'string' ? entry.name : 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,
|
key: style.key,
|
||||||
icon: style.icon,
|
icon: style.icon,
|
||||||
name: style.name,
|
name: style.name,
|
||||||
|
shortDesc:
|
||||||
|
typeof style.shortDesc === 'string' ? style.shortDesc : '',
|
||||||
|
longDesc: typeof style.longDesc === 'string' ? style.longDesc : '',
|
||||||
slots: (style.slots ?? []).map((slot) => ({
|
slots: (style.slots ?? []).map((slot) => ({
|
||||||
runes: (slot.runes ?? [])
|
runes: (slot.runes ?? [])
|
||||||
.filter((rune): rune is RuneDataEntry => isRuneEntry(rune))
|
.filter((rune): rune is RuneDataEntry => isRuneEntry(rune))
|
||||||
@@ -195,11 +240,46 @@ export class RiotDdragonService {
|
|||||||
key: rune.key,
|
key: rune.key,
|
||||||
icon: rune.icon,
|
icon: rune.icon,
|
||||||
name: rune.name,
|
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> {
|
private async fetchJson<T>(url: string): Promise<T> {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
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 {
|
function manifestCacheKey(locale: string): string {
|
||||||
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
|
return `ddragon:manifest:${CACHE_VERSION}:${locale}`;
|
||||||
}
|
}
|
||||||
@@ -4,14 +4,14 @@ import type {
|
|||||||
RiotMatch as StoredRiotMatch,
|
RiotMatch as StoredRiotMatch,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
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 type { RiotRegionalRoute } from './riot.types';
|
||||||
import { RiotMatchService } from './riot-match.service';
|
import { RiotMatchService } from './riot-match.service';
|
||||||
|
|
||||||
export const RIOT_RECENT_MATCH_LIMIT = 20;
|
export const RIOT_RECENT_MATCH_LIMIT = 20;
|
||||||
export const RIOT_SOLO_QUEUE_ID = 420;
|
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 MATCH_DETAIL_CONCURRENCY = 2;
|
||||||
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
|
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@ export class RiotRecentMatchesService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly connectionService: ConnectionService,
|
private readonly connectionService: ConnectionService,
|
||||||
private readonly matchService: RiotMatchService,
|
private readonly matchService: RiotMatchService,
|
||||||
private readonly redisService: RedisService,
|
private readonly distributedLockService: DistributedLockService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async syncRecentMatches(params: {
|
public async syncRecentMatches(params: {
|
||||||
@@ -34,39 +34,44 @@ export class RiotRecentMatchesService {
|
|||||||
const region = params.region ?? DEFAULT_REGION;
|
const region = params.region ?? DEFAULT_REGION;
|
||||||
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
|
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
|
||||||
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
|
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
|
||||||
const lockKey = `riot:enrich:matches:${params.puuid}`;
|
const result = await this.distributedLockService.runWithLock(
|
||||||
const lockValue = `${process.pid}:${Date.now()}`;
|
{
|
||||||
|
lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`,
|
||||||
const acquired = await this.redisService.setStringIfAbsent(
|
lockExpirationDurationMilliseconds:
|
||||||
lockKey,
|
MATCH_ENRICHMENT_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
||||||
lockValue,
|
},
|
||||||
MATCH_ENRICHMENT_LOCK_TTL_SECONDS,
|
async () => {
|
||||||
);
|
const matchIds = await this.matchService.getMatchIdsByPuuid(
|
||||||
if (!acquired) {
|
params.puuid,
|
||||||
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
{
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const matchIds = await this.matchService.getMatchIdsByPuuid(params.puuid, {
|
|
||||||
region,
|
region,
|
||||||
queue: queueId,
|
queue: queueId,
|
||||||
count: limit,
|
count: limit,
|
||||||
});
|
},
|
||||||
|
);
|
||||||
if (matchIds.length === 0) {
|
if (matchIds.length === 0) {
|
||||||
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
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({
|
const existingMatches = await RiotMatchModel.find({
|
||||||
matchId: { $in: matchIds },
|
matchId: { $in: matchIds },
|
||||||
})
|
})
|
||||||
.select({ matchId: 1 })
|
.select({ matchId: 1 })
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
const existingMatchIds = new Set(existingMatches.map((match) => match.matchId));
|
const existingMatchIds = new Set(
|
||||||
const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId));
|
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 {
|
try {
|
||||||
const dto = await this.matchService.getMatch(matchId, { region });
|
const dto = await this.matchService.getMatch(matchId, { region });
|
||||||
if (dto.info.queueId !== queueId) {
|
if (dto.info.queueId !== queueId) {
|
||||||
@@ -99,18 +104,14 @@ export class RiotRecentMatchesService {
|
|||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
|
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: {
|
public async ensureFreshForQueue(params: {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AuctionRedisModule } from '../auction/redis/auction-redis.module';
|
||||||
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
||||||
import { TournamentCodeController } from './tournament-code.controller';
|
import { TournamentCodeController } from './tournament-code.controller';
|
||||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||||
@@ -8,7 +9,7 @@ import { TournamentCodeService } from './tournament-code.service';
|
|||||||
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
|
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [TournamentResultModule],
|
imports: [TournamentResultModule, AuctionRedisModule],
|
||||||
controllers: [TournamentCodeController, TournamentCodeReplacementController],
|
controllers: [TournamentCodeController, TournamentCodeReplacementController],
|
||||||
providers: [
|
providers: [
|
||||||
TournamentCodeService,
|
TournamentCodeService,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import { TournamentCodeScheduler } from './tournament-code.scheduler';
|
import { TournamentCodeScheduler } from './tournament-code.scheduler';
|
||||||
|
|
||||||
describe('TournamentCodeScheduler', () => {
|
describe('TournamentCodeScheduler', () => {
|
||||||
@@ -18,16 +19,28 @@ describe('TournamentCodeScheduler', () => {
|
|||||||
scheduleInitialPoll:
|
scheduleInitialPoll:
|
||||||
params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null),
|
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(
|
const scheduler = new TournamentCodeScheduler(
|
||||||
tournamentCodeService as never,
|
tournamentCodeService as never,
|
||||||
autoProvisionService as never,
|
autoProvisionService as never,
|
||||||
tournamentResultService as never,
|
tournamentResultService as never,
|
||||||
|
distributedLockService as never,
|
||||||
) as unknown as { attachPending(): Promise<void> };
|
) as unknown as { attachPending(): Promise<void> };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
scheduler,
|
scheduler,
|
||||||
tournamentCodeService,
|
tournamentCodeService,
|
||||||
tournamentResultService,
|
tournamentResultService,
|
||||||
|
distributedLockService,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,4 +72,16 @@ describe('TournamentCodeScheduler', () => {
|
|||||||
|
|
||||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
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,8 +1,18 @@
|
|||||||
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||||
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
|
||||||
import { TournamentCodeService } from './tournament-code.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()
|
@Injectable()
|
||||||
export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||||
private readonly logger = new Logger(TournamentCodeScheduler.name);
|
private readonly logger = new Logger(TournamentCodeScheduler.name);
|
||||||
@@ -14,6 +24,7 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
private readonly tournamentCodeService: TournamentCodeService,
|
private readonly tournamentCodeService: TournamentCodeService,
|
||||||
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
|
private readonly autoProvisionService: TournamentCodeAutoProvisionService,
|
||||||
private readonly tournamentResultService: TournamentResultService,
|
private readonly tournamentResultService: TournamentResultService,
|
||||||
|
private readonly distributedLockService: DistributedLockService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public onModuleInit() {
|
public onModuleInit() {
|
||||||
@@ -47,6 +58,15 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
|
|
||||||
private async attachPending() {
|
private async attachPending() {
|
||||||
try {
|
try {
|
||||||
|
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 =
|
const matches =
|
||||||
await this.tournamentCodeService.attachPendingMatchDocuments();
|
await this.tournamentCodeService.attachPendingMatchDocuments();
|
||||||
if (matches.length > 0) {
|
if (matches.length > 0) {
|
||||||
@@ -57,6 +77,8 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to attach pending tournament codes: ${
|
`Failed to attach pending tournament codes: ${
|
||||||
@@ -68,7 +90,18 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
|
|
||||||
private async markExpired() {
|
private async markExpired() {
|
||||||
try {
|
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();
|
await this.tournamentCodeService.markExpired();
|
||||||
|
},
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to mark expired tournament codes: ${
|
`Failed to mark expired tournament codes: ${
|
||||||
@@ -80,7 +113,18 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
|||||||
|
|
||||||
private async ensureVendorPool() {
|
private async ensureVendorPool() {
|
||||||
try {
|
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();
|
await this.autoProvisionService.ensurePool();
|
||||||
|
},
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Failed to auto-provision tournament codes: ${
|
`Failed to auto-provision tournament codes: ${
|
||||||
|
|||||||
@@ -20,18 +20,36 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
|
|||||||
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
|
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() {
|
function createService() {
|
||||||
return new TournamentCodeService(
|
return new TournamentCodeService(
|
||||||
{} as never,
|
{} as never,
|
||||||
|
createAuctionRedisService() as never,
|
||||||
) as unknown as TournamentCodeServiceInternals;
|
) as unknown as TournamentCodeServiceInternals;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MatchOverrides {
|
interface MatchOverrides {
|
||||||
gameCount?: number;
|
gameCount?: number;
|
||||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
participants?: Array<{ excluded?: boolean }>;
|
participants?: Array<{ excluded?: boolean }>;
|
||||||
teams?: Array<{ teamIndex: number }>;
|
teams?: Array<{ teamIndex: number }>;
|
||||||
|
doubleElimination?: MatchDocument['doubleElimination'];
|
||||||
gameSchedule?: Array<{
|
gameSchedule?: Array<{
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
@@ -51,6 +69,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
|
|||||||
tournamentCodeIds: [],
|
tournamentCodeIds: [],
|
||||||
gameSchedule: [],
|
gameSchedule: [],
|
||||||
save: jest.fn().mockResolvedValue(undefined),
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
markModified: jest.fn(),
|
||||||
...overrides,
|
...overrides,
|
||||||
} as unknown as MatchDocument;
|
} as unknown as MatchDocument;
|
||||||
}
|
}
|
||||||
@@ -206,6 +225,35 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
expect(pair.gameSchedule).toEqual([]);
|
expect(pair.gameSchedule).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('creates a double-elimination bracket from built teams', () => {
|
||||||
|
const service = createService();
|
||||||
|
const match = createMatch({
|
||||||
|
gameMode: 'double-elimination',
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
|
||||||
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
it('creates a limited round-robin schedule grouped by playable rounds', () => {
|
||||||
const service = createService();
|
const service = createService();
|
||||||
const roundRobin = createMatch({
|
const roundRobin = createMatch({
|
||||||
@@ -266,6 +314,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
};
|
};
|
||||||
const service = new TournamentCodeService(
|
const service = new TournamentCodeService(
|
||||||
connectionService as never,
|
connectionService as never,
|
||||||
|
createAuctionRedisService() as never,
|
||||||
) as unknown as TournamentCodeServiceInternals;
|
) as unknown as TournamentCodeServiceInternals;
|
||||||
|
|
||||||
const slots = await service.buildSlots(
|
const slots = await service.buildSlots(
|
||||||
@@ -325,6 +374,40 @@ describe('TournamentCodeService round-robin scheduling', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('TournamentCodeService bulk upload', () => {
|
describe('TournamentCodeService bulk upload', () => {
|
||||||
|
it('defines unique 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({
|
||||||
|
unique: true,
|
||||||
|
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 () => {
|
it('preserves tournament code casing at the schema layer', async () => {
|
||||||
const connection = mongoose.createConnection();
|
const connection = mongoose.createConnection();
|
||||||
try {
|
try {
|
||||||
@@ -362,6 +445,7 @@ describe('TournamentCodeService bulk upload', () => {
|
|||||||
};
|
};
|
||||||
const service = new TournamentCodeService(
|
const service = new TournamentCodeService(
|
||||||
connectionService as never,
|
connectionService as never,
|
||||||
|
createAuctionRedisService() as never,
|
||||||
) as unknown as TournamentCodeServiceInternals;
|
) as unknown as TournamentCodeServiceInternals;
|
||||||
service.attachPendingMatches = jest.fn().mockResolvedValue(0);
|
service.attachPendingMatches = jest.fn().mockResolvedValue(0);
|
||||||
|
|
||||||
@@ -395,7 +479,10 @@ describe('TournamentCodeService pool stats', () => {
|
|||||||
const connectionService = {
|
const connectionService = {
|
||||||
getModel: jest.fn().mockResolvedValue({ countDocuments }),
|
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);
|
await expect(service.countUsableAvailable()).resolves.toBe(12);
|
||||||
expect(countDocuments).toHaveBeenCalledWith({
|
expect(countDocuments).toHaveBeenCalledWith({
|
||||||
@@ -446,7 +533,9 @@ describe('TournamentCodeService pending match attachment', () => {
|
|||||||
exec: jest.fn().mockResolvedValue({ _id: codeId }),
|
exec: jest.fn().mockResolvedValue({ _id: codeId }),
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
const session = createSession();
|
||||||
const connectionService = {
|
const connectionService = {
|
||||||
|
createSession: jest.fn().mockResolvedValue(session),
|
||||||
getModel: jest.fn().mockImplementation((modelName: string) => {
|
getModel: jest.fn().mockImplementation((modelName: string) => {
|
||||||
if (modelName === 'match') return Promise.resolve(MatchModel);
|
if (modelName === 'match') return Promise.resolve(MatchModel);
|
||||||
if (modelName === 'tournamentCode') {
|
if (modelName === 'tournamentCode') {
|
||||||
@@ -455,7 +544,11 @@ describe('TournamentCodeService pending match attachment', () => {
|
|||||||
throw new Error(`Unexpected model: ${modelName}`);
|
throw new Error(`Unexpected model: ${modelName}`);
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
const service = new TournamentCodeService(connectionService as never);
|
const auctionRedisService = createAuctionRedisService();
|
||||||
|
const service = new TournamentCodeService(
|
||||||
|
connectionService as never,
|
||||||
|
auctionRedisService as never,
|
||||||
|
);
|
||||||
|
|
||||||
const matches = await service.attachPendingMatchDocuments();
|
const matches = await service.attachPendingMatchDocuments();
|
||||||
|
|
||||||
@@ -463,6 +556,17 @@ describe('TournamentCodeService pending match attachment', () => {
|
|||||||
expect(MatchModel.findById).toHaveBeenCalledTimes(1);
|
expect(MatchModel.findById).toHaveBeenCalledTimes(1);
|
||||||
expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id);
|
expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id);
|
||||||
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
|
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([
|
expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([
|
||||||
codeId.toString(),
|
codeId.toString(),
|
||||||
]);
|
]);
|
||||||
@@ -538,8 +642,11 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
const TournamentCodeModel = {
|
const TournamentCodeModel = {
|
||||||
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
|
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
|
||||||
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
|
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
|
||||||
|
updateOne: jest.fn().mockReturnValue(queryResult({ modifiedCount: 1 })),
|
||||||
};
|
};
|
||||||
|
const session = createSession();
|
||||||
const connectionService = {
|
const connectionService = {
|
||||||
|
createSession: jest.fn().mockResolvedValue(session),
|
||||||
getModel: jest.fn().mockImplementation((modelName: string) => {
|
getModel: jest.fn().mockImplementation((modelName: string) => {
|
||||||
if (modelName === 'match') return Promise.resolve(MatchModel);
|
if (modelName === 'match') return Promise.resolve(MatchModel);
|
||||||
if (modelName === 'tournamentCode') {
|
if (modelName === 'tournamentCode') {
|
||||||
@@ -548,8 +655,10 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
throw new Error(`Unexpected model: ${modelName}`);
|
throw new Error(`Unexpected model: ${modelName}`);
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
const auctionRedisService = createAuctionRedisService();
|
||||||
const service = new TournamentCodeService(
|
const service = new TournamentCodeService(
|
||||||
connectionService as never,
|
connectionService as never,
|
||||||
|
auctionRedisService as never,
|
||||||
) as unknown as TournamentCodeServiceInternals;
|
) as unknown as TournamentCodeServiceInternals;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -560,6 +669,8 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
replacementCode,
|
replacementCode,
|
||||||
MatchModel,
|
MatchModel,
|
||||||
TournamentCodeModel,
|
TournamentCodeModel,
|
||||||
|
auctionRedisService,
|
||||||
|
session,
|
||||||
service,
|
service,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -573,6 +684,8 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
replacementCode,
|
replacementCode,
|
||||||
MatchModel,
|
MatchModel,
|
||||||
TournamentCodeModel,
|
TournamentCodeModel,
|
||||||
|
auctionRedisService,
|
||||||
|
session,
|
||||||
service,
|
service,
|
||||||
} = createReplacementFixture();
|
} = createReplacementFixture();
|
||||||
|
|
||||||
@@ -611,10 +724,30 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
}),
|
}),
|
||||||
expect.objectContaining({ returnDocument: 'after' }),
|
expect.objectContaining({ returnDocument: 'after' }),
|
||||||
);
|
);
|
||||||
expect(currentCode?.state).toBe('released');
|
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
|
||||||
expect(currentCode?.matchId).toBeUndefined();
|
`tournament-code:match:${matchId.toString()}:lock`,
|
||||||
expect(currentCode?.gameNumber).toBeUndefined();
|
expect.any(String),
|
||||||
expect(currentCode?.save).toHaveBeenCalled();
|
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([
|
expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([
|
||||||
replacementCode?._id.toString(),
|
replacementCode?._id.toString(),
|
||||||
]);
|
]);
|
||||||
@@ -652,8 +785,8 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
|
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('leaves the current code untouched when no replacement code is available', async () => {
|
it('aborts the transaction when no replacement code is available', async () => {
|
||||||
const { match, communityId, matchId, currentCode, service } =
|
const { match, communityId, matchId, currentCode, session, service } =
|
||||||
createReplacementFixture({
|
createReplacementFixture({
|
||||||
replacementCode: null,
|
replacementCode: null,
|
||||||
});
|
});
|
||||||
@@ -663,5 +796,6 @@ describe('TournamentCodeService code replacement', () => {
|
|||||||
).rejects.toThrow('No available tournament code');
|
).rejects.toThrow('No available tournament code');
|
||||||
expect(currentCode?.save).not.toHaveBeenCalled();
|
expect(currentCode?.save).not.toHaveBeenCalled();
|
||||||
expect(match.save).not.toHaveBeenCalled();
|
expect(match.save).not.toHaveBeenCalled();
|
||||||
|
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,11 +1,20 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
Injectable,
|
Injectable,
|
||||||
|
InternalServerErrorException,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import {
|
||||||
|
buildDoubleEliminationBracket,
|
||||||
|
findNextReadyDoubleEliminationBracketMatches,
|
||||||
|
} from '../double-elimination/double-elimination.util';
|
||||||
|
import { AuctionRedisService } from '../auction/redis/auction-redis.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type {
|
import type {
|
||||||
|
DoubleEliminationBracketMatch,
|
||||||
MatchGameAssignment,
|
MatchGameAssignment,
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
TournamentCode,
|
TournamentCode,
|
||||||
@@ -31,10 +40,15 @@ import {
|
|||||||
|
|
||||||
const DEFAULT_REGION = 'kr';
|
const DEFAULT_REGION = 'kr';
|
||||||
const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
|
const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
|
||||||
|
const TOURNAMENT_CODE_MATCH_LOCK_TTL_MS = 30_000;
|
||||||
|
const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3;
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TournamentCodeService {
|
export class TournamentCodeService {
|
||||||
constructor(private readonly connectionService: ConnectionService) {}
|
constructor(
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
private readonly auctionRedisService: AuctionRedisService,
|
||||||
|
) {}
|
||||||
|
|
||||||
public async bulkUpload(params: {
|
public async bulkUpload(params: {
|
||||||
communityId?: mongoose.Types.ObjectId;
|
communityId?: mongoose.Types.ObjectId;
|
||||||
@@ -226,21 +240,38 @@ export class TournamentCodeService {
|
|||||||
|
|
||||||
public async reserveForMatch(
|
public async reserveForMatch(
|
||||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
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> {
|
): Promise<MatchDocument> {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
await this.connectionService.getModel('tournamentCode');
|
await this.connectionService.getModel('tournamentCode');
|
||||||
const match =
|
const match = await this.execQuery<MatchDocument | null>(
|
||||||
matchOrId instanceof mongoose.Types.ObjectId
|
this.withQuerySession(MatchModel.findById(matchId), session),
|
||||||
? await MatchModel.findById(matchOrId)
|
);
|
||||||
: await MatchModel.findById(matchOrId._id);
|
|
||||||
if (!match) throw new NotFoundException('Match not found.');
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
|
|
||||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||||
this.ensureGameSchedule(match);
|
this.ensureGameSchedule(match);
|
||||||
|
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||||
|
return this.reserveForDoubleEliminationMatch(
|
||||||
|
match,
|
||||||
|
TournamentCodeModel,
|
||||||
|
session,
|
||||||
|
);
|
||||||
|
}
|
||||||
const shouldSaveMetadata =
|
const shouldSaveMetadata =
|
||||||
match.isModified('gameCount') || match.isModified('gameSchedule');
|
this.isMatchModified(match, 'gameCount') ||
|
||||||
|
this.isMatchModified(match, 'gameSchedule');
|
||||||
const requiredSlots = this.resolveRequiredSlots(match);
|
const requiredSlots = this.resolveRequiredSlots(match);
|
||||||
const need = requiredSlots - match.tournamentCodeIds.length;
|
const need = requiredSlots - match.tournamentCodeIds.length;
|
||||||
if (need <= 0) {
|
if (need <= 0) {
|
||||||
@@ -272,7 +303,7 @@ export class TournamentCodeService {
|
|||||||
},
|
},
|
||||||
$unset: { releasedAt: 1 },
|
$unset: { releasedAt: 1 },
|
||||||
},
|
},
|
||||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||||
).exec();
|
).exec();
|
||||||
if (!code) break;
|
if (!code) break;
|
||||||
reservedIds.push(code._id);
|
reservedIds.push(code._id);
|
||||||
@@ -282,7 +313,7 @@ export class TournamentCodeService {
|
|||||||
match.tournamentCodeIds.push(...reservedIds);
|
match.tournamentCodeIds.push(...reservedIds);
|
||||||
}
|
}
|
||||||
if (reservedIds.length > 0 || shouldSaveMetadata) {
|
if (reservedIds.length > 0 || shouldSaveMetadata) {
|
||||||
await match.save();
|
await match.save({ session });
|
||||||
}
|
}
|
||||||
return match;
|
return match;
|
||||||
}
|
}
|
||||||
@@ -292,13 +323,31 @@ export class TournamentCodeService {
|
|||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
}): Promise<TournamentCodeSlotView> {
|
}): 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 MatchModel = await this.connectionService.getModel('match');
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
await this.connectionService.getModel('tournamentCode');
|
await this.connectionService.getModel('tournamentCode');
|
||||||
const match = await MatchModel.findOne({
|
const match = await this.execQuery<MatchDocument | null>(
|
||||||
|
this.withQuerySession(
|
||||||
|
MatchModel.findOne({
|
||||||
_id: params.matchId,
|
_id: params.matchId,
|
||||||
communityId: params.communityId,
|
communityId: params.communityId,
|
||||||
}).exec();
|
}),
|
||||||
|
session,
|
||||||
|
),
|
||||||
|
);
|
||||||
if (!match) throw new NotFoundException('Match not found.');
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
if (match.status !== 'team-built' && match.status !== 'in-progress') {
|
if (match.status !== 'team-built' && match.status !== 'in-progress') {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
@@ -309,6 +358,13 @@ export class TournamentCodeService {
|
|||||||
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||||
this.ensureGameSchedule(match);
|
this.ensureGameSchedule(match);
|
||||||
|
const doubleEliminationBracketMatch =
|
||||||
|
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||||
|
? this.resolveDoubleEliminationBracketMatchByGameNumber(
|
||||||
|
match,
|
||||||
|
params.gameNumber,
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
const requiredSlots = this.resolveRequiredSlots(match);
|
const requiredSlots = this.resolveRequiredSlots(match);
|
||||||
if (
|
if (
|
||||||
@@ -320,7 +376,11 @@ export class TournamentCodeService {
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
(match.result?.games ?? []).some(
|
(match.result?.games ?? []).some(
|
||||||
(game) => game.gameNumber === params.gameNumber,
|
(game) =>
|
||||||
|
game.gameNumber === params.gameNumber ||
|
||||||
|
(doubleEliminationBracketMatch?.bracketMatchId &&
|
||||||
|
game.bracketMatchId ===
|
||||||
|
doubleEliminationBracketMatch.bracketMatchId),
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
@@ -328,11 +388,18 @@ export class TournamentCodeService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentCode = await TournamentCodeModel.findOne({
|
const currentCode = await this.execQuery<TournamentCodeDocument | null>(
|
||||||
|
this.withQuerySession(
|
||||||
|
TournamentCodeModel.findOne({
|
||||||
_id: { $in: match.tournamentCodeIds },
|
_id: { $in: match.tournamentCodeIds },
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
gameNumber: params.gameNumber,
|
...(doubleEliminationBracketMatch
|
||||||
}).exec();
|
? { bracketMatchId: doubleEliminationBracketMatch.bracketMatchId }
|
||||||
|
: { gameNumber: params.gameNumber }),
|
||||||
|
}),
|
||||||
|
session,
|
||||||
|
),
|
||||||
|
);
|
||||||
if (!currentCode) {
|
if (!currentCode) {
|
||||||
throw new NotFoundException('Assigned tournament code not found.');
|
throw new NotFoundException('Assigned tournament code not found.');
|
||||||
}
|
}
|
||||||
@@ -345,6 +412,25 @@ export class TournamentCodeService {
|
|||||||
const expiresAfter = new Date(
|
const expiresAfter = new Date(
|
||||||
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
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(
|
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
||||||
{
|
{
|
||||||
state: 'available',
|
state: 'available',
|
||||||
@@ -358,11 +444,16 @@ export class TournamentCodeService {
|
|||||||
state: 'reserved',
|
state: 'reserved',
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
gameNumber: params.gameNumber,
|
gameNumber: params.gameNumber,
|
||||||
|
...(doubleEliminationBracketMatch
|
||||||
|
? {
|
||||||
|
bracketMatchId: doubleEliminationBracketMatch.bracketMatchId,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
reservedAt: new Date(),
|
reservedAt: new Date(),
|
||||||
},
|
},
|
||||||
$unset: { releasedAt: 1 },
|
$unset: { releasedAt: 1 },
|
||||||
},
|
},
|
||||||
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||||
).exec();
|
).exec();
|
||||||
if (!replacement) {
|
if (!replacement) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
@@ -370,22 +461,18 @@ export class TournamentCodeService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
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 = this.replaceTournamentCodeId(
|
||||||
match.tournamentCodeIds,
|
match.tournamentCodeIds,
|
||||||
currentCode._id,
|
currentCode._id,
|
||||||
replacement._id,
|
replacement._id,
|
||||||
);
|
);
|
||||||
await currentCode.save();
|
await match.save({ session });
|
||||||
await match.save();
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
gameNumber: params.gameNumber,
|
gameNumber: params.gameNumber,
|
||||||
|
...(doubleEliminationBracketMatch
|
||||||
|
? this.toDoubleEliminationSlotBase(doubleEliminationBracketMatch)
|
||||||
|
: {}),
|
||||||
roundNumber: this.resolveRoundNumberForGameNumber(
|
roundNumber: this.resolveRoundNumberForGameNumber(
|
||||||
match,
|
match,
|
||||||
params.gameNumber,
|
params.gameNumber,
|
||||||
@@ -400,27 +487,46 @@ export class TournamentCodeService {
|
|||||||
|
|
||||||
public async releaseFromMatch(
|
public async releaseFromMatch(
|
||||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
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> {
|
): Promise<void> {
|
||||||
const MatchModel = await this.connectionService.getModel('match');
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
await this.connectionService.getModel('tournamentCode');
|
await this.connectionService.getModel('tournamentCode');
|
||||||
const match =
|
const match = await this.execQuery<MatchDocument | null>(
|
||||||
matchOrId instanceof mongoose.Types.ObjectId
|
this.withQuerySession(MatchModel.findById(matchId), session),
|
||||||
? await MatchModel.findById(matchOrId)
|
);
|
||||||
: await MatchModel.findById(matchOrId._id);
|
|
||||||
if (!match) return;
|
if (!match) return;
|
||||||
if (match.tournamentCodeIds.length === 0) return;
|
if (match.tournamentCodeIds.length === 0) return;
|
||||||
|
|
||||||
await TournamentCodeModel.updateMany(
|
await this.execQuery(
|
||||||
|
this.withQuerySession(
|
||||||
|
TournamentCodeModel.updateMany(
|
||||||
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
|
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
|
||||||
{
|
{
|
||||||
$set: { state: 'released', releasedAt: new Date() },
|
$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 = [];
|
match.tournamentCodeIds = [];
|
||||||
await match.save();
|
await match.save({ session });
|
||||||
}
|
}
|
||||||
|
|
||||||
public async markExpired(): Promise<number> {
|
public async markExpired(): Promise<number> {
|
||||||
@@ -483,6 +589,9 @@ export class TournamentCodeService {
|
|||||||
public async buildSlots(
|
public async buildSlots(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
): Promise<TournamentCodeSlotView[]> {
|
): Promise<TournamentCodeSlotView[]> {
|
||||||
|
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||||
|
return this.buildDoubleEliminationSlots(match);
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
(match.gameMode ?? 'pair') === 'round-robin' &&
|
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||||
(match.gameSchedule?.length ?? 0) === 0 &&
|
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||||
@@ -550,10 +659,240 @@ export class TournamentCodeService {
|
|||||||
return next;
|
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 readyBracketMatches = findNextReadyDoubleEliminationBracketMatches(
|
||||||
|
match.doubleElimination,
|
||||||
|
);
|
||||||
|
const existingCodes =
|
||||||
|
match.tournamentCodeIds.length > 0
|
||||||
|
? await this.execQuery<TournamentCodeDocument[]>(
|
||||||
|
this.withQuerySession(
|
||||||
|
TournamentCodeModel.find({
|
||||||
|
_id: { $in: match.tournamentCodeIds },
|
||||||
|
}),
|
||||||
|
session,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
const byBracketMatchId = new Map(
|
||||||
|
existingCodes
|
||||||
|
.filter(
|
||||||
|
(code) =>
|
||||||
|
code.bracketMatchId &&
|
||||||
|
(code.state === 'reserved' || code.state === 'used'),
|
||||||
|
)
|
||||||
|
.map((code) => [code.bracketMatchId as string, code]),
|
||||||
|
);
|
||||||
|
const expiresAfter = new Date(
|
||||||
|
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||||
|
);
|
||||||
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
|
|
||||||
|
for (const bracketMatch of readyBracketMatches) {
|
||||||
|
if (byBracketMatchId.has(bracketMatch.bracketMatchId)) 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: bracketMatch.gameNumber,
|
||||||
|
bracketMatchId: bracketMatch.bracketMatchId,
|
||||||
|
reservedAt: new Date(),
|
||||||
|
},
|
||||||
|
$unset: { releasedAt: 1 },
|
||||||
|
},
|
||||||
|
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
|
||||||
|
).exec();
|
||||||
|
if (!code) break;
|
||||||
|
reservedIds.push(code._id);
|
||||||
|
byBracketMatchId.set(bracketMatch.bracketMatchId, 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 TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const ids = match.tournamentCodeIds ?? [];
|
||||||
|
const codes =
|
||||||
|
ids.length > 0
|
||||||
|
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
||||||
|
: [];
|
||||||
|
const byBracketMatchId = new Map(
|
||||||
|
codes
|
||||||
|
.filter(
|
||||||
|
(code) =>
|
||||||
|
code.bracketMatchId &&
|
||||||
|
code.state !== 'released' &&
|
||||||
|
code.state !== 'voided',
|
||||||
|
)
|
||||||
|
.map((code) => [code.bracketMatchId as string, code]),
|
||||||
|
);
|
||||||
|
|
||||||
|
return bracketMatches.map((bracketMatch) => {
|
||||||
|
const code = byBracketMatchId.get(bracketMatch.bracketMatchId);
|
||||||
|
return {
|
||||||
|
...this.toDoubleEliminationSlotBase(bracketMatch),
|
||||||
|
code: code?.code ?? null,
|
||||||
|
expiresAt: code?.expiresAt.toISOString() ?? null,
|
||||||
|
state: code?.state ?? 'pending',
|
||||||
|
riotMatchId: code?.riotMatchId ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private toDoubleEliminationSlotBase(
|
||||||
|
bracketMatch: DoubleEliminationBracketMatch,
|
||||||
|
): Omit<TournamentCodeSlotView, 'code' | 'expiresAt' | 'state' | 'riotMatchId'> {
|
||||||
|
return {
|
||||||
|
gameNumber: bracketMatch.gameNumber,
|
||||||
|
bracketMatchId: bracketMatch.bracketMatchId,
|
||||||
|
bracketSide: bracketMatch.bracketSide,
|
||||||
|
roundNumber: bracketMatch.roundNumber,
|
||||||
|
matchNumber: bracketMatch.matchNumber,
|
||||||
|
teamAIndex: bracketMatch.teamAIndex,
|
||||||
|
teamBIndex: bracketMatch.teamBIndex,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private resolveRequiredSlots(match: MatchDocument): number {
|
private resolveRequiredSlots(match: MatchDocument): number {
|
||||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
|
if (gameMode === 'double-elimination') {
|
||||||
|
return match.doubleElimination?.bracketMatches.length ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
if (gameMode === 'round-robin') {
|
if (gameMode === 'round-robin') {
|
||||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||||
return match.gameSchedule.length;
|
return match.gameSchedule.length;
|
||||||
@@ -577,6 +916,17 @@ export class TournamentCodeService {
|
|||||||
): { teamAIndex: number; teamBIndex: number } {
|
): { teamAIndex: number; teamBIndex: number } {
|
||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
|
if (gameMode === 'double-elimination') {
|
||||||
|
const bracketMatch = this.resolveDoubleEliminationBracketMatchByGameNumber(
|
||||||
|
match,
|
||||||
|
gameNumber,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
teamAIndex: bracketMatch?.teamAIndex ?? 1,
|
||||||
|
teamBIndex: bracketMatch?.teamBIndex ?? 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (gameMode === 'round-robin') {
|
if (gameMode === 'round-robin') {
|
||||||
const persisted = match.gameSchedule?.find(
|
const persisted = match.gameSchedule?.find(
|
||||||
(entry) => entry.gameNumber === gameNumber,
|
(entry) => entry.gameNumber === gameNumber,
|
||||||
@@ -611,6 +961,10 @@ export class TournamentCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private ensureGameSchedule(match: MatchDocument): void {
|
private ensureGameSchedule(match: MatchDocument): void {
|
||||||
|
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||||
|
this.ensureDoubleEliminationBracket(match);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
|
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
|
||||||
if ((match.gameSchedule?.length ?? 0) > 0) return;
|
if ((match.gameSchedule?.length ?? 0) > 0) return;
|
||||||
|
|
||||||
@@ -620,6 +974,48 @@ export class TournamentCodeService {
|
|||||||
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
|
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,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
match.markModified?.('doubleElimination');
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveDoubleEliminationBracketMatchByGameNumber(
|
||||||
|
match: MatchDocument,
|
||||||
|
gameNumber: number,
|
||||||
|
): DoubleEliminationBracketMatch | undefined {
|
||||||
|
return match.doubleElimination?.bracketMatches.find(
|
||||||
|
(bracketMatch) => bracketMatch.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(
|
private resolveRoundNumberForGameNumber(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
gameNumber: number,
|
gameNumber: number,
|
||||||
|
|||||||
@@ -24,9 +24,12 @@ export interface BulkUploadTournamentCodesResponse {
|
|||||||
|
|
||||||
export interface TournamentCodeSlotView {
|
export interface TournamentCodeSlotView {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
|
bracketSide?: string;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
teamAIndex: number;
|
matchNumber?: number;
|
||||||
teamBIndex: number;
|
teamAIndex?: number;
|
||||||
|
teamBIndex?: number;
|
||||||
code: string | null;
|
code: string | null;
|
||||||
expiresAt: string | null;
|
expiresAt: string | null;
|
||||||
state: TournamentCodeState | 'pending';
|
state: TournamentCodeState | 'pending';
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import type { MatchDocument } from '../global/database/schema';
|
import type { MatchDocument } from '../global/database/schema';
|
||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import type { RiotMatchDto } from '../riot/riot.types';
|
import type { RiotMatchDto } from '../riot/riot.types';
|
||||||
import { TournamentResultService } from './tournament-result.service';
|
import { TournamentResultService } from './tournament-result.service';
|
||||||
|
|
||||||
@@ -10,18 +11,44 @@ type TournamentResultServiceInternals = TournamentResultService & {
|
|||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
gameNumber: number,
|
gameNumber: number,
|
||||||
): { teamAIndex: number; teamBIndex: number };
|
): { teamAIndex: number; teamBIndex: number };
|
||||||
|
buildSeriesResults(
|
||||||
|
games: NonNullable<MatchDocument['result']>['games'],
|
||||||
|
): NonNullable<MatchDocument['result']>['seriesResults'];
|
||||||
};
|
};
|
||||||
|
|
||||||
function createService() {
|
function createService() {
|
||||||
|
const distributedLockService = createDistributedLockService();
|
||||||
return new TournamentResultService(
|
return new TournamentResultService(
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
|
distributedLockService as never,
|
||||||
) as unknown as TournamentResultServiceInternals;
|
) 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 {
|
interface MatchOverrides {
|
||||||
gameCount?: number;
|
gameCount?: number;
|
||||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||||
@@ -100,6 +127,56 @@ describe('TournamentResultService round-robin scheduling', () => {
|
|||||||
teamBIndex: 4,
|
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,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('TournamentResultService tournament code polling', () => {
|
describe('TournamentResultService tournament code polling', () => {
|
||||||
@@ -228,12 +305,14 @@ describe('TournamentResultService tournament code polling', () => {
|
|||||||
const riotJobQueueService = {
|
const riotJobQueueService = {
|
||||||
enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined),
|
enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined),
|
||||||
};
|
};
|
||||||
|
const distributedLockService = createDistributedLockService();
|
||||||
const service = new TournamentResultService(
|
const service = new TournamentResultService(
|
||||||
connectionService as never,
|
connectionService as never,
|
||||||
riotMatchService as never,
|
riotMatchService as never,
|
||||||
riotJobQueueService as never,
|
riotJobQueueService as never,
|
||||||
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
|
distributedLockService as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
return { service, match, code, riotMatchService };
|
return { service, match, code, riotMatchService };
|
||||||
@@ -402,12 +481,14 @@ describe('TournamentResultService manual result collection', () => {
|
|||||||
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']),
|
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']),
|
||||||
getMatch: jest.fn().mockResolvedValue(detail),
|
getMatch: jest.fn().mockResolvedValue(detail),
|
||||||
};
|
};
|
||||||
|
const distributedLockService = createDistributedLockService();
|
||||||
const service = new TournamentResultService(
|
const service = new TournamentResultService(
|
||||||
connectionService as never,
|
connectionService as never,
|
||||||
riotMatchService as never,
|
riotMatchService as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
|
||||||
|
distributedLockService as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -5,12 +5,17 @@ import {
|
|||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import {
|
||||||
|
completeDoubleEliminationBracketMatch,
|
||||||
|
} from '../double-elimination/double-elimination.util';
|
||||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
||||||
import type {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
MatchGameResult,
|
MatchGameResult,
|
||||||
|
MatchSeriesResult,
|
||||||
RiotMatch as StoredRiotMatch,
|
RiotMatch as StoredRiotMatch,
|
||||||
TournamentCodeDocument,
|
TournamentCodeDocument,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
@@ -22,6 +27,7 @@ import {
|
|||||||
roundRobinGameSchedule,
|
roundRobinGameSchedule,
|
||||||
resolveRoundRobinTeamCount,
|
resolveRoundRobinTeamCount,
|
||||||
} from '../tournament-code/round-robin.util';
|
} from '../tournament-code/round-robin.util';
|
||||||
|
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants';
|
||||||
import {
|
import {
|
||||||
collectCaptainAndLimitedTeamMemberUserIds,
|
collectCaptainAndLimitedTeamMemberUserIds,
|
||||||
collectCaptainUserIds,
|
collectCaptainUserIds,
|
||||||
@@ -41,9 +47,16 @@ const POLL_EXPIRY_MS = 24 * 60 * 60_000;
|
|||||||
const EXPAND_AFTER_MS = 60 * 60_000;
|
const EXPAND_AFTER_MS = 60 * 60_000;
|
||||||
const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2;
|
const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2;
|
||||||
const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
|
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 {
|
interface ManualGameAssignment {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
teamAIndex: number;
|
teamAIndex: number;
|
||||||
teamBIndex: number;
|
teamBIndex: number;
|
||||||
}
|
}
|
||||||
@@ -58,11 +71,29 @@ export class TournamentResultService {
|
|||||||
private readonly riotJobQueueService: RiotJobQueueService,
|
private readonly riotJobQueueService: RiotJobQueueService,
|
||||||
private readonly communityStatsService: CommunityStatsService,
|
private readonly communityStatsService: CommunityStatsService,
|
||||||
private readonly matchStatsService: MatchStatsService,
|
private readonly matchStatsService: MatchStatsService,
|
||||||
|
private readonly distributedLockService: DistributedLockService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public async scheduleInitialPoll(
|
public async scheduleInitialPoll(
|
||||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||||
priority: RiotJobPriority = 'high',
|
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> {
|
): Promise<EnqueueTournamentResultPollResult | null> {
|
||||||
const match = await this.loadMatch(matchOrId);
|
const match = await this.loadMatch(matchOrId);
|
||||||
if (match.status === 'finished') return null;
|
if (match.status === 'finished') return null;
|
||||||
@@ -189,6 +220,29 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
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 MatchModel = await this.connectionService.getModel('match');
|
||||||
const TournamentCodeModel =
|
const TournamentCodeModel =
|
||||||
await this.connectionService.getModel('tournamentCode');
|
await this.connectionService.getModel('tournamentCode');
|
||||||
@@ -207,7 +261,11 @@ export class TournamentResultService {
|
|||||||
(code) => code.state === 'reserved' && !code.riotMatchId,
|
(code) => code.state === 'reserved' && !code.riotMatchId,
|
||||||
);
|
);
|
||||||
if (unmatched.length === 0) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -324,6 +382,7 @@ export class TournamentResultService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
gameResult.bracketMatchId = code.bracketMatchId;
|
||||||
code.state = 'used';
|
code.state = 'used';
|
||||||
code.usedAt = new Date(
|
code.usedAt = new Date(
|
||||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||||
@@ -332,10 +391,12 @@ export class TournamentResultService {
|
|||||||
await code.save();
|
await code.save();
|
||||||
|
|
||||||
this.upsertGameResult(match, gameResult);
|
this.upsertGameResult(match, gameResult);
|
||||||
|
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
||||||
if (match.status === 'team-built') {
|
if (match.status === 'team-built') {
|
||||||
match.status = 'in-progress';
|
match.status = 'in-progress';
|
||||||
}
|
}
|
||||||
await match.save();
|
await match.save();
|
||||||
|
await this.reserveReadyDoubleEliminationCodes(match);
|
||||||
await this.rebuildMatchStatsSafe(match);
|
await this.rebuildMatchStatsSafe(match);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -365,6 +426,7 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.upsertGameResult(match, gameResult);
|
this.upsertGameResult(match, gameResult);
|
||||||
|
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
|
||||||
await this.markTournamentCodeUsedForManualResult(
|
await this.markTournamentCodeUsedForManualResult(
|
||||||
match,
|
match,
|
||||||
gameResult,
|
gameResult,
|
||||||
@@ -379,6 +441,9 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
|
||||||
await match.save();
|
await match.save();
|
||||||
|
if (appliedRiotMatchIds.length > 0) {
|
||||||
|
await this.reserveReadyDoubleEliminationCodes(match);
|
||||||
|
}
|
||||||
if (appliedRiotMatchIds.length > 0) {
|
if (appliedRiotMatchIds.length > 0) {
|
||||||
await this.rebuildMatchStatsSafe(match);
|
await this.rebuildMatchStatsSafe(match);
|
||||||
}
|
}
|
||||||
@@ -399,6 +464,36 @@ export class TournamentResultService {
|
|||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
codes: TournamentCodeDocument[],
|
codes: TournamentCodeDocument[],
|
||||||
): Promise<boolean> {
|
): 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.length < this.resolveRequiredGameSlots(match)) return false;
|
||||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||||
return false;
|
return false;
|
||||||
@@ -585,7 +680,10 @@ export class TournamentResultService {
|
|||||||
const seriesResults = this.buildSeriesResults(games);
|
const seriesResults = this.buildSeriesResults(games);
|
||||||
|
|
||||||
match.result = {
|
match.result = {
|
||||||
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
|
winnerTeamIndex:
|
||||||
|
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||||
|
? match.doubleElimination?.placements.firstTeamIndex
|
||||||
|
: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||||
mvpUserId: match.result?.mvpUserId,
|
mvpUserId: match.result?.mvpUserId,
|
||||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||||
games,
|
games,
|
||||||
@@ -607,7 +705,10 @@ export class TournamentResultService {
|
|||||||
teamAIndex: assignment.teamAIndex,
|
teamAIndex: assignment.teamAIndex,
|
||||||
teamBIndex: assignment.teamBIndex,
|
teamBIndex: assignment.teamBIndex,
|
||||||
});
|
});
|
||||||
if (gameResult) return gameResult;
|
if (gameResult) {
|
||||||
|
gameResult.bracketMatchId = assignment.bracketMatchId;
|
||||||
|
return gameResult;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -618,7 +719,26 @@ export class TournamentResultService {
|
|||||||
const usedGameNumbers = new Set(
|
const usedGameNumbers = new Set(
|
||||||
(match.result?.games ?? []).map((game) => game.gameNumber),
|
(match.result?.games ?? []).map((game) => game.gameNumber),
|
||||||
);
|
);
|
||||||
|
const usedBracketMatchIds = new Set(
|
||||||
|
(match.result?.games ?? [])
|
||||||
|
.map((game) => game.bracketMatchId)
|
||||||
|
.filter((id): id is string => Boolean(id)),
|
||||||
|
);
|
||||||
const assignments: ManualGameAssignment[] = [];
|
const assignments: ManualGameAssignment[] = [];
|
||||||
|
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||||
|
for (const bracketMatch of match.doubleElimination?.bracketMatches ?? []) {
|
||||||
|
if (bracketMatch.state !== 'ready') continue;
|
||||||
|
if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue;
|
||||||
|
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
|
||||||
|
assignments.push({
|
||||||
|
gameNumber: bracketMatch.gameNumber,
|
||||||
|
bracketMatchId: bracketMatch.bracketMatchId,
|
||||||
|
teamAIndex: bracketMatch.teamAIndex,
|
||||||
|
teamBIndex: bracketMatch.teamBIndex,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return assignments;
|
||||||
|
}
|
||||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||||
|
|
||||||
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
|
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
|
||||||
@@ -641,6 +761,9 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private hasAllRequiredGameResults(match: MatchDocument): boolean {
|
private hasAllRequiredGameResults(match: MatchDocument): boolean {
|
||||||
|
if ((match.gameMode ?? 'pair') === 'double-elimination') {
|
||||||
|
return this.isDoubleEliminationComplete(match);
|
||||||
|
}
|
||||||
const requiredSlots = this.resolveRequiredGameSlots(match);
|
const requiredSlots = this.resolveRequiredGameSlots(match);
|
||||||
if (requiredSlots <= 0) return false;
|
if (requiredSlots <= 0) return false;
|
||||||
const resultGameNumbers = new Set(
|
const resultGameNumbers = new Set(
|
||||||
@@ -671,9 +794,10 @@ export class TournamentResultService {
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
match.status = 'finished';
|
match.status = 'finished';
|
||||||
if (match.result) {
|
if (match.result) {
|
||||||
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
|
match.result.winnerTeamIndex =
|
||||||
match.result.seriesResults ?? [],
|
(match.gameMode ?? 'pair') === 'double-elimination'
|
||||||
);
|
? match.doubleElimination?.placements.firstTeamIndex
|
||||||
|
: this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []);
|
||||||
}
|
}
|
||||||
match.resultPollState = {
|
match.resultPollState = {
|
||||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||||
@@ -708,6 +832,124 @@ export class TournamentResultService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private advanceDoubleEliminationIfNeeded(
|
||||||
|
match: MatchDocument,
|
||||||
|
gameResult: MatchGameResult,
|
||||||
|
completedBy: 'riot-result' | 'walkover',
|
||||||
|
): void {
|
||||||
|
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
|
||||||
|
if (!match.doubleElimination || !gameResult.bracketMatchId) return;
|
||||||
|
match.doubleElimination = completeDoubleEliminationBracketMatch(
|
||||||
|
match.doubleElimination,
|
||||||
|
{
|
||||||
|
bracketMatchId: gameResult.bracketMatchId,
|
||||||
|
winnerTeamIndex: gameResult.winnerTeamIndex,
|
||||||
|
completedBy,
|
||||||
|
completedAt: new Date(gameResult.gameCreation),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (match.result && this.isDoubleEliminationComplete(match)) {
|
||||||
|
match.result.winnerTeamIndex =
|
||||||
|
match.doubleElimination!.placements.firstTeamIndex;
|
||||||
|
}
|
||||||
|
match.markModified?.('doubleElimination');
|
||||||
|
}
|
||||||
|
|
||||||
|
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 readyBracketMatches = (match.doubleElimination?.bracketMatches ?? [])
|
||||||
|
.filter((bracketMatch) => bracketMatch.state === 'ready');
|
||||||
|
if (readyBracketMatches.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 existingByBracketMatchId = new Map(
|
||||||
|
existingCodes
|
||||||
|
.filter(
|
||||||
|
(code) =>
|
||||||
|
code.bracketMatchId &&
|
||||||
|
(code.state === 'reserved' || code.state === 'used'),
|
||||||
|
)
|
||||||
|
.map((code) => [code.bracketMatchId as string, code]),
|
||||||
|
);
|
||||||
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
|
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||||
|
|
||||||
|
for (const bracketMatch of readyBracketMatches) {
|
||||||
|
if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) 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: bracketMatch.gameNumber,
|
||||||
|
bracketMatchId: 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(
|
private async markTournamentCodeUsedForManualResult(
|
||||||
match: MatchDocument,
|
match: MatchDocument,
|
||||||
gameResult: MatchGameResult,
|
gameResult: MatchGameResult,
|
||||||
@@ -718,7 +960,9 @@ export class TournamentResultService {
|
|||||||
await TournamentCodeModel.updateOne(
|
await TournamentCodeModel.updateOne(
|
||||||
{
|
{
|
||||||
matchId: match._id,
|
matchId: match._id,
|
||||||
gameNumber: gameResult.gameNumber,
|
...(gameResult.bracketMatchId
|
||||||
|
? { bracketMatchId: gameResult.bracketMatchId }
|
||||||
|
: { gameNumber: gameResult.gameNumber }),
|
||||||
state: { $in: ['reserved', 'released'] },
|
state: { $in: ['reserved', 'released'] },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -728,6 +972,9 @@ export class TournamentResultService {
|
|||||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||||
),
|
),
|
||||||
riotMatchId: detail.metadata.matchId,
|
riotMatchId: detail.metadata.matchId,
|
||||||
|
...(gameResult.bracketMatchId
|
||||||
|
? { bracketMatchId: gameResult.bracketMatchId }
|
||||||
|
: {}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
).exec();
|
).exec();
|
||||||
@@ -736,22 +983,14 @@ export class TournamentResultService {
|
|||||||
private buildSeriesResults(
|
private buildSeriesResults(
|
||||||
games: MatchGameResult[],
|
games: MatchGameResult[],
|
||||||
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
): NonNullable<MatchDocument['result']>['seriesResults'] {
|
||||||
const bySeries = new Map<
|
const bySeries = new Map<string, MatchSeriesResult>();
|
||||||
string,
|
|
||||||
{
|
|
||||||
teamAIndex: number;
|
|
||||||
teamBIndex: number;
|
|
||||||
teamAWins: number;
|
|
||||||
teamBWins: number;
|
|
||||||
winnerTeamIndex?: number;
|
|
||||||
}
|
|
||||||
>();
|
|
||||||
|
|
||||||
for (const game of games) {
|
for (const game of games) {
|
||||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||||
const teamBIndex = Math.max(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) ?? {
|
const current = bySeries.get(key) ?? {
|
||||||
|
bracketMatchId: game.bracketMatchId,
|
||||||
teamAIndex,
|
teamAIndex,
|
||||||
teamBIndex,
|
teamBIndex,
|
||||||
teamAWins: 0,
|
teamAWins: 0,
|
||||||
@@ -770,6 +1009,9 @@ export class TournamentResultService {
|
|||||||
|
|
||||||
return [...bySeries.values()].sort(
|
return [...bySeries.values()].sort(
|
||||||
(left, right) =>
|
(left, right) =>
|
||||||
|
(left.bracketMatchId ?? '').localeCompare(
|
||||||
|
right.bracketMatchId ?? '',
|
||||||
|
) ||
|
||||||
left.teamAIndex - right.teamAIndex ||
|
left.teamAIndex - right.teamAIndex ||
|
||||||
left.teamBIndex - right.teamBIndex,
|
left.teamBIndex - right.teamBIndex,
|
||||||
);
|
);
|
||||||
@@ -781,6 +1023,21 @@ export class TournamentResultService {
|
|||||||
): { teamAIndex: number; teamBIndex: number } {
|
): { teamAIndex: number; teamBIndex: number } {
|
||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
|
if (gameMode === 'double-elimination') {
|
||||||
|
const bracketMatch = match.doubleElimination?.bracketMatches.find(
|
||||||
|
(entry) => entry.gameNumber === gameNumber,
|
||||||
|
);
|
||||||
|
return bracketMatch
|
||||||
|
? {
|
||||||
|
teamAIndex: bracketMatch.teamAIndex ?? 1,
|
||||||
|
teamBIndex: bracketMatch.teamBIndex ?? 2,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if (gameMode === 'round-robin') {
|
if (gameMode === 'round-robin') {
|
||||||
const persisted = match.gameSchedule?.find(
|
const persisted = match.gameSchedule?.find(
|
||||||
(entry) => entry.gameNumber === gameNumber,
|
(entry) => entry.gameNumber === gameNumber,
|
||||||
@@ -816,6 +1073,9 @@ export class TournamentResultService {
|
|||||||
|
|
||||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||||
const gameMode = match.gameMode ?? 'pair';
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
if (gameMode === 'double-elimination') {
|
||||||
|
return match.doubleElimination?.bracketMatches.length ?? 0;
|
||||||
|
}
|
||||||
if (gameMode === 'round-robin') {
|
if (gameMode === 'round-robin') {
|
||||||
if ((match.gameSchedule?.length ?? 0) > 0) {
|
if ((match.gameSchedule?.length ?? 0) > 0) {
|
||||||
return match.gameSchedule.length;
|
return match.gameSchedule.length;
|
||||||
@@ -941,6 +1201,24 @@ export class TournamentResultService {
|
|||||||
if (!match) throw new NotFoundException('Match not found.');
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
return match;
|
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 {
|
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { INestApplicationContext } from '@nestjs/common';
|
import { INestApplicationContext } from '@nestjs/common';
|
||||||
import { IoAdapter } from '@nestjs/platform-socket.io';
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
||||||
import { createAdapter } from '@socket.io/redis-adapter';
|
import { createAdapter } from '@socket.io/redis-adapter';
|
||||||
import type { ServerOptions } from 'socket.io';
|
import type { Server, ServerOptions } from 'socket.io';
|
||||||
import {
|
import {
|
||||||
AuctionRedisService,
|
AuctionRedisService,
|
||||||
type AuctionRedisClient,
|
type AuctionRedisClient,
|
||||||
@@ -26,8 +26,8 @@ export class RedisIoAdapter extends IoAdapter {
|
|||||||
this.adapterConstructor = createAdapter(pubClient, this.subClient);
|
this.adapterConstructor = createAdapter(pubClient, this.subClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
override createIOServer(port: number, options?: ServerOptions) {
|
override createIOServer(port: number, options?: ServerOptions): Server {
|
||||||
const server = super.createIOServer(port, options);
|
const server = super.createIOServer(port, options) as Server;
|
||||||
if (this.adapterConstructor) {
|
if (this.adapterConstructor) {
|
||||||
server.adapter(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;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -170,6 +170,10 @@ function App() {
|
|||||||
path="/communities/:cid/internal-stats/match/:matchId"
|
path="/communities/:cid/internal-stats/match/:matchId"
|
||||||
element={<InternalMatchDetailPage />}
|
element={<InternalMatchDetailPage />}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="/communities/:cid/internal-stats/match/:matchId/game/:gameNumber"
|
||||||
|
element={<MatchGameDetailPage />}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/admin/communities/:cid/matches"
|
path="/admin/communities/:cid/matches"
|
||||||
element={<MatchAdminPage />}
|
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(
|
function createUserHistoryPath(
|
||||||
communityId: string,
|
communityId: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
ApiRiotRecentStatsSummary,
|
ApiRiotRecentStatsSummary,
|
||||||
ApiTierHistoryEntry,
|
ApiTierHistoryEntry,
|
||||||
ApiTierInfo,
|
ApiTierInfo,
|
||||||
|
ApiDoubleEliminationBracket,
|
||||||
MatchStatus,
|
MatchStatus,
|
||||||
Position,
|
Position,
|
||||||
RiotLane,
|
RiotLane,
|
||||||
@@ -53,6 +54,7 @@ export interface MatchDetailView {
|
|||||||
maxParticipants: number;
|
maxParticipants: number;
|
||||||
gameCount: number;
|
gameCount: number;
|
||||||
gameMode: ApiMatch["gameMode"];
|
gameMode: ApiMatch["gameMode"];
|
||||||
|
doubleElimination?: ApiDoubleEliminationBracket;
|
||||||
tournamentCodes: TournamentCodeSlotView[];
|
tournamentCodes: TournamentCodeSlotView[];
|
||||||
joined: boolean;
|
joined: boolean;
|
||||||
participants: ParticipantView[];
|
participants: ParticipantView[];
|
||||||
@@ -63,6 +65,7 @@ export interface MatchDetailView {
|
|||||||
riotMatchIds: string[];
|
riotMatchIds: string[];
|
||||||
games: Array<{
|
games: Array<{
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
blueTeamIndex: number;
|
blueTeamIndex: number;
|
||||||
redTeamIndex: number;
|
redTeamIndex: number;
|
||||||
@@ -462,6 +465,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
|||||||
maxParticipants: match.maxParticipants,
|
maxParticipants: match.maxParticipants,
|
||||||
gameCount: match.gameCount ?? 3,
|
gameCount: match.gameCount ?? 3,
|
||||||
gameMode: match.gameMode ?? "pair",
|
gameMode: match.gameMode ?? "pair",
|
||||||
|
doubleElimination: match.doubleElimination,
|
||||||
tournamentCodes: match.tournamentCodes ?? [],
|
tournamentCodes: match.tournamentCodes ?? [],
|
||||||
joined: Boolean(match.joined),
|
joined: Boolean(match.joined),
|
||||||
participants,
|
participants,
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||||
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
|
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
|
||||||
export type TeamSide = 'blue' | 'red';
|
export type TeamSide = 'blue' | 'red';
|
||||||
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
|
export type MatchGameMode =
|
||||||
|
| 'pair'
|
||||||
|
| 'bracket'
|
||||||
|
| 'round-robin'
|
||||||
|
| 'double-elimination';
|
||||||
export type MatchStatus =
|
export type MatchStatus =
|
||||||
| 'recruiting'
|
| 'recruiting'
|
||||||
| 'team-built'
|
| 'team-built'
|
||||||
@@ -136,15 +140,19 @@ export type TournamentCodeState =
|
|||||||
| 'reserved'
|
| 'reserved'
|
||||||
| 'used'
|
| 'used'
|
||||||
| 'expired'
|
| 'expired'
|
||||||
| 'released';
|
| 'released'
|
||||||
|
| 'voided';
|
||||||
|
|
||||||
export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
||||||
|
|
||||||
export interface TournamentCodeSlotView {
|
export interface TournamentCodeSlotView {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
|
bracketSide?: string;
|
||||||
roundNumber?: number;
|
roundNumber?: number;
|
||||||
teamAIndex: number;
|
matchNumber?: number;
|
||||||
teamBIndex: number;
|
teamAIndex?: number;
|
||||||
|
teamBIndex?: number;
|
||||||
code: string | null;
|
code: string | null;
|
||||||
expiresAt: string | null;
|
expiresAt: string | null;
|
||||||
state: TournamentCodeSlotState;
|
state: TournamentCodeSlotState;
|
||||||
@@ -189,6 +197,7 @@ export interface ApiMatchGameResultParticipant {
|
|||||||
|
|
||||||
export interface ApiMatchGameResult {
|
export interface ApiMatchGameResult {
|
||||||
gameNumber: number;
|
gameNumber: number;
|
||||||
|
bracketMatchId?: string;
|
||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
blueTeamIndex: number;
|
blueTeamIndex: number;
|
||||||
redTeamIndex: number;
|
redTeamIndex: number;
|
||||||
@@ -205,6 +214,7 @@ export interface ApiMatchResult {
|
|||||||
riotMatchIds: string[];
|
riotMatchIds: string[];
|
||||||
games: ApiMatchGameResult[];
|
games: ApiMatchGameResult[];
|
||||||
seriesResults?: Array<{
|
seriesResults?: Array<{
|
||||||
|
bracketMatchId?: string;
|
||||||
teamAIndex: number;
|
teamAIndex: number;
|
||||||
teamBIndex: number;
|
teamBIndex: number;
|
||||||
teamAWins: number;
|
teamAWins: number;
|
||||||
@@ -225,6 +235,56 @@ export interface ApiMatchGameAssignment {
|
|||||||
teamBIndex: number;
|
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;
|
||||||
|
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 {
|
export interface ManualTournamentResultCollectResponse {
|
||||||
scanned: number;
|
scanned: number;
|
||||||
matched: number;
|
matched: number;
|
||||||
@@ -247,6 +307,7 @@ export interface ApiMatch {
|
|||||||
gameMode: MatchGameMode;
|
gameMode: MatchGameMode;
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
gameSchedule?: ApiMatchGameAssignment[];
|
gameSchedule?: ApiMatchGameAssignment[];
|
||||||
|
doubleElimination?: ApiDoubleEliminationBracket;
|
||||||
tournamentCodes?: TournamentCodeSlotView[];
|
tournamentCodes?: TournamentCodeSlotView[];
|
||||||
hostUserId?: string;
|
hostUserId?: string;
|
||||||
participants: ApiMatchParticipant[];
|
participants: ApiMatchParticipant[];
|
||||||
@@ -407,6 +468,7 @@ export interface MatchMutationRequest {
|
|||||||
gameCount?: number;
|
gameCount?: number;
|
||||||
gameMode?: MatchGameMode;
|
gameMode?: MatchGameMode;
|
||||||
roundRobinMaxRounds?: number;
|
roundRobinMaxRounds?: number;
|
||||||
|
doubleEliminationResetFinalEnabled?: boolean;
|
||||||
prizes?: string[];
|
prizes?: string[];
|
||||||
notices?: string[];
|
notices?: string[];
|
||||||
schedule?: ApiMatchScheduleItem[];
|
schedule?: ApiMatchScheduleItem[];
|
||||||
@@ -420,6 +482,8 @@ export interface DdragonChampionEntry {
|
|||||||
export interface DdragonSummonerSpellEntry {
|
export interface DdragonSummonerSpellEntry {
|
||||||
key: string;
|
key: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
description: string;
|
||||||
|
tooltip: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DdragonRuneEntry {
|
export interface DdragonRuneEntry {
|
||||||
@@ -427,12 +491,26 @@ export interface DdragonRuneEntry {
|
|||||||
key: string;
|
key: string;
|
||||||
icon: string;
|
icon: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
shortDesc: string;
|
||||||
|
longDesc: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
export interface DdragonRuneStyleEntry extends DdragonRuneEntry {
|
||||||
slots: Array<{ runes: 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 {
|
export interface DdragonManifest {
|
||||||
version: string;
|
version: string;
|
||||||
cdn: string;
|
cdn: string;
|
||||||
@@ -440,6 +518,7 @@ export interface DdragonManifest {
|
|||||||
champions: Record<string, DdragonChampionEntry>;
|
champions: Record<string, DdragonChampionEntry>;
|
||||||
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
summonerSpells: Record<string, DdragonSummonerSpellEntry>;
|
||||||
runesReforged: DdragonRuneStyleEntry[];
|
runesReforged: DdragonRuneStyleEntry[];
|
||||||
|
items: Record<string, DdragonItemEntry>;
|
||||||
fetchedAt: string;
|
fetchedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -2,6 +2,25 @@ import type { DdragonManifest } from '../api/types';
|
|||||||
|
|
||||||
const FALLBACK_VERSION = '15.24.1';
|
const FALLBACK_VERSION = '15.24.1';
|
||||||
const FALLBACK_CDN = 'https://ddragon.leagueoflegends.com/cdn';
|
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) {
|
function cdn(manifest: DdragonManifest | null | undefined) {
|
||||||
return manifest?.cdn ?? FALLBACK_CDN;
|
return manifest?.cdn ?? FALLBACK_CDN;
|
||||||
@@ -42,6 +61,34 @@ export function itemIconUrl(
|
|||||||
return `${cdn(manifest)}/${version(manifest)}/img/item/${itemId}.png`;
|
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(
|
export function summonerSpellIconUrl(
|
||||||
manifest: DdragonManifest | null | undefined,
|
manifest: DdragonManifest | null | undefined,
|
||||||
spellId: number,
|
spellId: number,
|
||||||
@@ -51,21 +98,44 @@ export function summonerSpellIconUrl(
|
|||||||
return `${cdn(manifest)}/${version(manifest)}/img/spell/${spell.key}.png`;
|
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(
|
export function runeStyleIconUrl(
|
||||||
manifest: DdragonManifest | null | undefined,
|
manifest: DdragonManifest | null | undefined,
|
||||||
styleId: number | 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;
|
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(
|
export function runeKeystoneIconUrl(
|
||||||
manifest: DdragonManifest | null | undefined,
|
manifest: DdragonManifest | null | undefined,
|
||||||
runeId: number | undefined,
|
runeId: number | undefined,
|
||||||
) {
|
) {
|
||||||
const rune = manifest?.runesReforged
|
const rune = runeDetails(manifest, runeId);
|
||||||
.flatMap((style) => style.slots.flatMap((slot) => slot.runes))
|
|
||||||
.find((entry) => entry.id === runeId);
|
|
||||||
|
|
||||||
return rune ? `${cdn(manifest)}/img/${rune.icon}` : null;
|
return rune ? `${cdn(manifest)}/img/${rune.icon}` : null;
|
||||||
}
|
}
|
||||||
@@ -76,3 +146,12 @@ export function runeIconUrl(
|
|||||||
) {
|
) {
|
||||||
return runeKeystoneIconUrl(manifest, runeId);
|
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}`;
|
||||||
|
}
|
||||||
@@ -50,6 +50,7 @@ import {
|
|||||||
teamIndexColorClasses,
|
teamIndexColorClasses,
|
||||||
teamIndexLabel,
|
teamIndexLabel,
|
||||||
} from "../lib/league";
|
} from "../lib/league";
|
||||||
|
import { internalMatchGamePath } from "../lib/internal-match-routes";
|
||||||
import { formatRankDetail, RankBadge } from "../components/RankBadge";
|
import { formatRankDetail, RankBadge } from "../components/RankBadge";
|
||||||
import type {
|
import type {
|
||||||
ApiAuction,
|
ApiAuction,
|
||||||
@@ -780,7 +781,11 @@ function InternalRecentMatchRow({
|
|||||||
const resultTone = match.win ? "text-blue-400" : "text-red-400";
|
const resultTone = match.win ? "text-blue-400" : "text-red-400";
|
||||||
const detailPath =
|
const detailPath =
|
||||||
match.internalMatchId && match.gameNumber
|
match.internalMatchId && match.gameNumber
|
||||||
? `/match/${match.internalMatchId}/game/${match.gameNumber}`
|
? internalMatchGamePath(
|
||||||
|
DEFAULT_COMMUNITY_ID,
|
||||||
|
match.internalMatchId,
|
||||||
|
match.gameNumber,
|
||||||
|
)
|
||||||
: null;
|
: null;
|
||||||
const content = (
|
const content = (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -5,14 +5,15 @@ import { DEFAULT_COMMUNITY_ID } from "../config";
|
|||||||
import {
|
import {
|
||||||
championDisplayName,
|
championDisplayName,
|
||||||
championIconUrl,
|
championIconUrl,
|
||||||
itemIconUrl,
|
|
||||||
} from "../lib/ddragon";
|
} from "../lib/ddragon";
|
||||||
import {
|
import {
|
||||||
sideShortLabel,
|
sideShortLabel,
|
||||||
teamIndexColorClasses,
|
teamIndexColorClasses,
|
||||||
teamIndexLabel,
|
teamIndexLabel,
|
||||||
} from "../lib/league";
|
} from "../lib/league";
|
||||||
|
import { internalMatchGamePath } from "../lib/internal-match-routes";
|
||||||
import { LANE_LABELS } from "../lib/riot-history";
|
import { LANE_LABELS } from "../lib/riot-history";
|
||||||
|
import { ItemIcon } from "../components/ItemTooltip";
|
||||||
|
|
||||||
function formatDateTime(value: string | number) {
|
function formatDateTime(value: string | number) {
|
||||||
return new Intl.DateTimeFormat("ko-KR", {
|
return new Intl.DateTimeFormat("ko-KR", {
|
||||||
@@ -71,27 +72,28 @@ function ItemStrip({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-wrap gap-1">
|
<div className="flex flex-wrap gap-1">
|
||||||
{[...items, trinket].map((itemId, index) => {
|
{[...items, trinket].map((itemId, index) => (
|
||||||
const icon = itemIconUrl(manifest, itemId);
|
<ItemIcon
|
||||||
return (
|
|
||||||
<span
|
|
||||||
key={`${itemId}-${index}`}
|
key={`${itemId}-${index}`}
|
||||||
className="w-5 h-5 bg-base-content/10 border border-base-content/5 overflow-hidden"
|
itemId={itemId}
|
||||||
>
|
manifest={manifest}
|
||||||
{icon ? (
|
trinket={index === items.length}
|
||||||
<img src={icon} alt="" className="w-full h-full object-cover" />
|
className="h-5 w-5"
|
||||||
) : null}
|
imageClassName=""
|
||||||
</span>
|
/>
|
||||||
);
|
))}
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function GamePanel({
|
function GamePanel({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
game,
|
game,
|
||||||
manifest,
|
manifest,
|
||||||
}: {
|
}: {
|
||||||
|
communityId: string;
|
||||||
|
matchId: string;
|
||||||
game: ApiInternalMatchDetailResponse["games"][number];
|
game: ApiInternalMatchDetailResponse["games"][number];
|
||||||
manifest: ReturnType<typeof useDdragonManifest>["data"];
|
manifest: ReturnType<typeof useDdragonManifest>["data"];
|
||||||
}) {
|
}) {
|
||||||
@@ -112,6 +114,13 @@ function GamePanel({
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<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) => (
|
{game.teams.map((team) => (
|
||||||
<span
|
<span
|
||||||
key={team.side}
|
key={team.side}
|
||||||
@@ -316,7 +325,13 @@ export default function InternalMatchDetailPage() {
|
|||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{detail.games.map((game) => (
|
{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>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
+1183
-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: "페어 매치",
|
pair: "페어 매치",
|
||||||
bracket: "토너먼트",
|
bracket: "토너먼트",
|
||||||
"round-robin": "리그전",
|
"round-robin": "리그전",
|
||||||
|
"double-elimination": "더블 엘리미네이션",
|
||||||
};
|
};
|
||||||
|
|
||||||
function resultBadgeClass(won: boolean) {
|
function resultBadgeClass(won: boolean) {
|
||||||
return won
|
return won
|
||||||
? "border-blue-500/20 bg-blue-500/10 text-blue-400"
|
? "border-info/20 bg-info/10 text-info"
|
||||||
: "border-red-500/20 bg-red-500/10 text-red-400";
|
: "border-error/20 bg-error/10 text-error";
|
||||||
}
|
}
|
||||||
|
|
||||||
function captainName(
|
function captainName(
|
||||||
@@ -131,7 +132,7 @@ function ParticipantLine({
|
|||||||
{name}
|
{name}
|
||||||
</span>
|
</span>
|
||||||
{isCaptain && (
|
{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>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -191,9 +192,11 @@ function UpcomingGameCard({
|
|||||||
const opponentIndex =
|
const opponentIndex =
|
||||||
slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex;
|
slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex;
|
||||||
const ourTeam = teamByIndex.get(parsedTeamIndex);
|
const ourTeam = teamByIndex.get(parsedTeamIndex);
|
||||||
const opponentTeam = teamByIndex.get(opponentIndex);
|
const opponentTeam = opponentIndex ? teamByIndex.get(opponentIndex) : undefined;
|
||||||
const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name);
|
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 ourCaptainName = captainName(ourTeam, participantByUserId);
|
||||||
const opponentCaptainName = captainName(opponentTeam, participantByUserId);
|
const opponentCaptainName = captainName(opponentTeam, participantByUserId);
|
||||||
const opponentMembers = opponentTeam?.members ?? [];
|
const opponentMembers = opponentTeam?.members ?? [];
|
||||||
@@ -433,7 +436,7 @@ function TeamGameCardsSection({
|
|||||||
|
|
||||||
<div className="p-4">
|
<div className="p-4">
|
||||||
{replaceError && (
|
{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}
|
{replaceError}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -531,7 +534,7 @@ export default function MatchTeamProgressPage() {
|
|||||||
|
|
||||||
if (!DEFAULT_COMMUNITY_ID) {
|
if (!DEFAULT_COMMUNITY_ID) {
|
||||||
return (
|
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` 설정이 필요합니다.
|
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
@@ -701,9 +704,9 @@ export default function MatchTeamProgressPage() {
|
|||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
aria-labelledby="team-tournament-code-replace-title"
|
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">
|
<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" />
|
<AlertTriangle className="h-4 w-4" />
|
||||||
</span>
|
</span>
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
@@ -743,7 +746,7 @@ export default function MatchTeamProgressPage() {
|
|||||||
handleConfirmReplaceTournamentCode();
|
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="예"
|
placeholder="예"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -24,6 +24,7 @@ const DEFAULT_FORM: MatchMutationRequest = {
|
|||||||
maxParticipants: 10,
|
maxParticipants: 10,
|
||||||
gameCount: 3,
|
gameCount: 3,
|
||||||
gameMode: 'pair',
|
gameMode: 'pair',
|
||||||
|
doubleEliminationResetFinalEnabled: true,
|
||||||
prizes: [],
|
prizes: [],
|
||||||
notices: [],
|
notices: [],
|
||||||
schedule: [],
|
schedule: [],
|
||||||
@@ -33,6 +34,7 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
|
|||||||
pair: '페어',
|
pair: '페어',
|
||||||
bracket: '브래킷',
|
bracket: '브래킷',
|
||||||
'round-robin': '라운드 로빈',
|
'round-robin': '라운드 로빈',
|
||||||
|
'double-elimination': '더블 엘리미네이션',
|
||||||
};
|
};
|
||||||
|
|
||||||
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
|
function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
|
||||||
@@ -122,6 +124,8 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & {
|
|||||||
gameCount: match.gameCount,
|
gameCount: match.gameCount,
|
||||||
gameMode: match.gameMode ?? 'pair',
|
gameMode: match.gameMode ?? 'pair',
|
||||||
roundRobinMaxRounds: match.roundRobinMaxRounds,
|
roundRobinMaxRounds: match.roundRobinMaxRounds,
|
||||||
|
doubleEliminationResetFinalEnabled:
|
||||||
|
match.doubleElimination?.resetFinalEnabled ?? true,
|
||||||
prizes: match.prizes,
|
prizes: match.prizes,
|
||||||
notices: match.notices,
|
notices: match.notices,
|
||||||
schedule: match.schedule,
|
schedule: match.schedule,
|
||||||
@@ -188,6 +192,10 @@ export default function MatchAdminPage() {
|
|||||||
maxParticipants: Number(form.maxParticipants ?? 10),
|
maxParticipants: Number(form.maxParticipants ?? 10),
|
||||||
gameCount: Number(form.gameCount ?? 3),
|
gameCount: Number(form.gameCount ?? 3),
|
||||||
gameMode: form.gameMode,
|
gameMode: form.gameMode,
|
||||||
|
doubleEliminationResetFinalEnabled:
|
||||||
|
form.gameMode === 'double-elimination'
|
||||||
|
? Boolean(form.doubleEliminationResetFinalEnabled)
|
||||||
|
: undefined,
|
||||||
roundRobinMaxRounds:
|
roundRobinMaxRounds:
|
||||||
form.gameMode === 'round-robin'
|
form.gameMode === 'round-robin'
|
||||||
? normalizeRoundRobinMaxRounds(
|
? normalizeRoundRobinMaxRounds(
|
||||||
@@ -329,7 +337,10 @@ export default function MatchAdminPage() {
|
|||||||
}}
|
}}
|
||||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
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>
|
<option key={value} value={value}>{value}명</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
@@ -339,16 +350,36 @@ export default function MatchAdminPage() {
|
|||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
value={form.gameCount}
|
disabled={form.gameMode === 'double-elimination'}
|
||||||
|
value={form.gameMode === 'double-elimination' ? 1 : form.gameCount}
|
||||||
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
|
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"
|
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">
|
||||||
|
더블 엘리미네이션은 단판으로 진행됩니다.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</label>
|
</label>
|
||||||
<label className="text-xs text-base-content/45">
|
<label className="text-xs text-base-content/45">
|
||||||
게임 모드
|
게임 모드
|
||||||
<select
|
<select
|
||||||
value={form.gameMode}
|
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' ? 1 : current.gameCount,
|
||||||
|
}));
|
||||||
|
}}
|
||||||
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
|
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]) => (
|
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
|
||||||
@@ -385,6 +416,22 @@ export default function MatchAdminPage() {
|
|||||||
</span>
|
</span>
|
||||||
</label>
|
</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">
|
<label className="text-xs text-base-content/45">
|
||||||
상품 (줄바꿈 구분)
|
상품 (줄바꿈 구분)
|
||||||
<textarea
|
<textarea
|
||||||
@@ -474,6 +521,14 @@ export default function MatchAdminPage() {
|
|||||||
최대 {match.roundRobinMaxRounds}R
|
최대 {match.roundRobinMaxRounds}R
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{match.gameMode === 'double-elimination' && (
|
||||||
|
<span className="block text-xs text-base-content/30">
|
||||||
|
GF 리셋{' '}
|
||||||
|
{match.doubleElimination?.resetFinalEnabled
|
||||||
|
? '허용'
|
||||||
|
: '없음'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2 text-right">
|
<td className="px-3 py-2 text-right">
|
||||||
<div className="inline-flex gap-2">
|
<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.
|
||||||
Reference in new issue
Block a user