Compare commits

..
29 Commits
Author SHA1 Message Date
dahyeon 2bac89d3dc chore(deps): resolve high audit findings
Upgrade direct dependencies and pin patched transitive versions so the high-severity pnpm audit gate passes. Document the dev-only brace-expansion exception and the separate Mongoose type-migration follow-up.
2026-07-25 01:51:00 -07:00
dahyeon ca786fd80a fix(dakao): hide started matches from schedule 2026-07-25 01:01:57 -07:00
dahyeon a4215f86fb fix(web): satisfy React hook lint rules 2026-07-24 22:36:53 -07:00
dahyeon bb68be14fa fix(api): eliminate unsafe lint warnings 2026-07-24 22:16:53 -07:00
dahyeon fd1fa2366c fix(api): resolve lint errors 2026-07-24 21:52:35 -07:00
dahyeon 96fede9fe5 style(api): apply prettier formatting 2026-07-24 21:42:28 -07:00
dahyeon 80fef25af3 chore: upgrade runtime to Node.js 26 2026-07-18 05:21:49 +00:00
dahyeon c9140b8622 feat: unify competition schedule and results 2026-07-15 01:01:49 -07:00
dahyeon 4e10998794 chore: add macOS Playwright MCP config 2026-07-15 00:18:28 -07:00
dahyeon b115072005 feat: polish double-elimination bracket navigation
Highlight connected routes, add readable round labels and accessible path descriptions, widen routing gaps, and centralize brand colors for winner progression.
2026-07-13 23:17:19 -07:00
dahyeon 03e88a03bc feat: improve series score card presentation
Show outcome-aware labels and scores, prioritize readable match names, and provide complete accessible summaries for bracket cards.
2026-07-13 23:16:43 -07:00
dahyeon 43c25c05cd feat(web): improve competition result history
Prioritize match outcomes, distinguish adjudicated results, and preserve detail context when navigating back.
2026-07-13 23:04:56 -07:00
dahyeon dc77b37494 feat(web): align team match names with bracket 2026-07-13 22:41:16 -07:00
dahyeon bb32c26694 feat(web): redesign team progress experience 2026-07-13 21:40:01 -07:00
dahyeon 81b951889f test(web): specify team progress presentation 2026-07-13 21:16:23 -07:00
dahyeon 96bae0ce28 feat(web): add match detail tabs 2026-07-14 03:22:33 +00:00
dahyeon a88562b208 fix: stabilize competition results flow 2026-07-13 13:55:08 +00:00
dahyeon 3bd3120eb1 feat: link competition games to detail analysis
Route each result-history Game by its global display number and preserve the Competition return target. Refuse stale detail fallbacks so a missing requested Game cannot silently show another Game.
2026-07-13 10:41:44 +00:00
dahyeon 3c60081ece feat: add competition series result history 2026-07-13 09:39:26 +00:00
dahyeon aa675199af feat: enrich internal match game analysis 2026-07-13 09:35:25 +00:00
dahyeon 9f698a8fec test: define competition series history 2026-07-13 09:22:12 +00:00
dahyeon 075fb52848 feat: render double-elimination bracket 2026-07-13 08:37:52 +00:00
dahyeon 738d274095 fix: include contracts workspace in api image 2026-07-13 05:52:59 +00:00
dahyeon ef47de7e4f fix: recover legacy tournament code transitions 2026-07-13 05:34:12 +00:00
dahyeon 489d040d8f fix: normalize reused tournament code lifecycle 2026-07-13 04:52:29 +00:00
dahyeon 6b1c450752 fix: harden competition migration recovery 2026-07-13 04:33:35 +00:00
dahyeon bbcb2f43dc test: harden competition migration assertions 2026-07-13 03:59:52 +00:00
dahyeon a307780752 fix: preserve legacy competition slot identity 2026-07-13 03:56:22 +00:00
dahyeon c2f89f9cb2 feat: preserve explicit round robin pairings 2026-07-13 03:50:32 +00:00
202 changed files with 18768 additions and 3753 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
[mcp_servers.playwright_macos]
url = "http://100.96.0.26:8931/mcp"
tool_timeout_sec = 120
startup_timeout_sec = 30
+2
View File
@@ -26,6 +26,8 @@ website/LICENSE
*.md *.md
!README.md !README.md
!AGENTS.md !AGENTS.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!agents/**/*.md !agents/**/*.md
!skills/**/*.md !skills/**/*.md
/tmp/ /tmp/
+1
View File
@@ -0,0 +1 @@
26
+8 -3
View File
@@ -1,11 +1,11 @@
# syntax=docker/dockerfile:1.7 # syntax=docker/dockerfile:1.7
FROM node:24-bookworm-slim AS pnpm-base FROM node:26-bookworm-slim AS pnpm-base
ENV PNPM_HOME=/pnpm ENV PNPM_HOME=/pnpm
ENV PATH="${PNPM_HOME}:${PATH}" ENV PATH="${PNPM_HOME}:${PATH}"
RUN corepack enable RUN npm install --global pnpm@10.4.1
WORKDIR /app WORKDIR /app
@@ -14,20 +14,23 @@ FROM pnpm-base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json COPY apps/web/package.json apps/web/package.json
COPY packages/contracts/package.json packages/contracts/package.json
RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM deps AS build FROM deps AS build
COPY packages/contracts packages/contracts
COPY apps/api apps/api COPY apps/api apps/api
RUN pnpm --filter api build RUN pnpm --filter api... build
FROM pnpm-base AS prod-deps FROM pnpm-base AS prod-deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json COPY apps/web/package.json apps/web/package.json
COPY packages/contracts/package.json packages/contracts/package.json
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
@@ -41,6 +44,8 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/package.json ./packages/contracts/package.json
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/dist ./packages/contracts/dist
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
COPY --chown=nonroot:nonroot apps/project.env ./project.env COPY --chown=nonroot:nonroot apps/project.env ./project.env
+22 -1
View File
@@ -29,7 +29,28 @@ export default tseslint.config(
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn', '@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn', '@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }], 'prettier/prettier': ['error', { endOfLine: 'auto' }],
},
},
{
files: ['**/*.spec.ts', 'test/**/*.ts'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/unbound-method': 'off',
},
},
{
files: ['src/modules/global/database/migrations/**/*.ts'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
}, },
}, },
); );
+9 -9
View File
@@ -29,20 +29,20 @@
}, },
"dependencies": { "dependencies": {
"@lolympus/contracts": "workspace:*", "@lolympus/contracts": "workspace:*",
"@nestjs/common": "^11.0.1", "@nestjs/common": "^11.1.28",
"@nestjs/config": "^4.0.4", "@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-socket.io": "^11.1.19", "@nestjs/platform-socket.io": "^11.1.28",
"@nestjs/swagger": "^11.2.7", "@nestjs/swagger": "^11.4.6",
"@nestjs/websockets": "^11.1.19", "@nestjs/websockets": "^11.1.28",
"@socket.io/redis-adapter": "^8.3.0", "@socket.io/redis-adapter": "^8.3.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.15.1", "class-validator": "^0.15.1",
"jose": "^6.2.2", "jose": "^6.2.2",
"mongoose": "^9.4.1", "mongoose": "9.4.1",
"nats": "^2.29.3", "nats": "^2.29.3",
"newrelic": "^14.1.2", "newrelic": "^14.3.3",
"redis": "^5.12.1", "redis": "^5.12.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
@@ -57,7 +57,7 @@
"@nestjs/testing": "^11.0.1", "@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0", "@types/express": "^5.0.0",
"@types/jest": "^30.0.0", "@types/jest": "^30.0.0",
"@types/node": "^24.0.0", "@types/node": "^26.1.1",
"@types/supertest": "^7.0.0", "@types/supertest": "^7.0.0",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1", "eslint-config-prettier": "^10.0.1",
@@ -79,7 +79,9 @@ describe('AuctionDeadlineScheduler', () => {
.spyOn(scheduler, 'processDueBidRoundDeadlines') .spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick(); await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1]; const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1];
expect(redis.acquireTokenLock).toHaveBeenCalledWith( expect(redis.acquireTokenLock).toHaveBeenCalledWith(
@@ -100,7 +102,9 @@ describe('AuctionDeadlineScheduler', () => {
.spyOn(scheduler, 'processDueBidRoundDeadlines') .spyOn(scheduler, 'processDueBidRoundDeadlines')
.mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick(); await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled(); expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled();
expect(redis.releaseTokenLock).not.toHaveBeenCalled(); expect(redis.releaseTokenLock).not.toHaveBeenCalled();
@@ -129,10 +133,12 @@ describe('AuctionDeadlineScheduler', () => {
it('prepares and completes due auction deadlines', async () => { it('prepares and completes due auction deadlines', async () => {
const matchId = '665f2f01f1f1f1f1f1f1f1f1'; const matchId = '665f2f01f1f1f1f1f1f1f1f1';
const completedState = { phase: 'passed', revision: 3 }; const completedState = { phase: 'passed', revision: 3 };
const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({ const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler(
dueReply: [matchId], {
completedState, dueReply: [matchId],
}); completedState,
},
);
await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({
completed: 1, completed: 1,
@@ -149,7 +155,10 @@ describe('AuctionDeadlineScheduler', () => {
expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1); expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1);
// 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰 // 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰
// 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작). // 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작).
expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState); expect(eventBus.broadcastState).toHaveBeenCalledWith(
matchId,
completedState,
);
}); });
it('skips noop expiry preparations', async () => { it('skips noop expiry preparations', async () => {
@@ -189,10 +198,7 @@ describe('AuctionDeadlineScheduler', () => {
}); });
it('continues processing later deadline items after one item fails', async () => { it('continues processing later deadline items after one item fails', async () => {
const matchIds = [ const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1'];
'665f2f01f1f1f1f1f1f1f1f1',
'665f2f02f1f1f1f1f1f1f1f1',
];
const { auctionService, redisCommand, scheduler } = makeScheduler({ const { auctionService, redisCommand, scheduler } = makeScheduler({
dueReply: matchIds, dueReply: matchIds,
}); });
@@ -101,15 +101,17 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
currentRedisTimestampMS: number, currentRedisTimestampMS: number,
batchLimit: number, batchLimit: number,
): Promise<string[]> { ): Promise<string[]> {
const reply = await this.auctionRedisService.raw().sendCommand([ const reply = await this.auctionRedisService
'ZRANGEBYSCORE', .raw()
BID_ROUND_DEADLINE_QUEUE_KEY, .sendCommand([
'-inf', 'ZRANGEBYSCORE',
String(currentRedisTimestampMS), BID_ROUND_DEADLINE_QUEUE_KEY,
'LIMIT', '-inf',
'0', String(currentRedisTimestampMS),
String(batchLimit), 'LIMIT',
]); '0',
String(batchLimit),
]);
return Array.isArray(reply) ? reply.map(String) : []; return Array.isArray(reply) ? reply.map(String) : [];
} }
@@ -177,11 +179,11 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy {
return { completed, prepared, skipped }; return { completed, prepared, skipped };
} }
private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise<void> { private async removeBidRoundDeadlineQueueEntry(
await this.auctionRedisService.raw().sendCommand([ matchId: string,
'ZREM', ): Promise<void> {
BID_ROUND_DEADLINE_QUEUE_KEY, await this.auctionRedisService
matchId, .raw()
]); .sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]);
} }
} }
@@ -20,9 +20,8 @@ export class AuctionEventBusService {
} }
public broadcastState(matchId: string, state: AuctionStateResponse): void { public broadcastState(matchId: string, state: AuctionStateResponse): void {
this.auctionNamespace?.to(matchId).emit( this.auctionNamespace
'state', ?.to(matchId)
serializeRealtimeAuction(state), .emit('state', serializeRealtimeAuction(state));
);
} }
} }
@@ -74,13 +74,11 @@ function serializeRealtimeAuctionPlayer(
return player; return player;
} }
const { const lightweightPlayer = { ...player };
masteries: _masteries, delete lightweightPlayer.masteries;
puuid: _puuid, delete lightweightPlayer.puuid;
recentStatsSummary: _recentStatsSummary, delete lightweightPlayer.recentStatsSummary;
tierHistory: _tierHistory, delete lightweightPlayer.tierHistory;
...lightweightPlayer
} = player;
return lightweightPlayer; return lightweightPlayer;
} }
@@ -22,7 +22,10 @@ describe('resolveAuctionRejectionReason', () => {
it('maps known BadRequest messages without a structured code', () => { it('maps known BadRequest messages without a structured code', () => {
expect( expect(
resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'), resolveAuctionRejectionReason(
undefined,
'Cannot advance from current phase.',
),
).toBe( ).toBe(
AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE, AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE,
); );
@@ -41,22 +41,24 @@ export class AuctionSideEffectService {
matchSideEffectStatus: AuctionMatchSideEffectStatus; matchSideEffectStatus: AuctionMatchSideEffectStatus;
}): Promise<boolean> { }): Promise<boolean> {
const keys = buildAuctionRedisKeys(params.matchId); const keys = buildAuctionRedisKeys(params.matchId);
const result = await this.auctionRedisService.raw().sendCommand([ const result = await this.auctionRedisService
'EVAL', .raw()
[ .sendCommand([
"if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end", 'EVAL',
"local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')", [
'local nextRevision = tonumber(ARGV[2])', "if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end",
'if currentRevision >= nextRevision then return 0 end', "local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')",
"redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])", 'local nextRevision = tonumber(ARGV[2])',
'return 1', 'if currentRevision >= nextRevision then return 0 end',
].join('\n'), "redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])",
'1', 'return 1',
keys.liveStateKey, ].join('\n'),
params.auctionLifecycleId, '1',
String(params.matchSideEffectRevision), keys.liveStateKey,
params.matchSideEffectStatus, params.auctionLifecycleId,
]); String(params.matchSideEffectRevision),
params.matchSideEffectStatus,
]);
return Number(result) === 1; return Number(result) === 1;
} }
} }
@@ -78,8 +80,7 @@ export function canAcquireSideEffectLease(
if (state.state === 'pending' || state.state === 'failed') return true; if (state.state === 'pending' || state.state === 'failed') return true;
if (state.state !== 'processing') return false; if (state.state !== 'processing') return false;
return ( return (
(state.processingLeaseExpiresAtTimestampMS ?? 0) <= (state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS
currentRedisTimestampMS
); );
} }
@@ -59,8 +59,7 @@ export class AuctionController {
initialTeamBidPointAmount: c.initialTeamBidPointAmount, initialTeamBidPointAmount: c.initialTeamBidPointAmount,
})), })),
initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000, initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000,
maximumBidRoundDurationSeconds: maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30,
body.maximumBidRoundDurationSeconds ?? 30,
bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5, bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5,
topTierAuctionPriorityThreshold: topTierAuctionPriorityThreshold:
body.topTierAuctionPriorityThreshold ?? 'NONE', body.topTierAuctionPriorityThreshold ?? 'NONE',
+96 -56
View File
@@ -13,7 +13,7 @@ import {
} from '@nestjs/websockets'; } from '@nestjs/websockets';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { JWTPayload } from 'jose'; import type { JWTPayload } from 'jose';
import { Namespace, Socket } from 'socket.io'; import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
import { AuthService } from '../auth/auth.service'; import { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service'; import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service'; import { JwtService } from '../auth/jwt.service';
@@ -78,6 +78,20 @@ interface BidRateLimitState {
windowStartedAtTimestampMS: number; windowStartedAtTimestampMS: number;
} }
interface AuctionSocketData {
auctionBidRateLimit?: BidRateLimitState;
identity?: IdentityDocument;
matchId?: string;
user?: UserDocument;
}
type AuctionSocket = Socket<
DefaultEventsMap,
DefaultEventsMap,
DefaultEventsMap,
AuctionSocketData
>;
const BID_RATE_LIMIT_WINDOW_MS = 1000; const BID_RATE_LIMIT_WINDOW_MS = 1000;
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8; const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED'; const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
@@ -92,9 +106,7 @@ const BID_RATE_LIMIT_REJECTION_MESSAGE =
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
}, },
}) })
export class AuctionGateway export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
implements OnGatewayConnection, OnGatewayInit
{
@WebSocketServer() @WebSocketServer()
private server!: Namespace; private server!: Namespace;
@@ -114,14 +126,14 @@ export class AuctionGateway
this.auctionEventBusService.attachAuctionNamespace(server); this.auctionEventBusService.attachAuctionNamespace(server);
} }
public async handleConnection(socket: Socket) { public async handleConnection(socket: AuctionSocket) {
try { try {
await this.authenticateSocket(socket); await this.authenticateSocket(socket);
this.logger.debug(`Auction client connected: ${socket.id}`); this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) { } catch (err) {
this.logger.warn( this.logger.warn(
`Auction client authentication failed: ${ `Auction client authentication failed: ${
err instanceof Error ? err.message : err err instanceof Error ? err.message : String(err)
}`, }`,
); );
socket.disconnect(true); socket.disconnect(true);
@@ -130,7 +142,7 @@ export class AuctionGateway
@SubscribeMessage('join') @SubscribeMessage('join')
public async handleJoin( public async handleJoin(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: JoinAuctionPayload, @MessageBody() payload: JoinAuctionPayload,
) { ) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
@@ -158,7 +170,7 @@ export class AuctionGateway
@SubscribeMessage('bid') @SubscribeMessage('bid')
public async handleBid( public async handleBid(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: BidPayload, @MessageBody() payload: BidPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -205,7 +217,9 @@ export class AuctionGateway
ack?.({ ack?.({
...(bidDelta ...(bidDelta
? {} ? {}
: { state: this.serializeAuction(bidResult as AuctionStateResponse) }), : {
state: this.serializeAuction(bidResult as AuctionStateResponse),
}),
ok: true, ok: true,
bidRequestId, bidRequestId,
bidDelta: broadcastBidDelta, bidDelta: broadcastBidDelta,
@@ -220,7 +234,12 @@ export class AuctionGateway
error, error,
); );
const bidServerTiming = this.extractBidServerTiming(rejectionAckFields); const bidServerTiming = this.extractBidServerTiming(rejectionAckFields);
this.emitError(socket, String(rejectionAckFields.message ?? '')); this.emitError(
socket,
typeof rejectionAckFields.message === 'string'
? rejectionAckFields.message
: '',
);
ack?.({ ack?.({
...rejectionAckFields, ...rejectionAckFields,
bidRequestId, bidRequestId,
@@ -263,7 +282,7 @@ export class AuctionGateway
@SubscribeMessage('open-bidding') @SubscribeMessage('open-bidding')
public async handleOpenBidding( public async handleOpenBidding(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload, @MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -292,7 +311,7 @@ export class AuctionGateway
@SubscribeMessage('sold') @SubscribeMessage('sold')
public async handleSold( public async handleSold(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: SoldPayload, @MessageBody() payload: SoldPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -322,7 +341,7 @@ export class AuctionGateway
@SubscribeMessage('next') @SubscribeMessage('next')
public async handleNext( public async handleNext(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload, @MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -351,7 +370,7 @@ export class AuctionGateway
@SubscribeMessage('passed') @SubscribeMessage('passed')
public async handlePassed( public async handlePassed(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: AuctionActionPayload, @MessageBody() payload: AuctionActionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void, @Ack() ack?: (response: Record<string, unknown>) => void,
) { ) {
@@ -380,7 +399,7 @@ export class AuctionGateway
@SubscribeMessage('chat-message') @SubscribeMessage('chat-message')
public async handleChatMessage( public async handleChatMessage(
@ConnectedSocket() socket: Socket, @ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: ChatMessagePayload, @MessageBody() payload: ChatMessagePayload,
) { ) {
const matchId = this.requireJoinedMatchId(socket); const matchId = this.requireJoinedMatchId(socket);
@@ -406,7 +425,7 @@ export class AuctionGateway
} }
} }
private requireJoinedMatchId(socket: Socket): string | null { private requireJoinedMatchId(socket: AuctionSocket): string | null {
const matchId = this.getSocketMatchId(socket); const matchId = this.getSocketMatchId(socket);
if (!matchId) { if (!matchId) {
this.emitError(socket, 'Join a match room before sending events.'); this.emitError(socket, 'Join a match room before sending events.');
@@ -415,10 +434,9 @@ export class AuctionGateway
return matchId; return matchId;
} }
private consumeBidRateLimit(socket: Socket): boolean { private consumeBidRateLimit(socket: AuctionSocket): boolean {
const currentTimestampMS = Date.now(); const currentTimestampMS = Date.now();
const previousState = socket.data const previousState = socket.data.auctionBidRateLimit;
.auctionBidRateLimit as BidRateLimitState | undefined;
if ( if (
!previousState || !previousState ||
currentTimestampMS - previousState.windowStartedAtTimestampMS >= currentTimestampMS - previousState.windowStartedAtTimestampMS >=
@@ -436,10 +454,8 @@ export class AuctionGateway
return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW; return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW;
} }
private getSocketMatchId(socket: Socket): string | undefined { private getSocketMatchId(socket: AuctionSocket): string | undefined {
return typeof socket.data.matchId === 'string' return socket.data.matchId;
? socket.data.matchId
: undefined;
} }
private toAuctionActionRequest(payload?: AuctionActionPayload) { private toAuctionActionRequest(payload?: AuctionActionPayload) {
@@ -463,8 +479,9 @@ export class AuctionGateway
}; };
} }
private readHandshakeUserId(socket: Socket): string | undefined { private readHandshakeUserId(socket: AuctionSocket): string | undefined {
const authUserId = socket.handshake.auth['x-auth-user-id']; const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
const authUserId = handshakeAuth['x-auth-user-id'];
if (typeof authUserId === 'string') return authUserId; if (typeof authUserId === 'string') return authUserId;
const header = socket.handshake.headers['x-auth-user-id']; const header = socket.handshake.headers['x-auth-user-id'];
@@ -472,16 +489,16 @@ export class AuctionGateway
} }
private resolveSocketUserId( private resolveSocketUserId(
socket: Socket, socket: AuctionSocket,
): mongoose.Types.ObjectId | undefined { ): mongoose.Types.ObjectId | undefined {
return (socket.data.user as UserDocument | undefined)?._id; return socket.data.user?._id;
} }
private resolveChatDisplayName( private resolveChatDisplayName(
socket: Socket, socket: AuctionSocket,
fallbackDisplayName?: string, fallbackDisplayName?: string,
): string { ): string {
const user = socket.data.user as UserDocument | undefined; const user = socket.data.user;
const primaryRiotAccount = const primaryRiotAccount =
user?.riotAccounts.find((entry) => entry.isPrimary) ?? user?.riotAccounts.find((entry) => entry.isPrimary) ??
user?.riotAccounts[0]; user?.riotAccounts[0];
@@ -494,14 +511,14 @@ export class AuctionGateway
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname; if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
if (user?.discordNickname) return user.discordNickname; if (user?.discordNickname) return user.discordNickname;
const identity = socket.data.identity as IdentityDocument | undefined; const identity = socket.data.identity;
if (identity?.displayName) return identity.displayName; if (identity?.displayName) return identity.displayName;
if (identity?.email) return identity.email; if (identity?.email) return identity.email;
return fallbackDisplayName ?? '관전자'; return fallbackDisplayName ?? '관전자';
} }
private async authenticateSocket(socket: Socket): Promise<void> { private async authenticateSocket(socket: AuctionSocket): Promise<void> {
const fallback = await this.authService.resolveDevUserById( const fallback = await this.authService.resolveDevUserById(
this.readHandshakeUserId(socket), this.readHandshakeUserId(socket),
); );
@@ -531,14 +548,20 @@ export class AuctionGateway
}); });
} }
private readHandshakeToken(socket: Socket): string | undefined { private readHandshakeToken(socket: AuctionSocket): string | undefined {
const authToken = socket.handshake.auth.token; const handshakeAuth = socket.handshake.auth as Record<string, unknown>;
const authToken = handshakeAuth.token;
if (typeof authToken === 'string' && authToken.trim()) { if (typeof authToken === 'string' && authToken.trim()) {
return authToken.trim().replace(/^Bearer\s+/i, ''); return authToken.trim().replace(/^Bearer\s+/i, '');
} }
const header = socket.handshake.headers.authorization; const header: unknown = socket.handshake.headers.authorization;
const authorization = Array.isArray(header) ? header[0] : header; const authorization =
typeof header === 'string'
? header
: Array.isArray(header) && typeof header[0] === 'string'
? header[0]
: undefined;
if (authorization?.startsWith('Bearer ')) { if (authorization?.startsWith('Bearer ')) {
return authorization.slice('Bearer '.length).trim(); return authorization.slice('Bearer '.length).trim();
} }
@@ -546,10 +569,11 @@ export class AuctionGateway
} }
private async resolveSocketUserForMatch( private async resolveSocketUserForMatch(
socket: Socket, socket: AuctionSocket,
matchId: string, matchId: string,
): Promise<void> { ): Promise<void> {
if (socket.data.user || !socket.data.identity) return; if (socket.data.user || !socket.data.identity) return;
const identity = socket.data.identity;
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({ const match = await MatchModel.findById(matchId).select({
@@ -558,10 +582,11 @@ export class AuctionGateway
if (!match) return; if (!match) return;
const UserModel = await this.connectionService.getModel('user'); const UserModel = await this.connectionService.getModel('user');
socket.data.user = await UserModel.findOne({ const user = await UserModel.findOne({
communityId: match.communityId, communityId: match.communityId,
identityId: (socket.data.identity as IdentityDocument)._id, identityId: identity._id,
}).exec(); }).exec();
socket.data.user = user ?? undefined;
} }
private requireStringClaim(payload: JWTPayload, key: string): string { private requireStringClaim(payload: JWTPayload, key: string): string {
@@ -595,7 +620,7 @@ export class AuctionGateway
this.server.to(matchId).emit('match-side-effect', delta); this.server.to(matchId).emit('match-side-effect', delta);
} }
private emitChatHistory(socket: Socket, auction: AuctionDocument) { private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) {
socket.emit('chat-history', { socket.emit('chat-history', {
messages: (auction.chatMessages ?? []).map((message) => messages: (auction.chatMessages ?? []).map((message) =>
this.serializeChatMessage(message), this.serializeChatMessage(message),
@@ -603,16 +628,21 @@ export class AuctionGateway
}); });
} }
private emitKnownError(socket: Socket, error: unknown) { private emitKnownError(socket: AuctionSocket, error: unknown) {
this.emitError(socket, this.resolveErrorPayload(error).message); this.emitError(socket, this.resolveErrorPayload(error).message);
} }
private emitError(socket: Socket, message: string) { private emitError(socket: AuctionSocket, message: string) {
socket.emit('error', { message }); socket.emit('error', { message });
} }
private serializeAuction(auction: AuctionStateResponse) { private serializeAuction(
return JSON.parse(JSON.stringify(auction)); auction: AuctionStateResponse,
): Record<string, unknown> {
const serialized: unknown = JSON.parse(JSON.stringify(auction));
return typeof serialized === 'object' && serialized !== null
? (serialized as Record<string, unknown>)
: {};
} }
/** /**
@@ -633,7 +663,9 @@ export class AuctionGateway
typeof errorPayload.code === 'string' ? errorPayload.code : undefined, typeof errorPayload.code === 'string' ? errorPayload.code : undefined,
errorPayload.message, errorPayload.message,
); );
const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason); const resyncRecommended = isAuctionResyncRecommended(
auctionRejectionReason,
);
const state = resyncRecommended const state = resyncRecommended
? await this.fetchSerializedAuctionState(matchId) ? await this.fetchSerializedAuctionState(matchId)
: undefined; : undefined;
@@ -688,7 +720,9 @@ export class AuctionGateway
return { return {
code: error instanceof Error ? error.message : 'UNKNOWN', code: error instanceof Error ? error.message : 'UNKNOWN',
message: message:
error instanceof Error ? error.message : 'Unexpected auction gateway error.', error instanceof Error
? error.message
: 'Unexpected auction gateway error.',
}; };
} }
@@ -716,7 +750,8 @@ export class AuctionGateway
bidDelta: Record<string, unknown> | null, bidDelta: Record<string, unknown> | null,
): Record<string, unknown> | null { ): Record<string, unknown> | null {
if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta; if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta;
const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta; const publicBidDelta = { ...bidDelta };
delete publicBidDelta.bidServerTiming;
return publicBidDelta; return publicBidDelta;
} }
@@ -724,7 +759,7 @@ export class AuctionGateway
auction: AuctionStateResponse, auction: AuctionStateResponse,
bidRequestId?: string, bidRequestId?: string,
): Record<string, unknown> | null { ): Record<string, unknown> | null {
const serialized = this.serializeAuction(auction) as Record<string, unknown>; const serialized = this.serializeAuction(auction);
const revision = Number(serialized.revision); const revision = Number(serialized.revision);
const currentHighestBidPointAmount = Number( const currentHighestBidPointAmount = Number(
serialized.currentHighestBidPointAmount ?? serialized.currentBid, serialized.currentHighestBidPointAmount ?? serialized.currentBid,
@@ -739,11 +774,13 @@ export class AuctionGateway
? Date.parse(serialized.currentDeadline) ? Date.parse(serialized.currentDeadline)
: 0), : 0),
); );
const redisBidHistory = Array.isArray(serialized.auctionBidHistory) const redisBidHistory: unknown[] = Array.isArray(
? serialized.auctionBidHistory serialized.auctionBidHistory,
)
? (serialized.auctionBidHistory as unknown[])
: []; : [];
const legacyBidHistory = Array.isArray(serialized.bids) const legacyBidHistory: unknown[] = Array.isArray(serialized.bids)
? serialized.bids ? (serialized.bids as unknown[])
: []; : [];
const auctionBidHistoryEntry = const auctionBidHistoryEntry =
redisBidHistory[redisBidHistory.length - 1] ?? redisBidHistory[redisBidHistory.length - 1] ??
@@ -775,9 +812,7 @@ export class AuctionGateway
}; };
} }
private isBidDeltaResponse( private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse {
value: unknown,
): value is AuctionBidDeltaResponse {
return ( return (
typeof value === 'object' && typeof value === 'object' &&
value !== null && value !== null &&
@@ -804,7 +839,12 @@ export class AuctionGateway
}; };
} }
private serializeChatMessage(message: AuctionChatMessage) { private serializeChatMessage(
return JSON.parse(JSON.stringify(message)); message: AuctionChatMessage,
): Record<string, unknown> {
const serialized: unknown = JSON.parse(JSON.stringify(message));
return typeof serialized === 'object' && serialized !== null
? (serialized as Record<string, unknown>)
: {};
} }
} }
@@ -2,6 +2,30 @@ import mongoose from 'mongoose';
import { AuctionService } from './auction.service'; import { AuctionService } from './auction.service';
describe('AuctionService', () => { describe('AuctionService', () => {
function requireRecord(
value: unknown,
label: string,
): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${label} must be an object.`);
}
return value as Record<string, unknown>;
}
function requireArray(value: unknown, label: string): unknown[] {
if (!Array.isArray(value)) {
throw new Error(`${label} must be an array.`);
}
return value as unknown[];
}
function parseJsonRecord(value: unknown, label: string) {
if (typeof value !== 'string') {
throw new Error(`${label} must be a JSON string.`);
}
return requireRecord(JSON.parse(value) as unknown, label);
}
function createService(models: Record<string, unknown>) { function createService(models: Record<string, unknown>) {
const auctionHistoryModel = { const auctionHistoryModel = {
findOne: jest.fn().mockReturnValue({ findOne: jest.fn().mockReturnValue({
@@ -158,12 +182,11 @@ describe('AuctionService', () => {
it('rejects non-positive or fractional bid amounts before loading auction state', async () => { it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const auctionFindOne = jest.fn(); const auctionFindOne = jest.fn();
const { service, auctionRedisCommandService, auctionRedisService } = const { service, auctionRedisCommandService } = createService({
createService({ auction: {
auction: { findOne: auctionFindOne,
findOne: auctionFindOne, },
}, });
});
await expect( await expect(
service.placeBid({ service.placeBid({
@@ -1008,7 +1031,12 @@ describe('AuctionService', () => {
); );
const transitionInput = const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1]; auctionRedisCommandService.applyTransition.mock.calls[0][1];
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({ expect(
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: expect.objectContaining({ afterAuctionMongoProjection: expect.objectContaining({
phase: 'bidding', phase: 'bidding',
revision: 2, revision: 2,
@@ -1179,17 +1207,40 @@ describe('AuctionService', () => {
const transitionInput = const transitionInput =
auctionRedisCommandService.applyTransition.mock.calls[0][1]; auctionRedisCommandService.applyTransition.mock.calls[0][1];
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson); const durabilityPayload = parseJsonRecord(
expect(durabilityPayload.snapshotBefore).toMatchObject({ transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
const snapshotBefore = requireRecord(
durabilityPayload.snapshotBefore,
'snapshotBefore',
);
const snapshotBeforeTeams = requireArray(
snapshotBefore.auctionTeams,
'snapshotBefore.auctionTeams',
);
const snapshotBeforeTeam = requireRecord(
snapshotBeforeTeams[0],
'snapshotBefore.auctionTeams[0]',
);
const afterAuctionMongoProjection = requireRecord(
durabilityPayload.afterAuctionMongoProjection,
'afterAuctionMongoProjection',
);
const projectedTeams = requireArray(
afterAuctionMongoProjection.auctionTeams,
'afterAuctionMongoProjection.auctionTeams',
);
const projectedTeam = requireRecord(
projectedTeams[0],
'afterAuctionMongoProjection.auctionTeams[0]',
);
expect(snapshotBefore).toMatchObject({
phase: 'bidding', phase: 'bidding',
revision: 4, revision: 4,
}); });
expect(durabilityPayload.snapshotBefore.auctionTeams[0].members).toEqual( expect(snapshotBeforeTeam.members).toEqual([]);
[], expect(projectedTeam.members).toEqual([
);
expect(
durabilityPayload.afterAuctionMongoProjection.auctionTeams[0].members,
).toEqual([
expect.objectContaining({ expect.objectContaining({
memberAcquisitionBidPointAmount: 120, memberAcquisitionBidPointAmount: 120,
userId: playerUserId.toString(), userId: playerUserId.toString(),
@@ -1397,7 +1448,12 @@ describe('AuctionService', () => {
}); });
const [, transitionInput] = const [, transitionInput] =
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? []; auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
expect(JSON.parse(transitionInput.durabilityPayloadJson)).toMatchObject({ expect(
parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
),
).toMatchObject({
afterAuctionMongoProjection: { afterAuctionMongoProjection: {
matchSideEffectStatus: 'pending', matchSideEffectStatus: 'pending',
phase: 'complete', phase: 'complete',
@@ -2568,7 +2624,10 @@ describe('AuctionService', () => {
durationSeconds: 30, durationSeconds: 30,
mode: 'set-relative', mode: 'set-relative',
}); });
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson); const durabilityPayload = parseJsonRecord(
transitionInput.durabilityPayloadJson,
'durabilityPayloadJson',
);
expect(durabilityPayload).toMatchObject({ expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo', auctionActionType: 'undo',
historyMutation: { historyMutation: {
@@ -210,21 +210,25 @@ describe('AuctionRedisCommandService', () => {
it('parses apply transition replay and rejected replies', async () => { it('parses apply transition replay and rejected replies', async () => {
await expect( await expect(
makeService(['REPLAY', 'APPLIED', 'transition-1', '2100']) makeService([
.service.applyTransition('match-1', { 'REPLAY',
afterAuctionStructureStateJson: '{}', 'APPLIED',
auctionHistorySequence: 5, 'transition-1',
auctionLifecycleId: 'life-1', '2100',
auctionStateTransitionId: 'transition-1', ]).service.applyTransition('match-1', {
broadcastStateRevision: 11, afterAuctionStructureStateJson: '{}',
deadline: { mode: 'none' }, auctionHistorySequence: 5,
durabilityPayloadJson: '{}', auctionLifecycleId: 'life-1',
expectedPhase: 'sold', auctionStateTransitionId: 'transition-1',
expectedRevision: 10, broadcastStateRevision: 11,
liveStatePatch: {}, deadline: { mode: 'none' },
matchId: 'match-1', durabilityPayloadJson: '{}',
shouldBroadcastState: false, expectedPhase: 'sold',
}), expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
).resolves.toEqual({ ).resolves.toEqual({
auctionStateTransitionId: 'transition-1', auctionStateTransitionId: 'transition-1',
currentServerTimestampMS: 2100, currentServerTimestampMS: 2100,
@@ -233,21 +237,25 @@ describe('AuctionRedisCommandService', () => {
}); });
await expect( await expect(
makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200']) makeService([
.service.applyTransition('match-1', { 'REJECTED',
afterAuctionStructureStateJson: '{}', 'CONFLICT',
auctionHistorySequence: 5, 'transition-1',
auctionLifecycleId: 'life-1', '2200',
auctionStateTransitionId: 'transition-1', ]).service.applyTransition('match-1', {
broadcastStateRevision: 11, afterAuctionStructureStateJson: '{}',
deadline: { mode: 'none' }, auctionHistorySequence: 5,
durabilityPayloadJson: '{}', auctionLifecycleId: 'life-1',
expectedPhase: 'sold', auctionStateTransitionId: 'transition-1',
expectedRevision: 10, broadcastStateRevision: 11,
liveStatePatch: {}, deadline: { mode: 'none' },
matchId: 'match-1', durabilityPayloadJson: '{}',
shouldBroadcastState: false, expectedPhase: 'sold',
}), expectedRevision: 10,
liveStatePatch: {},
matchId: 'match-1',
shouldBroadcastState: false,
}),
).resolves.toEqual({ ).resolves.toEqual({
auctionStateTransitionId: 'transition-1', auctionStateTransitionId: 'transition-1',
code: 'CONFLICT', code: 'CONFLICT',
@@ -288,12 +296,17 @@ describe('AuctionRedisCommandService', () => {
it('parses expire prepare replay and noop replies', async () => { it('parses expire prepare replay and noop replies', async () => {
await expect( await expect(
makeService(['REPLAY', 'passed', 'expire-1', '12', '3100']) makeService([
.service.expirePrepare('match-1', { 'REPLAY',
auctionStateTransitionId: 'expire-1', 'passed',
bidRoundExpiryRetryDelayMS: 3000, 'expire-1',
matchId: 'match-1', '12',
}), '3100',
]).service.expirePrepare('match-1', {
auctionStateTransitionId: 'expire-1',
bidRoundExpiryRetryDelayMS: 3000,
matchId: 'match-1',
}),
).resolves.toMatchObject({ ).resolves.toMatchObject({
auctionStateTransitionId: 'expire-1', auctionStateTransitionId: 'expire-1',
bidRoundExpiryDecision: 'passed', bidRoundExpiryDecision: 'passed',
@@ -360,16 +373,19 @@ describe('AuctionRedisCommandService', () => {
}); });
await expect( await expect(
makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200']) makeService([
.service.hydrateState('match-1', { 'REJECTED',
auctionHistorySequence: 3, 'INVALID_PATCH_ARITY',
auctionLifecycleId: 'life-1', '4200',
maximumBidRoundDurationSeconds: 30, ]).service.hydrateState('match-1', {
matchId: 'match-1', auctionHistorySequence: 3,
phase: 'presenting', auctionLifecycleId: 'life-1',
revision: 6, maximumBidRoundDurationSeconds: 30,
structureStateJson: '{}', matchId: 'match-1',
}), phase: 'presenting',
revision: 6,
structureStateJson: '{}',
}),
).resolves.toEqual({ ).resolves.toEqual({
code: 'INVALID_PATCH_ARITY', code: 'INVALID_PATCH_ARITY',
currentServerTimestampMS: 4200, currentServerTimestampMS: 4200,
@@ -85,7 +85,9 @@ export function stringifyAuctionRedisStructureState(
return JSON.stringify(buildAuctionRedisStructureState(input)); return JSON.stringify(buildAuctionRedisStructureState(input));
} }
function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number { function countAuctionTeamMembersIncludingCaptain(
team: RedisAuctionTeam,
): number {
const userIds = new Set<string>([team.captainUserId.toString()]); const userIds = new Set<string>([team.captainUserId.toString()]);
for (const member of team.members) { for (const member of team.members) {
userIds.add(member.userId.toString()); userIds.add(member.userId.toString());
@@ -1,7 +1,10 @@
import { AuctionRedisService } from './auction-redis.service'; import { AuctionRedisService } from './auction-redis.service';
import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service'; import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service';
function makeService(commandReplies: unknown[], currentServerTimestampMS = 1000) { function makeService(
commandReplies: unknown[],
currentServerTimestampMS = 1000,
) {
const sendCommand = jest const sendCommand = jest
.fn() .fn()
.mockImplementation(() => Promise.resolve(commandReplies.shift())); .mockImplementation(() => Promise.resolve(commandReplies.shift()));
@@ -149,7 +152,9 @@ describe('AuctionRedisStateReaderService', () => {
[], [],
]); ]);
await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({ await expect(
service.readAuctionStateView('match-1'),
).resolves.toMatchObject({
auctionLifecycleId: 'life-1', auctionLifecycleId: 'life-1',
auctionTeams: [], auctionTeams: [],
phase: 'presenting', phase: 'presenting',
@@ -181,7 +186,6 @@ describe('AuctionRedisStateReaderService', () => {
}); });
}); });
it('returns null when live or structure state is absent', async () => { it('returns null when live or structure state is absent', async () => {
await expect( await expect(
makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView( makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView(
@@ -42,12 +42,14 @@ export class AuctionRedisStateReaderService {
matchId: string, matchId: string,
): Promise<AuctionRedisLiveStateIdentity | null> { ): Promise<AuctionRedisLiveStateIdentity | null> {
const keys = buildAuctionRedisKeys(matchId); const keys = buildAuctionRedisKeys(matchId);
const reply = await this.auctionRedisService.raw().sendCommand([ const reply = await this.auctionRedisService
'HMGET', .raw()
keys.liveStateKey, .sendCommand([
'auctionLifecycleId', 'HMGET',
'revision', keys.liveStateKey,
]); 'auctionLifecycleId',
'revision',
]);
if (!Array.isArray(reply)) return null; if (!Array.isArray(reply)) return null;
const auctionLifecycleId = const auctionLifecycleId =
typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined; typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined;
@@ -68,14 +70,16 @@ export class AuctionRedisStateReaderService {
): Promise<AuctionRedisBidContext | null> { ): Promise<AuctionRedisBidContext | null> {
const keys = buildAuctionRedisKeys(matchId); const keys = buildAuctionRedisKeys(matchId);
const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`; const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`;
const liveReply = await this.auctionRedisService.raw().sendCommand([ const liveReply = await this.auctionRedisService
'HMGET', .raw()
keys.liveStateKey, .sendCommand([
'phase', 'HMGET',
'auctionLifecycleId', keys.liveStateKey,
'currentBidRoundPlayerUserId', 'phase',
bidderTeamCaptainUserIdField, 'auctionLifecycleId',
]); 'currentBidRoundPlayerUserId',
bidderTeamCaptainUserIdField,
]);
if (!Array.isArray(liveReply)) return null; if (!Array.isArray(liveReply)) return null;
const phase = stringValue(liveReply[0]); const phase = stringValue(liveReply[0]);
@@ -102,18 +106,23 @@ export class AuctionRedisStateReaderService {
options: AuctionRedisStateViewReadOptions = {}, options: AuctionRedisStateViewReadOptions = {},
): Promise<Record<string, unknown> | null> { ): Promise<Record<string, unknown> | null> {
const keys = buildAuctionRedisKeys(matchId); const keys = buildAuctionRedisKeys(matchId);
const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] = const [
await Promise.all([ currentServerTimestampMS,
this.auctionRedisService.getCurrentRedisTimestampMS(), liveReply,
this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]), structureStateJson,
this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]), bidEntries,
this.auctionRedisService.raw().sendCommand([ ] = await Promise.all([
'LRANGE', this.auctionRedisService.getCurrentRedisTimestampMS(),
keys.bidHistoryKey, this.auctionRedisService
'0', .raw()
'-1', .sendCommand(['HGETALL', keys.liveStateKey]),
]), this.auctionRedisService
]); .raw()
.sendCommand(['GET', keys.structureStateKey]),
this.auctionRedisService
.raw()
.sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']),
]);
const liveState = parseHashReply(liveReply, { const liveState = parseHashReply(liveReply, {
includeInternalLiveStateFields: includeInternalLiveStateFields:
@@ -142,7 +151,7 @@ export class AuctionRedisStateReaderService {
revision: number; revision: number;
}, },
shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, shouldForceAuctionStateResync: options.shouldForceAuctionStateResync,
structureState: JSON.parse(structureStateJson) as Record<string, unknown>, structureState: parseJsonRecord(structureStateJson),
}); });
view.matchId = matchId; view.matchId = matchId;
if (options.includeInternalLiveStateFields) { if (options.includeInternalLiveStateFields) {
@@ -161,12 +170,9 @@ export class AuctionRedisStateReaderService {
if (typeof structureStateJson !== 'string' || !structureStateJson) { if (typeof structureStateJson !== 'string' || !structureStateJson) {
return undefined; return undefined;
} }
const structureState = JSON.parse(structureStateJson) as Record< const structureState = parseJsonRecord(structureStateJson);
string, const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams)
unknown ? (structureState.auctionTeams as unknown[])
>;
const auctionTeams = Array.isArray(structureState.auctionTeams)
? structureState.auctionTeams
: []; : [];
const bidderTeam = auctionTeams.find((entry) => { const bidderTeam = auctionTeams.find((entry) => {
if (!entry || typeof entry !== 'object') return false; if (!entry || typeof entry !== 'object') return false;
@@ -183,6 +189,13 @@ function stringValue(value: unknown): string | undefined {
return typeof value === 'string' && value ? value : undefined; return typeof value === 'string' && value ? value : undefined;
} }
function parseJsonRecord(json: string): Record<string, unknown> {
const value: unknown = JSON.parse(json);
return typeof value === 'object' && value !== null
? (value as Record<string, unknown>)
: {};
}
function parseHashReply( function parseHashReply(
reply: unknown, reply: unknown,
options: { includeInternalLiveStateFields?: boolean } = {}, options: { includeInternalLiveStateFields?: boolean } = {},
@@ -210,7 +223,10 @@ function parseHashEntries(
): Record<string, unknown> { ): Record<string, unknown> {
const result: Record<string, unknown> = {}; const result: Record<string, unknown> = {};
for (const [field, rawValue] of entries) { for (const [field, rawValue] of entries) {
if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) { if (
!options.includeInternalLiveStateFields &&
isInternalLiveStateField(field)
) {
continue; continue;
} }
const value = String(rawValue); const value = String(rawValue);
@@ -91,9 +91,7 @@ describe('auction apply transition redis script contract', () => {
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
'shouldBroadcastState', 'shouldBroadcastState',
); );
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('SADD'");
"redis.call('SADD'",
);
expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain(
"redis.call('HINCRBY'", "redis.call('HINCRBY'",
); );
@@ -64,9 +64,7 @@ describe('auction bid redis script contract', () => {
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')"); expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'"); expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'");
expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT'); expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT');
expect(AUCTION_BID_SCRIPT.lua).toContain( expect(AUCTION_BID_SCRIPT.lua).toContain('currentHighestBidPointAmount');
'currentHighestBidPointAmount',
);
expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode'); expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode');
}); });
}); });
@@ -3,9 +3,11 @@ import { buildAuctionRedisKeys } from './auction-redis.keys';
describe('auction redis keys', () => { describe('auction redis keys', () => {
it('builds lifecycle-safe key names from match id', () => { it('builds lifecycle-safe key names from match id', () => {
expect(buildAuctionRedisKeys('match-1')).toMatchObject({ expect(buildAuctionRedisKeys('match-1')).toMatchObject({
actionRequestResultOrderKey: 'auction:match-1:auctionActionRequestResultOrder', actionRequestResultOrderKey:
'auction:match-1:auctionActionRequestResultOrder',
actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults', actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults',
appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds', appliedTransitionIdsKey:
'auction:match-1:appliedAuctionStateTransitionIds',
bidHistoryKey: 'auction:match-1:auctionBidHistory', bidHistoryKey: 'auction:match-1:auctionBidHistory',
bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder', bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder',
bidRequestResultsKey: 'auction:match-1:bidRequestResults', bidRequestResultsKey: 'auction:match-1:bidRequestResults',
@@ -74,9 +74,11 @@ async function readFirstSecret(
const logger = new Logger('AuctionRedisClient'); const logger = new Logger('AuctionRedisClient');
const client = createClient(auctionRedisOptions); const client = createClient(auctionRedisOptions);
client.on('error', (error) => { client.on('error', (error: unknown) => {
logger.error( logger.error(
`Auction Redis client error: ${error?.message ?? error}`, `Auction Redis client error: ${
error instanceof Error ? error.message : String(error)
}`,
); );
}); });
@@ -15,7 +15,9 @@ function makeService(sendCommand: jest.Mock) {
describe('AuctionRedisService', () => { describe('AuctionRedisService', () => {
it('uses Redis TIME as the timestamp source', async () => { it('uses Redis TIME as the timestamp source', async () => {
const service = makeService(jest.fn().mockResolvedValue(['1781700000', '123000'])); const service = makeService(
jest.fn().mockResolvedValue(['1781700000', '123000']),
);
await expect(service.getCurrentRedisTimestampMS()).resolves.toBe( await expect(service.getCurrentRedisTimestampMS()).resolves.toBe(
1_781_700_000_123, 1_781_700_000_123,
@@ -22,7 +22,11 @@ export class AuctionRedisNoscriptError extends Error {
function isNoscriptError(error: unknown): boolean { function isNoscriptError(error: unknown): boolean {
if (error instanceof AuctionRedisNoscriptError) return true; if (error instanceof AuctionRedisNoscriptError) return true;
const message = const message =
error instanceof Error ? error.message : typeof error === 'string' ? error : ''; error instanceof Error
? error.message
: typeof error === 'string'
? error
: '';
return /\bNOSCRIPT\b/iu.test(message); return /\bNOSCRIPT\b/iu.test(message);
} }
@@ -81,9 +85,15 @@ export class AuctionRedisService implements OnModuleDestroy {
if (!isNoscriptError(error)) throw error; if (!isNoscriptError(error)) throw error;
} }
const loadedSha = String( const loadedShaReply = await this.client.sendCommand([
await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]), 'SCRIPT',
); 'LOAD',
params.script,
]);
if (typeof loadedShaReply !== 'string') {
throw new Error('Redis SCRIPT LOAD returned a non-string SHA.');
}
const loadedSha = loadedShaReply;
return (await this.client.sendCommand( return (await this.client.sendCommand(
buildEvalShaCommand(loadedSha, params.keys, params.values), buildEvalShaCommand(loadedSha, params.keys, params.values),
)) as T; )) as T;
@@ -107,7 +117,7 @@ export class AuctionRedisService implements OnModuleDestroy {
token: string, token: string,
ttlMS: number, ttlMS: number,
): Promise<boolean> { ): Promise<boolean> {
const result = await this.client.sendCommand([ const result = await this.client.sendCommand<string | null>([
'SET', 'SET',
key, key,
token, token,
@@ -115,7 +125,7 @@ export class AuctionRedisService implements OnModuleDestroy {
String(ttlMS), String(ttlMS),
'NX', 'NX',
]); ]);
return String(result) === 'OK'; return result === 'OK';
} }
public async releaseTokenLock(key: string, token: string): Promise<boolean> { public async releaseTokenLock(key: string, token: string): Promise<boolean> {
@@ -100,9 +100,7 @@ describe('auction redis state assembly', () => {
'1000', '1000',
]); ]);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')"); expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')");
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain('INVALID_PATCH_ARITY');
'INVALID_PATCH_ARITY',
);
expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain(
'mongoRevision > redisRevision', 'mongoRevision > redisRevision',
); );
@@ -78,9 +78,7 @@ export function assembleAuctionViewFromRedisState(
return { return {
...params.structureState, ...params.structureState,
...params.liveState, ...params.liveState,
auctionBidHistory: params.auctionBidHistoryEntries.map((entry) => auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue),
JSON.parse(entry),
),
canPlaceBidInCurrentBidRound: !isExpiring, canPlaceBidInCurrentBidRound: !isExpiring,
currentServerTimestampMS: params.currentServerTimestampMS, currentServerTimestampMS: params.currentServerTimestampMS,
isAuctionStateTransitionInProgress: isExpiring, isAuctionStateTransitionInProgress: isExpiring,
@@ -90,6 +88,11 @@ export function assembleAuctionViewFromRedisState(
}; };
} }
function parseJsonValue(json: string): unknown {
const value: unknown = JSON.parse(json);
return value;
}
export function buildHydrateAuctionStateScriptInvocation( export function buildHydrateAuctionStateScriptInvocation(
keys: AuctionRedisKeys, keys: AuctionRedisKeys,
input: HydrateAuctionStateScriptInput, input: HydrateAuctionStateScriptInput,
+1 -4
View File
@@ -1,8 +1,5 @@
import type { JWTHeaderParameters, JWTPayload } from 'jose'; import type { JWTHeaderParameters, JWTPayload } from 'jose';
import type { import type { IdentityDocument, UserDocument } from '../global/database/schema';
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import type { IdentityProviderName } from './jwt.service'; import type { IdentityProviderName } from './jwt.service';
declare module 'express' { declare module 'express' {
+1 -4
View File
@@ -2,10 +2,7 @@ import { Injectable } from '@nestjs/common';
import type { Request } from 'express'; import type { Request } from 'express';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { import { IdentityDocument, UserDocument } from '../global/database/schema';
IdentityDocument,
UserDocument,
} from '../global/database/schema';
import { SecretService } from '../global/secret/secret.service'; import { SecretService } from '../global/secret/secret.service';
import './auth-request'; import './auth-request';
+4 -4
View File
@@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate {
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
[context.getHandler(), context.getClass()], [context.getHandler(), context.getClass()],
); );
const authz = request.headers?.authorization; const authzHeader = request.get('authorization');
const authzHeader = Array.isArray(authz) ? authz[0] : authz;
if (!authzHeader) { if (!authzHeader) {
const fallback = const fallback =
@@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate {
private pickIdPFromToken(token: string): IdentityProviderName { private pickIdPFromToken(token: string): IdentityProviderName {
try { try {
const { iss } = decodeJwt(token) as { iss?: string }; const { iss } = decodeJwt(token);
if (!iss) { if (!iss) {
throw new Error('Token has no issuer (iss) claim'); throw new Error('Token has no issuer (iss) claim');
} }
@@ -84,7 +83,8 @@ export class JwtAuthGuard implements CanActivate {
} }
throw new Error(`Unknown issuer: ${iss}`); throw new Error(`Unknown issuer: ${iss}`);
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : 'Unable to decode token'; const message =
err instanceof Error ? err.message : 'Unable to decode token';
throw new UnauthorizedException(message); throw new UnauthorizedException(message);
} }
} }
+32 -9
View File
@@ -35,11 +35,13 @@ export class JwtService {
throw new Error('Empty token'); throw new Error('Empty token');
} }
if (identityProvider !== 'MICROSOFT_ENTRAID') { const provider =
throw new Error(`Identity provider not configured: ${identityProvider}`); identityProvider === 'MICROSOFT_ENTRAID'
? await this.getEntraConfig()
: undefined;
if (!provider) {
throw new Error('Identity provider not configured.');
} }
const provider = await this.getEntraConfig();
const result = await jwtVerify(token, provider.jwks, { const result = await jwtVerify(token, provider.jwks, {
issuer: provider.issuer, issuer: provider.issuer,
audience: provider.audience, audience: provider.audience,
@@ -48,14 +50,22 @@ export class JwtService {
}); });
const { payload, protectedHeader } = result; const { payload, protectedHeader } = result;
if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) { if (!provider.allowedAlgs.includes(protectedHeader.alg)) {
throw new Error(`Unexpected alg: ${protectedHeader.alg}`); throw new Error(`Unexpected alg: ${protectedHeader.alg}`);
} }
if (payload.ver && payload.ver !== '2.0') { if (
throw new Error(`Unsupported Entra token version: ${payload.ver}`); payload.ver !== undefined &&
(typeof payload.ver !== 'string' || payload.ver !== '2.0')
) {
throw new Error(
`Unsupported Entra token version: ${formatClaimValue(payload.ver)}`,
);
} }
if (payload.tid && payload.tid !== provider.tenantId) { if (
throw new Error(`Unexpected tenant: ${payload.tid}`); payload.tid !== undefined &&
(typeof payload.tid !== 'string' || payload.tid !== provider.tenantId)
) {
throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`);
} }
return result; return result;
@@ -98,3 +108,16 @@ export class JwtService {
return this.entraConfig; return this.entraConfig;
} }
} }
function formatClaimValue(value: unknown): string {
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'bigint'
) {
return String(value);
}
if (value === null) return 'null';
return JSON.stringify(value) ?? typeof value;
}
+2 -2
View File
@@ -7,7 +7,7 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { Reflector } from '@nestjs/core'; import { Reflector } from '@nestjs/core';
import type { Request } from 'express'; import type { Request } from 'express';
import { CommunityRole, UserDocument } from '../global/database/schema'; import type { CommunityRole } from '../global/database/schema';
import { ROLES_KEY } from './roles.decorator'; import { ROLES_KEY } from './roles.decorator';
import './auth-request'; import './auth-request';
@@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate {
if (!requiredRoles || requiredRoles.length === 0) return true; if (!requiredRoles || requiredRoles.length === 0) return true;
const req = context.switchToHttp().getRequest<Request>(); const req = context.switchToHttp().getRequest<Request>();
const user = req.user as UserDocument | undefined; const user = req.user;
if (!user && req.identity) { if (!user && req.identity) {
throw new ForbiddenException('No membership in this community.'); throw new ForbiddenException('No membership in this community.');
} }
@@ -7,9 +7,10 @@ import {
import mongoose from 'mongoose'; import mongoose from 'mongoose';
@Injectable() @Injectable()
export class ParseObjectIdPipe export class ParseObjectIdPipe implements PipeTransform<
implements PipeTransform<string, mongoose.Types.ObjectId> string,
{ mongoose.Types.ObjectId
> {
public transform( public transform(
value: string, value: string,
metadata: ArgumentMetadata, metadata: ArgumentMetadata,
@@ -34,16 +34,29 @@ export class CommunityStatsCacheService {
let deleted = 0; let deleted = 0;
do { do {
const reply = (await client.sendCommand([ const reply = await client.sendCommand([
'SCAN', 'SCAN',
cursor, cursor,
'MATCH', 'MATCH',
match, match,
'COUNT', 'COUNT',
'100', '100',
])) as [string, string[]]; ]);
cursor = reply[0]; if (!Array.isArray(reply)) {
const keys = reply[1] ?? []; throw new Error('Redis SCAN returned an invalid response.');
}
const values = reply as unknown[];
const nextCursor = values[0];
const rawKeys = values[1];
if (typeof nextCursor !== 'string') {
throw new Error('Redis SCAN returned an invalid cursor.');
}
cursor = nextCursor;
const keys = Array.isArray(rawKeys)
? (rawKeys as unknown[]).filter(
(key): key is string => typeof key === 'string',
)
: [];
if (keys.length > 0) { if (keys.length > 0) {
deleted += await client.del(keys); deleted += await client.del(keys);
} }
@@ -23,7 +23,14 @@ export class CommunityStatsController {
) { ) {
return this.communityStatsService.getMatches({ return this.communityStatsService.getMatches({
communityId, communityId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
}); });
} }
@@ -85,7 +92,14 @@ export class CommunityStatsController {
return this.communityStatsService.getUserInternalHistory({ return this.communityStatsService.getUserInternalHistory({
communityId, communityId,
userId, userId,
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
}); });
} }
@@ -83,7 +83,7 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
} }
describe('CommunityStatsService', () => { describe('CommunityStatsService', () => {
it('ignores stale detail cache entries missing timeline build fields', async () => { it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = { const match: InternalMatchCardView = {
@@ -97,6 +97,20 @@ describe('CommunityStatsService', () => {
seriesResults: [], seriesResults: [],
}; };
const participant = record(matchId); const participant = record(matchId);
Object.assign(participant, {
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
});
const gameDetail: InternalGameDetail = { const gameDetail: InternalGameDetail = {
gameNumber: 1, gameNumber: 1,
riotMatchId: 'KR_1', riotMatchId: 'KR_1',
@@ -125,38 +139,81 @@ describe('CommunityStatsService', () => {
}, },
], ],
}; };
const staleCache = { Object.assign(gameDetail, {
match, timelineEvents: [
games: [
{ {
gameNumber: 1, timestamp: 300,
riotMatchId: 'KR_1', side: 'blue',
gameCreation: 1_000, type: 'championKill',
gameDuration: 1_800, killerParticipantId: 1,
teams: [ victimParticipantId: 2,
assistingParticipantIds: [],
},
],
});
const otherwiseCompleteCachedGame = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
timeline: [],
objectiveEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [
{ {
teamIndex: 1, summonerName: 'Cached Player',
side: 'blue', tagLine: 'KR1',
win: true, itemBuild: [],
objectives: { tower: 1, dragon: 0, baron: 0 }, skillBuild: [],
participants: [
{
summonerName: 'Player',
perks: {
primaryStyle: 8000,
subStyle: 8400,
keystone: 8010,
},
},
],
}, },
], ],
}, },
], ],
};
const missingTimelineEventsCache = {
match,
games: [otherwiseCompleteCachedGame],
} as unknown as InternalMatchDetailResponse; } as unknown as InternalMatchDetailResponse;
const invalidCheckpointCache = {
match,
games: [
{
...otherwiseCompleteCachedGame,
timelineEvents: [],
teams: otherwiseCompleteCachedGame.teams.map((team) => ({
...team,
participants: team.participants.map((cachedParticipant) => ({
...cachedParticipant,
participantId: 1,
checkpoints: {
at10: {
timestamp: '590',
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
})),
})),
},
],
} as unknown as InternalMatchDetailResponse;
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = { const cacheService = {
get: jest.fn().mockResolvedValue(staleCache), get: jest
setDetail: jest.fn().mockResolvedValue(undefined), .fn()
.mockResolvedValueOnce(missingTimelineEventsCache)
.mockResolvedValueOnce(invalidCheckpointCache),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>; } as unknown as jest.Mocked<CommunityStatsCacheService>;
const matchStatsService = { const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined), buildAndUpsert: jest.fn().mockResolvedValue(undefined),
@@ -180,22 +237,245 @@ describe('CommunityStatsService', () => {
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]), detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
}); });
const response = await service.getMatchDetail({ communityId, matchId }); const missingEventsResponse = await service.getMatchDetail({
communityId,
matchId,
});
const invalidCheckpointResponse = await service.getMatchDetail({
communityId,
matchId,
});
expect(response.games[0].timeline).toHaveLength(1); expect(missingEventsResponse.games[0].timeline).toHaveLength(1);
expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength( expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1);
1, expect(invalidCheckpointResponse.games[0]).toMatchObject({
); timelineEvents: [
expect(response.games[0].teams[0].participants[0].perks).toMatchObject({ {
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], timestamp: 300,
side: 'blue',
type: 'championKill',
},
],
});
expect(
invalidCheckpointResponse.games[0].teams[0].participants[0],
).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
},
itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }],
perks: {
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
},
}); });
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled(); expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
expect(cacheService.setDetail).toHaveBeenCalledWith( expect(setDetail).toHaveBeenCalledTimes(2);
expect.stringContaining(':r3:'), expect(setDetail).toHaveBeenNthCalledWith(
response, 2,
expect.stringContaining(':r4:'),
invalidCheckpointResponse,
); );
}); });
it('backs off failed timeline hydration and retries after the short cache expires', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const gameDetail: InternalGameDetail = {
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
};
const dataset = (timelineLoaded: boolean) => ({
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[matchId.toString(), [{ ...gameDetail, timelineLoaded }]],
]),
});
let cachedResponse: InternalMatchDetailResponse | null = null;
const set = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const setDetail = jest
.fn()
.mockImplementation(
(_key: string, value: InternalMatchDetailResponse) => {
cachedResponse = value;
return Promise.resolve();
},
);
const cacheService = {
get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)),
set,
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest
.fn()
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(false))
.mockResolvedValueOnce(dataset(true));
const fallback = await service.getMatchDetail({ communityId, matchId });
const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(set).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
fallback,
60,
);
expect(setDetail).not.toHaveBeenCalled();
cachedResponse = null;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.stringContaining(':r4:'),
recovered,
);
});
it('coalesces concurrent internal match detail cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match: InternalMatchCardView = {
matchId: matchId.toString(),
title: '내전',
scheduledAt: '2026-06-18T12:00:00.000Z',
status: 'finished',
gameCount: 1,
games: [],
teams: [],
seriesResults: [],
};
const participant = record(matchId);
const dataset = {
season: {
id: 'all',
label: '전체',
startTime: null,
endTime: null,
},
matches: [match],
records: [participant],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue' as const,
timelineLoaded: true,
timeline: [],
objectiveEvents: [],
timelineEvents: [],
teams: [
{
teamIndex: 1,
side: 'blue' as const,
win: true,
objectives: objectives(),
bans: [],
participants: [participant],
},
],
},
],
],
]),
};
let resolveDataset: ((value: typeof dataset) => void) | undefined;
const datasetPromise = new Promise<typeof dataset>((resolve) => {
resolveDataset = resolve;
});
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(null),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
);
const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise);
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
buildBaseDataset;
const first = service.getMatchDetail({ communityId, matchId });
const second = service.getMatchDetail({ communityId, matchId });
await Promise.resolve();
resolveDataset?.(dataset);
const [firstResponse, secondResponse] = await Promise.all([first, second]);
expect(firstResponse).toBe(secondResponse);
expect(buildBaseDataset).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledTimes(1);
});
it('includes internal match route fields in user internal history matches', async () => { it('includes internal match route fields in user internal history matches', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
@@ -40,7 +40,8 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50; const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300; const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5; const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3; const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext { interface CommunityStatsContext {
community: CommunityDocument; community: CommunityDocument;
@@ -59,6 +60,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 matchDetailInFlight = new Map<
string,
Promise<InternalMatchDetailResponse>
>();
private readonly userInternalHistoryInFlight = new Map< private readonly userInternalHistoryInFlight = new Map<
string, string,
Promise<UserInternalHistoryResponse> Promise<UserInternalHistoryResponse>
@@ -219,6 +224,27 @@ export class CommunityStatsService {
await this.cacheService.get<InternalMatchDetailResponse>(key); await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached; if (cached && isCompleteMatchDetailResponse(cached)) return cached;
const inFlight = this.matchDetailInFlight.get(key);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key) === promise) {
this.matchDetailInFlight.delete(key);
}
}
}
private async buildMatchDetailResponse(
params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
},
key: string,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, { const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all', seasonId: 'all',
}); });
@@ -246,6 +272,7 @@ export class CommunityStatsService {
gameVersion: game.gameVersion, gameVersion: game.gameVersion,
timeline: game.timeline ?? [], timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [], objectiveEvents: game.objectiveEvents ?? [],
timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({ teams: game.teams.map((team) => ({
teamIndex: team.teamIndex, teamIndex: team.teamIndex,
side: team.side, side: team.side,
@@ -253,6 +280,8 @@ export class CommunityStatsService {
objectives: team.objectives, objectives: team.objectives,
bans: team.bans ?? [], bans: team.bans ?? [],
participants: team.participants.map((record) => ({ participants: team.participants.map((record) => ({
participantId: record.participantId,
checkpoints: record.checkpoints,
userId: record.userId, userId: record.userId,
summonerName: record.summonerName, summonerName: record.summonerName,
tagLine: record.tagLine, tagLine: record.tagLine,
@@ -289,7 +318,15 @@ export class CommunityStatsService {
})), })),
})), })),
}; };
await this.cacheService.setDetail(key, response); if (gameDetails.every((game) => game.timelineLoaded === true)) {
await this.cacheService.setDetail(key, response);
} else {
await this.cacheService.set(
key,
response,
INCOMPLETE_MATCH_DETAIL_TTL_SECONDS,
);
}
return response; return response;
} }
@@ -1160,6 +1197,7 @@ function isCompleteMatchDetailResponse(
(game) => (game) =>
Array.isArray(game.timeline) && Array.isArray(game.timeline) &&
Array.isArray(game.objectiveEvents) && Array.isArray(game.objectiveEvents) &&
Array.isArray(game.timelineEvents) &&
game.teams.every( game.teams.every(
(team) => (team) =>
Array.isArray(team.bans) && Array.isArray(team.bans) &&
@@ -1167,8 +1205,41 @@ function isCompleteMatchDetailResponse(
(participant) => (participant) =>
typeof participant.tagLine === 'string' && typeof participant.tagLine === 'string' &&
Array.isArray(participant.itemBuild) && Array.isArray(participant.itemBuild) &&
Array.isArray(participant.skillBuild), Array.isArray(participant.skillBuild) &&
isOptionalFiniteNumber(participant.participantId) &&
isCompleteParticipantCheckpoints(participant.checkpoints),
), ),
), ),
); );
} }
function isCompleteParticipantCheckpoints(value: unknown): boolean {
if (value === undefined) return true;
if (!isRecord(value)) return false;
return ['at10', 'at15'].every((key) => {
const checkpoint = value[key];
if (checkpoint === undefined) return true;
if (!isRecord(checkpoint)) return false;
return [
'timestamp',
'gold',
'cs',
'xp',
'kills',
'deaths',
'assists',
].every((field) => isFiniteNumber(checkpoint[field]));
});
}
function isOptionalFiniteNumber(value: unknown): boolean {
return value === undefined || isFiniteNumber(value);
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -1,11 +1,16 @@
import type { import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent, MatchStatsItemBuildEvent,
MatchStatsRunePerks, MatchStatsRunePerks,
MatchStatsSkillBuildEvent, MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
RiotLane, RiotLane,
TeamSide, TeamSide,
} from '../global/database/schema'; } from '../global/database/schema';
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; import type {
RecentMatchView,
HistorySeasonDto,
} from '../match-history/match-history.types';
export interface CommunityStatsFilters { export interface CommunityStatsFilters {
seasonId?: string; seasonId?: string;
@@ -78,7 +83,9 @@ export interface LeaderboardRow {
avgCsPerMin: number; avgCsPerMin: number;
avgDamageShare: number; avgDamageShare: number;
avgVisionScore: number; avgVisionScore: number;
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>; byLane: Partial<
Record<RiotLane, { games: number; wins: number; kda: number }>
>;
topChampions: Array<{ championId: number; games: number; winRate: number }>; topChampions: Array<{ championId: number; games: number; winRate: number }>;
} }
@@ -128,6 +135,7 @@ export interface InternalMatchDetailResponse {
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
monsterSubType?: string; monsterSubType?: string;
}>; }>;
timelineEvents: MatchStatsTimelineEvent[];
teams: Array<{ teams: Array<{
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
@@ -143,6 +151,8 @@ export interface InternalMatchDetailResponse {
}; };
bans: Array<{ championId: number; pickTurn: number }>; bans: Array<{ championId: number; pickTurn: number }>;
participants: Array<{ participants: Array<{
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string | null; userId: string | null;
summonerName: string; summonerName: string;
tagLine: string; tagLine: string;
@@ -100,6 +100,24 @@ describe('MatchStatsFragmentBuilder', () => {
it('builds rich set detail from raw Riot match data', () => { it('builds rich set detail from raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder(); const builder = new MatchStatsFragmentBuilder();
const match = makeMatch(); const match = makeMatch();
const redUserId = new mongoose.Types.ObjectId();
match.participants.push({
userId: redUserId,
puuid: 'puuid-2',
gameName: 'Opponent',
profileIconId: 8,
});
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
match.result?.games[0].participants.push({
userId: redUserId,
teamIndex: 2,
side: 'red',
championId: 24,
kills: 1,
deaths: 3,
assists: 0,
win: false,
});
const raw = { const raw = {
metadata: { metadata: {
dataVersion: '2', dataVersion: '2',
@@ -206,6 +224,51 @@ describe('MatchStatsFragmentBuilder', () => {
], ],
}, },
}; };
raw.info.participants.push(
{
...raw.info.participants[0],
assists: 0,
championId: 24,
championName: 'Jax',
deaths: 3,
kills: 1,
participantId: 2,
puuid: 'puuid-2',
riotIdGameName: 'Opponent',
summonerId: 'summoner-2',
summonerName: 'Opponent',
teamId: 200,
win: false,
},
{
...raw.info.participants[0],
assists: 2,
championId: 64,
championName: 'LeeSin',
deaths: 0,
kills: 1,
participantId: 3,
puuid: 'puuid-3',
riotIdGameName: 'Jungler',
summonerId: 'summoner-3',
summonerName: 'Jungler',
teamId: 100,
},
);
raw.info.teams.push({
bans: [],
objectives: {
baron: { first: false, kills: 0 },
champion: { first: false, kills: 3 },
dragon: { first: false, kills: 0 },
horde: { first: false, kills: 0 },
inhibitor: { first: false, kills: 0 },
riftHerald: { first: false, kills: 0 },
tower: { first: false, kills: 0 },
},
teamId: 200,
win: false,
});
const timeline = { const timeline = {
metadata: { metadata: {
dataVersion: '2', dataVersion: '2',
@@ -218,7 +281,20 @@ describe('MatchStatsFragmentBuilder', () => {
{ {
timestamp: 0, timestamp: 0,
participantFrames: { participantFrames: {
'1': { participantId: 1, totalGold: 500, xp: 0 }, '1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
'2': {
participantId: 2,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
}, },
}, },
{ {
@@ -291,7 +367,137 @@ describe('MatchStatsFragmentBuilder', () => {
}, },
], ],
participantFrames: { participantFrames: {
'1': { participantId: 1, totalGold: 1_150, xp: 550 }, '1': {
participantId: 1,
totalGold: 1_150,
xp: 550,
minionsKilled: 5,
jungleMinionsKilled: 1,
},
'2': {
participantId: 2,
totalGold: 1_050,
xp: 500,
minionsKilled: 4,
jungleMinionsKilled: 0,
},
},
},
{
timestamp: 540_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 300_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
{
type: 'CHAMPION_KILL',
timestamp: 400_000,
killerId: 0,
victimId: 1,
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 0,
teamId: 200,
buildingType: 'TOWER_BUILDING',
towerType: 'OUTER_TURRET',
},
{
type: 'BUILDING_KILL',
timestamp: 450_000,
killerId: 1,
teamId: 200,
buildingType: 'INHIBITOR_BUILDING',
},
{
type: 'CHAMPION_KILL',
timestamp: 500_000,
killerId: 3,
victimId: 2,
assistingParticipantIds: [1],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 4_900,
xp: 3_900,
minionsKilled: 72,
jungleMinionsKilled: 8,
},
'2': {
participantId: 2,
totalGold: 4_300,
xp: 3_500,
minionsKilled: 68,
jungleMinionsKilled: 2,
},
},
},
{
timestamp: 590_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 5_200,
xp: 4_200,
minionsKilled: 80,
jungleMinionsKilled: 10,
},
},
},
{
timestamp: 900_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 900_000,
killerId: 1,
victimId: 2,
assistingParticipantIds: [3],
},
],
participantFrames: {
'1': {
participantId: 1,
totalGold: 8_100,
xp: 7_300,
minionsKilled: 130,
jungleMinionsKilled: 15,
},
'2': {
participantId: 2,
totalGold: 6_700,
xp: 6_100,
minionsKilled: 115,
jungleMinionsKilled: 5,
},
},
},
{
timestamp: 1_800_000,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 12_500,
xp: 14_000,
minionsKilled: 205,
jungleMinionsKilled: 23,
},
'2': {
participantId: 2,
totalGold: 10_200,
xp: 12_700,
minionsKilled: 190,
jungleMinionsKilled: 10,
},
}, },
}, },
], ],
@@ -329,19 +535,105 @@ describe('MatchStatsFragmentBuilder', () => {
{ {
timestamp: 0, timestamp: 0,
blue: { gold: 500, xp: 0 }, blue: { gold: 500, xp: 0 },
red: { gold: 0, xp: 0 }, red: { gold: 500, xp: 0 },
goldDiff: 500, goldDiff: 0,
xpDiff: 0, xpDiff: 0,
}, },
{ {
timestamp: 60, timestamp: 60,
blue: { gold: 1_150, xp: 550 }, blue: { gold: 1_150, xp: 550 },
red: { gold: 1_050, xp: 500 },
goldDiff: 100,
xpDiff: 50,
},
{
timestamp: 540,
blue: { gold: 4_900, xp: 3_900 },
red: { gold: 4_300, xp: 3_500 },
goldDiff: 600,
xpDiff: 400,
},
{
timestamp: 590,
blue: { gold: 5_200, xp: 4_200 },
red: { gold: 0, xp: 0 }, red: { gold: 0, xp: 0 },
goldDiff: 1_150, goldDiff: 5_200,
xpDiff: 550, xpDiff: 4_200,
},
{
timestamp: 900,
blue: { gold: 8_100, xp: 7_300 },
red: { gold: 6_700, xp: 6_100 },
goldDiff: 1_400,
xpDiff: 1_200,
},
{
timestamp: 1_800,
blue: { gold: 12_500, xp: 14_000 },
red: { gold: 10_200, xp: 12_700 },
goldDiff: 2_300,
xpDiff: 1_300,
}, },
], ],
}); });
expect(fragment.gameDetails[0].timelineEvents).toEqual([
{
timestamp: 20,
side: 'blue',
type: 'dragon',
monsterSubType: 'FIRE_DRAGON',
},
{
timestamp: 30,
side: 'blue',
type: 'elderDragon',
monsterSubType: 'ELDER_DRAGON',
},
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
{ timestamp: 50, side: 'blue', type: 'baron' },
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
{
timestamp: 300,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
{
timestamp: 400,
type: 'championKill',
victimParticipantId: 1,
},
{
timestamp: 450,
side: 'blue',
type: 'tower',
towerType: 'OUTER_TURRET',
},
{
timestamp: 450,
side: 'blue',
type: 'inhibitor',
killerParticipantId: 1,
},
{
timestamp: 500,
side: 'blue',
type: 'championKill',
killerParticipantId: 3,
victimParticipantId: 2,
assistingParticipantIds: [1],
},
{
timestamp: 900,
side: 'blue',
type: 'championKill',
killerParticipantId: 1,
victimParticipantId: 2,
assistingParticipantIds: [3],
},
]);
expect(fragment.gameDetails[0].teams[0].bans).toEqual([ expect(fragment.gameDetails[0].teams[0].bans).toEqual([
{ championId: 14, pickTurn: 1 }, { championId: 14, pickTurn: 1 },
{ championId: 43, pickTurn: 2 }, { championId: 43, pickTurn: 2 },
@@ -356,6 +648,27 @@ describe('MatchStatsFragmentBuilder', () => {
voidGrub: 1, voidGrub: 1,
}); });
expect(fragment.records[0]).toMatchObject({ expect(fragment.records[0]).toMatchObject({
participantId: 1,
checkpoints: {
at10: {
timestamp: 590,
gold: 5_200,
cs: 90,
xp: 4_200,
kills: 1,
deaths: 1,
assists: 1,
},
at15: {
timestamp: 900,
gold: 8_100,
cs: 145,
xp: 7_300,
kills: 2,
deaths: 1,
assists: 1,
},
},
championLevel: 15, championLevel: 15,
cs: 228, cs: 228,
damageDealtToChampions: 18_765, damageDealtToChampions: 18_765,
@@ -392,5 +705,118 @@ describe('MatchStatsFragmentBuilder', () => {
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' }, { timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
], ],
}); });
expect(fragment.records[1]).toMatchObject({
participantId: 2,
checkpoints: {
at15: {
timestamp: 900,
gold: 6_700,
cs: 120,
xp: 6_100,
kills: 0,
deaths: 3,
assists: 0,
},
},
});
expect(fragment.records[1].checkpoints).not.toHaveProperty('at10');
const timelineWithoutEvents = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: [],
})),
},
} as RiotMatchTimelineDto;
const objectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]),
});
expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({
baron: 1,
dragon: 2,
elderDragon: 0,
riftHerald: 0,
voidGrub: 3,
});
const dragonOnlyTimeline = {
...timeline,
info: {
...timeline.info,
frames: timeline.info.frames.map((frame) => ({
...frame,
events: (frame.events ?? []).filter(
(event) =>
event.type !== 'ELITE_MONSTER_KILL' ||
event.monsterType === 'DRAGON',
),
})),
},
} as RiotMatchTimelineDto;
const partialObjectiveFallback = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]),
});
expect(
partialObjectiveFallback.gameDetails[0].teams[0].objectives,
).toMatchObject({
baron: 1,
dragon: 1,
elderDragon: 1,
riftHerald: 0,
voidGrub: 3,
});
const shortMatch = {
...match,
result: {
...match.result!,
games: match.result!.games.map((game) => ({
...game,
gameDuration: 599,
})),
},
} as MatchDocument;
const shortFragment = builder.buildFragment({
match: shortMatch,
rawByRiotMatchId: new Map([
[
'KR_1',
{
...raw,
info: { ...raw.info, gameDuration: 599 },
} as RiotMatchDto,
],
]),
timelineByRiotMatchId: new Map([
['KR_1', timeline as RiotMatchTimelineDto],
]),
});
expect(
shortFragment.records.every((record) => record.checkpoints === undefined),
).toBe(true);
const invalidIntervalTimeline = {
...timeline,
info: { ...timeline.info, frameInterval: Number.NaN },
} as RiotMatchTimelineDto;
const invalidIntervalFragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]),
});
expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false);
expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]);
expect(
invalidIntervalFragment.records.every(
(record) => record.checkpoints === undefined,
),
).toBe(true);
}); });
}); });
@@ -3,10 +3,13 @@ import mongoose from 'mongoose';
import type { import type {
MatchDocument, MatchDocument,
MatchGameResultParticipant, MatchGameResultParticipant,
MatchStatsCheckpoint,
MatchStatsItemBuildEvent, MatchStatsItemBuildEvent,
MatchStatsObjectiveEvent, MatchStatsObjectiveEvent,
MatchStatsObjectiveSummary, MatchStatsObjectiveSummary,
MatchStatsParticipantCheckpoints,
MatchStatsSkillBuildEvent, MatchStatsSkillBuildEvent,
MatchStatsTimelineEvent,
MatchStatsTimelinePoint, MatchStatsTimelinePoint,
TeamSide, TeamSide,
} from '../global/database/schema'; } from '../global/database/schema';
@@ -27,13 +30,17 @@ interface ParticipantBuildEvents {
skills: MatchStatsSkillBuildEvent[]; skills: MatchStatsSkillBuildEvent[];
} }
interface TimelineProjection {
objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents: MatchStatsTimelineEvent[];
}
@Injectable() @Injectable()
export class MatchStatsFragmentBuilder { export class MatchStatsFragmentBuilder {
public buildFragment(params: { public buildFragment(params: {
match: MatchDocument; match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>; rawByRiotMatchId: Map<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>; timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
timelineLoadAttempted?: boolean;
}): MatchStatsFragment { }): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort( const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber, (left, right) => left.gameNumber - right.gameNumber,
@@ -43,13 +50,7 @@ export class MatchStatsFragmentBuilder {
const raw = params.rawByRiotMatchId.get(game.riotMatchId); const raw = params.rawByRiotMatchId.get(game.riotMatchId);
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId); const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
return raw return raw
? this.toGameDetail( ? this.toGameDetail(params.match, game, raw, timeline)
params.match,
game,
raw,
timeline,
params.timelineLoadAttempted === true,
)
: this.toFallbackGameDetail(params.match, game); : this.toFallbackGameDetail(params.match, game);
}); });
const records = gameDetails.flatMap((detail) => const records = gameDetails.flatMap((detail) =>
@@ -130,8 +131,10 @@ export class MatchStatsFragmentBuilder {
game: NonNullable<MatchDocument['result']>['games'][number], game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto, raw: RiotMatchDto,
timeline?: RiotMatchTimelineDto, timeline?: RiotMatchTimelineDto,
timelineLoadAttempted = false,
): InternalGameDetail { ): InternalGameDetail {
const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration)
? timeline
: undefined;
const puuidByUserId = new Map( const puuidByUserId = new Map(
match.participants match.participants
.filter((participant) => participant.puuid) .filter((participant) => participant.puuid)
@@ -158,14 +161,18 @@ export class MatchStatsFragmentBuilder {
raw, raw,
rawTeamIdBySide, rawTeamIdBySide,
); );
const objectiveEvents = this.toObjectiveEvents( const { objectiveEvents, timelineEvents } = this.toTimelineEvents(
timeline, usableTimeline,
rawTeamIdBySide, rawTeamIdBySide,
sideByParticipantId, sideByParticipantId,
); );
const timelineObjectives = this.toTimelineObjectives(objectiveEvents); const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
const buildEventsByParticipantId = const buildEventsByParticipantId =
this.toBuildEventsByParticipantId(timeline); this.toBuildEventsByParticipantId(usableTimeline);
const checkpointsByParticipantId = this.toCheckpointsByParticipantId(
usableTimeline,
raw.info.gameDuration,
);
return { return {
gameNumber: game.gameNumber, gameNumber: game.gameNumber,
@@ -174,9 +181,10 @@ export class MatchStatsFragmentBuilder {
gameDuration: game.gameDuration, gameDuration: game.gameDuration,
gameVersion: raw.info.gameVersion, gameVersion: raw.info.gameVersion,
winnerSide: game.winnerSide, winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline), timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: timelineLoadAttempted || Boolean(timeline), timelineLoaded: Boolean(usableTimeline),
objectiveEvents, objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => { teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex = const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
@@ -202,7 +210,6 @@ export class MatchStatsFragmentBuilder {
objectives: this.toObjectiveSummary( objectives: this.toObjectiveSummary(
rawTeam, rawTeam,
timelineObjectives.get(side), timelineObjectives.get(side),
Boolean(timeline),
), ),
bans: (rawTeam?.bans ?? []).map((ban) => ({ bans: (rawTeam?.bans ?? []).map((ban) => ({
championId: ban.championId, championId: ban.championId,
@@ -220,9 +227,10 @@ export class MatchStatsFragmentBuilder {
participant, participant,
rawParticipant, rawParticipant,
buildEvents: rawParticipant buildEvents: rawParticipant
? buildEventsByParticipantId.get( ? buildEventsByParticipantId.get(rawParticipant.participantId)
rawParticipant.participantId, : undefined,
) checkpoints: rawParticipant
? checkpointsByParticipantId.get(rawParticipant.participantId)
: undefined, : undefined,
teamKills, teamKills,
teamDamage, teamDamage,
@@ -246,6 +254,7 @@ export class MatchStatsFragmentBuilder {
timeline: [], timeline: [],
timelineLoaded: false, timelineLoaded: false,
objectiveEvents: [], objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side, side,
@@ -273,6 +282,7 @@ export class MatchStatsFragmentBuilder {
participant: MatchGameResultParticipant; participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto; rawParticipant?: RiotMatchParticipantDto;
buildEvents?: ParticipantBuildEvents; buildEvents?: ParticipantBuildEvents;
checkpoints?: MatchStatsParticipantCheckpoints;
teamKills: number; teamKills: number;
teamDamage: number; teamDamage: number;
}): InternalRecord { }): InternalRecord {
@@ -282,6 +292,7 @@ export class MatchStatsFragmentBuilder {
participant, participant,
rawParticipant, rawParticipant,
buildEvents, buildEvents,
checkpoints,
teamKills, teamKills,
teamDamage, teamDamage,
} = params; } = params;
@@ -319,6 +330,8 @@ export class MatchStatsFragmentBuilder {
riotMatchId: game.riotMatchId, riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation, gameCreation: game.gameCreation,
gameDuration: game.gameDuration, gameDuration: game.gameDuration,
participantId: rawParticipant?.participantId,
checkpoints,
userId: participant.userId.toString(), userId: participant.userId.toString(),
summonerName: summonerName:
snapshot?.gameName ?? snapshot?.gameName ??
@@ -405,7 +418,10 @@ export class MatchStatsFragmentBuilder {
private toBuildEventsByParticipantId( private toBuildEventsByParticipantId(
timeline?: RiotMatchTimelineDto, timeline?: RiotMatchTimelineDto,
): Map<number, ParticipantBuildEvents> { ): Map<number, ParticipantBuildEvents> {
const buildEventsByParticipantId = new Map<number, ParticipantBuildEvents>(); const buildEventsByParticipantId = new Map<
number,
ParticipantBuildEvents
>();
if (!timeline?.info.frames.length) return buildEventsByParticipantId; if (!timeline?.info.frames.length) return buildEventsByParticipantId;
const getEvents = (participantId: number): ParticipantBuildEvents => { const getEvents = (participantId: number): ParticipantBuildEvents => {
@@ -455,6 +471,107 @@ export class MatchStatsFragmentBuilder {
return buildEventsByParticipantId; return buildEventsByParticipantId;
} }
private toCheckpointsByParticipantId(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): Map<number, MatchStatsParticipantCheckpoints> {
const checkpointsByParticipantId = new Map<
number,
MatchStatsParticipantCheckpoints
>();
if (
!timeline?.info.frames.length ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0
) {
return checkpointsByParticipantId;
}
const participantIds = new Set<number>();
const championKillEvents = timeline.info.frames.flatMap((frame) =>
(frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'),
);
for (const frame of timeline.info.frames) {
for (const participantFrame of Object.values(frame.participantFrames)) {
participantIds.add(participantFrame.participantId);
}
}
const targets = [
['at10', 600_000],
['at15', 900_000],
] as const;
for (const participantId of participantIds) {
const checkpoints: MatchStatsParticipantCheckpoints = {};
for (const [key, targetTimestamp] of targets) {
if (gameDurationSeconds * 1_000 < targetTimestamp) continue;
const selectedFrame = timeline.info.frames.reduce<
RiotMatchTimelineDto['info']['frames'][number] | undefined
>((latest, frame) => {
if (
frame.timestamp > targetTimestamp ||
!Object.values(frame.participantFrames).some(
(participantFrame) =>
participantFrame.participantId === participantId,
)
) {
return latest;
}
return !latest || frame.timestamp > latest.timestamp ? frame : latest;
}, undefined);
if (
!selectedFrame ||
targetTimestamp - selectedFrame.timestamp >=
timeline.info.frameInterval
) {
continue;
}
const participantFrame = Object.values(
selectedFrame.participantFrames,
).find((frame) => frame.participantId === participantId);
if (
!participantFrame ||
typeof participantFrame.minionsKilled !== 'number' ||
!Number.isFinite(participantFrame.minionsKilled) ||
typeof participantFrame.jungleMinionsKilled !== 'number' ||
!Number.isFinite(participantFrame.jungleMinionsKilled)
) {
continue;
}
const checkpoint: MatchStatsCheckpoint = {
timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)),
gold: participantFrame.totalGold,
cs:
participantFrame.minionsKilled +
participantFrame.jungleMinionsKilled,
xp: participantFrame.xp,
kills: 0,
deaths: 0,
assists: 0,
};
for (const event of championKillEvents) {
if (event.timestamp > selectedFrame.timestamp) continue;
if (event.killerId === participantId && event.killerId > 0) {
checkpoint.kills += 1;
}
if (event.victimId === participantId) checkpoint.deaths += 1;
if (event.assistingParticipantIds?.includes(participantId)) {
checkpoint.assists += 1;
}
}
checkpoints[key] = checkpoint;
}
if (checkpoints.at10 || checkpoints.at15) {
checkpointsByParticipantId.set(participantId, checkpoints);
}
}
return checkpointsByParticipantId;
}
private toTimeline( private toTimeline(
raw: RiotMatchDto, raw: RiotMatchDto,
rawTeamIdBySide: Map<TeamSide, number>, rawTeamIdBySide: Map<TeamSide, number>,
@@ -511,65 +628,124 @@ export class MatchStatsFragmentBuilder {
return sideByParticipantId; return sideByParticipantId;
} }
private toObjectiveEvents( private toTimelineEvents(
timeline: RiotMatchTimelineDto | undefined, timeline: RiotMatchTimelineDto | undefined,
rawTeamIdBySide: Map<TeamSide, number>, rawTeamIdBySide: Map<TeamSide, number>,
sideByParticipantId: Map<number, TeamSide>, sideByParticipantId: Map<number, TeamSide>,
): MatchStatsObjectiveEvent[] { ): TimelineProjection {
if (!timeline?.info.frames.length) return []; if (!timeline?.info.frames.length) {
return { objectiveEvents: [], timelineEvents: [] };
}
const sideByTeamId = new Map<number, TeamSide>(); const sideByTeamId = new Map<number, TeamSide>();
for (const [side, teamId] of rawTeamIdBySide.entries()) { for (const [side, teamId] of rawTeamIdBySide.entries()) {
sideByTeamId.set(teamId, side); sideByTeamId.set(teamId, side);
} }
const objectiveEvents: MatchStatsObjectiveEvent[] = []; const projected: Array<{
sourceSequence: number;
event: MatchStatsTimelineEvent;
}> = [];
let sourceSequence = 0;
for (const frame of timeline.info.frames) { for (const frame of timeline.info.frames) {
for (const event of frame.events ?? []) { for (const event of frame.events ?? []) {
if (event.type !== 'ELITE_MONSTER_KILL') continue; const currentSequence = sourceSequence;
const side = sourceSequence += 1;
(typeof event.killerTeamId === 'number'
? sideByTeamId.get(event.killerTeamId)
: undefined) ??
(typeof event.killerId === 'number'
? sideByParticipantId.get(event.killerId)
: undefined);
if (!side) continue;
const timestamp = Math.max(0, Math.round(event.timestamp / 1000)); const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
switch (event.monsterType) { if (event.type === 'ELITE_MONSTER_KILL') {
case 'BARON_NASHOR': const side =
objectiveEvents.push({ timestamp, side, type: 'baron' }); (typeof event.killerTeamId === 'number'
break; ? sideByTeamId.get(event.killerTeamId)
case 'RIFTHERALD': : undefined) ??
objectiveEvents.push({ timestamp, side, type: 'riftHerald' }); (typeof event.killerId === 'number'
break; ? sideByParticipantId.get(event.killerId)
case 'HORDE': : undefined);
objectiveEvents.push({ timestamp, side, type: 'voidGrub' }); if (!side) continue;
break; const objectiveEvent = toObjectiveTimelineEvent({
case 'DRAGON': timestamp,
if (event.monsterSubType === 'ELDER_DRAGON') { side,
objectiveEvents.push({ monsterType: event.monsterType,
timestamp, monsterSubType: event.monsterSubType,
side, });
type: 'elderDragon', if (objectiveEvent) {
monsterSubType: event.monsterSubType, projected.push({
}); sourceSequence: currentSequence,
} else { event: objectiveEvent,
objectiveEvents.push({ });
timestamp, }
side, continue;
type: 'dragon',
monsterSubType: event.monsterSubType,
});
}
break;
default:
break;
} }
if (event.type === 'CHAMPION_KILL') {
const side =
typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
type: 'championKill',
...(side ? { side } : {}),
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(typeof event.victimId === 'number' && event.victimId > 0
? { victimParticipantId: event.victimId }
: {}),
...(event.assistingParticipantIds
? { assistingParticipantIds: event.assistingParticipantIds }
: {}),
},
});
continue;
}
if (event.type !== 'BUILDING_KILL') continue;
const destroyedSide =
typeof event.teamId === 'number'
? sideByTeamId.get(event.teamId)
: undefined;
const side =
(typeof event.killerId === 'number' && event.killerId > 0
? sideByParticipantId.get(event.killerId)
: undefined) ??
(destroyedSide ? oppositeSide(destroyedSide) : undefined);
const type =
event.buildingType === 'TOWER_BUILDING'
? 'tower'
: event.buildingType === 'INHIBITOR_BUILDING'
? 'inhibitor'
: undefined;
if (!side || !type) continue;
projected.push({
sourceSequence: currentSequence,
event: {
timestamp,
side,
type,
...(typeof event.killerId === 'number' && event.killerId > 0
? { killerParticipantId: event.killerId }
: {}),
...(type === 'tower' && event.towerType
? { towerType: event.towerType }
: {}),
},
});
} }
} }
return objectiveEvents.sort((left, right) => left.timestamp - right.timestamp); const timelineEvents = projected
.sort(
(left, right) =>
left.event.timestamp - right.event.timestamp ||
left.sourceSequence - right.sourceSequence,
)
.map(({ event }) => event);
return {
timelineEvents,
objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent),
};
} }
private toTimelineObjectives( private toTimelineObjectives(
@@ -608,29 +784,32 @@ export class MatchStatsFragmentBuilder {
} }
private toObjectiveSummary( private toObjectiveSummary(
rawTeam: rawTeam: RiotMatchDto['info']['teams'][number] | undefined,
| RiotMatchDto['info']['teams'][number]
| undefined,
timelineObjectives: MatchStatsObjectiveSummary | undefined, timelineObjectives: MatchStatsObjectiveSummary | undefined,
hasTimeline: boolean,
): MatchStatsObjectiveSummary { ): MatchStatsObjectiveSummary {
const rawObjectives = rawTeam?.objectives; const rawObjectives = rawTeam?.objectives;
const timelineDragon = timelineObjectives?.dragon ?? 0;
const timelineElder = timelineObjectives?.elderDragon ?? 0;
const hasProjectedDragon = timelineDragon + timelineElder > 0;
return { return {
tower: rawObjectives?.tower?.kills ?? 0, tower: rawObjectives?.tower?.kills ?? 0,
dragon: hasTimeline dragon: hasProjectedDragon
? (timelineObjectives?.dragon ?? 0) ? timelineDragon
: (rawObjectives?.dragon?.kills ?? 0), : (rawObjectives?.dragon?.kills ?? 0),
inhibitor: rawObjectives?.inhibitor?.kills ?? 0, inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
baron: hasTimeline baron:
? (timelineObjectives?.baron ?? 0) (timelineObjectives?.baron ?? 0) > 0
: (rawObjectives?.baron?.kills ?? 0), ? (timelineObjectives?.baron ?? 0)
riftHerald: hasTimeline : (rawObjectives?.baron?.kills ?? 0),
? (timelineObjectives?.riftHerald ?? 0) riftHerald:
: (rawObjectives?.riftHerald?.kills ?? 0), (timelineObjectives?.riftHerald ?? 0) > 0
voidGrub: hasTimeline ? (timelineObjectives?.riftHerald ?? 0)
? (timelineObjectives?.voidGrub ?? 0) : (rawObjectives?.riftHerald?.kills ?? 0),
: (rawObjectives?.horde?.kills ?? 0), voidGrub:
elderDragon: timelineObjectives?.elderDragon ?? 0, (timelineObjectives?.voidGrub ?? 0) > 0
? (timelineObjectives?.voidGrub ?? 0)
: (rawObjectives?.horde?.kills ?? 0),
elderDragon: hasProjectedDragon ? timelineElder : 0,
}; };
} }
@@ -687,6 +866,79 @@ function toItemBuildType(
} }
} }
function toObjectiveTimelineEvent(params: {
timestamp: number;
side: TeamSide;
monsterType?: string;
monsterSubType?: string;
}): MatchStatsObjectiveEvent | null {
switch (params.monsterType) {
case 'BARON_NASHOR':
return { timestamp: params.timestamp, side: params.side, type: 'baron' };
case 'RIFTHERALD':
return {
timestamp: params.timestamp,
side: params.side,
type: 'riftHerald',
};
case 'HORDE':
return {
timestamp: params.timestamp,
side: params.side,
type: 'voidGrub',
};
case 'DRAGON':
return {
timestamp: params.timestamp,
side: params.side,
type:
params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon',
monsterSubType: params.monsterSubType,
};
default:
return null;
}
}
function isObjectiveTimelineEvent(
event: MatchStatsTimelineEvent,
): event is MatchStatsObjectiveEvent {
return (
event.type === 'dragon' ||
event.type === 'elderDragon' ||
event.type === 'baron' ||
event.type === 'riftHerald' ||
event.type === 'voidGrub'
);
}
function oppositeSide(side: TeamSide): TeamSide {
return side === 'blue' ? 'red' : 'blue';
}
function isUsableTimeline(
timeline: RiotMatchTimelineDto | undefined,
gameDurationSeconds: number,
): timeline is RiotMatchTimelineDto {
if (
!timeline ||
!Number.isFinite(timeline.info.frameInterval) ||
timeline.info.frameInterval <= 0 ||
!Array.isArray(timeline.info.frames) ||
timeline.info.frames.length === 0
) {
return false;
}
const finalTimestamp = Math.max(
...timeline.info.frames.map((frame) => frame.timestamp),
);
return (
Number.isFinite(finalTimestamp) &&
Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) <
timeline.info.frameInterval
);
}
function round(value: number): number { function round(value: number): number {
return Math.round(value * 10) / 10; return Math.round(value * 10) / 10;
} }
@@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => {
if ( if (
stored && stored &&
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) && stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) &&
stored.sourceRevision! <= fragment.sourceRevision! stored.sourceRevision <= fragment.sourceRevision
) { ) {
stored = fragment; stored = fragment;
return { matchedCount: 1, upsertedCount: 0 }; return { matchedCount: 1, upsertedCount: 0 };
@@ -3,6 +3,7 @@ import { ConnectionService } from '../global/database/connection.service';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service'; import { MatchStatsService } from './match-stats.service';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
describe('MatchStatsService', () => { describe('MatchStatsService', () => {
it('deletes an existing fragment when the match is no longer eligible', async () => { it('deletes an existing fragment when the match is no longer eligible', async () => {
@@ -158,8 +159,10 @@ describe('MatchStatsService', () => {
match, match,
rawByRiotMatchId: expect.any(Map), rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map), timelineByRiotMatchId: expect.any(Map),
timelineLoadAttempted: false,
}); });
expect(
builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId,
).toHaveProperty('size', 0);
expect(repository.upsert).toHaveBeenCalledWith( expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
matchId, matchId,
@@ -167,11 +170,169 @@ describe('MatchStatsService', () => {
scheduledAt, scheduledAt,
gameCreationMin: 1_000, gameCreationMin: 1_000,
gameCreationMax: 2_000, gameCreationMax: 2_000,
builderVersion: 9, builderVersion: MATCH_STATS_BUILDER_VERSION,
}), }),
); );
}); });
it('retries unusable timeline caches and stores a later usable fetch', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const emptyTimeline = {
info: { frameInterval: 60_000, frames: [] },
};
const partialTimeline = {
info: {
frameInterval: 60_000,
frames: [{ timestamp: 0, events: [] }],
},
};
const nonPositiveTimeline = {
info: {
frameInterval: 0,
frames: [timelineFrame(120_000)],
},
};
const truncatedTimeline = {
info: {
frameInterval: 60_000,
frames: [timelineFrame()],
},
};
const usableTimeline = {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: ['puuid-1'],
},
info: {
frameInterval: 60_000,
frames: [timelineFrame(120_000)],
},
};
const cachedTimelines = [
emptyTimeline,
partialTimeline,
nonPositiveTimeline,
truncatedTimeline,
];
let buildIndex = 0;
const riotFind = jest.fn().mockImplementation(() => ({
lean: () => ({
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: { info: { gameDuration: 120 } },
timeline: cachedTimelines[Math.min(buildIndex++, 3)],
},
]),
}),
}));
const updateExec = jest.fn().mockResolvedValue(undefined);
let storedUpdate:
| {
filter: unknown;
update: { $set: { timeline: unknown; timelineFetchedAt: Date } };
}
| undefined;
const updateOne = jest.fn(
(
filter: unknown,
update: { $set: { timeline: unknown; timelineFetchedAt: Date } },
) => {
storedUpdate = { filter, update };
return { exec: updateExec };
},
);
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') {
return Promise.resolve({ findById: () => queryResult(match, false) });
}
if (name === 'competition') {
return Promise.resolve({ findOne: () => queryResult(null) });
}
if (name === 'riotMatch') {
return Promise.resolve({ find: riotFind, updateOne });
}
if (name === 'community') {
return Promise.resolve({
findById: () => ({
select: () => queryResult({ riotRegion: 'asia' }),
}),
});
}
return Promise.reject(new Error(`Unexpected model: ${name}`));
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
type BuildParams = Parameters<
MatchStatsFragmentBuilder['buildFragment']
>[0];
const buildCalls: BuildParams[] = [];
const builtFragment = {
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
const buildFragment = jest.fn((params: BuildParams) => {
buildCalls.push(params);
return builtFragment;
});
const builder = {
buildFragment,
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const getMatchTimeline = jest
.fn()
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockRejectedValueOnce(new Error('temporary Riot failure'))
.mockResolvedValueOnce(usableTimeline);
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline } as never,
);
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
await service.buildAndUpsert(matchId, { includeTimeline: true });
expect(getMatchTimeline).toHaveBeenCalledTimes(4);
expect(buildFragment).toHaveBeenCalledTimes(4);
expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0);
expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined();
expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe(
usableTimeline,
);
for (const call of buildCalls) {
expect(call).not.toHaveProperty('timelineLoadAttempted');
}
expect(updateOne).toHaveBeenCalledTimes(1);
expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' });
expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline);
expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date);
expect(updateExec).toHaveBeenCalledTimes(1);
});
it('builds from the Competition projection and records its source revision', async () => { it('builds from the Competition projection and records its source revision', 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();
@@ -451,3 +612,19 @@ function queryResult<T>(value: T, lean = true) {
query.lean.mockReturnValue(query); query.lean.mockReturnValue(query);
return lean ? query : { exec: query.exec }; return lean ? query : { exec: query.exec };
} }
function timelineFrame(timestamp = 0) {
return {
timestamp,
events: [],
participantFrames: {
'1': {
participantId: 1,
totalGold: 500,
xp: 0,
minionsKilled: 0,
jungleMinionsKilled: 0,
},
},
};
}
@@ -77,7 +77,7 @@ export class MatchStatsService {
); );
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>(); const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
for (const doc of riotDocs) { for (const doc of riotDocs) {
if (isRiotMatchTimelineDto(doc.timeline)) { if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) {
timelineByRiotMatchId.set(doc.matchId, doc.timeline); timelineByRiotMatchId.set(doc.matchId, doc.timeline);
} }
} }
@@ -94,6 +94,12 @@ export class MatchStatsService {
doc.matchId, doc.matchId,
{ region }, { region },
); );
if (!isUsableRiotMatchTimeline(timeline, doc.raw)) {
this.logger.warn(
`Ignored unusable match timeline for ${doc.matchId}.`,
);
continue;
}
await RiotMatchModel.updateOne( await RiotMatchModel.updateOne(
{ matchId: doc.matchId }, { matchId: doc.matchId },
{ {
@@ -118,7 +124,6 @@ export class MatchStatsService {
match: sourceMatch, match: sourceMatch,
rawByRiotMatchId, rawByRiotMatchId,
timelineByRiotMatchId, timelineByRiotMatchId,
timelineLoadAttempted: options.includeTimeline === true,
}); });
await this.repository.upsert({ await this.repository.upsert({
@@ -253,9 +258,65 @@ export class MatchStatsService {
} }
} }
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto { function isUsableRiotMatchTimeline(
if (!isRecord(value) || !isRecord(value.info)) return false; value: unknown,
return Array.isArray(value.info.frames); rawMatch: unknown,
): value is RiotMatchTimelineDto {
if (
!isRecord(value) ||
!isRecord(value.info) ||
!isRecord(rawMatch) ||
!isRecord(rawMatch.info)
) {
return false;
}
const frameInterval = finiteNumber(value.info.frameInterval);
const gameDuration = finiteNumber(rawMatch.info.gameDuration);
const frames = value.info.frames;
if (
frameInterval === undefined ||
frameInterval <= 0 ||
gameDuration === undefined ||
gameDuration < 0 ||
!Array.isArray(frames) ||
frames.length === 0 ||
!frames.every(isUsableTimelineFrame)
) {
return false;
}
const lastTimestamp = Math.max(
...frames.map((frame) => (frame as { timestamp: number }).timestamp),
);
return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval;
}
function isUsableTimelineFrame(value: unknown): boolean {
if (
!isRecord(value) ||
finiteNumber(value.timestamp) === undefined ||
!Array.isArray(value.events) ||
!value.events.every(
(event) =>
isRecord(event) &&
typeof event.type === 'string' &&
finiteNumber(event.timestamp) !== undefined,
) ||
!isRecord(value.participantFrames)
) {
return false;
}
const participantFrames = Object.values(value.participantFrames);
return (
participantFrames.length > 0 &&
participantFrames.every(
(participantFrame) =>
isRecord(participantFrame) &&
finiteNumber(participantFrame.participantId) !== undefined &&
finiteNumber(participantFrame.totalGold) !== undefined &&
finiteNumber(participantFrame.xp) !== undefined,
)
);
} }
function isRecord(value: unknown): value is Record<string, unknown> { function isRecord(value: unknown): value is Record<string, unknown> {
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema'; } from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types'; import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 9; export const MATCH_STATS_BUILDER_VERSION = 10;
export type InternalRecord = MatchStatsRecord; export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail; export type InternalGameDetail = MatchStatsGameDetail;
@@ -6,10 +6,7 @@ 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 { import { CommunityDocument, UserDocument } from '../global/database/schema';
CommunityDocument,
UserDocument,
} from '../global/database/schema';
export interface CreateCommunityInput { export interface CreateCommunityInput {
name: string; name: string;
@@ -485,11 +485,7 @@ function createHarness(
let competitionCall = 0; let competitionCall = 0;
const competitionModel = { const competitionModel = {
findOneAndUpdate: jest.fn( findOneAndUpdate: jest.fn(
( (_filter: unknown, update: { $setOnInsert: InsertPayload }) => {
_filter: unknown,
update: { $setOnInsert: InsertPayload },
_queryOptions: unknown,
) => {
insertedPayloads.push(update.$setOnInsert); insertedPayloads.push(update.$setOnInsert);
const selected = options.competitionResults?.[competitionCall++]; const selected = options.competitionResults?.[competitionCall++];
if (selected instanceof Error) return rejectedQuery(selected); if (selected instanceof Error) return rejectedQuery(selected);
@@ -66,7 +66,10 @@ describe('CompetitionCommandService', () => {
$inc: { revision: 1 }, $inc: { revision: 1 },
$set: { projection: PROJECTION }, $set: { projection: PROJECTION },
}); });
expect(casOptions).toMatchObject({ new: true, session: harness.session }); expect(casOptions).toMatchObject({
returnDocument: 'after',
session: harness.session,
});
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1); expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled(); expect(harness.session.commitTransaction).not.toHaveBeenCalled();
}); });
@@ -321,7 +321,7 @@ export class CompetitionCommandService {
phase: projection.phase, phase: projection.phase,
}, },
}, },
{ new: true, runValidators: true, session }, { returnDocument: 'after', runValidators: true, session },
) )
.lean() .lean()
.exec(); .exec();
@@ -475,7 +475,7 @@ export class CompetitionCommandService {
phase: projection.phase, phase: projection.phase,
}, },
}, },
{ new: true, runValidators: true, session }, { returnDocument: 'after', runValidators: true, session },
) )
.lean() .lean()
.exec(); .exec();
@@ -1,4 +1,8 @@
import { ConflictException, ForbiddenException } from '@nestjs/common'; import {
ConflictException,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { CompetitionQueryService } from './competition-query.service'; import { CompetitionQueryService } from './competition-query.service';
@@ -55,6 +59,38 @@ describe('CompetitionQueryService', () => {
}); });
}); });
it('resolves a team view from an explicit team id without a caller identity', async () => {
const harness = createHarness();
const service = createService(harness);
const result = await service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: TEAM_A_ID,
});
expect(result).toMatchObject({
teamId: TEAM_A_ID.toHexString(),
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
tournamentCodes: [
expect.objectContaining({ code: 'TEAM-A-SECRET-CODE' }),
],
});
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
});
it('does not resolve a team view for an unknown team id', async () => {
const service = createService(createHarness());
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: new Types.ObjectId('64c000000000000000000098'),
}),
).rejects.toBeInstanceOf(NotFoundException);
});
it('does not reveal a team view to an authenticated non-participant', async () => { it('does not reveal a team view to an authenticated non-participant', async () => {
const service = createService(createHarness()); const service = createService(createHarness());
@@ -22,6 +22,17 @@ export interface CompetitionScope {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
} }
/**
* A team view is addressed either by the caller's membership (signed-in) or by
* an explicit team id. The explicit form exists so that the team progress page
* stays usable while community members have not all signed in yet.
*/
export type TeamViewScope = CompetitionScope &
(
| { userId: mongoose.Types.ObjectId; teamId?: undefined }
| { teamId: mongoose.Types.ObjectId; userId?: undefined }
);
interface CompetitionProjectionSource { interface CompetitionProjectionSource {
series?: Array<Record<string, unknown>>; series?: Array<Record<string, unknown>>;
gameSlots?: Array<Record<string, unknown>>; gameSlots?: Array<Record<string, unknown>>;
@@ -68,15 +79,21 @@ export class CompetitionQueryService {
} }
public async getTeamView( public async getTeamView(
scope: CompetitionScope & { userId: mongoose.Types.ObjectId }, scope: TeamViewScope,
): Promise<TeamCompetitionViewResponse> { ): Promise<TeamCompetitionViewResponse> {
const competition = (await this.getCompetition(scope)) as Competition & { const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId; _id: PersistenceId;
}; };
const team = competition.teams.find(({ members }) => const requestedTeamId = scope.teamId;
members.some(({ userId }) => sameId(userId, scope.userId)), const team = requestedTeamId
); ? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId))
: competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
if (!team) { if (!team) {
if (requestedTeamId) {
throw new NotFoundException('Competition team not found.');
}
throw new ForbiddenException( throw new ForbiddenException(
'Only a Competition team member may access the team view.', 'Only a Competition team member may access the team view.',
); );
@@ -7,7 +7,7 @@ import { CompetitionController } from './competition.controller';
import { CompetitionQueryService } from './competition-query.service'; import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionController', () => { describe('CompetitionController', () => {
it('marks only the detail endpoint public and writes a revision ETag', async () => { it('marks the read endpoints public and writes a revision ETag', async () => {
const { controller, queryService } = createHarness(); const { controller, queryService } = createHarness();
const response = { setHeader: jest.fn() }; const response = { setHeader: jest.fn() };
@@ -17,18 +17,14 @@ describe('CompetitionController', () => {
response as never, response as never,
); );
expect( for (const method of ['getDetail', 'getTeamView'] as const) {
Reflect.getMetadata( expect(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, Reflect.getMetadata(
CompetitionController.prototype.getDetail, METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
), CompetitionController.prototype[method],
).toBe(true); ),
expect( ).toBe(true);
Reflect.getMetadata( }
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getTeamView,
),
).not.toBe(true);
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"'); expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 }); expect(result).toMatchObject({ revision: 7 });
expect(queryService.getCompetition).toHaveBeenCalledWith({ expect(queryService.getCompetition).toHaveBeenCalledWith({
@@ -37,6 +33,65 @@ describe('CompetitionController', () => {
}); });
}); });
it('reads a team view by explicit team id without an authenticated caller', async () => {
const { controller, queryService } = createHarness();
queryService.getTeamView.mockResolvedValue({ revision: 7 });
const response = { setHeader: jest.fn() };
const result = await controller.getTeamView(
undefined,
COMMUNITY_ID,
MATCH_ID,
TEAM_A_ID.toHexString(),
response as never,
);
expect(queryService.getTeamView).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: TEAM_A_ID,
});
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
});
it('falls back to the membership-scoped team view for a signed-in caller', async () => {
const { controller, queryService } = createHarness();
queryService.getTeamView.mockResolvedValue({ revision: 7 });
await controller.getTeamView(adminUser(), COMMUNITY_ID, MATCH_ID);
expect(queryService.getTeamView).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: ADMIN_ID,
});
});
it('rejects an anonymous team view request that names no team', async () => {
const { controller, queryService } = createHarness();
await expect(
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID),
).rejects.toMatchObject({
status: 401,
response: { error: { code: 'COMPETITION_TEAM_UNIDENTIFIED' } },
});
expect(queryService.getTeamView).not.toHaveBeenCalled();
});
it('rejects a malformed team id', async () => {
const { controller, queryService } = createHarness();
await expect(
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID, 'not-an-id'),
).rejects.toMatchObject({
status: 422,
response: { error: { code: 'INVALID_COMPETITION_REQUEST' } },
});
expect(queryService.getTeamView).not.toHaveBeenCalled();
});
it('protects audit and mutation endpoints with admin roles', () => { it('protects audit and mutation endpoints with admin roles', () => {
for (const method of [ for (const method of [
'listFacts', 'listFacts',
@@ -63,20 +63,36 @@ export class CompetitionController {
}); });
} }
// Temporarily public: community members are not all signed in yet, so the
// team progress page addresses a team through an explicit `teamId` instead of
// the caller's identity. A signed-in caller with no `teamId` keeps the
// membership-scoped behaviour.
@Get('team') @Get('team')
@AllowPublicAccess()
public async getTeamView( public async getTeamView(
@CurrentUser() currentUser: UserDocument, @CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe) @Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query('teamId') requestedTeamId?: string,
@Res({ passthrough: true }) response?: Response, @Res({ passthrough: true }) response?: Response,
): Promise<TeamCompetitionViewResponse> { ): Promise<TeamCompetitionViewResponse> {
return this.translate(async () => { return this.translate(async () => {
assertSameCommunity(currentUser, communityId); const teamId = parseOptionalObjectId(requestedTeamId, 'teamId');
if (!teamId) {
if (!currentUser) {
throw apiHttpError(
401,
'COMPETITION_TEAM_UNIDENTIFIED',
'Sign in or provide a teamId query parameter to read a team view.',
);
}
assertSameCommunity(currentUser, communityId);
}
const result = await this.queryService.getTeamView({ const result = await this.queryService.getTeamView({
communityId, communityId,
matchId, matchId,
userId: currentUser._id, ...(teamId ? { teamId } : { userId: currentUser!._id }),
}); });
response?.setHeader('ETag', revisionEtag(result.revision)); response?.setHeader('ETag', revisionEtag(result.revision));
return result; return result;
@@ -298,6 +314,21 @@ function requireCommandHeaders(
return revision; return revision;
} }
function parseOptionalObjectId(
value: string | undefined,
field: string,
): mongoose.Types.ObjectId | undefined {
if (value === undefined || value.trim().length === 0) return undefined;
if (!mongoose.isValidObjectId(value)) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
`The ${field} query parameter must be a valid ObjectId.`,
);
}
return new mongoose.Types.ObjectId(value);
}
function requireRevisionHeader(ifMatch: string | undefined): number { function requireRevisionHeader(ifMatch: string | undefined): number {
const revision = parseRevision(ifMatch); const revision = parseRevision(ifMatch);
if (revision === undefined) { if (revision === undefined) {
@@ -429,8 +429,14 @@ export function applyCompetitionDomainInvariantIndexes(
} }
} }
export type CompetitionModelName =
| 'competition'
| 'competitionFact'
| 'competitionOutbox'
| 'tournamentCodeAssignment';
export const competitionModelDefinitions: Array<{ export const competitionModelDefinitions: Array<{
name: string; name: CompetitionModelName;
schema: mongoose.Schema; schema: mongoose.Schema;
schemaName: string; schemaName: string;
}> = [ }> = [
@@ -1,4 +1,8 @@
import { projectCompetition } from './competition-projector'; import { projectCompetition } from './competition-projector';
import {
CompetitionDomainError,
type CompetitionDomainErrorCode,
} from './domain-error';
import { generateSeriesGraph } from './series-graph'; import { generateSeriesGraph } from './series-graph';
describe('projectCompetition', () => { describe('projectCompetition', () => {
@@ -323,20 +327,18 @@ describe('projectCompetition', () => {
'team-1', 'team-1',
); );
expect(() => expectCompetitionDomainError(
projectCompetition({ () =>
competitionId, projectCompetition({
revision: 1, competitionId,
projectorVersion: 1, revision: 1,
teams, projectorVersion: 1,
format, teams,
seriesGraph, format,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }], seriesGraph,
}), facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
).toThrow( }),
expect.objectContaining({ 'GAME_SERIES_MISMATCH',
code: 'GAME_SERIES_MISMATCH',
}),
); );
}); });
@@ -356,20 +358,18 @@ describe('projectCompetition', () => {
'team-1', 'team-1',
); );
expect(() => expectCompetitionDomainError(
projectCompetition({ () =>
competitionId, projectCompetition({
revision: 1, competitionId,
projectorVersion: 1, revision: 1,
teams, projectorVersion: 1,
format, teams,
seriesGraph, format,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }], seriesGraph,
}), facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
).toThrow( }),
expect.objectContaining({ 'GAME_SLOT_INVALID',
code: 'GAME_SLOT_INVALID',
}),
); );
}); });
@@ -382,36 +382,34 @@ describe('projectCompetition', () => {
}; };
const seriesGraph = generateSeriesGraph({ competitionId, teams, format }); const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
expect(() => expectCompetitionDomainError(
projectCompetition({ () =>
competitionId, projectCompetition({
revision: 1, competitionId,
projectorVersion: 1, revision: 1,
teams, projectorVersion: 1,
format, teams,
seriesGraph, format,
facts: [ seriesGraph,
{ facts: [
id: 'fact-unknown-adjudication-series', {
type: 'series-adjudicated', id: 'fact-unknown-adjudication-series',
competitionId, type: 'series-adjudicated',
revision: 1, competitionId,
ordinalWithinRevision: 1, revision: 1,
commandId: 'command-unknown-adjudication-series', ordinalWithinRevision: 1,
schemaVersion: 1, commandId: 'command-unknown-adjudication-series',
actor: { type: 'user' }, schemaVersion: 1,
occurredAt: new Date('2026-07-12T00:00:01.000Z'), actor: { type: 'user' },
recordedAt: new Date('2026-07-12T00:00:02.000Z'), occurredAt: new Date('2026-07-12T00:00:01.000Z'),
seriesId: 'series-does-not-exist', recordedAt: new Date('2026-07-12T00:00:02.000Z'),
decision: { type: 'administrative', winnerTeamId: 'team-1' }, seriesId: 'series-does-not-exist',
reason: 'Manual correction', decision: { type: 'administrative', winnerTeamId: 'team-1' },
}, reason: 'Manual correction',
], },
}), ],
).toThrow( }),
expect.objectContaining({ 'ADJUDICATION_INVALID',
code: 'ADJUDICATION_INVALID',
}),
); );
}); });
@@ -617,3 +615,23 @@ interface GameSlotLike {
id: string; id: string;
ordinal: number; ordinal: number;
} }
function expectCompetitionDomainError(
action: () => unknown,
expectedCode: CompetitionDomainErrorCode,
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionDomainError);
if (!(thrown instanceof CompetitionDomainError)) {
throw new Error(
`Expected CompetitionDomainError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
@@ -1,6 +1,7 @@
import { import {
assertReversalPreview, assertReversalPreview,
buildReversalFacts, buildReversalFacts,
CompetitionReversalError,
previewSeriesReversal, previewSeriesReversal,
} from './competition-reversal'; } from './competition-reversal';
@@ -19,18 +20,18 @@ describe('Competition reversal planning', () => {
]; ];
it('rejects strict reversal when a descendant has result activity', () => { it('rejects strict reversal when a descendant has result activity', () => {
expect(() => expectCompetitionReversalError(
previewSeriesReversal({ () =>
competitionId: 'competition-1', previewSeriesReversal({
revision: 2, competitionId: 'competition-1',
seriesId: 'series-parent', revision: 2,
mode: 'strict', seriesId: 'series-parent',
graph, mode: 'strict',
facts, graph,
assignments, facts,
}), assignments,
).toThrow( }),
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }), 'REVERSAL_DESCENDANT_ACTIVITY',
); );
}); });
@@ -105,20 +106,22 @@ describe('Competition reversal planning', () => {
assignments, assignments,
}); });
expect(() => expectCompetitionReversalError(
assertReversalPreview( () =>
{ assertReversalPreview(
competitionId: 'competition-1', {
revision: 3, competitionId: 'competition-1',
seriesId: 'series-parent', revision: 3,
mode: 'cascade', seriesId: 'series-parent',
graph, mode: 'cascade',
facts, graph,
assignments, facts,
}, assignments,
preview.impactHash, },
), preview.impactHash,
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' })); ),
'REVERSAL_PREVIEW_STALE',
);
}); });
it('emits one append-only reversal fact for every active result fact', () => { it('emits one append-only reversal fact for every active result fact', () => {
@@ -160,6 +163,26 @@ describe('Competition reversal planning', () => {
}); });
}); });
function expectCompetitionReversalError(
action: () => unknown,
expectedCode: CompetitionReversalError['code'],
): void {
let thrown: unknown;
try {
action();
} catch (error: unknown) {
thrown = error;
}
expect(thrown).toBeInstanceOf(CompetitionReversalError);
if (!(thrown instanceof CompetitionReversalError)) {
throw new Error(
`Expected CompetitionReversalError, received ${String(thrown)}`,
);
}
expect(thrown.code).toBe(expectedCode);
}
function series(id: string, sources: Array<Record<string, unknown>>) { function series(id: string, sources: Array<Record<string, unknown>>) {
return { return {
id, id,
@@ -1,5 +1,18 @@
import { generateSeriesGraph } from './series-graph'; import { generateSeriesGraph } from './series-graph';
type GraphInput = Parameters<typeof generateSeriesGraph>[0];
type ExplicitRoundRobinPairing = {
roundNumber: number;
matchNumber: number;
teamAId: string;
teamBId: string;
};
type ExplicitRoundRobinGraphInput = Omit<GraphInput, 'format'> & {
format: Extract<GraphInput['format'], { type: 'round-robin' }> & {
pairings: readonly ExplicitRoundRobinPairing[];
};
};
describe('generateSeriesGraph', () => { describe('generateSeriesGraph', () => {
it('generates a deterministic graph with stable opaque ids', () => { it('generates a deterministic graph with stable opaque ids', () => {
const input = { const input = {
@@ -112,8 +125,254 @@ describe('generateSeriesGraph', () => {
expect(error).toMatchObject({ code: 'INVALID_FIRST_TO_RULE' }); expect(error).toMatchObject({ code: 'INVALID_FIRST_TO_RULE' });
} }
}); });
it('reproduces an explicit persisted round-robin schedule by TeamId and pairing position', () => {
const input: ExplicitRoundRobinGraphInput = {
competitionId: 'competition-persisted-round-robin',
teams: Array.from({ length: 8 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: 8 - index,
seedNumber: index + 1,
})),
format: {
type: 'round-robin',
rule: fixedGames(1),
maxRounds: 3,
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
// Persisted schedules need not arrive in display order. Their explicit
// round/match positions, rather than array position, define identity.
pairings: [
pairing(3, 4, 'team-6', 'team-7'),
pairing(1, 2, 'team-3', 'team-4'),
pairing(2, 1, 'team-1', 'team-3'),
pairing(1, 4, 'team-7', 'team-8'),
pairing(3, 1, 'team-1', 'team-4'),
pairing(2, 3, 'team-5', 'team-7'),
pairing(1, 1, 'team-1', 'team-2'),
pairing(3, 3, 'team-5', 'team-8'),
pairing(2, 4, 'team-6', 'team-8'),
pairing(1, 3, 'team-5', 'team-6'),
pairing(3, 2, 'team-2', 'team-3'),
pairing(2, 2, 'team-2', 'team-4'),
],
},
};
const first = generateSeriesGraph(input);
const second = generateSeriesGraph({
...input,
format: {
...input.format,
pairings: [...input.format.pairings].reverse(),
},
});
expect(second).toEqual(first);
expect(
first.map((series) => ({
code: series.code,
roundNumber: series.stage.roundNumber,
displayOrder: series.stage.displayOrder,
sources: series.slots.map((slot) => slot.source),
})),
).toEqual([
roundRobinSeries('RR_R1_M1', 1, 1, 'team-1', 'team-2'),
roundRobinSeries('RR_R1_M2', 1, 2, 'team-3', 'team-4'),
roundRobinSeries('RR_R1_M3', 1, 3, 'team-5', 'team-6'),
roundRobinSeries('RR_R1_M4', 1, 4, 'team-7', 'team-8'),
roundRobinSeries('RR_R2_M1', 2, 5, 'team-1', 'team-3'),
roundRobinSeries('RR_R2_M2', 2, 6, 'team-2', 'team-4'),
roundRobinSeries('RR_R2_M3', 2, 7, 'team-5', 'team-7'),
roundRobinSeries('RR_R2_M4', 2, 8, 'team-6', 'team-8'),
roundRobinSeries('RR_R3_M1', 3, 9, 'team-1', 'team-4'),
roundRobinSeries('RR_R3_M2', 3, 10, 'team-2', 'team-3'),
roundRobinSeries('RR_R3_M3', 3, 11, 'team-5', 'team-8'),
roundRobinSeries('RR_R3_M4', 3, 12, 'team-6', 'team-7'),
]);
});
it.each([
{
name: 'a TeamId that is absent from the Competition',
replacement: pairing(1, 1, 'team-1', 'team-9'),
},
{
name: 'the same TeamId in both slots',
replacement: pairing(1, 1, 'team-1', 'team-1'),
},
{
name: 'a non-positive round number',
replacement: pairing(0, 1, 'team-1', 'team-2'),
},
{
name: 'a non-positive match number',
replacement: pairing(1, 0, 'team-1', 'team-2'),
},
])(
'rejects an explicit round-robin pairing with $name',
({ replacement }) => {
const input = explicitRoundRobinInput([
replacement,
pairing(1, 2, 'team-3', 'team-4'),
]);
expectGraphError(input, 'INVALID_ROUND_ROBIN_PAIRING');
},
);
it.each([
{
name: 'round and match position',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(1, 1, 'team-3', 'team-4'),
],
code: 'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
},
{
name: 'opponents with reversed slots',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(2, 1, 'team-2', 'team-1'),
],
code: 'DUPLICATE_ROUND_ROBIN_OPPONENTS',
},
])('rejects a duplicate explicit $name', ({ pairings, code }) => {
expectGraphError(explicitRoundRobinInput(pairings), code);
});
it('keeps distinct opponent pairs when opaque TeamIds contain delimiters', () => {
const input = explicitRoundRobinInput([
pairing(1, 1, 'a', 'b:c'),
pairing(1, 2, 'a:b', 'c'),
]);
input.format.maxRounds = 1;
input.teams = ['a', 'b:c', 'a:b', 'c'].map((teamId, index) => ({
teamId,
displayOrder: index + 1,
seedNumber: index + 1,
}));
expect(generateSeriesGraph(input)).toHaveLength(2);
});
it('validates complete odd-team rounds and clamps maxRounds to the full schedule', () => {
const pairings = [
pairing(1, 1, 'team-2', 'team-5'),
pairing(1, 2, 'team-3', 'team-4'),
pairing(2, 1, 'team-1', 'team-5'),
pairing(2, 2, 'team-2', 'team-3'),
pairing(3, 1, 'team-1', 'team-4'),
pairing(3, 2, 'team-3', 'team-5'),
pairing(4, 1, 'team-1', 'team-3'),
pairing(4, 2, 'team-2', 'team-4'),
pairing(5, 1, 'team-1', 'team-2'),
pairing(5, 2, 'team-4', 'team-5'),
];
const input = explicitRoundRobinInput(pairings);
input.teams = Array.from({ length: 5 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
}));
input.format.maxRounds = 10;
expect(generateSeriesGraph(input)).toHaveLength(10);
});
it.each([
{
name: 'an expected round',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(1, 2, 'team-3', 'team-4'),
],
},
{
name: 'a match from an expected round',
pairings: [
pairing(1, 1, 'team-1', 'team-2'),
pairing(1, 2, 'team-3', 'team-4'),
pairing(2, 1, 'team-1', 'team-3'),
],
},
])('rejects explicit pairings missing $name', ({ pairings }) => {
expectGraphError(
explicitRoundRobinInput(pairings),
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
);
});
}); });
function firstTo(winsRequired: number, maxGames: number) { function firstTo(winsRequired: number, maxGames: number) {
return { type: 'first-to' as const, winsRequired, maxGames }; return { type: 'first-to' as const, winsRequired, maxGames };
} }
function expectGraphError(input: GraphInput, code: string): void {
try {
generateSeriesGraph(input);
throw new Error(`Expected graph error ${code}.`);
} catch (error) {
expect(error).toMatchObject({ code });
}
}
function fixedGames(gameCount: number) {
return {
type: 'fixed-games' as const,
gameCount,
drawPolicy: 'allow' as const,
};
}
function pairing(
roundNumber: number,
matchNumber: number,
teamAId: string,
teamBId: string,
): ExplicitRoundRobinPairing {
return {
roundNumber,
matchNumber,
teamAId,
teamBId,
};
}
function explicitRoundRobinInput(
pairings: readonly ExplicitRoundRobinPairing[],
): ExplicitRoundRobinGraphInput {
return {
competitionId: 'competition-explicit-round-robin-validation',
teams: Array.from({ length: 4 }, (_, index) => ({
teamId: `team-${index + 1}`,
displayOrder: index + 1,
seedNumber: index + 1,
})),
format: {
type: 'round-robin',
rule: fixedGames(1),
maxRounds: 2,
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
pairings,
},
};
}
function roundRobinSeries(
code: string,
roundNumber: number,
displayOrder: number,
teamAId: string,
teamBId: string,
) {
return {
code,
roundNumber,
displayOrder,
sources: [
{ type: 'team', teamId: teamAId },
{ type: 'team', teamId: teamBId },
],
};
}
@@ -51,6 +51,11 @@ export interface SeriesDefinition {
{ position: 'B'; source: ParticipantSource }, { position: 'B'; source: ParticipantSource },
]; ];
rule: SeriesRule; rule: SeriesRule;
schedule?: {
date: string;
time: string | null;
timeZone: 'Asia/Seoul';
};
activation?: { activation?: {
type: 'grand-final-reset-required'; type: 'grand-final-reset-required';
grandFinalSeriesId: string; grandFinalSeriesId: string;
@@ -68,6 +73,13 @@ export interface CompetitionGraphTeam {
seedNumber?: number; seedNumber?: number;
} }
export interface RoundRobinPairing {
roundNumber: number;
matchNumber: number;
teamAId: string;
teamBId: string;
}
export type CompetitionGraphFormat = export type CompetitionGraphFormat =
| { | {
type: 'paired-series'; type: 'paired-series';
@@ -77,6 +89,7 @@ export type CompetitionGraphFormat =
type: 'round-robin'; type: 'round-robin';
rule: FixedGamesSeriesRule; rule: FixedGamesSeriesRule;
maxRounds?: number; maxRounds?: number;
pairings?: readonly RoundRobinPairing[];
tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head']; tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head'];
} }
| { | {
@@ -116,7 +129,7 @@ type TemplateParticipantSource =
} }
| { type: 'series-slot'; seriesCode: string; slot: SeriesSlot }; | { type: 'series-slot'; seriesCode: string; slot: SeriesSlot };
interface RoundRobinPairing { interface CanonicalRoundRobinPairing {
roundNumber: number; roundNumber: number;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
@@ -143,12 +156,7 @@ export function generateSeriesGraph(
); );
break; break;
case 'round-robin': case 'round-robin':
graph = generateRoundRobinGraph( graph = generateRoundRobinGraph(input.competitionId, teams, input.format);
input.competitionId,
teams,
input.format.rule,
input.format.maxRounds,
);
break; break;
case 'double-elimination': case 'double-elimination':
graph = generateDoubleEliminationGraph( graph = generateDoubleEliminationGraph(
@@ -200,10 +208,9 @@ function generatePairedSeriesGraph(
function generateRoundRobinGraph( function generateRoundRobinGraph(
competitionId: string, competitionId: string,
teams: CompetitionGraphTeam[], teams: CompetitionGraphTeam[],
rule: FixedGamesSeriesRule, format: Extract<CompetitionGraphFormat, { type: 'round-robin' }>,
maxRounds?: number,
): SeriesDefinition[] { ): SeriesDefinition[] {
assertFixedGamesRule(rule); assertFixedGamesRule(format.rule);
if (teams.length < 2) { if (teams.length < 2) {
throw graphError( throw graphError(
'INVALID_ROUND_ROBIN_TEAM_COUNT', 'INVALID_ROUND_ROBIN_TEAM_COUNT',
@@ -211,13 +218,16 @@ function generateRoundRobinGraph(
); );
} }
const pairings = roundRobinPairings(teams.length, maxRounds); const pairings = format.pairings
const matchNumberByRound = new Map<number, number>(); ? validateExplicitRoundRobinPairings(
teams,
format.pairings,
format.maxRounds,
)
: canonicalRoundRobinPairings(teams, format.maxRounds);
return pairings.map((pairing, index) => { return pairings.map((pairing, index) => {
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1; const code = `RR_R${pairing.roundNumber}_M${pairing.matchNumber}`;
matchNumberByRound.set(pairing.roundNumber, matchNumber);
const code = `RR_R${pairing.roundNumber}_M${matchNumber}`;
return createSeriesDefinition({ return createSeriesDefinition({
competitionId, competitionId,
code, code,
@@ -225,14 +235,139 @@ function generateRoundRobinGraph(
roundNumber: pairing.roundNumber, roundNumber: pairing.roundNumber,
displayOrder: index + 1, displayOrder: index + 1,
sources: [ sources: [
{ type: 'team', teamId: teams[pairing.teamAIndex].teamId }, { type: 'team', teamId: pairing.teamAId },
{ type: 'team', teamId: teams[pairing.teamBIndex].teamId }, { type: 'team', teamId: pairing.teamBId },
], ],
rule, rule: format.rule,
}); });
}); });
} }
function canonicalRoundRobinPairings(
teams: CompetitionGraphTeam[],
maxRounds?: number,
): RoundRobinPairing[] {
const matchNumberByRound = new Map<number, number>();
return roundRobinPairings(teams.length, maxRounds).map((pairing) => {
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
matchNumberByRound.set(pairing.roundNumber, matchNumber);
return {
roundNumber: pairing.roundNumber,
matchNumber,
teamAId: teams[pairing.teamAIndex].teamId,
teamBId: teams[pairing.teamBIndex].teamId,
};
});
}
function validateExplicitRoundRobinPairings(
teams: CompetitionGraphTeam[],
pairings: readonly RoundRobinPairing[],
maxRounds?: number,
): RoundRobinPairing[] {
if (pairings.length === 0) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'Explicit round-robin pairings cannot be empty.',
);
}
const teamIds = new Set(teams.map(({ teamId }) => teamId));
const positions = new Set<string>();
const opponentPairs = new Set<string>();
const teamsByRound = new Map<number, Set<string>>();
const sorted = pairings
.map((pairing) => ({ ...pairing }))
.sort(
(left, right) =>
left.roundNumber - right.roundNumber ||
left.matchNumber - right.matchNumber,
);
for (const pairing of sorted) {
if (
!Number.isInteger(pairing.roundNumber) ||
pairing.roundNumber < 1 ||
!Number.isInteger(pairing.matchNumber) ||
pairing.matchNumber < 1 ||
(maxRounds !== undefined && pairing.roundNumber > maxRounds) ||
!teamIds.has(pairing.teamAId) ||
!teamIds.has(pairing.teamBId) ||
pairing.teamAId === pairing.teamBId
) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'Every explicit round-robin pairing needs a valid position and two known, distinct teams.',
);
}
const position = `${pairing.roundNumber}:${pairing.matchNumber}`;
if (positions.has(position)) {
throw graphError(
'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
`Round-robin pairing position ${position} occurs more than once.`,
);
}
positions.add(position);
const opponents = JSON.stringify([pairing.teamAId, pairing.teamBId].sort());
if (opponentPairs.has(opponents)) {
throw graphError(
'DUPLICATE_ROUND_ROBIN_OPPONENTS',
'A round-robin opponent pair occurs more than once.',
);
}
opponentPairs.add(opponents);
const roundTeams = teamsByRound.get(pairing.roundNumber) ?? new Set();
if (roundTeams.has(pairing.teamAId) || roundTeams.has(pairing.teamBId)) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'A team cannot appear in multiple Series in the same round.',
);
}
roundTeams.add(pairing.teamAId);
roundTeams.add(pairing.teamBId);
teamsByRound.set(pairing.roundNumber, roundTeams);
}
for (const roundNumber of new Set(
sorted.map((pairing) => pairing.roundNumber),
)) {
const matches = sorted.filter(
(pairing) => pairing.roundNumber === roundNumber,
);
if (matches.some((pairing, index) => pairing.matchNumber !== index + 1)) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
`Round ${roundNumber} match numbers must be contiguous from one.`,
);
}
}
const expectedRoundCount = roundRobinRoundCount(teams.length, maxRounds);
const expectedMatchesPerRound = Math.floor(teams.length / 2);
for (
let roundNumber = 1;
roundNumber <= expectedRoundCount;
roundNumber += 1
) {
const matchCount = (teamsByRound.get(roundNumber)?.size ?? 0) / 2;
if (matchCount !== expectedMatchesPerRound) {
throw graphError(
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
`Round ${roundNumber} must contain ${expectedMatchesPerRound} Series.`,
);
}
}
if (teamsByRound.size !== expectedRoundCount) {
throw graphError(
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
`Explicit round-robin pairings must contain rounds 1 through ${expectedRoundCount}.`,
);
}
return sorted;
}
function generateDoubleEliminationGraph( function generateDoubleEliminationGraph(
competitionId: string, competitionId: string,
teams: CompetitionGraphTeam[], teams: CompetitionGraphTeam[],
@@ -436,20 +571,13 @@ function ruleForStage(
function roundRobinPairings( function roundRobinPairings(
teamCount: number, teamCount: number,
maxRounds?: number, maxRounds?: number,
): RoundRobinPairing[] { ): CanonicalRoundRobinPairing[] {
const bye = -1; const bye = -1;
const rotating = Array.from({ length: teamCount }, (_, index) => index); const rotating = Array.from({ length: teamCount }, (_, index) => index);
if (rotating.length % 2 === 1) rotating.push(bye); if (rotating.length % 2 === 1) rotating.push(bye);
const fullRoundCount = rotating.length - 1; const roundCount = roundRobinRoundCount(teamCount, maxRounds);
const requestedRounds = const pairings: CanonicalRoundRobinPairing[] = [];
maxRounds === undefined
? fullRoundCount
: Number.isFinite(maxRounds)
? Math.floor(maxRounds)
: fullRoundCount;
const roundCount = Math.max(0, Math.min(fullRoundCount, requestedRounds));
const pairings: RoundRobinPairing[] = [];
for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) { for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) {
for (let index = 0; index < rotating.length / 2; index += 1) { for (let index = 0; index < rotating.length / 2; index += 1) {
@@ -472,6 +600,17 @@ function roundRobinPairings(
return pairings; return pairings;
} }
function roundRobinRoundCount(teamCount: number, maxRounds?: number): number {
const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount;
const requestedRounds =
maxRounds === undefined
? fullRoundCount
: Number.isFinite(maxRounds)
? Math.floor(maxRounds)
: fullRoundCount;
return Math.max(0, Math.min(fullRoundCount, requestedRounds));
}
function normalizeTeams( function normalizeTeams(
teams: readonly CompetitionGraphTeam[], teams: readonly CompetitionGraphTeam[],
): CompetitionGraphTeam[] { ): CompetitionGraphTeam[] {
@@ -1,6 +1,110 @@
import { projectSeries } from './series-projector'; import { projectSeries } from './series-projector';
describe('projectSeries', () => { describe('projectSeries', () => {
it.each([
['a known local time', '21:30'],
['an unknown local time', null],
] as const)('preserves an optional Series schedule with %s', (_, time) => {
const schedule = {
date: '2026-07-15',
time,
timeZone: 'Asia/Seoul' as const,
};
const definition = {
...seriesDefinition({
id: `series-scheduled-${time ?? 'unknown'}`,
stage: 'upper',
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
}),
schedule,
};
const projection = projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [],
});
expect(projection).toMatchObject({
status: 'ready',
schedule,
});
});
it('keeps an existing definition without a schedule explicitly unscheduled', () => {
const definition = seriesDefinition({
id: 'series-unscheduled',
stage: 'upper',
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
});
const projection = projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [],
});
expect(projection).not.toHaveProperty('schedule');
});
it.each([
[
'an impossible calendar date',
{ date: '2026-02-30', time: '21:30', timeZone: 'Asia/Seoul' },
],
[
'an out-of-range local time',
{ date: '2026-07-15', time: '24:00', timeZone: 'Asia/Seoul' },
],
[
'a non-canonical time zone',
{ date: '2026-07-15', time: '21:30', timeZone: 'UTC' },
],
])('rejects a Series schedule with %s', (_, schedule) => {
const definition = {
...seriesDefinition({
id: `series-invalid-schedule-${schedule.date}-${schedule.time}`,
stage: 'upper',
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
}),
schedule,
} as unknown as Parameters<typeof projectSeries>[0]['definition'];
expectInvariant(
() =>
projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [],
}),
'SERIES_DEFINITION_INVALID',
);
});
it.each([null, false, ''])(
'rejects a non-object Series schedule value %p',
(schedule) => {
const definition = {
...seriesDefinition({
id: 'series-invalid-schedule-shape',
stage: 'upper',
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
}),
schedule,
} as unknown as Parameters<typeof projectSeries>[0]['definition'];
expectInvariant(
() =>
projectSeries({
definition,
participants: ['team-8', 'team-3'],
facts: [],
}),
'SERIES_DEFINITION_INVALID',
);
},
);
it('keeps a fixed-games pair in progress until every game slot is filled', () => { it('keeps a fixed-games pair in progress until every game slot is filled', () => {
const definition = seriesDefinition({ const definition = seriesDefinition({
id: 'series-pair', id: 'series-pair',
@@ -13,6 +13,12 @@ export type SeriesRule =
drawPolicy: 'allow' | 'tiebreak-required'; drawPolicy: 'allow' | 'tiebreak-required';
}; };
export interface SeriesSchedule {
date: string;
time: string | null;
timeZone: 'Asia/Seoul';
}
export interface SeriesDefinitionLike { export interface SeriesDefinitionLike {
id: string; id: string;
code?: string; code?: string;
@@ -26,6 +32,7 @@ export interface SeriesDefinitionLike {
source: Readonly<Record<string, unknown>>; source: Readonly<Record<string, unknown>>;
}>; }>;
rule: SeriesRule; rule: SeriesRule;
schedule?: SeriesSchedule;
gameSlots: ReadonlyArray<{ gameSlots: ReadonlyArray<{
id: string; id: string;
seriesId: string; seriesId: string;
@@ -75,6 +82,7 @@ interface SeriesProjectionBase {
code?: string; code?: string;
stage: SeriesDefinitionLike['stage']; stage: SeriesDefinitionLike['stage'];
rule: SeriesRule; rule: SeriesRule;
schedule?: SeriesSchedule;
entries: [SeriesProjectionEntry, SeriesProjectionEntry]; entries: [SeriesProjectionEntry, SeriesProjectionEntry];
} }
@@ -311,6 +319,15 @@ function validateDefinition(definition: SeriesDefinitionLike): void {
`Series ${definition.id} must define exactly the local A and B slots`, `Series ${definition.id} must define exactly the local A and B slots`,
); );
const schedule: unknown = definition.schedule;
if (schedule !== undefined) {
assertCompetitionInvariant(
isSeriesSchedule(schedule),
'SERIES_DEFINITION_INVALID',
`Series ${definition.id} has an invalid schedule`,
);
}
const requiredSlots = const requiredSlots =
definition.rule.type === 'fixed-games' definition.rule.type === 'fixed-games'
? definition.rule.gameCount ? definition.rule.gameCount
@@ -753,6 +770,7 @@ function projectionBase(
...(definition.code ? { code: definition.code } : {}), ...(definition.code ? { code: definition.code } : {}),
stage: definition.stage, stage: definition.stage,
rule: definition.rule, rule: definition.rule,
...(definition.schedule ? { schedule: { ...definition.schedule } } : {}),
entries: [ entries: [
{ slot: 'A', teamId: participants[0], gameWins: 0 }, { slot: 'A', teamId: participants[0], gameWins: 0 },
{ slot: 'B', teamId: participants[1], gameWins: 0 }, { slot: 'B', teamId: participants[1], gameWins: 0 },
@@ -760,6 +778,35 @@ function projectionBase(
}; };
} }
function isValidLocalDate(value: string): boolean {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (!match) return false;
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const date = new Date(Date.UTC(year, month - 1, day));
return (
date.getUTCFullYear() === year &&
date.getUTCMonth() === month - 1 &&
date.getUTCDate() === day
);
}
function isSeriesSchedule(value: unknown): value is SeriesSchedule {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return false;
}
const schedule = value as Record<string, unknown>;
return (
typeof schedule.date === 'string' &&
isValidLocalDate(schedule.date) &&
(schedule.time === null ||
(typeof schedule.time === 'string' &&
/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(schedule.time))) &&
schedule.timeZone === 'Asia/Seoul'
);
}
function entriesFor( function entriesFor(
participants: [string, string], participants: [string, string],
winsByTeam: Map<string, number>, winsByTeam: Map<string, number>,
@@ -9,7 +9,8 @@ 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_KEY =
'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000; const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
@Injectable() @Injectable()
@@ -78,35 +78,29 @@ export class DakaoOutboxService {
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, {
updateFilter, $set: {
{ state: 'published',
$set: { publishedAt: new Date(),
state: 'published',
publishedAt: new Date(),
},
$inc: { publishAttempts: 1 },
$unset: {
lastPublishError: '',
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
}, },
).exec(); $inc: { publishAttempts: 1 },
$unset: {
lastPublishError: '',
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
}).exec();
} catch (err) { } catch (err) {
await OutboxModel.updateOne( await OutboxModel.updateOne(updateFilter, {
updateFilter, $inc: { publishAttempts: 1 },
{ $set: {
$inc: { publishAttempts: 1 }, lastPublishError: (err as Error)?.message ?? String(err),
$set: {
lastPublishError: (err as Error)?.message ?? String(err),
},
$unset: {
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
}, },
).exec(); $unset: {
publishLeaseOwnerIdentifier: '',
publishLeaseExpiresAt: '',
},
}).exec();
this.logger.error( this.logger.error(
`Failed to publish Dakao outbox eventId=${params.eventId}: ${ `Failed to publish Dakao outbox eventId=${params.eventId}: ${
(err as Error)?.stack ?? err (err as Error)?.stack ?? err
@@ -105,7 +105,7 @@ describe('DakaoUserService', () => {
tagLine: 'KR2', tagLine: 'KR2',
isPrimary: false, isPrimary: false,
}); });
expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({ expect(result.user.riotAccounts[0]).toMatchObject({
puuid: 'puuid-1', puuid: 'puuid-1',
isPrimary: true, isPrimary: true,
}); });
@@ -87,7 +87,7 @@ export class DakaoUserService {
if (!community) { if (!community) {
throw new DakaoUserError('community_not_found', dakaoProjectId); throw new DakaoUserError('community_not_found', dakaoProjectId);
} }
return community._id as mongoose.Types.ObjectId; return community._id;
} }
public async upsertUser(params: { public async upsertUser(params: {
@@ -301,7 +301,7 @@ export class DakaoSubscriber implements OnModuleInit {
text: text:
index === this.usageCommands.length - 1 index === this.usageCommands.length - 1
? ` ${command}` ? ` ${command}`
: ` ${command} \n`, : ` ${command}\u3000\n`,
} as const, } as const,
]); ]);
} }
@@ -104,9 +104,11 @@ describe('MatchCancelHandler', () => {
const handler = makeHandler({ const handler = makeHandler({
matchService: { matchService: {
cancelJoin, cancelJoin,
list: jest.fn().mockResolvedValue([ list: jest
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, .fn()
]), .mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
} as Partial<MatchService>, } as Partial<MatchService>,
dakaoUserService: { dakaoUserService: {
findUserByKakaoTalkId, findUserByKakaoTalkId,
@@ -230,9 +230,11 @@ describe('MatchJoinHandler', () => {
const resolveRiotAccount = jest.fn(); const resolveRiotAccount = jest.fn();
const handler = makeHandler({ const handler = makeHandler({
matchService: { matchService: {
list: jest.fn().mockResolvedValue([ list: jest
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, .fn()
]), .mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
join, join,
} as Partial<MatchService>, } as Partial<MatchService>,
dakaoUserService: { dakaoUserService: {
@@ -282,9 +284,11 @@ describe('MatchJoinHandler', () => {
const join = jest.fn(); const join = jest.fn();
const handler = makeHandler({ const handler = makeHandler({
matchService: { matchService: {
list: jest.fn().mockResolvedValue([ list: jest
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, .fn()
]), .mockResolvedValue([
{ _id: matchId, title: '저녁 내전', shortCode: 'AB12' },
]),
join, join,
} as Partial<MatchService>, } as Partial<MatchService>,
dakaoUserService: { dakaoUserService: {
@@ -44,9 +44,7 @@ export class MatchJoinHandler {
return this.errorReply(params, joinTarget); return this.errorReply(params, joinTarget);
} }
let resolved: let resolved: { user: UserDocument; riotAccount: RiotAccount } | string;
| { user: UserDocument; riotAccount: RiotAccount }
| string;
try { try {
resolved = resolved =
joinTarget.gameName && joinTarget.tagLine joinTarget.gameName && joinTarget.tagLine
@@ -243,10 +241,7 @@ export class MatchJoinHandler {
const gameName = normalizeRiotIdPart(value.slice(splitAt + 1)); const gameName = normalizeRiotIdPart(value.slice(splitAt + 1));
if (!matchTitlePrefix || !gameName) continue; if (!matchTitlePrefix || !gameName) continue;
const result = resolveRecruitingMatchReference( const result = resolveRecruitingMatchReference(matchTitlePrefix, matches);
matchTitlePrefix,
matches,
);
if (result.kind === 'matched') { if (result.kind === 'matched') {
return { kind: 'matched', match: result.match, gameName }; return { kind: 'matched', match: result.match, gameName };
} }
@@ -22,6 +22,33 @@ function makeHandler(params: {
} }
describe('MatchListHandler', () => { describe('MatchListHandler', () => {
afterEach(() => {
jest.useRealTimers();
});
it('queries only matches scheduled at or after command processing time', async () => {
const now = new Date('2026-07-25T07:30:00.000Z');
jest.useFakeTimers().setSystemTime(now);
const communityId = objectId('111111111111111111111111');
const list = jest.fn().mockResolvedValue([]);
const handler = makeHandler({
matchService: { list },
});
await handler.handle({
communityId,
senderUserId: 'kakao-user-1',
senderNickname: '프리리',
});
expect(list).toHaveBeenCalledWith({
communityId,
status: 'recruiting',
scheduledFrom: now,
limit: 10,
});
});
it('prints short codes, compact KST dates, and short links', async () => { it('prints short codes, compact KST dates, and short links', async () => {
const match = { const match = {
_id: objectId('333333333333333333333333'), _id: objectId('333333333333333333333333'),
@@ -19,9 +19,11 @@ export class MatchListHandler {
senderUserId: string; senderUserId: string;
senderNickname: string; senderNickname: string;
}): Promise<DakaoSegment[]> { }): Promise<DakaoSegment[]> {
const scheduledFrom = new Date();
const matches = await this.matchService.list({ const matches = await this.matchService.list({
communityId: params.communityId, communityId: params.communityId,
status: 'recruiting', status: 'recruiting',
scheduledFrom,
limit: 10, limit: 10,
}); });
@@ -20,8 +20,8 @@ export class IdempotencyCache {
public remember(key: string): void { public remember(key: string): void {
this.evictExpired(); this.evictExpired();
if (this.entries.size >= MAX_ENTRIES) { if (this.entries.size >= MAX_ENTRIES) {
const oldestKey = this.entries.keys().next().value; const oldestKey: unknown = this.entries.keys().next().value;
if (oldestKey !== undefined) this.entries.delete(oldestKey); if (typeof oldestKey === 'string') this.entries.delete(oldestKey);
} }
this.entries.set(key, Date.now() + TTL_MS); this.entries.set(key, Date.now() + TTL_MS);
} }
@@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket(
teamIndex, teamIndex,
})); }));
const bracket: DoubleEliminationBracket = { const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length as 4 | 8, teamCount: seededTeamIndexes.length,
resetFinalEnabled: options.resetFinalEnabled, resetFinalEnabled: options.resetFinalEnabled,
resetFinalCreated: false, resetFinalCreated: false,
seeds, seeds,
@@ -19,7 +19,9 @@ describe('auction Redis schema foundation', () => {
expect(AuctionSchema.path('revision')).toBeDefined(); expect(AuctionSchema.path('revision')).toBeDefined();
expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined(); expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined();
expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined(); expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined();
expect(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined(); expect(
AuctionSchema.path('lastAppliedAuctionStateTransitionId'),
).toBeDefined();
expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined(); expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined();
expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined(); expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined();
expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined(); expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined();
@@ -36,46 +38,75 @@ describe('auction Redis schema foundation', () => {
expect(AuctionSchema.path('auctionBidHistory')).toBeDefined(); expect(AuctionSchema.path('auctionBidHistory')).toBeDefined();
expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined(); expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined();
expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined(); expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined();
expect(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined(); expect(
AuctionSchema.path('currentBidRoundDeadlineTimestampMS'),
).toBeDefined();
expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined(); expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined();
expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined(); expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined();
expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined(); expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined();
expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined(); expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined();
expect(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined(); expect(
AuctionSchema.path('manualTopTierAuctionPriorityUserIds'),
).toBeDefined();
expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined(); expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined();
expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined(); expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined();
}); });
it('adds history transition fields and reset/undo action enum values', () => { it('adds history transition fields and reset/undo action enum values', () => {
expect(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined(); expect(
AuctionHistoryEntrySchema.path('auctionStateTransitionId'),
).toBeDefined();
expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined(); expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined();
expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined(); expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined();
expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined(); expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined();
expect(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined(); expect(
AuctionHistoryEntrySchema.path('matchSideEffectMutation'),
).toBeDefined();
expect( expect(
AuctionHistoryEntrySchema.path<string>('action').options.enum, AuctionHistoryEntrySchema.path<string>('action').options.enum,
).toEqual( ).toEqual(
expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']), expect.arrayContaining([
'start',
'open-bidding',
'bid',
'sold',
'passed',
'next',
'complete',
'reset',
'undo',
]),
); );
}); });
it('adds unique history indexes for sequence and transition idempotency', () => { it('adds unique history indexes for sequence and transition idempotency', () => {
const indexes = AuctionHistoryEntrySchema.indexes(); const indexes = AuctionHistoryEntrySchema.indexes();
expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({ expect(
indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1],
).toMatchObject({
unique: true, unique: true,
}); });
expect( expect(
indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1], indexWithKeys(indexes, {
auctionId: 1,
auctionStateTransitionId: 1,
})?.[1],
).toMatchObject({ unique: true, sparse: true }); ).toMatchObject({ unique: true, sparse: true });
}); });
it('registers auction side effect application model with lease fields and unique idempotency index', () => { it('registers auction side effect application model with lease fields and unique idempotency index', () => {
expect(AuctionSideEffectApplicationSchema.path('processingOwnerToken')).toBeDefined();
expect( expect(
AuctionSideEffectApplicationSchema.path('processingLeaseExpiresAtTimestampMS'), AuctionSideEffectApplicationSchema.path('processingOwnerToken'),
).toBeDefined();
expect(
AuctionSideEffectApplicationSchema.path(
'processingLeaseExpiresAtTimestampMS',
),
).toBeDefined();
expect(
AuctionSideEffectApplicationSchema.path('payloadChecksum'),
).toBeDefined(); ).toBeDefined();
expect(AuctionSideEffectApplicationSchema.path('payloadChecksum')).toBeDefined();
const indexes = AuctionSideEffectApplicationSchema.indexes(); const indexes = AuctionSideEffectApplicationSchema.indexes();
expect( expect(
@@ -1,9 +1,75 @@
import mongoose from 'mongoose';
import { import {
ConnectionService,
resolveMongoAppName, resolveMongoAppName,
resolveMongoConnectionOptions, resolveMongoConnectionOptions,
resolveMongoDbName, resolveMongoDbName,
} from './connection.service'; } from './connection.service';
function createFakeConnection(connectionId: string) {
const models: Record<string, unknown> = {};
return {
readyState: mongoose.ConnectionStates.connected,
models,
model: jest.fn((name: string) => {
const model = { connectionId, modelName: name };
models[name] = model;
return model;
}),
};
}
describe('ConnectionService', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('shares one MongoDB connection across concurrent initialization calls', async () => {
const connection = createFakeConnection('shared');
const createConnection = jest
.spyOn(mongoose, 'createConnection')
.mockReturnValue({
asPromise: jest.fn().mockResolvedValue(connection),
} as never);
const service = new ConnectionService({
get: jest.fn().mockResolvedValue('mongodb://localhost/test'),
} as never);
const [first, second] = await Promise.all([
service.getConnection(),
service.getConnection(),
]);
expect(first).toBe(connection);
expect(second).toBe(connection);
expect(createConnection).toHaveBeenCalledTimes(1);
});
it('rebuilds models from the replacement connection after disconnect', async () => {
const firstConnection = createFakeConnection('first');
const secondConnection = createFakeConnection('second');
jest
.spyOn(mongoose, 'createConnection')
.mockReturnValueOnce({
asPromise: jest.fn().mockResolvedValue(firstConnection),
} as never)
.mockReturnValueOnce({
asPromise: jest.fn().mockResolvedValue(secondConnection),
} as never);
const service = new ConnectionService({
get: jest.fn().mockResolvedValue('mongodb://localhost/test'),
} as never);
const firstModel = await service.getModel('match');
firstConnection.readyState = mongoose.ConnectionStates.disconnected;
const secondModel = await service.getModel('match');
expect(firstModel).toMatchObject({ connectionId: 'first' });
expect(secondModel).toMatchObject({ connectionId: 'second' });
expect(secondModel).not.toBe(firstModel);
});
});
describe('resolveMongoDbName', () => { describe('resolveMongoDbName', () => {
it('uses production database only for prod', () => { it('uses production database only for prod', () => {
expect(resolveMongoDbName('prod')).toBe('lolympus'); expect(resolveMongoDbName('prod')).toBe('lolympus');
@@ -2,7 +2,10 @@ import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin'; 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,
type TournamentModelTypes,
} from './schema';
export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string { export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string {
if (nodeEnv === 'prod') return 'lolympus'; if (nodeEnv === 'prod') return 'lolympus';
@@ -39,9 +42,11 @@ export function resolveMongoConnectionOptions(
export class ConnectionService implements OnModuleInit { export class ConnectionService implements OnModuleInit {
private readonly logger = new Logger(ConnectionService.name); private readonly logger = new Logger(ConnectionService.name);
private connection: mongoose.Connection | null = null; private connection: mongoose.Connection | null = null;
private connectionPromise: Promise<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<keyof TournamentModelTypes, unknown> | null =
null;
public async getConnection(): Promise<mongoose.Connection> { public async getConnection(): Promise<mongoose.Connection> {
if ( if (
@@ -51,37 +56,55 @@ export class ConnectionService implements OnModuleInit {
return this.connection; return this.connection;
} }
const pendingConnection = this.connectionPromise ?? this.openConnection();
this.connectionPromise = pendingConnection;
try {
return await pendingConnection;
} finally {
if (this.connectionPromise === pendingConnection) {
this.connectionPromise = null;
}
}
}
private async openConnection(): Promise<mongoose.Connection> {
const connectionString = await this.secretService.get( const connectionString = await this.secretService.get(
'MONGODB_CONNECTION_STRING', 'MONGODB_CONNECTION_STRING',
); );
const dbName = resolveMongoDbName(); const dbName = resolveMongoDbName();
const appName = resolveMongoAppName(); const appName = resolveMongoAppName();
const connectionOptions = resolveMongoConnectionOptions(dbName, appName); const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
const defaultConnection = await mongoose const connection = await mongoose
.createConnection(connectionString, connectionOptions) .createConnection(connectionString, connectionOptions)
.asPromise(); .asPromise();
this.connection = defaultConnection;
this.connection = connection;
this.tournamentModels = null;
this.logger.log( this.logger.log(
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${ `MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
connectionOptions.autoIndex === true connectionOptions.autoIndex === true
}`, }`,
); );
return this.connection; return connection;
} }
public async getModel<K extends keyof TournamentModelTypes>( public async getModel<K extends keyof TournamentModelTypes>(
modelKey: K, modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> { ): Promise<mongoose.Model<TournamentModelTypes[K]>> {
if (this.tournamentModels)
return this.tournamentModels.get(modelKey) as mongoose.Model<
TournamentModelTypes[K]
>;
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
const connection = await this.getConnection(); const connection = await this.getConnection();
if (this.tournamentModels) {
return this.requireTournamentModel(this.tournamentModels, modelKey);
}
const models = new Map<keyof TournamentModelTypes, unknown>();
tournamentModelDefinitions.forEach((modelDefinition) => { tournamentModelDefinitions.forEach((modelDefinition) => {
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
throw new Error(
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
);
}
applyMongoosePerformancePlugin(modelDefinition.schema); applyMongoosePerformancePlugin(modelDefinition.schema);
// 이미 생성된 경우 컴파일 스킵. // 이미 생성된 경우 컴파일 스킵.
if ( if (
@@ -91,14 +114,14 @@ export class ConnectionService implements OnModuleInit {
) )
) { ) {
models.set( models.set(
modelDefinition.name as K, modelDefinition.name,
connection.models[modelDefinition.name], connection.models[modelDefinition.name],
); );
return; return;
} else { } else {
models.set( models.set(
modelDefinition.name as K, modelDefinition.name,
connection.model<TournamentModelTypes[K]>( connection.model(
modelDefinition.name, modelDefinition.name,
modelDefinition.schema, modelDefinition.schema,
modelDefinition.schemaName, modelDefinition.schemaName,
@@ -108,7 +131,18 @@ export class ConnectionService implements OnModuleInit {
}); });
this.tournamentModels = models; this.tournamentModels = models;
return models.get(modelKey) as mongoose.Model<TournamentModelTypes[K]>; return this.requireTournamentModel(models, modelKey);
}
private requireTournamentModel<K extends keyof TournamentModelTypes>(
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
modelKey: K,
): mongoose.Model<TournamentModelTypes[K]> {
const model = models.get(modelKey);
if (model === undefined) {
throw new Error(`Mongoose model ${modelKey} is not registered.`);
}
return model as mongoose.Model<TournamentModelTypes[K]>;
} }
public async createSession( public async createSession(
@@ -1,4 +1,4 @@
import { DynamicModule, Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConnectionService } from './connection.service'; import { ConnectionService } from './connection.service';
@Module({ @Module({
@@ -45,7 +45,10 @@ export async function migrateAuctionPassHistory(
}; };
}> = []; }> = [];
for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) { for await (const doc of db
.collection('auction')
.find({})
.limit(options.limit ?? 0)) {
stats.scannedAuctions += 1; stats.scannedAuctions += 1;
const set: Record<string, unknown> = {}; const set: Record<string, unknown> = {};
let changed = false; let changed = false;
@@ -27,17 +27,21 @@ function createDb(params: {
}, },
}; };
}, },
async bulkWrite(writes: Array<{ async bulkWrite(
updateOne: { writes: Array<{
filter: { _id: unknown }; updateOne: {
update: { filter: { _id: unknown };
$set: Record<string, unknown>; update: {
$unset: Record<string, ''>; $set: Record<string, unknown>;
$unset: Record<string, ''>;
};
}; };
}; }>,
}>) { ) {
for (const write of writes) { for (const write of writes) {
const doc = docs.find((item) => item._id === write.updateOne.filter._id); const doc = docs.find(
(item) => item._id === write.updateOne.filter._id,
);
if (!doc) continue; if (!doc) continue;
Object.assign(doc, write.updateOne.update.$set); Object.assign(doc, write.updateOne.update.$set);
for (const key of Object.keys(write.updateOne.update.$unset)) { for (const key of Object.keys(write.updateOne.update.$unset)) {
@@ -57,7 +61,10 @@ describe('migrateTeamIndex', () => {
auctions: [ auctions: [
{ {
_id: 'auction-1', _id: 'auction-1',
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], teams: [
{ side: 'blue', groupIndex: 1 },
{ side: 'red', groupIndex: 1 },
],
bids: [{ side: 'red', groupIndex: 1, amount: 100 }], bids: [{ side: 'red', groupIndex: 1, amount: 100 }],
currentBidder: 'red', currentBidder: 'red',
currentBidderGroupIndex: 1, currentBidderGroupIndex: 1,
@@ -66,7 +73,10 @@ describe('migrateTeamIndex', () => {
matches: [ matches: [
{ {
_id: 'match-1', _id: 'match-1',
teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], teams: [
{ side: 'blue', groupIndex: 1 },
{ side: 'red', groupIndex: 1 },
],
result: { result: {
winnerSide: 'blue', winnerSide: 'blue',
blueScore: 1, blueScore: 1,
@@ -112,7 +122,10 @@ describe('migrateTeamIndex', () => {
currentBidderTeamIndex: 2, currentBidderTeamIndex: 2,
}); });
expect(collections.match[0]).toMatchObject({ expect(collections.match[0]).toMatchObject({
teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }], teams: [
{ teamIndex: 1, name: '1팀' },
{ teamIndex: 2, name: '2팀' },
],
result: { result: {
winnerTeamIndex: 1, winnerTeamIndex: 1,
games: [ games: [
@@ -45,8 +45,20 @@ export async function migrateTeamIndex(
changedMatches: 0, changedMatches: 0,
}; };
await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction'); await migrateCollection(
await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match'); db.collection('auction'),
options.limit,
dryRun,
stats,
'auction',
);
await migrateCollection(
db.collection('match'),
options.limit,
dryRun,
stats,
'match',
);
return stats; return stats;
} }
@@ -60,7 +72,7 @@ async function migrateCollection(
) { ) {
const cursor = collection.find({}).limit(limit ?? 0); const cursor = collection.find({}).limit(limit ?? 0);
const writes: Array<{ const writes: Array<{
updateOne: { updateOne: {
filter: { _id: unknown }; filter: { _id: unknown };
update: { $set: Record<string, unknown>; $unset: Record<string, ''> }; update: { $set: Record<string, unknown>; $unset: Record<string, ''> };
}; };
@@ -143,7 +155,8 @@ function migrateMatch(doc: AnyDoc) {
const migrated = { ...team }; const migrated = { ...team };
const teamIndex = readTeamIndex(migrated); const teamIndex = readTeamIndex(migrated);
if (teamIndex !== undefined) migrated.teamIndex = teamIndex; if (teamIndex !== undefined) migrated.teamIndex = teamIndex;
if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`; if (!migrated.name && typeof teamIndex === 'number')
migrated.name = `${teamIndex}팀`;
if ('side' in migrated || 'groupIndex' in migrated) changed = true; if ('side' in migrated || 'groupIndex' in migrated) changed = true;
delete migrated.side; delete migrated.side;
delete migrated.groupIndex; delete migrated.groupIndex;
@@ -200,7 +213,10 @@ function migrateResult(result: Record<string, unknown>) {
migrated.games = games; migrated.games = games;
const seriesResults = asArray(result.seriesResults).map((series) => { const seriesResults = asArray(result.seriesResults).map((series) => {
if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') { if (
typeof series.teamAIndex === 'number' &&
typeof series.teamBIndex === 'number'
) {
return series; return series;
} }
changed = true; changed = true;
@@ -216,7 +232,9 @@ function migrateResult(result: Record<string, unknown>) {
const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex); const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex);
const blueScore = numberOrDefault(series.blueScore, 0); const blueScore = numberOrDefault(series.blueScore, 0);
const redScore = numberOrDefault(series.redScore, 0); const redScore = numberOrDefault(series.redScore, 0);
const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined; const winnerSide = isSide(series.winnerSide)
? series.winnerSide
: undefined;
const winnerTeamIndex = const winnerTeamIndex =
winnerSide === 'blue' winnerSide === 'blue'
? legacyBlueTeamIndex ? legacyBlueTeamIndex
@@ -231,12 +249,11 @@ function migrateResult(result: Record<string, unknown>) {
winnerTeamIndex, winnerTeamIndex,
}; };
}); });
migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games); migrated.seriesResults =
seriesResults.length > 0 ? seriesResults : buildSeries(games);
if (typeof migrated.winnerTeamIndex !== 'number') { if (typeof migrated.winnerTeamIndex !== 'number') {
const migratedSeriesResults = Array.isArray(migrated.seriesResults) const migratedSeriesResults = asArray(migrated.seriesResults);
? migrated.seriesResults
: [];
migrated.winnerTeamIndex = migrated.winnerTeamIndex =
resolveWinnerTeamIndex(migratedSeriesResults) ?? resolveWinnerTeamIndex(migratedSeriesResults) ??
(isSide(migrated.winnerSide) (isSide(migrated.winnerSide)
@@ -244,7 +261,11 @@ function migrateResult(result: Record<string, unknown>) {
: undefined); : undefined);
} }
if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) { if (
'winnerSide' in migrated ||
'blueScore' in migrated ||
'redScore' in migrated
) {
changed = true; changed = true;
} }
delete migrated.winnerSide; delete migrated.winnerSide;
@@ -272,8 +293,12 @@ function buildSeries(games: Record<string, unknown>[]) {
const teamAIndex = Math.min(blueTeamIndex, redTeamIndex); const teamAIndex = Math.min(blueTeamIndex, redTeamIndex);
const teamBIndex = Math.max(blueTeamIndex, redTeamIndex); const teamBIndex = Math.max(blueTeamIndex, redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`; const key = `${teamAIndex}:${teamBIndex}`;
const current = const current = bySeries.get(key) ?? {
bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 }; teamAIndex,
teamBIndex,
teamAWins: 0,
teamBWins: 0,
};
if (winnerTeamIndex === teamAIndex) current.teamAWins += 1; if (winnerTeamIndex === teamAIndex) current.teamAWins += 1;
if (winnerTeamIndex === teamBIndex) current.teamBWins += 1; if (winnerTeamIndex === teamBIndex) current.teamBWins += 1;
current.winnerTeamIndex = current.winnerTeamIndex =
@@ -331,5 +356,7 @@ function numberOrDefault(value: unknown, fallback: number) {
} }
function numberOrUndefined(value: unknown) { function numberOrUndefined(value: unknown) {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined; return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
} }
@@ -30,20 +30,26 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) {
}, },
}; };
}, },
async bulkWrite(writes: Array<{ async bulkWrite(
updateOne: { writes: Array<{
filter: { _id: unknown }; updateOne: {
update: { filter: { _id: unknown };
$set?: Record<string, unknown>; update: {
$unset?: Record<string, ''>; $set?: Record<string, unknown>;
$unset?: Record<string, ''>;
};
}; };
}; }>,
}>) { ) {
for (const write of writes) { for (const write of writes) {
const doc = docs.find((item) => item._id === write.updateOne.filter._id); const doc = docs.find(
(item) => item._id === write.updateOne.filter._id,
);
if (!doc) continue; if (!doc) continue;
Object.assign(doc, write.updateOne.update.$set ?? {}); Object.assign(doc, write.updateOne.update.$set ?? {});
for (const key of Object.keys(write.updateOne.update.$unset ?? {})) { for (const key of Object.keys(
write.updateOne.update.$unset ?? {},
)) {
delete doc[key]; delete doc[key];
} }
} }
@@ -31,7 +31,10 @@ interface MigrationStats {
} }
type AnyDoc = Record<string, unknown> & { _id: unknown }; type AnyDoc = Record<string, unknown> & { _id: unknown };
type UpdateDoc = { $set?: Record<string, unknown>; $unset?: Record<string, ''> }; type UpdateDoc = {
$set?: Record<string, unknown>;
$unset?: Record<string, ''>;
};
const AUCTION_FIELD_RENAMES: Array<{ const AUCTION_FIELD_RENAMES: Array<{
from: string; from: string;
@@ -43,7 +46,11 @@ const AUCTION_FIELD_RENAMES: Array<{
{ from: 'passedQueue', to: 'passedAuctionPlayerQueue' }, { from: 'passedQueue', to: 'passedAuctionPlayerQueue' },
{ from: 'auctionRound', to: 'currentAuctionRound' }, { from: 'auctionRound', to: 'currentAuctionRound' },
{ from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' }, { from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' },
{ from: 'bids', to: 'auctionBidHistory', transform: transformAuctionBidHistory }, {
from: 'bids',
to: 'auctionBidHistory',
transform: transformAuctionBidHistory,
},
{ from: 'currentBid', to: 'currentHighestBidPointAmount' }, { from: 'currentBid', to: 'currentHighestBidPointAmount' },
{ from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' }, { from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' },
{ {
@@ -157,7 +164,8 @@ async function countDuplicateHistorySequences(
const duplicates = new Set<string>(); const duplicates = new Set<string>();
for await (const doc of collection.find({}).limit(limit ?? 0)) { for await (const doc of collection.find({}).limit(limit ?? 0)) {
const auctionId = stringifyId(doc.auctionId); const auctionId = stringifyId(doc.auctionId);
const sequence = typeof doc.sequence === 'number' ? doc.sequence : undefined; const sequence =
typeof doc.sequence === 'number' ? doc.sequence : undefined;
if (!auctionId || sequence === undefined) continue; if (!auctionId || sequence === undefined) continue;
const key = `${auctionId}:${sequence}`; const key = `${auctionId}:${sequence}`;
@@ -322,6 +330,9 @@ function legacyAuctionLifecycleId(value: unknown): string {
function stringifyId(value: unknown): string | undefined { function stringifyId(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined; if (value === undefined || value === null) return undefined;
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
// stable string representation.
// eslint-disable-next-line @typescript-eslint/no-base-to-string
return typeof value === 'string' ? value : String(value); return typeof value === 'string' ? value : String(value);
} }
@@ -117,7 +117,9 @@ function createDb(params: {
function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean { function matchesFilter(doc: Doc, filter: Record<string, unknown>): boolean {
const clauses = filter.$or; const clauses = filter.$or;
if (Array.isArray(clauses)) { if (Array.isArray(clauses)) {
return clauses.some((clause) => matchesFilter(doc, clause)); return (clauses as unknown[]).some(
(clause) => isRecord(clause) && matchesFilter(doc, clause),
);
} }
return Object.entries(filter).every(([key, value]) => { return Object.entries(filter).every(([key, value]) => {
@@ -1,11 +1,4 @@
type TournamentCodeState = type TournamentCodeState = string;
| 'available'
| 'reserved'
| 'used'
| 'released'
| 'expired'
| 'voided'
| string;
type AnyDoc = Record<string, unknown> & { _id: unknown }; type AnyDoc = Record<string, unknown> & { _id: unknown };
type IndexKey = Record<string, 1 | -1>; type IndexKey = Record<string, 1 | -1>;
@@ -36,7 +29,7 @@ interface MigrationCollection {
$unset?: Record<string, ''>; $unset?: Record<string, ''>;
}, },
options?: { ordered?: boolean }, options?: { ordered?: boolean },
): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>; ): Promise<unknown>;
indexes?(): Promise<MigrationIndex[]>; indexes?(): Promise<MigrationIndex[]>;
dropIndex?(name: string): Promise<unknown>; dropIndex?(name: string): Promise<unknown>;
createIndex?( createIndex?(
@@ -516,15 +509,17 @@ function summarizeGroups(
function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary { function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary {
return { return {
bracketMatchId: bracketMatchId:
doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId), doc.bracketMatchId === undefined
code: doc.code === undefined ? undefined : String(doc.code), ? undefined
: stringifyId(doc.bracketMatchId),
code: doc.code === undefined ? undefined : stringifyId(doc.code),
gameNumber: gameNumber:
doc.gameNumber === undefined ? undefined : String(doc.gameNumber), doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber),
id: stringifyId(doc._id) ?? '', id: stringifyId(doc._id) ?? '',
matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId), matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId),
riotMatchId: riotMatchId:
doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId), doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId),
state: doc.state === undefined ? undefined : String(doc.state), state: doc.state,
}; };
} }
@@ -749,16 +744,19 @@ function readModifiedCount(result: unknown): number {
} }
function hasField(doc: Record<string, unknown>, key: string): boolean { function hasField(doc: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(doc, key); return Object.hasOwn(doc, key);
} }
function stringifyKeyPart(value: unknown): string { function stringifyKeyPart(value: unknown): string {
if (value === null) return '<null>'; if (value === null) return '<null>';
if (value === undefined) return '<undefined>'; if (value === undefined) return '<undefined>';
return stringifyId(value) ?? String(value); return stringifyId(value) ?? '<unknown>';
} }
function stringifyId(value: unknown): string | undefined { function stringifyId(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined; if (value === undefined || value === null) return undefined;
// MongoDB ObjectId and migration fixture IDs intentionally rely on their
// stable string representation.
// eslint-disable-next-line @typescript-eslint/no-base-to-string
return typeof value === 'string' ? value : String(value); return typeof value === 'string' ? value : String(value);
} }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -33,12 +33,73 @@ describe('migrateCompetitionDomain', () => {
factCount: 1, factCount: 1,
assignmentCount: 1, assignmentCount: 1,
}); });
if (result.matches[0].status !== 'ready') {
throw new Error('Expected a ready dry-run result.');
}
expect(result.matches[0].planHash).toMatch(/^sha256:[a-f0-9]{64}$/);
const repeated = await migrateCompetitionDomain(db);
expect(repeated.matches[0]).toMatchObject({ status: 'ready' });
if (repeated.matches[0].status !== 'ready') {
throw new Error('Expected a repeated ready dry-run result.');
}
expect(repeated.matches[0].planHash).toBe(result.matches[0].planHash);
expect(startSession).not.toHaveBeenCalled(); expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0); expect(db.writeCount).toBe(0);
expect(db.docs('competition')).toHaveLength(0); expect(db.docs('competition')).toHaveLength(0);
expect(db.createdIndexes).toHaveLength(0); expect(db.createdIndexes).toHaveLength(0);
}); });
it('reports apply-time global identity conflicts during dry-run without writes', async () => {
const riotMatchId = 'KR_DRY_RUN_GLOBAL_CONFLICT';
const match = readyMatch(riotMatchId);
const conflictingFactId = objectId();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive(riotMatchId)],
tournamentCode: [usedTournamentCode(match, riotMatchId)],
competition_fact: [
{
_id: conflictingFactId,
competitionId: objectId(),
type: 'game-accepted',
evidence: { type: 'riot', riotMatchId },
},
],
});
const dryRun = await migrateCompetitionDomain(db);
expect(dryRun.summary).toMatchObject({
scanned: 1,
ready: 0,
applied: 0,
quarantined: 1,
failed: 0,
});
expect(dryRun.matches[0]).toMatchObject({ status: 'quarantined' });
if (dryRun.matches[0].status !== 'quarantined') {
throw new Error('Expected a quarantined dry-run result.');
}
const conflict = dryRun.matches[0].reasons.find(
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
);
expect(conflict?.details?.collection).toBe('competition_fact');
expect(conflict?.details?.indexName).toBe('evidence.riotMatchId_1');
expect(conflict?.details?.conflictingDocumentId).toBe(
conflictingFactId.toHexString(),
);
expect(db.writeCount).toBe(0);
expect(db.createdIndexes).toHaveLength(0);
const applied = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(applied.summary).toMatchObject({ applied: 0, quarantined: 1 });
expect(applied.matches[0]).toEqual(dryRun.matches[0]);
});
it.each([ it.each([
['absent', (match: AnyDoc) => delete match.gameMode], ['absent', (match: AnyDoc) => delete match.gameMode],
['null', (match: AnyDoc) => (match.gameMode = null)], ['null', (match: AnyDoc) => (match.gameMode = null)],
@@ -157,6 +218,188 @@ describe('migrateCompetitionDomain', () => {
expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 }); expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
}); });
it('persists the source voidedAt timestamp without synthesizing it from usedAt', async () => {
const match = readyMatch('KR_VOIDED_TIMESTAMP');
const code = usedTournamentCode(match, 'KR_VOIDED_TIMESTAMP');
code.state = 'voided';
code.voidedAt = new Date('2026-07-03T00:00:00.000Z');
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive('KR_VOIDED_TIMESTAMP')],
tournamentCode: [code],
});
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(result.summary).toMatchObject({ applied: 1, failed: 0 });
expect(db.docs('tournament_code_assignment')).toContainEqual(
expect.objectContaining({
state: 'voided',
voidedAt: new Date('2026-07-03T00:00:00.000Z'),
updatedAt: new Date('2026-07-03T00:00:00.000Z'),
}),
);
});
it('hydrates Riot occurrence evidence and persists the normalized used transition idempotently', async () => {
const riotMatchId = 'KR_LEGACY_USED_TRANSITION';
const match = readyMatch(riotMatchId);
match.updatedAt = new Date('2026-07-03T00:06:00.000Z');
const legacyOccurrenceAt = new Date(1_782_864_000_000 + 1800 * 1000);
const code = usedTournamentCode(match, riotMatchId);
code.reservedAt = new Date('2026-07-03T00:00:00.000Z');
code.usedAt = legacyOccurrenceAt;
code.updatedAt = new Date('2026-07-03T00:05:00.000Z');
const originalCode = canonical(code);
const archive = riotArchive(riotMatchId);
archive.raw = {
info: {
gameCreation: 1_782_864_000_000,
gameEndTimestamp: legacyOccurrenceAt.getTime(),
},
};
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [archive],
tournamentCode: [code],
});
const dryRun = await migrateCompetitionDomain(db);
expect(dryRun.summary).toMatchObject({
ready: 1,
quarantined: 0,
warnings: 1,
});
const warning = dryRun.matches[0].warnings.find(
({ code: warningCode }) =>
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
);
expect(warning?.details).toMatchObject({
originalReservedAt: '2026-07-03T00:00:00.000Z',
originalUsedAt: legacyOccurrenceAt.toISOString(),
sourceUpdatedAt: '2026-07-03T00:05:00.000Z',
normalizedUsedAt: '2026-07-03T00:05:00.000Z',
legacyOccurrenceSource: 'riot-archive-gameEndTimestamp',
riotMatchId,
strategy: 'use-persisted-transition-time',
});
expect(db.writeCount).toBe(0);
const firstApply = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(firstApply.summary).toMatchObject({ applied: 1, failed: 0 });
expect(db.docs('tournament_code_assignment')).toContainEqual(
expect.objectContaining({
state: 'used',
reservedAt: new Date('2026-07-03T00:00:00.000Z'),
usedAt: new Date('2026-07-03T00:05:00.000Z'),
createdAt: new Date('2026-07-03T00:00:00.000Z'),
updatedAt: new Date('2026-07-03T00:05:00.000Z'),
}),
);
expect(canonical(db.docs('tournamentCode')[0])).toBe(originalCode);
const replay = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(replay.summary).toMatchObject({
applied: 0,
alreadyApplied: 1,
failed: 0,
});
});
it.each([
[
'raw.info.gameCreation',
{ raw: { info: { gameCreation: 1_782_864_000_000 } } },
],
[
'top-level gameCreation',
{
gameCreation: 1_782_864_000_000,
raw: { metadata: { matchId: 'KR_GAME_CREATION_FALLBACK' } },
},
],
])(
'hydrates the %s Riot occurrence fallback',
async (_label, archiveFields) => {
const riotMatchId = 'KR_GAME_CREATION_FALLBACK';
const match = readyMatch(riotMatchId);
const code = usedTournamentCode(match, riotMatchId);
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
const archive = Object.assign(riotArchive(riotMatchId), archiveFields);
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [archive],
tournamentCode: [code],
});
const result = await migrateCompetitionDomain(db);
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
const warning = result.matches[0].warnings.find(
({ code: warningCode }) =>
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
);
expect(warning?.details).toMatchObject({
originalUsedAt: '2026-07-01T00:00:00.000Z',
normalizedUsedAt: '2026-07-01T00:20:00.000Z',
legacyOccurrenceSource: 'riot-archive-gameCreation',
});
},
);
it.each([
['null', null],
['blank', ''],
['invalid', 'not-a-date'],
])(
'falls back to archive gameCreation when gameEndTimestamp is %s',
async (_label, invalidGameEnd) => {
const riotMatchId = 'KR_INVALID_ARCHIVE_GAME_END';
const match = readyMatch(riotMatchId);
const code = usedTournamentCode(match, riotMatchId);
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
const archive = riotArchive(riotMatchId);
archive.raw = {
info: {
gameEndTimestamp: invalidGameEnd,
gameCreation: 1_782_864_000_000,
},
};
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [archive],
tournamentCode: [code],
});
const result = await migrateCompetitionDomain(db);
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
const warning = result.matches[0].warnings.find(
({ code: warningCode }) =>
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
);
expect(warning?.details).toMatchObject({
legacyOccurrenceSource: 'riot-archive-gameCreation',
});
},
);
it('quarantines an ambiguous Match without changing any legacy Match field', async () => { it('quarantines an ambiguous Match without changing any legacy Match field', async () => {
const match = ambiguousMatch(); const match = ambiguousMatch();
const before = canonical(match); const before = canonical(match);
@@ -364,6 +607,46 @@ describe('migrateCompetitionDomain', () => {
expect(db.docs('competition_migration_quarantine')).toHaveLength(1); expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
}); });
it('detects the same global identity collision between dry-run plans as sequential apply', async () => {
const riotMatchId = 'KR_SHARED_DRY_RUN_MIGRATION';
const firstMatch = readyMatch(riotMatchId);
const secondMatch = readyMatch(riotMatchId);
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive(riotMatchId)],
tournamentCode: [
usedTournamentCode(firstMatch, riotMatchId),
usedTournamentCode(secondMatch, riotMatchId),
],
});
const dryRun = await migrateCompetitionDomain(db);
expect(dryRun.summary).toMatchObject({ ready: 1, quarantined: 1 });
expect(dryRun.matches.map(({ status }) => status)).toEqual([
'ready',
'quarantined',
]);
expect(dryRun.matches[1]).toMatchObject({ status: 'quarantined' });
if (dryRun.matches[1].status !== 'quarantined') {
throw new Error('Expected the second dry-run result to be quarantined.');
}
expect(
dryRun.matches[1].reasons.some(
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
),
).toBe(true);
expect(db.writeCount).toBe(0);
const applied = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(applied.summary).toMatchObject({ applied: 1, quarantined: 1 });
expect(applied.matches[1]).toEqual(dryRun.matches[1]);
});
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => { it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
const firstMatch = readyMatch('KR_BATCH_1'); const firstMatch = readyMatch('KR_BATCH_1');
const secondMatch = readyMatch('KR_BATCH_2'); const secondMatch = readyMatch('KR_BATCH_2');
@@ -98,6 +98,7 @@ export type CompetitionDomainMigrationMatchResult =
status: 'ready' | 'applied'; status: 'ready' | 'applied';
factCount: number; factCount: number;
assignmentCount: number; assignmentCount: number;
planHash: string;
}) })
| (CompetitionDomainMigrationMatchBase & { | (CompetitionDomainMigrationMatchBase & {
status: 'already-applied'; status: 'already-applied';
@@ -206,11 +207,17 @@ export async function migrateCompetitionDomain(
resumeStart.startedAfterMatchId, resumeStart.startedAfterMatchId,
); );
const matches: CompetitionDomainMigrationMatchResult[] = []; const matches: CompetitionDomainMigrationMatchResult[] = [];
const dryRunUniquenessClaims = new Map<string, ClaimedUniqueIdentity>();
let checkpointAfterMatchId = resumeStart.startedAfterMatchId; let checkpointAfterMatchId = resumeStart.startedAfterMatchId;
let haltedOnFailure = false; let haltedOnFailure = false;
for (const [index, scannedMatch] of scan.matches.entries()) { for (const [index, scannedMatch] of scan.matches.entries()) {
const result = dryRun const result = dryRun
? await inspectMatch(db, scannedMatch, migrationRunId) ? await inspectMatch(
db,
scannedMatch,
migrationRunId,
dryRunUniquenessClaims,
)
: await applyMatch(db, scannedMatch, migrationRunId, options); : await applyMatch(db, scannedMatch, migrationRunId, options);
matches.push(result); matches.push(result);
options.onProgress?.({ options.onProgress?.({
@@ -433,6 +440,7 @@ async function inspectMatch(
db: CompetitionDomainMigrationDb, db: CompetitionDomainMigrationDb,
scannedMatch: AnyDocument, scannedMatch: AnyDocument,
migrationRunId: string, migrationRunId: string,
uniquenessClaims: Map<string, ClaimedUniqueIdentity>,
): Promise<CompetitionDomainMigrationMatchResult> { ): Promise<CompetitionDomainMigrationMatchResult> {
const matchId = idString(scannedMatch._id); const matchId = idString(scannedMatch._id);
try { try {
@@ -450,6 +458,21 @@ async function inspectMatch(
const legacy = await hydrateLegacyMatch(db, scannedMatch); const legacy = await hydrateLegacyMatch(db, scannedMatch);
const plan = planCompetitionMigration(legacy, { migrationRunId }); const plan = planCompetitionMigration(legacy, { migrationRunId });
if (plan.status === 'ready') {
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
db,
plan,
{ claims: uniquenessClaims },
);
if (uniquenessConflicts.length > 0) {
return {
status: 'quarantined',
matchId,
warnings: plan.warnings,
reasons: uniquenessConflicts,
};
}
}
return planResult(matchId, plan); return planResult(matchId, plan);
} catch (error) { } catch (error) {
return failedResult(matchId, error); return failedResult(matchId, error);
@@ -521,7 +544,7 @@ async function applyMatch(
const uniquenessConflicts = await findReadyPlanUniquenessConflicts( const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
db, db,
plan, plan,
session, { session },
); );
if (uniquenessConflicts.length > 0) { if (uniquenessConflicts.length > 0) {
await persistQuarantine( await persistQuarantine(
@@ -577,6 +600,7 @@ async function applyMatch(
competitionId, competitionId,
factCount: plan.facts.length, factCount: plan.facts.length,
assignmentCount: plan.assignments.length, assignmentCount: plan.assignments.length,
planHash: readyPlanHash(plan),
warnings: plan.warnings, warnings: plan.warnings,
}; };
} catch (error) { } catch (error) {
@@ -592,12 +616,21 @@ interface UniqueIdentityCheck {
indexName: string; indexName: string;
filter: Record<string, unknown>; filter: Record<string, unknown>;
expectedDocumentId: string; expectedDocumentId: string;
expectedCompetitionId?: string;
}
interface ClaimedUniqueIdentity {
documentId: string;
competitionId?: string;
} }
async function findReadyPlanUniquenessConflicts( async function findReadyPlanUniquenessConflicts(
db: CompetitionDomainMigrationDb, db: CompetitionDomainMigrationDb,
plan: ReadyCompetitionMigrationPlan, plan: ReadyCompetitionMigrationPlan,
session: CompetitionDomainMigrationSession, options: {
session?: CompetitionDomainMigrationSession;
claims?: Map<string, ClaimedUniqueIdentity>;
} = {},
): Promise<CompetitionMigrationIssue[]> { ): Promise<CompetitionMigrationIssue[]> {
const checks: UniqueIdentityCheck[] = [ const checks: UniqueIdentityCheck[] = [
{ {
@@ -619,6 +652,7 @@ async function findReadyPlanUniquenessConflicts(
ordinalWithinRevision: fact.ordinalWithinRevision, ordinalWithinRevision: fact.ordinalWithinRevision,
}, },
expectedDocumentId: fact.id, expectedDocumentId: fact.id,
expectedCompetitionId: fact.competitionId,
}, },
{ {
collection: 'competition_fact', collection: 'competition_fact',
@@ -629,6 +663,7 @@ async function findReadyPlanUniquenessConflicts(
ordinalWithinRevision: fact.ordinalWithinRevision, ordinalWithinRevision: fact.ordinalWithinRevision,
}, },
expectedDocumentId: fact.id, expectedDocumentId: fact.id,
expectedCompetitionId: fact.competitionId,
}, },
); );
if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') { if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') {
@@ -640,6 +675,7 @@ async function findReadyPlanUniquenessConflicts(
'evidence.riotMatchId': fact.evidence.riotMatchId, 'evidence.riotMatchId': fact.evidence.riotMatchId,
}, },
expectedDocumentId: fact.id, expectedDocumentId: fact.id,
expectedCompetitionId: fact.competitionId,
}); });
} }
} }
@@ -655,6 +691,7 @@ async function findReadyPlanUniquenessConflicts(
state: { $in: ['reserved', 'used'] }, state: { $in: ['reserved', 'used'] },
}, },
expectedDocumentId: assignment.id, expectedDocumentId: assignment.id,
expectedCompetitionId: assignment.competitionId,
}, },
{ {
collection: 'tournament_code_assignment', collection: 'tournament_code_assignment',
@@ -664,6 +701,7 @@ async function findReadyPlanUniquenessConflicts(
state: { $in: ['reserved', 'used'] }, state: { $in: ['reserved', 'used'] },
}, },
expectedDocumentId: assignment.id, expectedDocumentId: assignment.id,
expectedCompetitionId: assignment.competitionId,
}, },
); );
} }
@@ -673,6 +711,7 @@ async function findReadyPlanUniquenessConflicts(
indexName: 'riotMatchId_1', indexName: 'riotMatchId_1',
filter: { riotMatchId: assignment.riotMatchId }, filter: { riotMatchId: assignment.riotMatchId },
expectedDocumentId: assignment.id, expectedDocumentId: assignment.id,
expectedCompetitionId: assignment.competitionId,
}); });
} }
} }
@@ -680,30 +719,66 @@ async function findReadyPlanUniquenessConflicts(
const conflicts: CompetitionMigrationIssue[] = []; const conflicts: CompetitionMigrationIssue[] = [];
// Mongo sessions do not support parallel operations inside one transaction. // Mongo sessions do not support parallel operations inside one transaction.
for (const check of checks) { for (const check of checks) {
const claim = options.claims?.get(uniqueIdentityKey(check));
if (claim && claim.documentId !== check.expectedDocumentId) {
conflicts.push(
uniqueIdentityConflict(check, {
_id: persistenceId(claim.documentId),
...(claim.competitionId
? { competitionId: persistenceId(claim.competitionId) }
: {}),
}),
);
continue;
}
const existing = await db const existing = await db
.collection(check.collection) .collection(check.collection)
.findOne(check.filter, { session }); .findOne(
check.filter,
options.session ? { session: options.session } : undefined,
);
if (!existing || idString(existing._id) === check.expectedDocumentId) { if (!existing || idString(existing._id) === check.expectedDocumentId) {
continue; continue;
} }
conflicts.push({ conflicts.push(uniqueIdentityConflict(check, existing));
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT', }
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`, if (conflicts.length === 0 && options.claims) {
details: { for (const check of checks) {
collection: check.collection, options.claims.set(uniqueIdentityKey(check), {
indexName: check.indexName, documentId: check.expectedDocumentId,
key: canonicalValue(check.filter) as Record<string, unknown>, ...(check.expectedCompetitionId
expectedDocumentId: check.expectedDocumentId, ? { competitionId: check.expectedCompetitionId }
conflictingDocumentId: idString(existing._id),
...(existing.competitionId
? { conflictingCompetitionId: idString(existing.competitionId) }
: {}), : {}),
}, });
}); }
} }
return conflicts; return conflicts;
} }
function uniqueIdentityKey(check: UniqueIdentityCheck): string {
return `${check.collection}:${check.indexName}:${canonicalJson(check.filter)}`;
}
function uniqueIdentityConflict(
check: UniqueIdentityCheck,
existing: AnyDocument,
): CompetitionMigrationIssue {
return {
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
details: {
collection: check.collection,
indexName: check.indexName,
key: canonicalValue(check.filter) as Record<string, unknown>,
expectedDocumentId: check.expectedDocumentId,
conflictingDocumentId: idString(existing._id),
...(existing.competitionId
? { conflictingCompetitionId: idString(existing.competitionId) }
: {}),
},
};
}
async function hydrateLegacyMatch( async function hydrateLegacyMatch(
db: CompetitionDomainMigrationDb, db: CompetitionDomainMigrationDb,
match: AnyDocument, match: AnyDocument,
@@ -781,15 +856,67 @@ function hydrateLegacyGameEvidence(
typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0 typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0
? game.payloadHash ? game.payloadHash
: undefined; : undefined;
const archiveRaw = isRecord(archive.raw) ? archive.raw : undefined;
const archiveInfo = isRecord(archiveRaw?.info) ? archiveRaw.info : undefined;
const riotGameEndEvidence = resolveRiotGameEndEvidence(
archiveInfo,
archive.gameCreation,
);
return { return {
...game, ...game,
riotArchivePresent: true, riotArchivePresent: true,
...(riotGameEndEvidence === undefined
? {}
: {
riotGameEndedAt: riotGameEndEvidence.value,
riotGameEndedAtSource: riotGameEndEvidence.source,
}),
payloadHash: payloadHash:
existingPayloadHash ?? existingPayloadHash ??
`sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`, `sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`,
}; };
} }
function resolveRiotGameEndEvidence(
archiveInfo: Record<string, unknown> | undefined,
archiveGameCreation: unknown,
):
| {
value: unknown;
source: 'gameEndTimestamp' | 'gameCreation';
}
| undefined {
const candidates = [
{
value: archiveInfo?.gameEndTimestamp,
source: 'gameEndTimestamp' as const,
},
{
value: archiveInfo?.gameCreation,
source: 'gameCreation' as const,
},
{ value: archiveGameCreation, source: 'gameCreation' as const },
];
return candidates.find(({ value }) => isValidRiotTimestamp(value));
}
function isValidRiotTimestamp(value: unknown): boolean {
if (value === undefined || value === null || value === '') return false;
if (typeof value === 'string' && value.trim() === '') return false;
if (typeof value === 'number' && !Number.isFinite(value)) return false;
const normalized =
typeof value === 'number' && value < 10_000_000_000 ? value * 1000 : value;
try {
const date =
normalized instanceof Date
? normalized
: new Date(normalized as string | number);
return !Number.isNaN(date.getTime());
} catch {
return false;
}
}
async function upsertReadyPlan( async function upsertReadyPlan(
db: CompetitionDomainMigrationDb, db: CompetitionDomainMigrationDb,
plan: ReadyCompetitionMigrationPlan, plan: ReadyCompetitionMigrationPlan,
@@ -1085,12 +1212,18 @@ function assignmentForPersistence(
): AnyDocument { ): AnyDocument {
const reservedAt = new Date(assignment.reservedAt); const reservedAt = new Date(assignment.reservedAt);
const updatedAt = new Date( const updatedAt = new Date(
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt, assignment.voidedAt ??
assignment.releasedAt ??
assignment.usedAt ??
assignment.reservedAt,
); );
const voidedAt = const voidedAt =
assignment.state === 'voided' assignment.state === 'voided'
? new Date( ? new Date(
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt, assignment.voidedAt ??
assignment.releasedAt ??
assignment.usedAt ??
assignment.reservedAt,
) )
: undefined; : undefined;
return { return {
@@ -1138,10 +1271,23 @@ function planResult(
competitionId: plan.competition.id, competitionId: plan.competition.id,
factCount: plan.facts.length, factCount: plan.facts.length,
assignmentCount: plan.assignments.length, assignmentCount: plan.assignments.length,
planHash: readyPlanHash(plan),
warnings: plan.warnings, warnings: plan.warnings,
}; };
} }
function readyPlanHash(plan: ReadyCompetitionMigrationPlan): string {
return `sha256:${createHash('sha256')
.update(
canonicalJson({
competition: plan.competition,
facts: plan.facts,
assignments: plan.assignments,
}),
)
.digest('hex')}`;
}
function failedResult( function failedResult(
matchId: string, matchId: string,
error: unknown, error: unknown,
@@ -11,7 +11,11 @@ import {
} from '../../../double-elimination/double-elimination.util'; } from '../../../double-elimination/double-elimination.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants'; import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
import { ConnectionService } from '../connection.service'; import { ConnectionService } from '../connection.service';
import type { MatchDocument, TournamentCodeDocument } from '../schema'; import type {
MatchDocument,
TournamentCode,
TournamentCodeDocument,
} from '../schema';
import { SecretModule } from '../../secret/secret.module'; import { SecretModule } from '../../secret/secret.module';
interface CliOptions { interface CliOptions {
@@ -334,7 +338,7 @@ function printPlan(plan: MatchRepairPlan) {
async function applyPlan( async function applyPlan(
match: MatchDocument, match: MatchDocument,
plan: MatchRepairPlan, plan: MatchRepairPlan,
TournamentCodeModel: mongoose.Model<any>, TournamentCodeModel: mongoose.Model<TournamentCode>,
session: mongoose.ClientSession, session: mongoose.ClientSession,
) { ) {
if (plan.skippedReason) return; if (plan.skippedReason) return;
@@ -5,10 +5,7 @@ import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { readFile } from 'node:fs/promises'; import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path'; import { resolve } from 'node:path';
import { import { ConnectionService, resolveMongoDbName } from '../connection.service';
ConnectionService,
resolveMongoDbName,
} from '../connection.service';
import type { import type {
MatchDocument, MatchDocument,
MatchGameAssignment, MatchGameAssignment,
@@ -214,12 +211,16 @@ async function main() {
printPlan(options, match, codes, plan); printPlan(options, match, codes, plan);
if (options.dryRun) { if (options.dryRun) {
console.log('No writes were made. Re-run with --apply to update MongoDB.'); console.log(
'No writes were made. Re-run with --apply to update MongoDB.',
);
return; return;
} }
const now = new Date(); const now = new Date();
const session = await (await connectionService.getConnection()).startSession(); const session = await (
await connectionService.getConnection()
).startSession();
try { try {
await session.withTransaction(async () => { await session.withTransaction(async () => {
await applyTournamentCodeUpdates(plan, now, session); await applyTournamentCodeUpdates(plan, now, session);
@@ -230,9 +231,9 @@ async function main() {
status: 'finished', status: 'finished',
roundRobinMaxRounds: options.maxRounds, roundRobinMaxRounds: options.maxRounds,
gameSchedule: plan.schedule, gameSchedule: plan.schedule,
tournamentCodeIds: [ tournamentCodeIds: [...plan.usedCodeByOldGameNumber.values()].map(
...plan.usedCodeByOldGameNumber.values(), (code) => code._id,
].map((code) => code._id), ),
resultPollState: { resultPollState: {
startedAt: match.resultPollState?.startedAt ?? now, startedAt: match.resultPollState?.startedAt ?? now,
lastPolledAt: now, lastPolledAt: now,
@@ -423,7 +424,9 @@ function partitionIntoRounds(
} }
if (!fillRound(0)) { if (!fillRound(0)) {
throw new Error('Could not partition result games into simultaneous rounds.'); throw new Error(
'Could not partition result games into simultaneous rounds.',
);
} }
return rounds; return rounds;
@@ -586,8 +589,7 @@ function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] {
} }
return [...bySeries.values()].sort( return [...bySeries.values()].sort(
(left, right) => (left, right) =>
left.teamAIndex - right.teamAIndex || left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex,
left.teamBIndex - right.teamBIndex,
); );
} }
@@ -219,9 +219,9 @@ async function listDuplicateHistorySequences(
.toArray(); .toArray();
} }
function printDuplicateHistorySequences(groups: Awaited< function printDuplicateHistorySequences(
ReturnType<typeof listDuplicateHistorySequences> groups: Awaited<ReturnType<typeof listDuplicateHistorySequences>>,
>) { ) {
if (groups.length === 0) { if (groups.length === 0) {
console.log('No duplicate auctionHistory auctionId+sequence groups found.'); console.log('No duplicate auctionHistory auctionId+sequence groups found.');
return; return;
@@ -248,7 +248,8 @@ async function repairDuplicateHistorySequences(
): Promise<DuplicateSequenceRepairStats> { ): Promise<DuplicateSequenceRepairStats> {
const historyCollection = db.collection('auctionHistory'); const historyCollection = db.collection('auctionHistory');
const auctionCollection = db.collection('auction'); const auctionCollection = db.collection('auction');
const affectedAuctionIds = await findAuctionIdsWithDuplicateHistorySequences(db); const affectedAuctionIds =
await findAuctionIdsWithDuplicateHistorySequences(db);
const stats: DuplicateSequenceRepairStats = { const stats: DuplicateSequenceRepairStats = {
affectedAuctions: affectedAuctionIds.length, affectedAuctions: affectedAuctionIds.length,
changedAuctionSequenceFields: 0, changedAuctionSequenceFields: 0,
@@ -177,7 +177,9 @@ function parseArgs(argv: string[]): CliOptions {
function parseCommitQuorum(value: string | undefined, label: string) { function parseCommitQuorum(value: string | undefined, label: string) {
if (!value) { if (!value) {
throw new Error(`${label} requires a positive integer, majority, or votingMembers.`); throw new Error(
`${label} requires a positive integer, majority, or votingMembers.`,
);
} }
if (value === 'majority' || value === 'votingMembers') return value; if (value === 'majority' || value === 'votingMembers') return value;
return parsePositiveInteger(value, label); return parsePositiveInteger(value, label);
@@ -230,9 +232,7 @@ function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) {
kind: group.kind, kind: group.kind,
loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '), loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '),
loserIds: group.losers.map((loser) => loser.id).join(', '), loserIds: group.losers.map((loser) => loser.id).join(', '),
loserStates: group.losers loserStates: group.losers.map((loser) => loser.state ?? '').join(', '),
.map((loser) => loser.state ?? '')
.join(', '),
})), })),
); );
} }
+43 -1
View File
@@ -940,6 +940,21 @@ export interface MatchStatsSkillBuildEvent {
levelUpType?: string; levelUpType?: string;
} }
export interface MatchStatsCheckpoint {
timestamp: number;
gold: number;
cs: number;
xp: number;
kills: number;
deaths: number;
assists: number;
}
export interface MatchStatsParticipantCheckpoints {
at10?: MatchStatsCheckpoint;
at15?: MatchStatsCheckpoint;
}
export interface MatchStatsRecord { export interface MatchStatsRecord {
matchId: string; matchId: string;
title: string; title: string;
@@ -948,6 +963,8 @@ export interface MatchStatsRecord {
riotMatchId: string; riotMatchId: string;
gameCreation: number; gameCreation: number;
gameDuration: number; gameDuration: number;
participantId?: number;
checkpoints?: MatchStatsParticipantCheckpoints;
userId: string; userId: string;
summonerName: string; summonerName: string;
tagLine: string; tagLine: string;
@@ -994,6 +1011,7 @@ export interface MatchStatsGameDetail {
timeline: MatchStatsTimelinePoint[]; timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean; timelineLoaded?: boolean;
objectiveEvents: MatchStatsObjectiveEvent[]; objectiveEvents: MatchStatsObjectiveEvent[];
timelineEvents?: MatchStatsTimelineEvent[];
teams: Array<{ teams: Array<{
teamIndex: number; teamIndex: number;
side: TeamSide; side: TeamSide;
@@ -1021,6 +1039,28 @@ export interface MatchStatsObjectiveEvent {
monsterSubType?: string; monsterSubType?: string;
} }
export interface MatchStatsChampionKillEvent {
timestamp: number;
side?: TeamSide;
type: 'championKill';
killerParticipantId?: number;
victimParticipantId?: number;
assistingParticipantIds?: number[];
}
export interface MatchStatsBuildingEvent {
timestamp: number;
side: TeamSide;
type: 'tower' | 'inhibitor';
killerParticipantId?: number;
towerType?: string;
}
export type MatchStatsTimelineEvent =
| MatchStatsObjectiveEvent
| MatchStatsChampionKillEvent
| MatchStatsBuildingEvent;
export interface MatchStatsTimelinePoint { export interface MatchStatsTimelinePoint {
timestamp: number; timestamp: number;
blue: { gold: number; xp: number }; blue: { gold: number; xp: number };
@@ -2445,7 +2485,9 @@ MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -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: Array<
ModelDefinition & { name: keyof TournamentModelTypes }
> = [
...competitionModelDefinitions, ...competitionModelDefinitions,
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
+1 -1
View File
@@ -1,5 +1,5 @@
export interface ModelDefinition { export interface ModelDefinition {
name: string; name: string;
schema: mongoose.Schema<any>; schema: unknown;
schemaName?: string; schemaName?: string;
} }
@@ -1,5 +1,4 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import fs from 'fs/promises';
import { connect } from 'nats'; import { connect } from 'nats';
import type { NatsConnection } from 'nats'; import type { NatsConnection } from 'nats';
import { SecretModule } from '../secret/secret.module'; import { SecretModule } from '../secret/secret.module';
@@ -34,31 +34,32 @@ type SchemaWithPerformanceMarker = mongoose.Schema & {
[PERFORMANCE_PLUGIN_APPLIED]?: boolean; [PERFORMANCE_PLUGIN_APPLIED]?: boolean;
}; };
export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
const markedSchema = schema as SchemaWithPerformanceMarker; if (!(schemaValue instanceof mongoose.Schema)) {
if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return; throw new TypeError('Mongoose performance plugin requires a Schema.');
markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true; }
const hookableSchema = schema as any; const schema = schemaValue as SchemaWithPerformanceMarker;
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
hookableSchema.pre(QUERY_OPERATION_REGEX, function () { schema.pre(QUERY_OPERATION_REGEX, function () {
const query = this as QueryWithPerformanceState; const query = this as QueryWithPerformanceState;
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
query[QUERY_PERFORMANCE_RECORDED] = false; query[QUERY_PERFORMANCE_RECORDED] = false;
}); });
hookableSchema.post( schema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
QUERY_OPERATION_REGEX, recordQueryPerformance(this as QueryWithPerformanceState, result);
function (result: unknown) { });
recordQueryPerformance(
this as unknown as QueryWithPerformanceState,
result,
);
},
);
hookableSchema.post( schema.post(
QUERY_OPERATION_REGEX, QUERY_OPERATION_REGEX,
function (error: unknown, _result: unknown, next: (error: unknown) => void) { { errorHandler: true },
function (
error: Error,
_result: unknown,
next: (error?: mongoose.CallbackError) => void,
) {
recordQueryPerformance( recordQueryPerformance(
this as unknown as QueryWithPerformanceState, this as unknown as QueryWithPerformanceState,
undefined, undefined,
@@ -68,19 +69,24 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void {
}, },
); );
hookableSchema.pre('aggregate', function () { schema.pre('aggregate', function () {
const aggregate = this as AggregateWithPerformanceState; const aggregate = this as AggregateWithPerformanceState;
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
aggregate[QUERY_PERFORMANCE_RECORDED] = false; aggregate[QUERY_PERFORMANCE_RECORDED] = false;
}); });
hookableSchema.post('aggregate', function (result: unknown) { schema.post('aggregate', function (result: unknown) {
recordAggregatePerformance(this as AggregateWithPerformanceState, result); recordAggregatePerformance(this as AggregateWithPerformanceState, result);
}); });
hookableSchema.post( schema.post(
'aggregate', 'aggregate',
function (error: unknown, _result: unknown, next: (error: unknown) => void) { { errorHandler: true },
function (
error: Error,
_result: unknown,
next: (error?: mongoose.CallbackError) => void,
) {
recordAggregatePerformance( recordAggregatePerformance(
this as AggregateWithPerformanceState, this as AggregateWithPerformanceState,
undefined, undefined,
@@ -164,8 +170,8 @@ export function countHydratedDocuments(result: unknown): number {
function isHydratedDocument(value: unknown): boolean { function isHydratedDocument(value: unknown): boolean {
return Boolean( return Boolean(
value && value &&
typeof value === 'object' && typeof value === 'object' &&
'$__' in (value as Record<string, unknown>), '$__' in (value as Record<string, unknown>),
); );
} }
@@ -11,9 +11,7 @@ interface NewRelicCustomEventApi {
eventType: string, eventType: string,
attributes: Record<string, NewRelicAttributeValue>, attributes: Record<string, NewRelicAttributeValue>,
): void; ): void;
addCustomAttributes( addCustomAttributes(attributes: Record<string, NewRelicAttributeValue>): void;
attributes: Record<string, NewRelicAttributeValue>,
): void;
setTransactionName(name: string): void; setTransactionName(name: string): void;
} }
const agent = newrelicAgent as unknown as NewRelicCustomEventApi; const agent = newrelicAgent as unknown as NewRelicCustomEventApi;
@@ -52,8 +52,7 @@ export interface ApiRequestPerformanceEvent {
leanQueryCount: number; leanQueryCount: number;
} }
export interface MongooseQueryPerformanceEvent export interface MongooseQueryPerformanceEvent extends MongooseQueryPerformance {
extends MongooseQueryPerformance {
type: 'mongoose-query'; type: 'mongoose-query';
timestamp: string; timestamp: string;
requestId?: string; requestId?: string;
@@ -92,10 +91,7 @@ export function resolveApiPerformanceConfig(
const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false); const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false);
return { return {
enabled, enabled,
localEventsEnabled: readBoolean( localEventsEnabled: readBoolean(env.API_PERF_LOCAL_EVENTS_ENABLED, enabled),
env.API_PERF_LOCAL_EVENTS_ENABLED,
enabled,
),
localEventFile: localEventFile:
env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson', env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson',
newRelicRequestEventsEnabled: readBoolean( newRelicRequestEventsEnabled: readBoolean(
@@ -35,8 +35,7 @@ export interface RunWithDistributedLockOptions {
lockRetryDelayMilliseconds?: number; lockRetryDelayMilliseconds?: number;
} }
export interface RunWithRenewedDistributedLockOptions export interface RunWithRenewedDistributedLockOptions extends RunWithDistributedLockOptions {
extends RunWithDistributedLockOptions {
lockRenewalIntervalMilliseconds: number; lockRenewalIntervalMilliseconds: number;
} }
@@ -55,16 +54,13 @@ export class DistributedLockService {
); );
const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID(); const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID();
const result = await this.redisService.raw().sendCommand([ const result = await this.redisService
'SET', .raw()
options.lockKey, .sendCommand<
lockOwnershipToken, string | null
'NX', >(['SET', options.lockKey, lockOwnershipToken, 'NX', 'PX', String(options.lockExpirationDurationMilliseconds)]);
'PX',
String(options.lockExpirationDurationMilliseconds),
]);
if (String(result) !== 'OK') return null; if (result !== 'OK') return null;
return { return {
lockKey: options.lockKey, lockKey: options.lockKey,
lockOwnershipToken, lockOwnershipToken,
@@ -76,34 +72,37 @@ export class DistributedLockService {
public async releaseLockIfOwned( public async releaseLockIfOwned(
lockOwnership: DistributedLockOwnership, lockOwnership: DistributedLockOwnership,
): Promise<boolean> { ): Promise<boolean> {
const result = await this.redisService.raw().sendCommand([ const result = await this.redisService
'EVAL', .raw()
RELEASE_LOCK_IF_OWNED_SCRIPT, .sendCommand([
'1', 'EVAL',
lockOwnership.lockKey, RELEASE_LOCK_IF_OWNED_SCRIPT,
lockOwnership.lockOwnershipToken, '1',
]); lockOwnership.lockKey,
lockOwnership.lockOwnershipToken,
]);
return Number(result) === 1; return Number(result) === 1;
} }
public async extendLockIfOwned( public async extendLockIfOwned(
lockOwnership: DistributedLockOwnership, lockOwnership: DistributedLockOwnership,
lockExpirationDurationMilliseconds = lockExpirationDurationMilliseconds = lockOwnership.lockExpirationDurationMilliseconds,
lockOwnership.lockExpirationDurationMilliseconds,
): Promise<boolean> { ): Promise<boolean> {
this.assertPositiveDuration( this.assertPositiveDuration(
lockExpirationDurationMilliseconds, lockExpirationDurationMilliseconds,
'lockExpirationDurationMilliseconds', 'lockExpirationDurationMilliseconds',
); );
const result = await this.redisService.raw().sendCommand([ const result = await this.redisService
'EVAL', .raw()
EXTEND_LOCK_IF_OWNED_SCRIPT, .sendCommand([
'1', 'EVAL',
lockOwnership.lockKey, EXTEND_LOCK_IF_OWNED_SCRIPT,
lockOwnership.lockOwnershipToken, '1',
String(lockExpirationDurationMilliseconds), lockOwnership.lockKey,
]); lockOwnership.lockOwnershipToken,
String(lockExpirationDurationMilliseconds),
]);
return Number(result) === 1; return Number(result) === 1;
} }
@@ -120,7 +119,7 @@ export class DistributedLockService {
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn( this.logger.warn(
`Failed to release distributed lock ${lockOwnership.lockKey}: ${ `Failed to release distributed lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : String(error)
}`, }`,
); );
}); });
@@ -139,8 +138,7 @@ export class DistributedLockService {
const lockOwnership = await this.acquireLockWithRetry(options); const lockOwnership = await this.acquireLockWithRetry(options);
if (!lockOwnership) return null; if (!lockOwnership) return null;
let lockRenewalTimer: NodeJS.Timeout | undefined; const lockRenewalTimer = setInterval(() => {
lockRenewalTimer = setInterval(() => {
void this.extendLockIfOwned(lockOwnership).then((wasExtended) => { void this.extendLockIfOwned(lockOwnership).then((wasExtended) => {
if (wasExtended) return; if (wasExtended) return;
this.logger.warn( this.logger.warn(
@@ -153,11 +151,11 @@ export class DistributedLockService {
try { try {
return await operation(lockOwnership); return await operation(lockOwnership);
} finally { } finally {
if (lockRenewalTimer) clearInterval(lockRenewalTimer); clearInterval(lockRenewalTimer);
await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => {
this.logger.warn( this.logger.warn(
`Failed to release distributed lock ${lockOwnership.lockKey}: ${ `Failed to release distributed lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : String(error)
}`, }`,
); );
}); });
@@ -25,7 +25,9 @@ async function readFirstSecret(
{ {
provide: REDIS_CLIENT, provide: REDIS_CLIENT,
inject: [SecretService], inject: [SecretService],
useFactory: async (secretService: SecretService): Promise<RedisClient> => { useFactory: async (
secretService: SecretService,
): Promise<RedisClient> => {
await secretService.ready(); await secretService.ready();
const [url, endpoint, username, password] = await Promise.all([ const [url, endpoint, username, password] = await Promise.all([
@@ -52,8 +54,12 @@ async function readFirstSecret(
}), }),
); );
client.on('error', (error) => { client.on('error', (error: unknown) => {
logger.error(`Redis client error: ${error?.message ?? error}`); logger.error(
`Redis client error: ${
error instanceof Error ? error.message : String(error)
}`,
);
}); });
await client.connect(); await client.connect();
@@ -6,15 +6,17 @@ function createRedisService(client: Record<string, unknown>) {
describe('RedisService stream pending recovery', () => { describe('RedisService stream pending recovery', () => {
it('normalizes XAUTOCLAIM array replies into stream entries', async () => { it('normalizes XAUTOCLAIM array replies into stream entries', async () => {
const sendCommand = jest.fn().mockResolvedValue([ const sendCommand = jest
'0-0', .fn()
[ .mockResolvedValue([
'0-0',
[ [
'1700000000000-0', [
['job', '{"kind":"poll-tournament-result"}', 'source', 'test'], '1700000000000-0',
['job', '{"kind":"poll-tournament-result"}', 'source', 'test'],
],
], ],
], ]);
]);
const service = createRedisService({ sendCommand }); const service = createRedisService({ sendCommand });
await expect( await expect(
@@ -35,11 +35,14 @@ interface RawStreamReadResult {
function normalizeStreamFields(fields: unknown): Record<string, string> { function normalizeStreamFields(fields: unknown): Record<string, string> {
if (Array.isArray(fields)) { if (Array.isArray(fields)) {
const values = fields as unknown[];
const normalized: Record<string, string> = {}; const normalized: Record<string, string> = {};
for (let index = 0; index < fields.length; index += 2) { for (let index = 0; index < values.length; index += 2) {
const key = fields[index]; const key = values[index];
if (key === undefined) continue; if (key === undefined) continue;
normalized[String(key)] = String(fields[index + 1] ?? ''); normalized[redisValueToString(key)] = redisValueToString(
values[index + 1],
);
} }
return normalized; return normalized;
} }
@@ -223,9 +226,7 @@ export class RedisService implements OnModuleDestroy {
])) as unknown; ])) as unknown;
const responseItems = Array.isArray(response) ? response : []; const responseItems = Array.isArray(response) ? response : [];
const rawMessages = Array.isArray(responseItems[1]) const rawMessages = Array.isArray(responseItems[1]) ? responseItems[1] : [];
? responseItems[1]
: [];
return { return {
nextStartId: String(responseItems[0] ?? '0-0'), nextStartId: String(responseItems[0] ?? '0-0'),
@@ -258,12 +259,14 @@ export class RedisService implements OnModuleDestroy {
return this.client.publish(channel, message); return this.client.publish(channel, message);
} }
private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null { private normalizeClaimedStreamMessage(
rawMessage: unknown,
): StreamEntry | null {
if (Array.isArray(rawMessage)) { if (Array.isArray(rawMessage)) {
const [id, fields] = rawMessage; const [id, fields] = rawMessage as unknown[];
if (id === undefined) return null; if (id === undefined) return null;
return { return {
id: String(id), id: redisValueToString(id),
message: normalizeStreamFields(fields), message: normalizeStreamFields(fields),
}; };
} }
@@ -291,3 +294,17 @@ export class RedisService implements OnModuleDestroy {
return null; return null;
} }
} }
function redisValueToString(value: unknown): string {
if (typeof value === 'string') return value;
if (
typeof value === 'number' ||
typeof value === 'boolean' ||
typeof value === 'bigint'
) {
return String(value);
}
if (Buffer.isBuffer(value)) return value.toString('utf8');
if (value === undefined || value === null) return '';
return JSON.stringify(value) ?? '';
}
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more