Compare commits

...
Author SHA1 Message Date
dahyeon 8d741ef9a7 test(auction): add two-node Docker failure integration suite
Exercise Nginx routing, Mongo transaction ordering, history backfills, Undo, Pub/Sub TCP loss, safety polling, resync, and reconnection. Keep fixtures and results isolated from production and git.
2026-11-12 01:49:35 +09:00
dahyeon 23a0a3f8dd perf(auction): reduce polling with verified socket recovery
Keep fixed 30-second safety polling with separate recovery polling, confirm persistent heartbeat gaps, and refresh shared history after durable writes.
2026-11-12 01:49:27 +09:00
dahyeon e349684523 feat: expand auction emoji reactions to sixteen 2026-11-11 22:42:18 +09:00
dahyeon 9d7c888b0a fix: migrate deprecated APIs and patch vulnerable dependencies
Use current Mongoose, NATS, React, and ESLint APIs. Upgrade Vite and other affected dependencies, restrict the compatibility plugin to resolved module IDs, and keep qs unchanged.
2026-11-11 22:41:42 +09:00
dahyeon 5882585f69 fix: upgrade mongoose to 9.11.4 and align community model type 2026-11-11 20:26:38 +09:00
dahyeon 2d8027cb16 fix: preserve literal types for mongoose queries and seed data 2026-11-11 20:21:51 +09:00
dahyeon fbf22284e8 fix: use explicit match id in temporary match seed 2026-11-11 20:18:14 +09:00
dahyeon 6efbd50db7 fix: update dependencies to resolve critical audit findings 2026-11-11 20:15:51 +09:00
dahyeon 3f68997b9a style: format community stats service tests 2026-11-11 20:10:47 +09:00
dahyeon be4de61bb7 feat: enhance auction interactions and player statistics UI 2026-11-11 20:06:22 +09:00
dahyeonandClaude Fable 5.2 6c582ba3cf feat(web): use a pixel-art medal for recent match winners
Swap the lucide trophy in the home recent results for a hand-drawn
pixel medal, keep the two alternative trophy drafts as assets, and
tune the gold text tokens to match.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 13:48:48 +09:00
dahyeonandClaude Fable 5.2 9064340584 refactor(web): restyle home schedule and results as divided lists
Replace the panel cards on the home page with section lists separated
by horizontal rules, sharing one schedule row layout. Remove the
obsolete home history test and record the design QA notes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 13:48:41 +09:00
dahyeon cc358697d4 fix(web): consolidate player search in stats page 2026-11-11 02:10:37 +09:00
dahyeon f6686bbf17 fix(api): resolve formatting and iterator lint errors 2026-11-11 02:06:40 +09:00
dahyeon 0d7617e2d2 feat: connect tournament views to APIs and recover archived stats
Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
2026-11-11 02:00:35 +09:00
dahyeon 20e1e6ec04 feat(web): show winning teams in recent match results 2026-11-10 23:05:59 +09:00
dahyeon 664af15255 feat: refresh the home page and separate match event types
Add an inhouse hero, Hall of Fame, rankings, and event-specific schedules. Carry the event type through the API and admin tools, and improve results and player history displays.
2026-11-10 22:13:55 +09:00
dahyeon 7e0cd7cb19 fix: keep best-of-three grand finals open for results
Allow a separate grand final format and repair prematurely completed finals without dropping accepted games. Replay the correction record alongside subsequent results.
2026-11-10 18:49:26 +09:00
dahyeon 38a89b5374 feat: improve tournament workflows and prune outdated docs 2026-11-10 15:31:19 +09:00
dahyeon da7b502936 feat(web): refresh the app with Astryx and coral branding 2026-11-10 13:35:11 +09:00
351 changed files with 26695 additions and 7541 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "web-staging",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["--filter", "web", "start:staging"],
"port": 5173
}
]
}
+6 -5
View File
@@ -23,11 +23,12 @@ website/LICENSE
*.md
!README.md
!docs/specs/internal-match-game-analysis.md
!docs/plans/internal-match-game-analysis-p0-p1.md
!docs/specs/double-elimination-connector-routing.md
!docs/plans/double-elimination-connector-routing.md
!docs/plans/redis-8.10-optimization.md
!design-qa.md
!docs/specs/home-banner-production.md
!docs/specs/match-status-and-result-presentation.md
!docs/specs/information-visible-ui.md
!docs/ux-audit-2026-11-10/06-ui-improvement-review.md
!docs/ux-audit-2026-11-10/07-visual-design-review.md
/tmp/
/user-game-history/
/*.txt
+5 -1
View File
@@ -144,7 +144,9 @@ pnpm --filter api build
`test:redis`는 PATH의 `redis-server` 또는 `REDIS_TEST_SERVER`에 지정한 실행 파일로 Redis 8.10.x를 직접 실행합니다. 임의의 로컬 포트와 일회용 암호를 사용하고, 저장을 비활성화하며, 종료 후 프로세스와 임시 디렉터리를 정리합니다. 애플리케이션 Redis 연결 설정은 사용하지 않습니다. Windows에서는 PowerShell에서 `$env:REDIS_TEST_SERVER = 'C:\tools\redis\redis-server.exe'`처럼 지정할 수 있습니다.
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash로 전환됩니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초를 유지합니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 API 인스턴스를 같은 버전으로 함께 전환해야 합니다. 구현 범위와 검증 기록은 [Redis 변경 계획](docs/plans/redis-8.10-optimization.md)을 참고하세요.
커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash를 사용합니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초입니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 배포와 롤백 모두 API 인스턴스를 같은 버전으로 함께 전환해야 합니다.
스트림이 계속 커지면 소비자 그룹별 미처리 항목을 확인합니다. 사용이 중단된 그룹도 미처리 항목을 계속 보존할 수 있습니다.
### API New Relic APM
@@ -171,6 +173,8 @@ API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABI
카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다.
카카오톡 방을 옮긴 뒤에는 새 방에서 `!내전 데이터이관 예전 닉네임`을 실행합니다. 같은 커뮤니티에서 Riot 계정이 등록된 기존 사용자의 카카오톡 ID만 바뀝니다. 기존 사용자 ID, 권한, 참가 기록은 유지됩니다. 닉네임이 중복되거나 새 ID가 이미 다른 사용자에 연결돼 있으면 운영자가 확인합니다. 계정 소유권 확인은 운영 절차에서 담당합니다.
## 커맨드
| Command | Description |
+46
View File
@@ -72,6 +72,19 @@ executable path. The runner starts an isolated replica set on a random loopback
port, uses a temporary database directory, and removes it after the tests. It
does not use the application's database connection settings.
## Temporary auction role selection
Until captain accounts are issued, bids use the team selected in the auction UI.
By default, both WebSocket and HTTP bids accept guests and signed-in users without
checking whether the user is that team's captain. Team existence, bid amounts,
remaining points, roster limits, deadlines and round consistency are still checked.
Bid history continues to identify the selected team's captain, so it is not proof
of the account that submitted a bid in this temporary mode.
After issuing accounts, set `AUCTION_REQUIRE_CAPTAIN_AUTH=true` in the API
environment (or `project.env`) and restart the API to require a signed-in captain
for the selected team on all bid paths. Unset or `false` keeps temporary mode.
## Auction durability
Accepted Redis bids now enter `auction:bidArchivePayloads` and
@@ -117,6 +130,39 @@ The index is `{ auctionCancellationCleanupRetryAt: 1 }`, restricted to
`{ auctionCancellationCleanupPending: true }`. The worker only reads due pending
entries; it no longer scans legacy cancellation markers without a pending flag.
## Riot archive recovery
Newly saved or repaired Riot match data refreshes affected internal match
statistics at the same Competition revision. Existing archives and duplicate
imports do not trigger recovery. Recovery failures are logged and do not block
result collection or match refresh. Only communities with recovered statistics
have their caches invalidated, once per recovery batch; one failed rebuild does
not prevent other successful rebuilds from being reflected. Detail
requests also check for newly archived data when a cached game is missing raw
data. An absent archive does not trigger a rebuild or a Riot match fetch. If a
detail rebuild makes no progress, the process waits 60 seconds before retrying
that source revision and does not invalidate the community cache.
Recovery cache invalidations first try Redis with a one-second command timeout.
On failure they return immediately and schedule up to three in-process retries,
waiting 1, 5, then 30 seconds between attempts. A community has one retry budget;
additional immediate failures do not reset it, and a successful current request
cancels the pending retry. Timers are unreferenced and cleared on shutdown.
Retries are not persisted or resumed after a restart. Detail requests detect
newly archived raw data even behind a stale cache, and other response caches
expire after five minutes. A detail response whose immediate invalidation fails
is returned without being cached. No Mongo invalidation collection or periodic
queue scan is used.
Before deploying this recovery path, add its Riot ID lookup index. The migration
defaults to dry-run and leaves other indexes and game records unchanged.
```bash
pnpm --filter api stats:indexes -- --env staging --dry-run
pnpm --filter api stats:indexes -- --env staging --apply
# Use --env prod for production.
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
+2 -1
View File
@@ -1,10 +1,11 @@
// @ts-check
import eslint from '@eslint/js';
import { defineConfig } from 'eslint/config';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
export default defineConfig(
{
ignores: ['eslint.config.mjs'],
},
+8 -6
View File
@@ -9,7 +9,9 @@
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"competition:migrate": "ts-node src/modules/global/database/migrations/run-competition-domain.ts",
"competition:repair-grand-final": "ts-node src/modules/global/database/migrations/repair-grand-final-bo3.ts",
"auction:indexes": "ts-node src/modules/global/database/migrations/run-auction-cancellation-index.ts",
"stats:indexes": "ts-node src/modules/global/database/migrations/run-match-stats-raw-index.ts",
"seed:dev": "ts-node src/seed.ts",
"seed:dakao-participant": "ts-node src/seed-dakao-participant.ts",
"start:dev": "NODE_ENV=dev NEW_RELIC_HOME=. node --import newrelic/esm-loader.mjs -r newrelic dist/main.js",
@@ -33,19 +35,20 @@
},
"dependencies": {
"@lolympus/contracts": "workspace:*",
"@nats-io/jetstream": "^3.4.0",
"@nats-io/transport-node": "^3.4.0",
"@nestjs/common": "^11.1.28",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.1.28",
"@nestjs/platform-express": "^11.1.28",
"@nestjs/platform-socket.io": "^11.1.28",
"@nestjs/swagger": "^11.4.6",
"@nestjs/swagger": "^11.4.8",
"@nestjs/websockets": "^11.1.28",
"@socket.io/redis-adapter": "^8.3.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"jose": "^6.2.2",
"mongoose": "9.4.1",
"nats": "^2.29.3",
"mongoose": "9.12.1",
"newrelic": "^14.3.3",
"redis": "^5.12.1",
"reflect-metadata": "^0.2.2",
@@ -54,8 +57,7 @@
"temporal-polyfill": "^0.3.2"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@eslint/js": "^10.0.1",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
@@ -63,7 +65,7 @@
"@types/jest": "^30.0.0",
"@types/node": "^26.1.1",
"@types/supertest": "^7.0.0",
"eslint": "^9.18.0",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^17.0.0",
@@ -0,0 +1,9 @@
/**
* 계정 지급 전에는 화면에서 선택한 팀으로 입찰하는 임시 운영 모드가 기본이다.
* 계정 지급 후 AUCTION_REQUIRE_CAPTAIN_AUTH=true로 로그인·팀장 검증을 복구한다.
*/
export function isAuctionCaptainAuthRequired(): boolean {
return (
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH?.trim().toLowerCase() === 'true'
);
}
@@ -0,0 +1,156 @@
import mongoose from 'mongoose';
import { BadRequestException } from '@nestjs/common';
jest.mock('../auth/jwt.service', () => ({ JwtService: class JwtService {} }));
import { AuctionGateway } from './auction.gateway';
function setup() {
const appendChatMessage = jest.fn();
const gateway = new AuctionGateway(
{ appendChatMessage } as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const broadcast = jest.fn();
const to = jest.fn().mockReturnValue({ emit: broadcast });
(gateway as unknown as { server: unknown }).server = {
to,
};
const socket = {
data: {
matchId: new mongoose.Types.ObjectId().toString(),
user: {
_id: new mongoose.Types.ObjectId(),
role: 'admin',
riotAccounts: [],
kakaoTalkNickname: '운영자',
},
},
emit: jest.fn(),
};
return { gateway, appendChatMessage, broadcast, socket, to };
}
describe('Auction chat delivery', () => {
const payload = {
message: '준비해 주세요',
clientMessageId: '0589e8a4-bccd-4ccd-a3ae-28f117401e79',
};
it('acknowledges only after saving and assigns the operator role from the socket user', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
const message = { id: 'saved', ...payload, sentAt: new Date() };
let finish!: (result: unknown) => void;
appendChatMessage.mockReturnValue(
new Promise((resolve) => {
finish = resolve;
}),
);
const ack = jest.fn();
const pending = gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).not.toHaveBeenCalled();
expect(broadcast).not.toHaveBeenCalled();
finish({ message, created: true });
await pending;
expect(appendChatMessage).toHaveBeenCalledWith(
expect.objectContaining({
clientMessageId: payload.clientMessageId,
senderRole: 'operator',
displayName: '운영자',
}),
);
expect(ack).toHaveBeenCalledWith({
ok: true,
message: expect.objectContaining({ id: 'saved' }),
});
expect(broadcast).toHaveBeenCalledTimes(1);
});
it('acknowledges a retry without broadcasting a duplicate', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
appendChatMessage.mockResolvedValue({
message: { id: 'saved' },
created: false,
});
const ack = jest.fn();
await gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).toHaveBeenCalledWith({ ok: true, message: { id: 'saved' } });
expect(broadcast).not.toHaveBeenCalled();
});
it('returns rejection to the requesting composer without reporting success', async () => {
const { gateway, appendChatMessage, broadcast, socket } = setup();
appendChatMessage.mockRejectedValue(
new BadRequestException('Chat message is required.'),
);
const ack = jest.fn();
await gateway.handleChatMessage(socket as never, payload, ack);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
ok: false,
message: 'Chat message is required.',
}),
);
expect(broadcast).not.toHaveBeenCalled();
});
});
describe('Auction live reactions', () => {
it('broadcasts to the joined room with the server-resolved name, without saving a chat message', () => {
const { gateway, appendChatMessage, broadcast, socket, to } = setup();
const ack = jest.fn();
gateway.handleChatReaction(socket as never, { kind: 'clap' }, ack);
expect(to).toHaveBeenCalledWith(socket.data.matchId);
expect(broadcast).toHaveBeenCalledWith(
'chat-reaction',
expect.objectContaining({
id: expect.any(String),
kind: 'clap',
displayName: '운영자',
userId: socket.data.user._id.toString(),
}),
);
expect(ack).toHaveBeenCalledWith({
ok: true,
reaction: broadcast.mock.calls[0][1],
});
expect(appendChatMessage).not.toHaveBeenCalled();
});
it('rejects unjoined clients and arbitrary reaction values', () => {
const { gateway, broadcast, socket } = setup();
const ack = jest.fn();
gateway.handleChatReaction({ data: {} } as never, { kind: 'heart' }, ack);
expect(ack).toHaveBeenLastCalledWith({ ok: false, code: 'NOT_JOINED' });
for (const kind of ['__proto__', 'not-supported', 1, null]) {
gateway.handleChatReaction(socket as never, { kind }, ack);
expect(ack).toHaveBeenLastCalledWith({
ok: false,
code: 'INVALID_REACTION',
});
}
expect(broadcast).not.toHaveBeenCalled();
});
it('throttles bursts, then accepts the next reaction after the interval', () => {
const { gateway, broadcast, socket } = setup();
const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);
const ack = jest.fn();
try {
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
expect(ack).toHaveBeenLastCalledWith({
ok: false,
code: 'REACTION_RATE_LIMITED',
});
expect(broadcast).toHaveBeenCalledTimes(1);
clock.mockReturnValue(1400);
gateway.handleChatReaction(socket as never, { kind: 'celebrate' }, ack);
expect(broadcast).toHaveBeenCalledTimes(2);
} finally {
clock.mockRestore();
}
});
});
@@ -233,6 +233,56 @@ describe('auction durability projection helpers', () => {
expect(session.endSession).toHaveBeenCalledTimes(1);
});
it('notifies history only after commit, including when state rebroadcast is disabled', async () => {
let finishCommit!: () => void;
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockImplementation(
() =>
new Promise<void>((resolve) => {
finishCommit = resolve;
}),
),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const broadcastHistoryUpdated = jest.fn();
const scheduler = new AuctionDurabilityScheduler(
{
createSession: async () => session,
getModel: async () => ({ updateOne }),
} as never,
{} as never,
undefined,
undefined,
undefined,
{ broadcastHistoryUpdated } as never,
);
const pending = scheduler.applyDurabilityPayload({
...payload,
shouldBroadcastState: false,
});
await new Promise((resolve) => setImmediate(resolve));
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
finishCommit();
await pending;
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
matchId: 'match-1',
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
});
session.commitTransaction.mockRejectedValueOnce(new Error('commit failed'));
await expect(scheduler.applyDurabilityPayload(payload)).rejects.toThrow(
'commit failed',
);
expect(broadcastHistoryUpdated).toHaveBeenCalledTimes(1);
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
});
it('broadcasts latest Redis state when durability payload requests it', async () => {
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
@@ -265,7 +315,7 @@ describe('auction durability projection helpers', () => {
undefined,
undefined,
undefined,
{ broadcastState } as never,
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
{ readAuctionStateView } as never,
);
@@ -315,7 +365,7 @@ describe('auction durability projection helpers', () => {
undefined,
undefined,
undefined,
{ broadcastState } as never,
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
{ readAuctionStateView } as never,
);
@@ -407,60 +457,71 @@ describe('auction durability projection helpers', () => {
);
});
it('skips destructive history mutation for stale payloads', async () => {
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
startTransaction: jest.fn(),
};
const historyDeleteMany = jest.fn();
const historyUpdateOne = jest.fn();
const auctionUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
});
const projectionExec = jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
it.each(['life-1', 'new-life'])(
'skips stale history changes and notifications for current lifecycle %s',
async (auctionLifecycleId) => {
const broadcastHistoryUpdated = jest.fn();
const session = {
abortTransaction: jest.fn().mockResolvedValue(undefined),
commitTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
startTransaction: jest.fn(),
};
const historyDeleteMany = jest.fn();
const historyUpdateOne = jest.fn();
const auctionUpdateOne = jest.fn().mockReturnValue({
exec: jest
.fn()
.mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
});
const projectionExec = jest.fn().mockResolvedValue({
auctionLifecycleId,
revision: 10,
});
const auctionFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
}),
}),
}),
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: jest.fn() };
}),
} as never,
{ raw: jest.fn() } as never,
);
});
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
}
return { updateOne: jest.fn() };
}),
} as never,
{ raw: jest.fn() } as never,
undefined,
undefined,
undefined,
{ broadcastHistoryUpdated } as never,
);
await scheduler.applyDurabilityPayload({
...payload,
historyMutation: {
targetHistorySequence: 2,
type: 'deleteAfterSequenceAndAppendUndo',
},
});
await scheduler.applyDurabilityPayload({
...payload,
historyMutation: {
targetHistorySequence: 2,
type: 'deleteAfterSequenceAndAppendUndo',
},
});
expect(historyDeleteMany).not.toHaveBeenCalled();
expect(historyUpdateOne).not.toHaveBeenCalled();
expect(auctionUpdateOne).not.toHaveBeenCalled();
});
expect(historyDeleteMany).not.toHaveBeenCalled();
expect(historyUpdateOne).not.toHaveBeenCalled();
expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
},
);
it('recovers stale append payloads as history-only records', async () => {
const session = {
@@ -597,6 +658,7 @@ describe('auction durability projection helpers', () => {
});
it('clears stale append payloads after history-only recovery', async () => {
const broadcastHistoryUpdated = jest.fn();
const sendCommand = jest
.fn()
.mockResolvedValueOnce(['payload-1'])
@@ -653,6 +715,10 @@ describe('auction durability projection helpers', () => {
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
raw: jest.fn().mockReturnValue({ sendCommand }),
} as never,
undefined,
undefined,
undefined,
{ broadcastHistoryUpdated } as never,
);
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
@@ -662,6 +728,11 @@ describe('auction durability projection helpers', () => {
});
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
matchId: 'match-1',
auctionLifecycleId: 'life-1',
auctionStateTransitionId: 'transition-1',
});
expect(auctionUpdateOne).not.toHaveBeenCalled();
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
expect(sendCommand).toHaveBeenNthCalledWith(3, [
@@ -1006,7 +1077,7 @@ describe('auction durability projection helpers', () => {
{ reserveForMatch } as never,
{ scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never,
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
);
await scheduler.applyDurabilityPayload(completePayload);
@@ -1203,7 +1274,7 @@ describe('auction durability projection helpers', () => {
{ reserveForMatch } as never,
{ scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never,
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
);
await expect(
@@ -1332,7 +1403,7 @@ describe('auction durability projection helpers', () => {
{ releaseFromMatch } as never,
{ cancelPolling } as never,
{ mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never,
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
);
await scheduler.applyDurabilityPayload(resetPayload);
@@ -356,6 +356,15 @@ export class AuctionDurabilityScheduler
if (session) await session.endSession();
}
if (shouldApplyHistoryMutation) {
// This is independent of the primary state broadcast. HTTP reads on every
// node can see the committed history before clients are notified.
this.auctionEventBusService?.broadcastHistoryUpdated({
matchId: String(payload.matchId),
auctionLifecycleId: payload.auctionLifecycleId,
auctionStateTransitionId: payload.auctionStateTransitionId,
});
}
await this.broadcastLatestRedisAuctionStateIfRequested(payload);
if (sideEffectMutation && shouldApplySideEffects) {
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import type { Namespace } from 'socket.io';
import type { AuctionHistoryUpdatedEvent } from '@lolympus/contracts';
import type { AuctionStateResponse } from './auction.service';
import type { MatchSideEffectDelta } from './auction-side-effect.service';
import { serializeRealtimeAuction } from './auction-realtime-serializer';
@@ -25,6 +26,10 @@ export class AuctionEventBusService {
.emit('state', serializeRealtimeAuction(state));
}
public broadcastHistoryUpdated(event: AuctionHistoryUpdatedEvent): void {
this.auctionNamespace?.to(event.matchId).emit('history-updated', event);
}
public broadcastReset(matchId: string, auctionLifecycleId: string): void {
this.auctionNamespace
?.to(matchId)
@@ -0,0 +1,101 @@
import 'reflect-metadata';
import mongoose from 'mongoose';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import type { UserDocument } from '../global/database/schema';
jest.mock('../auth/jwt.service', () => ({
JwtService: class JwtService {},
}));
import { AuctionController } from './auction.controller';
describe('AuctionController bid authentication', () => {
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => jest.restoreAllMocks());
it('allows HTTP guests to reach the configurable bid checks', () => {
const handler = AuctionController.prototype.placeBid;
expect(
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
).toBe(true);
expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toBeUndefined();
});
it.each([undefined, 'false', 'true'])(
'handles HTTP guests with captain auth=%s',
async (auth) => {
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
const controller = new AuctionController(
{ placeBid } as never,
{} as never,
{} as never,
);
const matchId = new mongoose.Types.ObjectId();
const result = controller.placeBid(
undefined,
new mongoose.Types.ObjectId(),
matchId,
{
bidderTeamIndex: 2,
bidPointAmount: 20,
},
);
if (auth === 'true') {
await expect(result).rejects.toThrow(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
expect(placeBid).not.toHaveBeenCalled();
} else {
await expect(result).resolves.toEqual({ revision: 2 });
expect(placeBid).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
teamIndex: 2,
amount: 20,
bidderUserId: undefined,
}),
);
}
},
);
it('passes the signed-in user to service checks and restores community validation in strict mode', async () => {
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
const controller = new AuctionController(
{ placeBid } as never,
{} as never,
{} as never,
);
const user = {
_id: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
} as UserDocument;
const matchId = new mongoose.Types.ObjectId();
const body = { bidderTeamIndex: 2, bidPointAmount: 20 };
await controller.placeBid(
user,
new mongoose.Types.ObjectId(),
matchId,
body,
);
expect(placeBid).toHaveBeenLastCalledWith(
expect.objectContaining({ bidderUserId: user._id }),
);
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
await expect(
controller.placeBid(user, new mongoose.Types.ObjectId(), matchId, body),
).rejects.toThrow('Different community.');
expect(placeBid).toHaveBeenCalledTimes(1);
await expect(
controller.placeBid(user, user.communityId, matchId, body),
).resolves.toEqual({ revision: 2 });
expect(placeBid).toHaveBeenCalledTimes(2);
});
});
@@ -3,6 +3,7 @@ import {
Body,
Controller,
Delete,
ForbiddenException,
Get,
HttpCode,
HttpStatus,
@@ -19,6 +20,7 @@ import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import { AuctionService } from './auction.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import { AuctionGateway } from './auction.gateway';
import { AuctionBidArchiveService } from './auction-bid-archive.service';
import {
@@ -80,7 +82,7 @@ export class AuctionController {
return this.auctionService.getStateByMatchId(matchId);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
// 공개 입찰 기록 조회.
@Get('bids/history')
@AllowPublicAccess()
public async getBidHistory(
@@ -109,11 +111,23 @@ export class AuctionController {
@AllowPublicAccess()
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
if (isAuctionCaptainAuthRequired()) {
if (!currentUser) {
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
}
this.assertSameCommunity(currentUser, communityId);
}
return this.auctionService.placeBid({
matchId,
bidderUserId: currentUser?._id,
teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount,
bidRequestId: body.bidRequestId,
@@ -8,6 +8,15 @@ jest.mock('../auth/jwt.service', () => ({
import { AuctionGateway } from './auction.gateway';
describe('AuctionGateway', () => {
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => {
jest.restoreAllMocks();
});
it('signals pending initial state so the client can retry privately after recovery', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const gateway = new AuctionGateway(
@@ -28,7 +37,11 @@ describe('AuctionGateway', () => {
{} as never,
);
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
await gateway.handleJoin(socket as never, { matchId });
const ack = jest.fn();
await gateway.handleJoin(socket as never, { matchId }, ack);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ ok: false, code: 'AUCTION_STATE_RECOVERING' }),
);
expect(socket.emit).toHaveBeenCalledTimes(1);
expect(socket.emit).toHaveBeenCalledWith('state-pending', {
retryAfterMS: 500,
@@ -78,12 +91,17 @@ describe('AuctionGateway', () => {
expect(broadcast).not.toHaveBeenCalled();
});
const bidderUserId = new mongoose.Types.ObjectId();
function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock;
getRealtimeIdentity?: jest.Mock;
}) {
const auctionService = {
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
getRealtimeIdentity:
params?.getRealtimeIdentity ?? jest.fn().mockResolvedValue(null),
};
const auctionRedisService = {
getCurrentRedisTimestampMS:
@@ -112,6 +130,67 @@ describe('AuctionGateway', () => {
};
}
it('requires an authenticated user when captain authentication is enabled', async () => {
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway, auctionService } = createGateway();
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{ bidderTeamIndex: 1, bidPointAmount: 100 },
ack,
);
expect(auctionService.placeBidDelta).not.toHaveBeenCalled();
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ rejected: true }),
);
});
it.each([undefined, bidderUserId])(
'accepts the selected team in temporary mode for user %s',
async (userId) => {
const matchId = new mongoose.Types.ObjectId().toString();
const placeBidDelta = jest.fn().mockResolvedValue({
auctionBidHistoryEntry: {
bidderTeamIndex: 2,
bidderUserId: new mongoose.Types.ObjectId().toString(),
bidPointAmount: 120,
bidPlacedAtTimestampMS: 1780000000000,
},
currentHighestBidderTeamIndex: 2,
currentHighestBidPointAmount: 120,
currentServerTimestampMS: 1780000000000,
revision: 9,
});
const { gateway, emit } = createGateway({ placeBidDelta });
const ack = jest.fn();
await gateway.handleBid(
{
data: { matchId, user: userId ? { _id: userId } : undefined },
emit: jest.fn(),
} as never,
{ bidderTeamIndex: 2, bidPointAmount: 120 },
ack,
);
expect(placeBidDelta).toHaveBeenCalledWith(
expect.objectContaining({
teamIndex: 2,
amount: 120,
bidderUserId: userId,
}),
);
expect(ack).toHaveBeenCalledWith(expect.objectContaining({ ok: true }));
expect(emit).toHaveBeenCalledWith(
'bid',
expect.objectContaining({ currentHighestBidderTeamIndex: 2 }),
);
},
);
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const auctionBidHistoryEntry = {
@@ -133,7 +212,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{
bidPointAmount: 120,
bidderTeamIndex: 2,
@@ -147,6 +229,7 @@ describe('AuctionGateway', () => {
expect(placeBidDelta).toHaveBeenCalledWith({
amount: 120,
bidRequestId: 'bid-1',
bidderUserId,
clientObservedAuctionLifecycleId: 'life-1',
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
matchId: new mongoose.Types.ObjectId(matchId),
@@ -200,7 +283,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: jest.fn() } as never,
{
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
} as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
@@ -247,7 +333,10 @@ describe('AuctionGateway', () => {
const ack = jest.fn();
await gateway.handleBid(
{ data: { matchId }, emit: socketEmit } as never,
{
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
} as never,
{
bidPointAmount: 50,
bidderTeamIndex: 1,
@@ -305,6 +394,46 @@ describe('AuctionGateway', () => {
);
});
it('adds lightweight auction identity to heartbeats for the joined match', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const identity = {
auctionLifecycleId: 'life-1',
revision: 11,
matchSideEffectRevision: 3,
};
const getRealtimeIdentity = jest.fn().mockResolvedValue(identity);
const { gateway } = createGateway({ getRealtimeIdentity });
const ack = jest.fn();
await gateway.handleTimeSync({ sequence: 1 }, ack, {
data: { matchId },
} as never);
expect(getRealtimeIdentity).toHaveBeenCalledWith(matchId);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({ ok: true, auctionState: identity }),
);
});
it('continues clock sync when the optional auction identity read fails', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const { gateway } = createGateway({
getRealtimeIdentity: jest
.fn()
.mockRejectedValue(new Error('identity unavailable')),
});
const ack = jest.fn();
await gateway.handleTimeSync({ sequence: 2 }, ack, {
data: { matchId },
} as never);
expect(ack).toHaveBeenCalledWith(
expect.objectContaining({
ok: true,
sequence: 2,
currentServerTimestampMS: 1780000000000,
auctionStateUnavailable: true,
}),
);
});
it('rate limits excessive bid requests from the same socket', async () => {
jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
const matchId = new mongoose.Types.ObjectId().toString();
@@ -318,7 +447,10 @@ describe('AuctionGateway', () => {
revision: 3,
});
const socketEmit = jest.fn();
const socket = { data: { matchId }, emit: socketEmit };
const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: socketEmit,
};
const { gateway } = createGateway({ placeBidDelta });
const acknowledgements: Array<Record<string, unknown>> = [];
@@ -359,7 +491,10 @@ describe('AuctionGateway', () => {
currentHighestBidPointAmount: 50,
revision: 3,
});
const socket = { data: { matchId }, emit: jest.fn() };
const socket = {
data: { matchId, user: { _id: bidderUserId } },
emit: jest.fn(),
};
const { gateway } = createGateway({ placeBidDelta });
for (let index = 0; index < 8; index += 1) {
+133 -16
View File
@@ -1,4 +1,4 @@
import { Logger } from '@nestjs/common';
import { ForbiddenException, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { performance } from 'perf_hooks';
import {
@@ -14,6 +14,11 @@ import {
import mongoose from 'mongoose';
import type { JWTPayload } from 'jose';
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
import type {
AuctionReactionEvent,
AuctionReactionKind,
AuctionReactionReply,
} from '@lolympus/contracts';
import { AuthService } from '../auth/auth.service';
import { IdentityService } from '../auth/identity.service';
import { JwtService } from '../auth/jwt.service';
@@ -31,6 +36,7 @@ import type {
AuctionStateResponse,
} from './auction.service';
import { AuctionEventBusService } from './auction-event-bus.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import {
isAuctionResyncRecommended,
resolveAuctionRejectionReason,
@@ -72,6 +78,7 @@ type AuctionActionPayload = Omit<SoldPayload, 'assignedPosition'>;
interface ChatMessagePayload {
message?: string;
displayName?: string;
clientMessageId?: string;
}
interface BidRateLimitState {
@@ -80,12 +87,14 @@ interface BidRateLimitState {
}
interface AuctionSocketData {
auctionReactionSentAt?: number;
auctionResyncAtTimestampMS?: number;
auctionResyncInProgress?: boolean;
auctionBidRateLimit?: BidRateLimitState;
identity?: IdentityDocument;
matchId?: string;
user?: UserDocument;
devUser?: UserDocument;
}
type AuctionSocket = Socket<
@@ -96,6 +105,24 @@ type AuctionSocket = Socket<
>;
const BID_RATE_LIMIT_WINDOW_MS = 1000;
const REACTION_KINDS: Record<AuctionReactionKind, true> = {
'thumbs-up': true,
heart: true,
clap: true,
laugh: true,
wow: true,
sad: true,
fire: true,
celebrate: true,
eyes: true,
thinking: true,
'skull-crossbones': true,
poop: true,
pray: true,
'sweat-smile': true,
money: true,
trophy: true,
};
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
const BID_RATE_LIMIT_REJECTION_MESSAGE =
@@ -114,6 +141,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
private server!: Namespace;
private readonly logger = new Logger(AuctionGateway.name);
private readonly socketAuthentication = new WeakMap<
AuctionSocket,
Promise<void>
>();
constructor(
private readonly auctionService: AuctionService,
@@ -130,8 +161,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}
public async handleConnection(socket: AuctionSocket) {
const authentication = this.authenticateSocket(socket);
this.socketAuthentication.set(socket, authentication);
try {
await this.authenticateSocket(socket);
await authentication;
this.logger.debug(`Auction client connected: ${socket.id}`);
} catch (err) {
this.logger.warn(
@@ -147,17 +180,21 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
public async handleJoin(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: JoinAuctionPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
this.emitError(socket, 'Invalid matchId.');
ack?.({ ok: false, code: 'INVALID_MATCH_ID' });
return;
}
await socket.join(payload.matchId);
socket.data.matchId = payload.matchId;
try {
socket.data.matchId = undefined;
socket.data.user = undefined;
await this.socketAuthentication.get(socket);
await socket.join(payload.matchId);
await this.resolveSocketUserForMatch(socket, payload.matchId);
socket.data.matchId = payload.matchId;
const auction = await this.auctionService.getByMatchId(
new mongoose.Types.ObjectId(payload.matchId),
);
@@ -166,8 +203,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
);
this.emitChatHistory(socket, auction);
socket.emit('state', serializeRealtimeAuction(auctionState));
ack?.({ ok: true });
} catch (error) {
const rejection = this.resolveErrorPayload(error);
ack?.({ ...rejection, ok: false });
if (rejection.code === 'AUCTION_STATE_RECOVERING') {
socket.emit('state-pending', { retryAfterMS: 500 });
} else {
@@ -240,11 +279,17 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}
try {
const bidderUserId = this.resolveSocketUserId(socket);
if (isAuctionCaptainAuthRequired() && !bidderUserId)
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
const bidResult = await this.auctionService.placeBidDelta({
matchId: new mongoose.Types.ObjectId(matchId),
teamIndex: payload.bidderTeamIndex,
amount: payload.bidPointAmount,
bidRequestId,
bidderUserId,
clientObservedBidRoundId: payload.clientObservedBidRoundId,
clientObservedAuctionLifecycleId:
payload.clientObservedAuctionLifecycleId,
@@ -306,14 +351,27 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
public async handleTimeSync(
@MessageBody() payload: TimeSyncPayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
@ConnectedSocket() socket?: AuctionSocket,
) {
const receivedAtMonotonicMS = performance.now();
try {
const currentServerTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS();
const [currentServerTimestampMS, auctionState] = await Promise.all([
this.auctionRedisService.getCurrentRedisTimestampMS(),
socket?.data.matchId
? this.auctionService
.getRealtimeIdentity(socket.data.matchId)
.catch(() => undefined)
: undefined,
]);
ack?.({
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
currentServerTimestampMS,
...(socket?.data.matchId
? {
auctionState,
auctionStateUnavailable: auctionState === undefined,
}
: {}),
ok: true,
sequence: payload?.sequence,
serverProcessingDurationMS:
@@ -451,30 +509,82 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
public async handleChatMessage(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: ChatMessagePayload,
@Ack() ack?: (response: Record<string, unknown>) => void,
) {
const matchId = this.requireJoinedMatchId(socket);
if (!matchId) return;
if (!matchId) {
ack?.({ ok: false, message: 'Join a match room before sending events.' });
return;
}
if (typeof payload?.message !== 'string') {
this.emitError(socket, 'Chat message is required.');
ack?.({ ok: false, message: 'Chat message is required.' });
return;
}
try {
const { message } = await this.auctionService.appendChatMessage({
const { message, created } = await this.auctionService.appendChatMessage({
matchId: new mongoose.Types.ObjectId(matchId),
clientMessageId: payload.clientMessageId,
senderRole: ['owner', 'admin'].includes(socket.data.user?.role ?? '')
? 'operator'
: undefined,
userId: this.resolveSocketUserId(socket),
displayName: this.resolveChatDisplayName(socket, payload.displayName),
message: payload.message,
});
this.server
.to(matchId)
.emit('chat-message', this.serializeChatMessage(message));
const serialized = this.serializeChatMessage(message);
if (created) this.server.to(matchId).emit('chat-message', serialized);
ack?.({ ok: true, message: serialized });
} catch (error) {
this.emitKnownError(socket, error);
if (ack) ack({ ok: false, ...this.resolveErrorPayload(error) });
else this.emitKnownError(socket, error);
}
}
@SubscribeMessage('chat-reaction')
public handleChatReaction(
@ConnectedSocket() socket: AuctionSocket,
@MessageBody() payload: { kind?: unknown },
@Ack() ack?: (response: AuctionReactionReply) => void,
) {
const matchId = this.getSocketMatchId(socket);
if (!matchId) {
ack?.({ ok: false, code: 'NOT_JOINED' });
return;
}
if (
typeof payload?.kind !== 'string' ||
!Object.hasOwn(REACTION_KINDS, payload.kind)
) {
ack?.({ ok: false, code: 'INVALID_REACTION' });
return;
}
const now = Date.now();
if (
socket.data.auctionReactionSentAt !== undefined &&
now - socket.data.auctionReactionSentAt < 400
) {
ack?.({ ok: false, code: 'REACTION_RATE_LIMITED' });
return;
}
socket.data.auctionReactionSentAt = now;
const reaction: AuctionReactionEvent = {
id: randomUUID(),
kind: payload.kind as AuctionReactionKind,
displayName: Array.from(this.resolveChatDisplayName(socket))
.slice(0, 40)
.join(''),
userId: this.resolveSocketUserId(socket)?.toString(),
sentAt: now,
};
// The room adapter fans out to all viewers. Reactions never enter the
// persisted message history, so reconnects do not replay old animations.
this.server.to(matchId).emit('chat-reaction', reaction);
ack?.({ ok: true, reaction });
}
private requireJoinedMatchId(socket: AuctionSocket): string | null {
const matchId = this.getSocketMatchId(socket);
if (!matchId) {
@@ -573,14 +683,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
this.readHandshakeUserId(socket),
);
if (fallback) {
socket.data.user = fallback.user;
socket.data.devUser = fallback.user;
socket.data.identity = fallback.identity;
return;
}
const token = this.readHandshakeToken(socket);
if (!token) {
// 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다.
return;
}
@@ -622,14 +731,22 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
socket: AuctionSocket,
matchId: string,
): Promise<void> {
if (socket.data.user || !socket.data.identity) return;
const devUser = socket.data.devUser;
const identity = socket.data.identity;
if (!devUser && !identity) return;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId).select({
communityId: 1,
});
if (!match) return;
if (devUser) {
socket.data.user = devUser.communityId.equals(match.communityId)
? devUser
: undefined;
return;
}
if (!identity) return;
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findOne({
@@ -156,6 +156,11 @@ describe('AuctionService', () => {
};
}
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env });
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
});
afterEach(() => {
jest.restoreAllMocks();
jest.useRealTimers();
@@ -210,8 +215,7 @@ describe('AuctionService', () => {
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
});
it('lists auction history with a summary projection and short local cache', async () => {
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
it('reads committed history on every node without retaining a local cache', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
@@ -237,7 +241,7 @@ describe('AuctionService', () => {
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
const { service } = createService({
const models = {
auctionHistory: {
find: historyFind,
},
@@ -246,7 +250,9 @@ describe('AuctionService', () => {
select: jest.fn().mockResolvedValue(match),
}),
},
});
};
const { service } = createService(models);
const otherNode = createService(models).service;
await expect(
service.listHistory({ matchId, communityId }),
@@ -266,7 +272,7 @@ describe('AuctionService', () => {
]);
await service.listHistory({ matchId, communityId });
expect(historyFind).toHaveBeenCalledTimes(1);
expect(historyFind).toHaveBeenCalledTimes(2);
expect(historySelect).toHaveBeenCalledWith({
_id: 0,
action: 1,
@@ -276,9 +282,17 @@ describe('AuctionService', () => {
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
expect(historyLimit).toHaveBeenCalledWith(100);
nowSpy.mockReturnValue(3101);
await service.listHistory({ matchId, communityId });
expect(historyFind).toHaveBeenCalledTimes(2);
historyExec.mockResolvedValue([
{ action: 'undo', sequence: 5, takenAt: new Date() },
historyRows[1],
]);
const [firstNodeHistory, secondNodeHistory] = await Promise.all([
service.listHistory({ matchId, communityId }),
otherNode.listHistory({ matchId, communityId }),
]);
expect(firstNodeHistory.map(({ sequence }) => sequence)).toEqual([5, 3]);
expect(secondNodeHistory).toEqual(firstNodeHistory);
expect(historyFind).toHaveBeenCalledTimes(4);
});
it('starts an auction without reserving tournament codes before teams are complete', async () => {
@@ -1055,6 +1069,113 @@ describe('AuctionService', () => {
});
});
describe.each(['realtime', 'redis-fallback', 'legacy'] as const)(
'%s bid authorization',
(path) => {
it.each([
[undefined, 'guest'],
[undefined, 'other-user'],
['false', 'other-user'],
['true', 'guest'],
['true', 'other-user'],
['true', 'captain'],
] as const)('checks auth=%s for %s', async (auth, actor) => {
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const playerUserId = new mongoose.Types.ObjectId();
const bidderUserId =
actor === 'guest'
? undefined
: actor === 'captain'
? captainUserId
: new mongoose.Types.ObjectId();
const team = { teamIndex: 2, captainUserId, points: 1000, members: [] };
const auction = {
_id: new mongoose.Types.ObjectId(),
matchId,
auctionEngineVersion: path === 'legacy' ? undefined : 'redis-v1',
phase: 'bidding',
teams: [team],
currentBid: 0,
bidExtensionSeconds: 5,
bids: [],
save: jest.fn().mockResolvedValue(undefined),
toObject: () => ({ matchId, teams: [team], phase: 'bidding' }),
};
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: { findOne: jest.fn().mockResolvedValue(auction) },
});
const state = {
auctionLifecycleId: 'life-1',
currentBidRoundPlayerUserId: playerUserId.toString(),
phase: 'bidding',
revision: 2,
auctionTeams: [
{
teamIndex: 2,
captainUserId: captainUserId.toString(),
remainingBidPointAmount: 1000,
members: [],
},
],
};
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
state,
);
if (path === 'realtime') {
auctionRedisStateReaderService.readBidContext.mockResolvedValue({
...state,
bidderTeamCaptainUserId: captainUserId.toString(),
});
}
const result = service.placeBidDelta({
matchId,
teamIndex: 2,
amount: 20,
bidderUserId,
bidRequestId: 'auth-mode-bid',
});
if (auth === 'true' && actor !== 'captain') {
await expect(result).rejects.toThrow(
actor === 'guest'
? '팀장 계정으로 로그인해야 입찰할 수 있습니다.'
: '해당 팀의 팀장만 입찰할 수 있습니다.',
);
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
expect(auction.save).not.toHaveBeenCalled();
return;
}
await expect(result).resolves.toBeDefined();
if (path === 'legacy') {
expect(auction.bids).toEqual([
expect.objectContaining({
teamIndex: 2,
amount: 20,
bidderUserId: captainUserId,
}),
]);
expect(auction.save).toHaveBeenCalledTimes(1);
} else {
expect(auctionRedisCommandService.placeBid).toHaveBeenCalledWith(
matchId.toString(),
expect.objectContaining({
bidderTeamIndex: 2,
bidPointAmount: 20,
bidderUserId: captainUserId.toString(),
}),
);
}
});
},
);
it('places bids through Redis for redis-v1 auctions', async () => {
const matchId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
@@ -1747,9 +1868,17 @@ describe('AuctionService', () => {
chatMessages: oldMessages,
save: jest.fn().mockResolvedValue(undefined),
};
const findOneAndUpdate = jest.fn().mockImplementation((_filter, update) => {
auction.chatMessages = [
...auction.chatMessages,
...update.$push.chatMessages.$each,
].slice(-200);
return auction;
});
const { service } = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
findOneAndUpdate,
},
});
@@ -1770,7 +1899,54 @@ describe('AuctionService', () => {
expect(auction.chatMessages).toHaveLength(200);
expect(auction.chatMessages[0].id).toBe('old-1');
expect(auction.chatMessages.at(-1)).toBe(appended.message);
expect(auction.save).toHaveBeenCalledTimes(1);
expect(auction.save).not.toHaveBeenCalled();
expect(appended.created).toBe(true);
expect(findOneAndUpdate).toHaveBeenCalledWith(
{ matchId, 'chatMessages.id': { $ne: appended.message.id } },
{ $push: { chatMessages: { $each: [appended.message], $slice: -200 } } },
{ returnDocument: 'after' },
);
});
it('returns the saved message on retry without appending or broadcasting it again', async () => {
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const clientMessageId = '0589e8a4-bccd-4ccd-a3ae-28f117401e79';
const saved = {
id: `${userId.toString()}:${clientMessageId}`,
clientMessageId,
userId,
displayName: '팀장',
message: '확인했습니다',
sentAt: new Date(),
};
const findOneAndUpdate = jest.fn().mockResolvedValue(null);
const auction = { matchId, chatMessages: [saved] };
const { service } = createService({
auction: {
findOneAndUpdate,
findOne: jest.fn().mockResolvedValue(auction),
},
});
await expect(
service.appendChatMessage({
matchId,
userId,
clientMessageId,
message: '확인했습니다',
}),
).resolves.toEqual({ auction, message: saved, created: false });
expect(findOneAndUpdate.mock.calls[0][0]['chatMessages.id']).toEqual({
$ne: saved.id,
});
await expect(
service.appendChatMessage({
matchId,
userId,
clientMessageId,
message: '다른 메시지',
}),
).rejects.toThrow('Chat message conflicts with an earlier request.');
});
it('rejects blank and overly long chat messages', async () => {
+79 -67
View File
@@ -1,5 +1,6 @@
import {
BadRequestException,
ForbiddenException,
ConflictException,
Injectable,
InternalServerErrorException,
@@ -9,12 +10,14 @@ import {
Optional,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import type { AuctionStateIdentity } from '@lolympus/contracts';
import {
AuctionLifecycleLock,
AuctionLifecycleBusyError,
} from './auction-lifecycle-lock';
import { AUCTION_OPTIONAL_PROJECTION_FIELDS } from './auction-projection';
import { AuctionEventBusService } from './auction-event-bus.service';
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
import { performance } from 'perf_hooks';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
@@ -67,8 +70,6 @@ const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
const AUCTION_HISTORY_LIST_LIMIT = 100;
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
@@ -141,6 +142,8 @@ type RedisActionRequestContext =
interface AppendChatMessageParams {
matchId: mongoose.Types.ObjectId;
clientMessageId?: string;
senderRole?: 'operator';
userId?: mongoose.Types.ObjectId;
displayName?: string;
message: string;
@@ -159,11 +162,6 @@ interface AuctionHistorySummaryRecord {
takenAt: Date;
}
interface AuctionHistoryListCacheEntry {
entries: AuctionHistoryView[];
expiresAtTimestampMS: number;
}
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
export interface AuctionBidDeltaResponse {
@@ -207,10 +205,6 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
@Injectable()
export class AuctionService {
private readonly logger = new Logger(AuctionService.name);
private readonly auctionHistoryListCache = new Map<
string,
AuctionHistoryListCacheEntry
>();
constructor(
private readonly connectionService: ConnectionService,
@@ -575,6 +569,12 @@ export class AuctionService {
}
}
public getRealtimeIdentity(
matchId: string,
): Promise<AuctionStateIdentity | null> {
return this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
}
private async getStateByMatchIdOnce(
matchId: mongoose.Types.ObjectId,
): Promise<AuctionStateResponse> {
@@ -665,26 +665,57 @@ export class AuctionService {
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
auction: AuctionDocument;
message: AuctionChatMessage;
created: boolean;
}> {
const auction = await this.getByMatchId(params.matchId);
const messageText = this.normalizeChatMessage(params.message);
if (
params.clientMessageId !== undefined &&
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
params.clientMessageId,
)
) {
throw new BadRequestException('Invalid chat message id.');
}
// A retry keeps its ID. The conditional push is atomic, including when
// the first request is still saving after the client has timed out.
const id = params.clientMessageId
? `${params.userId?.toString() ?? 'guest'}:${params.clientMessageId}`
: randomUUID();
const message: AuctionChatMessage = {
id: randomUUID(),
id,
clientMessageId: params.clientMessageId,
senderRole: params.senderRole,
userId: params.userId,
displayName: this.normalizeChatDisplayName(params.displayName),
message: messageText,
sentAt: new Date(),
};
auction.chatMessages ??= [];
auction.chatMessages.push(message);
const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES;
if (overflow > 0) {
auction.chatMessages.splice(0, overflow);
}
const AuctionModel = await this.connectionService.getModel('auction');
const auction = await AuctionModel.findOneAndUpdate(
{ matchId: params.matchId, 'chatMessages.id': { $ne: id } },
{
$push: {
chatMessages: {
$each: [message],
$slice: -AUCTION_CHAT_MAX_MESSAGES,
},
},
},
{ returnDocument: 'after' },
);
if (auction) return { auction, message, created: true };
await auction.save();
return { auction, message };
const existingAuction = await this.getByMatchId(params.matchId);
const existing = existingAuction.chatMessages.find(
(entry) => entry.id === id,
);
if (!existing || existing.message !== messageText) {
throw new BadRequestException(
'Chat message conflicts with an earlier request.',
);
}
return { auction: existingAuction, message: existing, created: false };
}
public async listHistory(params: {
@@ -702,10 +733,6 @@ export class AuctionService {
throw new BadRequestException('Match does not belong to this community.');
}
const cacheKey = this.buildAuctionHistoryListCacheKey(params);
const cachedHistory = this.getCachedAuctionHistoryList(cacheKey);
if (cachedHistory) return cachedHistory;
const entries = (await AuctionHistoryModel.find({ matchId: params.matchId })
.select({ _id: 0, action: 1, sequence: 1, takenAt: 1 })
.sort({ sequence: -1 })
@@ -719,49 +746,9 @@ export class AuctionService {
actionLabel: this.formatHistoryActionLabel(entry.action),
takenAt: entry.takenAt,
}));
this.setCachedAuctionHistoryList(cacheKey, history);
return history;
}
private buildAuctionHistoryListCacheKey(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): string {
return `${params.communityId.toString()}:${params.matchId.toString()}`;
}
private getCachedAuctionHistoryList(
cacheKey: string,
): AuctionHistoryView[] | null {
const cached = this.auctionHistoryListCache.get(cacheKey);
if (!cached) return null;
if (cached.expiresAtTimestampMS <= Date.now()) {
this.auctionHistoryListCache.delete(cacheKey);
return null;
}
return cached.entries;
}
private setCachedAuctionHistoryList(
cacheKey: string,
entries: AuctionHistoryView[],
): void {
if (
!this.auctionHistoryListCache.has(cacheKey) &&
this.auctionHistoryListCache.size >=
AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES
) {
const oldestKey = this.auctionHistoryListCache.keys().next().value as
| string
| undefined;
if (oldestKey) this.auctionHistoryListCache.delete(oldestKey);
}
this.auctionHistoryListCache.set(cacheKey, {
entries,
expiresAtTimestampMS: Date.now() + AUCTION_HISTORY_LIST_CACHE_TTL_MS,
});
}
public async openBidding(
matchId: mongoose.Types.ObjectId,
actionRequest: AuctionStructureActionRequestParams = {},
@@ -795,6 +782,10 @@ export class AuctionService {
}
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
if (!team) throw new BadRequestException('Unknown team.');
this.assertBidderIsCaptain(
params.bidderUserId,
team.captainUserId.toString(),
);
if (params.amount <= auction.currentBid) {
throw new BadRequestException('Bid must exceed current bid.');
}
@@ -807,8 +798,6 @@ export class AuctionService {
'Bid must reserve minimum points for remaining slots.',
);
}
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
auction.currentBid = params.amount;
auction.currentBidderTeamIndex = params.teamIndex;
@@ -929,6 +918,10 @@ export class AuctionService {
if (!bidContext.bidderTeamCaptainUserId) {
throw new BadRequestException('Unknown team.');
}
this.assertBidderIsCaptain(
params.bidderUserId,
bidContext.bidderTeamCaptainUserId,
);
const auctionLifecycleId =
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
@@ -1005,6 +998,10 @@ export class AuctionService {
(entry) => Number(entry.teamIndex) === params.teamIndex,
);
if (!team) throw new BadRequestException('Unknown team.');
this.assertBidderIsCaptain(
params.bidderUserId,
this.stringFromState(team.captainUserId),
);
const auctionLifecycleId =
params.clientObservedAuctionLifecycleId ??
@@ -2906,6 +2903,21 @@ export class AuctionService {
return auction.teams.find((team) => team.teamIndex === teamIndex);
}
private assertBidderIsCaptain(
bidderUserId: mongoose.Types.ObjectId | undefined,
captainUserId: string,
) {
if (!isAuctionCaptainAuthRequired()) return;
if (!bidderUserId) {
throw new ForbiddenException(
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
);
}
if (bidderUserId.toString() !== captainUserId) {
throw new ForbiddenException('해당 팀의 팀장만 입찰할 수 있습니다.');
}
}
private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000);
}
@@ -30,17 +30,23 @@ function makeService(
describe('AuctionRedisStateReaderService', () => {
it('reads live state identity', async () => {
const { service, sendCommand } = makeService([['life-1', '7']]);
const { service, sendCommand } = makeService([
['life-1', '7', '3', 'transition-1'],
]);
await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({
auctionLifecycleId: 'life-1',
revision: 7,
matchSideEffectRevision: 3,
matchSideEffectTransitionId: 'transition-1',
});
expect(sendCommand).toHaveBeenCalledWith([
'HMGET',
'auction:match-1:liveAuctionState',
'auctionLifecycleId',
'revision',
'matchSideEffectRevision',
'matchSideEffectTransitionId',
]);
});
@@ -118,7 +124,9 @@ describe('AuctionRedisStateReaderService', () => {
expect(view).toMatchObject({
auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }],
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: 'life-1',
matchId: 'match-1',
auctionTeams: [{ teamIndex: 1 }],
canPlaceBidInCurrentBidRound: false,
currentHighestBidderTeamIndex: 2,
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import type { AuctionStateIdentity } from '@lolympus/contracts';
import { buildAuctionRedisKeys } from './auction-redis.keys';
import { AuctionRedisService } from './auction-redis.service';
import { assembleAuctionViewFromRedisState } from './auction-redis.state';
@@ -17,10 +18,7 @@ const NUMERIC_LIVE_STATE_FIELDS = new Set([
'revision',
]);
export interface AuctionRedisLiveStateIdentity {
auctionLifecycleId?: string;
revision?: number;
}
export type AuctionRedisLiveStateIdentity = AuctionStateIdentity;
export interface AuctionRedisBidContext {
auctionLifecycleId: string;
@@ -49,6 +47,8 @@ export class AuctionRedisStateReaderService {
keys.liveStateKey,
'auctionLifecycleId',
'revision',
'matchSideEffectRevision',
'matchSideEffectTransitionId',
]);
if (!Array.isArray(reply)) return null;
const auctionLifecycleId =
@@ -61,6 +61,12 @@ export class AuctionRedisStateReaderService {
return {
auctionLifecycleId,
revision: Number.isFinite(revision) ? revision : undefined,
matchSideEffectRevision:
reply[2] !== null && Number.isFinite(Number(reply[2]))
? Number(reply[2])
: undefined,
matchSideEffectTransitionId:
typeof reply[3] === 'string' && reply[3] ? reply[3] : undefined,
};
}
@@ -147,6 +153,7 @@ export class AuctionRedisStateReaderService {
structureState: parseJsonRecord(structureStateJson),
});
view.matchId = matchId;
view.auctionEngineVersion = 'redis-v1';
if (options.includeInternalLiveStateFields) {
view.redisInternalPhase = liveState.phase;
}
@@ -0,0 +1,198 @@
import { Logger } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service';
describe('Community stats cache invalidation retries', () => {
let service: CommunityStatsCacheService;
let invalidate: jest.SpyInstance<Promise<number>, [string, number?]>;
beforeEach(() => {
jest.useFakeTimers();
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
service = new CommunityStatsCacheService({} as never);
invalidate = jest
.spyOn(service, 'invalidateCommunity')
.mockRejectedValue(new Error('Redis down'));
});
afterEach(() => {
service.onModuleDestroy();
jest.restoreAllMocks();
jest.useRealTimers();
});
it('returns true even when successful invalidation deletes no cache entries', async () => {
invalidate.mockResolvedValue(0);
expect(await service.invalidateCommunityWithRetry('community')).toBe(true);
expect(invalidate).toHaveBeenCalledWith('community', 1_000);
expect(jest.getTimerCount()).toBe(0);
});
it('returns false immediately, then retries at most three times with increasing delays', async () => {
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
for (const [index, delay] of [1_000, 5_000, 30_000].entries()) {
await jest.advanceTimersByTimeAsync(delay - 1);
expect(invalidate).toHaveBeenCalledTimes(index + 1);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(index + 2);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(Logger.prototype.warn).toHaveBeenCalledWith(
expect.stringContaining('retries exhausted for community'),
);
});
it('does not reset the scheduled delay or remaining budget after another immediate failure', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
await jest.advanceTimersByTimeAsync(2_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(jest.getTimerCount()).toBe(1);
await jest.advanceTimersByTimeAsync(2_999);
expect(invalidate).toHaveBeenCalledTimes(3);
await jest.advanceTimersByTimeAsync(1);
expect(invalidate).toHaveBeenCalledTimes(4);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(6);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(6);
});
it.each(['immediate', 'background'] as const)(
'cancels remaining retries after a successful %s attempt',
async (attempt) => {
await service.invalidateCommunityWithRetry('community');
invalidate.mockResolvedValue(0);
if (attempt === 'immediate') {
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
} else {
await jest.advanceTimersByTimeAsync(1_000);
}
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(2);
},
);
it('unrefs every retry timer so it does not keep the process alive', async () => {
const setTimeoutSpy = jest.spyOn(global, 'setTimeout');
await service.invalidateCommunityWithRetry('community');
for (const delay of [1_000, 5_000, 30_000]) {
const timer = setTimeoutSpy.mock.results.at(-1)!.value as NodeJS.Timeout;
expect(timer.hasRef()).toBe(false);
await jest.advanceTimersByTimeAsync(delay);
}
});
it('keeps different communities independent when one continues to fail', async () => {
await service.invalidateCommunityWithRetry('first');
await service.invalidateCommunityWithRetry('second');
invalidate.mockImplementation(async (id) => {
if (id === 'first') throw new Error('still unavailable');
return 1;
});
await jest.advanceTimersByTimeAsync(36_000);
expect(invalidate.mock.calls.filter(([id]) => id === 'first')).toHaveLength(
4,
);
expect(
invalidate.mock.calls.filter(([id]) => id === 'second'),
).toHaveLength(2);
expect(jest.getTimerCount()).toBe(0);
});
it('clears scheduled retries on shutdown', async () => {
await service.invalidateCommunityWithRetry('community');
service.onModuleDestroy();
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
expect(invalidate).toHaveBeenCalledTimes(1);
});
it.each(['shutdown', 'immediate success'] as const)(
'does not reschedule an in-flight retry after %s',
async (finish) => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(2);
if (finish === 'shutdown') {
service.onModuleDestroy();
} else {
invalidate.mockResolvedValueOnce(1);
expect(await service.invalidateCommunityWithRetry('community')).toBe(
true,
);
}
pending.reject(new Error('late failure'));
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(finish === 'shutdown' ? 2 : 3);
expect(jest.getTimerCount()).toBe(0);
},
);
it('does not cancel a newer failed request when an older immediate attempt succeeds late', async () => {
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const first = service.invalidateCommunityWithRetry('community');
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
pending.resolve(1);
expect(await first).toBe(true);
expect(jest.getTimerCount()).toBe(1);
invalidate.mockResolvedValue(1);
await jest.advanceTimersByTimeAsync(1_000);
expect(invalidate).toHaveBeenCalledTimes(3);
expect(jest.getTimerCount()).toBe(0);
});
it('preserves the retry budget when an immediate request fails during an in-flight retry', async () => {
await service.invalidateCommunityWithRetry('community');
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
await jest.advanceTimersByTimeAsync(1_000);
expect(await service.invalidateCommunityWithRetry('community')).toBe(false);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(3);
pending.resolve(1);
await jest.advanceTimersByTimeAsync(5_000);
expect(invalidate).toHaveBeenCalledTimes(4);
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
expect(jest.getTimerCount()).toBe(0);
});
it('does not restart an exhausted budget when an older immediate request fails late', async () => {
await service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(6_000);
const pending = deferred();
invalidate.mockImplementationOnce(() => pending.promise);
const immediate = service.invalidateCommunityWithRetry('community');
await jest.advanceTimersByTimeAsync(30_000);
expect(invalidate).toHaveBeenCalledTimes(5);
pending.reject(new Error('late failure'));
expect(await immediate).toBe(false);
expect(jest.getTimerCount()).toBe(0);
await jest.advanceTimersByTimeAsync(60_000);
expect(invalidate).toHaveBeenCalledTimes(5);
});
});
function deferred() {
let resolve!: (value: number) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<number>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
@@ -1,9 +1,15 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import { randomUUID } from 'crypto';
import { RedisService } from '../global/redis/redis.service';
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
const INVALIDATION_RETRY_DELAYS_MS = [1_000, 5_000, 30_000] as const;
interface InvalidationRetry {
attempts: number;
requestVersion: number;
timer?: NodeJS.Timeout;
}
const CACHE_SCOPES = [
'matches',
'leaderboard',
@@ -64,11 +70,105 @@ return deleted
`;
@Injectable()
export class CommunityStatsCacheService {
export class CommunityStatsCacheService implements OnModuleDestroy {
private readonly logger = new Logger(CommunityStatsCacheService.name);
private readonly invalidationRetries = new Map<string, InvalidationRetry>();
private destroyed = false;
constructor(private readonly redisService: RedisService) {}
public onModuleDestroy(): void {
this.destroyed = true;
for (const pending of this.invalidationRetries.values()) {
if (pending.timer) clearTimeout(pending.timer);
}
this.invalidationRetries.clear();
}
// Only the immediate attempt determines whether the caller may cache its response.
public async invalidateCommunityWithRetry(
communityId: string,
): Promise<boolean> {
if (this.destroyed) return false;
const pending = this.invalidationRetries.get(communityId) ?? {
attempts: 0,
requestVersion: 0,
};
this.invalidationRetries.set(communityId, pending);
const version = ++pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else if (!succeeded) {
// An existing retry keeps its remaining budget, including while in flight.
this.scheduleInvalidationRetry(communityId, pending);
}
return succeeded;
}
private scheduleInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (
this.destroyed ||
this.invalidationRetries.get(communityId) !== pending ||
pending.timer
)
return;
const delay = INVALIDATION_RETRY_DELAYS_MS[pending.attempts];
if (delay === undefined) {
this.clearInvalidationRetry(communityId, pending);
this.logger.warn(
`Stats cache invalidation retries exhausted for ${communityId}; detail recovery and cache expiry will refresh stale responses.`,
);
return;
}
pending.attempts += 1;
pending.timer = setTimeout(
() => void this.retryInvalidation(communityId, pending),
delay,
);
pending.timer.unref();
}
private async retryInvalidation(
communityId: string,
pending: InvalidationRetry,
): Promise<void> {
const version = pending.requestVersion;
const succeeded = await this.tryInvalidateCommunity(communityId);
if (this.invalidationRetries.get(communityId) !== pending) return;
pending.timer = undefined;
// An older completion must not cancel a newer request's retry.
if (succeeded && pending.requestVersion === version) {
this.clearInvalidationRetry(communityId, pending);
} else {
this.scheduleInvalidationRetry(communityId, pending);
}
}
private clearInvalidationRetry(
communityId: string,
pending: InvalidationRetry,
): void {
if (this.invalidationRetries.get(communityId) !== pending) return;
if (pending.timer) clearTimeout(pending.timer);
this.invalidationRetries.delete(communityId);
}
private async tryInvalidateCommunity(communityId: string): Promise<boolean> {
try {
await this.invalidateCommunity(communityId, 1_000);
return true;
} catch (error) {
this.logger.warn(
`Stats cache invalidation failed for ${communityId}: ${String(error)}`,
);
return false;
}
}
public async get<T>(key: CommunityStatsCacheKey): Promise<T | null> {
const reply = await this.redisService
.raw()
@@ -117,19 +217,25 @@ export class CommunityStatsCacheService {
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
}
public async invalidateCommunity(communityId: string): Promise<number> {
public async invalidateCommunity(
communityId: string,
timeoutMs?: number,
): Promise<number> {
const prefix = communityPrefix(communityId);
const deleted = Number(
await this.redisService
.raw()
.sendCommand([
'EVAL',
INVALIDATE_CACHE_SCRIPT,
String(CACHE_SCOPES.length + 1),
`${prefix}:generation`,
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
randomUUID(),
]),
.sendCommand(
[
'EVAL',
INVALIDATE_CACHE_SCRIPT,
String(CACHE_SCOPES.length + 1),
`${prefix}:generation`,
...CACHE_SCOPES.map((scope) => `${prefix}:${scope}`),
randomUUID(),
],
timeoutMs === undefined ? undefined : { timeout: timeoutMs },
),
);
if (deleted > 0) {
@@ -0,0 +1,321 @@
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsCacheKey } from './community-stats-cache.service';
import type { InternalMatchDetailResponse } from './community-stats.types';
describe('Community stats raw archive recovery', () => {
it.each([true, false])(
'recovers a cached missing game even if invalidation needs retry (%s)',
async (invalidationSucceeds) => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let archived = false;
let enriched = false;
let generation = 'before';
let cached: InternalMatchDetailResponse | null = null;
const exists = jest.fn(() => query(archived ? { _id: 'archive' } : null));
const buildAndUpsert = jest.fn(async () => {
enriched = true;
});
const invalidateCommunity = jest.fn(async () => {
if (!invalidationSucceeds) return false;
cached = null;
generation = 'after';
return true;
});
const setDetail = jest.fn(
async (
key: CommunityStatsCacheKey,
value: InternalMatchDetailResponse,
) => {
expect(key.generation).toBe(generation);
cached = value;
},
);
const service = new CommunityStatsService(
{ getModel: async () => ({ exists }) } as never,
{
get: async (key: CommunityStatsCacheKey) => {
key.generation = generation;
return cached;
},
setDetail,
invalidateCommunityWithRetry: invalidateCommunity,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
matchDetailInFlight: Map<string, unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest
.spyOn(internals, 'buildBaseDataset')
.mockImplementation(async () => ({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: enriched,
timelineLoaded: enriched,
teams: [],
},
],
],
]),
competition: {
projection: {
games: [
{
id: 'official-game',
displayNumber: 1,
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
],
},
},
}));
const missing = await service.getMatchDetail({ communityId, matchId });
expect(missing.games[0].analysisAvailability).toBe('missing');
expect(await service.getMatchDetail({ communityId, matchId })).toBe(
missing,
);
expect(buildAndUpsert).not.toHaveBeenCalled();
archived = true;
const recovered = await service.getMatchDetail({ communityId, matchId });
expect(recovered.games[0]).toMatchObject({
gameId: 'official-game',
analysisAvailability: 'available',
riotMatchId: 'KR_1',
});
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(invalidateCommunity).toHaveBeenCalledWith(communityId.toString());
expect(internals.matchDetailInFlight.size).toBe(0);
expect(setDetail).toHaveBeenCalledTimes(invalidationSucceeds ? 2 : 1);
expect(await service.getMatchDetail({ communityId, matchId })).toEqual(
recovered,
);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
},
);
it('rebuilds only affected missing fragments and invalidates every affected community after the writes', async () => {
const first = new mongoose.Types.ObjectId();
const second = new mongoose.Types.ObjectId();
const fragments = [
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: first,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
},
{
matchId: new mongoose.Types.ObjectId(),
communityId: second,
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: false }],
},
];
const order: string[] = [];
const buildAndUpsert = jest.fn(async () => {
order.push('build');
});
const invalidateCommunity = jest.fn(async () => {
order.push('invalidate');
return true;
});
const findByRiotMatchIds = jest.fn().mockResolvedValue(fragments);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds,
findByMatch: async () => ({
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: true }],
}),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1', 'KR_1', 'KR_ABSENT']);
expect(findByRiotMatchIds).toHaveBeenCalledWith(['KR_1']);
expect(buildAndUpsert.mock.calls).toEqual([
[fragments[0].matchId],
[fragments[2].matchId],
]);
expect(invalidateCommunity.mock.calls).toEqual([
[first.toString()],
[second.toString()],
]);
expect(order).toEqual(['build', 'build', 'invalidate', 'invalidate']);
});
it('does not invalidate already enriched games or builds that make no progress', async () => {
const game = { riotMatchId: 'KR_1', rawAvailable: false };
const fragment = {
matchId: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
gameDetails: [game],
};
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidateCommunity = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidateCommunity } as never,
{
findByRiotMatchIds: async () => [fragment],
findByMatch: async () => fragment,
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
game.rawAvailable = true;
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(invalidateCommunity).not.toHaveBeenCalled();
});
it('does not rebuild when raw is still absent', async () => {
const findByRiotMatchIds = jest.fn();
const buildAndUpsert = jest.fn();
const service = new CommunityStatsService(
{ getModel: async () => ({ find: () => query([]) }) } as never,
{} as never,
{ findByRiotMatchIds } as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(findByRiotMatchIds).not.toHaveBeenCalled();
expect(buildAndUpsert).not.toHaveBeenCalled();
});
it('invalidates successful communities once even when another game fails mid-batch', async () => {
const communities = Array.from(
{ length: 4 },
() => new mongoose.Types.ObjectId(),
);
const fragments = [0, 1, 0, 2, 3].map((community, index) => ({
matchId: new mongoose.Types.ObjectId(),
communityId: communities[community],
gameDetails: [{ riotMatchId: 'KR_1', rawAvailable: index === 4 }],
}));
const buildAndUpsert = jest.fn(async (matchId: mongoose.Types.ObjectId) => {
const fragment = fragments.find((item) => item.matchId === matchId)!;
if (fragment === fragments[1]) throw new Error('one build fails');
fragment.gameDetails[0].rawAvailable = true;
});
const invalidate = jest.fn().mockResolvedValue(true);
const service = new CommunityStatsService(
{
getModel: async () => ({ find: () => query([{ matchId: 'KR_1' }]) }),
} as never,
{ invalidateCommunityWithRetry: invalidate } as never,
{
findByRiotMatchIds: async () => fragments,
findByMatch: async (id: mongoose.Types.ObjectId) =>
fragments.find((item) => item.matchId === id),
} as never,
{ buildAndUpsert } as never,
);
await service.refreshForRiotMatches(['KR_1']);
expect(buildAndUpsert).toHaveBeenCalledTimes(4);
expect(invalidate.mock.calls).toEqual([
[communities[0].toString()],
[communities[2].toString()],
]);
});
it('backs off raw recovery that makes no progress and does not invalidate the community', async () => {
let now = 1000;
const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);
try {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
let cached: InternalMatchDetailResponse | null = null;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const invalidate = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({ exists: () => query({ _id: 'archive' }) }),
} as never,
{
get: async () => cached,
setDetail: async (
_key: unknown,
value: InternalMatchDetailResponse,
) => {
cached = value;
},
invalidateCommunityWithRetry: invalidate,
} as never,
{} as never,
{ buildAndUpsert } as never,
);
const internals = service as unknown as {
getDetailRevision: () => Promise<string>;
buildBaseDataset: () => Promise<unknown>;
};
jest
.spyOn(internals, 'getDetailRevision')
.mockResolvedValue('same-revision');
jest.spyOn(internals, 'buildBaseDataset').mockResolvedValue({
matches: [{ matchId: matchId.toString() }],
detailsByMatchId: new Map([
[
matchId.toString(),
[
{
gameNumber: 1,
riotMatchId: 'KR_1',
rawAvailable: false,
timelineLoaded: false,
teams: [],
},
],
],
]),
});
await service.getMatchDetail({ communityId, matchId });
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
now += 60_000;
await service.getMatchDetail({ communityId, matchId });
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(invalidate).not.toHaveBeenCalled();
} finally {
clock.mockRestore();
}
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
exec: async () => value,
};
}
@@ -1,4 +1,10 @@
import { Controller, Get, Param, Query } from '@nestjs/common';
import {
BadRequestException,
Controller,
Get,
Param,
Query,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
@@ -9,6 +15,15 @@ import type { CommunityStatsFilters } from './community-stats.types';
export class CommunityStatsController {
constructor(private readonly communityStatsService: CommunityStatsService) {}
@Get('internal-stats/seasons')
@AllowPublicAccess()
public getSeasons(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
) {
return this.communityStatsService.getSeasons(communityId);
}
@Get('internal-stats/matches')
@AllowPublicAccess()
public getMatches(
@@ -20,7 +35,30 @@ export class CommunityStatsController {
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
@Query('q') query?: string,
@Query('format') format?: string,
@Query('playerId') playerId?: string,
@Query('cursorMatchId') cursorMatchId?: string,
) {
if (format !== undefined && format !== 'pair' && format !== 'tournament') {
throw new BadRequestException('Invalid format.');
}
if (playerId !== undefined && !mongoose.isObjectIdOrHexString(playerId)) {
throw new BadRequestException('Invalid playerId.');
}
if (
cursorMatchId !== undefined &&
(!mongoose.isObjectIdOrHexString(cursorMatchId) ||
this.toNumber(cursor) === undefined)
) {
throw new BadRequestException('Invalid cursor.');
}
if (
cursor !== undefined &&
Number.isNaN(new Date(this.toNumber(cursor) ?? NaN).getTime())
) {
throw new BadRequestException('Invalid cursor.');
}
return this.communityStatsService.getMatches({
communityId,
filters: this.toFilters({
@@ -30,6 +68,10 @@ export class CommunityStatsController {
championId,
cursor,
limit,
query,
format,
playerId,
cursorMatchId,
}),
});
}
@@ -43,10 +85,12 @@ export class CommunityStatsController {
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('q') query?: string,
@Query('lane') lane?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
filters: this.toFilters({ seasonId, from, to, championId, query, lane }),
});
}
@@ -88,18 +132,24 @@ export class CommunityStatsController {
@Query('championId') championId?: string,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
@Query('lane') lane?: string,
@Query('includePositionCounts') includePositionCounts?: string,
) {
return this.communityStatsService.getUserInternalHistory({
communityId,
userId,
filters: this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
}),
filters: {
...this.toFilters({
seasonId,
from,
to,
championId,
cursor,
limit,
lane,
}),
includePositionCounts: includePositionCounts === 'true',
},
});
}
@@ -110,7 +160,24 @@ export class CommunityStatsController {
championId?: string;
cursor?: string;
limit?: string;
query?: string;
format?: CommunityStatsFilters['format'];
playerId?: string;
cursorMatchId?: string;
lane?: string;
}): CommunityStatsFilters {
if (
params.lane !== undefined &&
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
) {
throw new BadRequestException('Invalid lane.');
}
if (
params.query !== undefined &&
(typeof params.query !== 'string' || params.query.length > 100)
) {
throw new BadRequestException('Invalid search query.');
}
return {
seasonId: params.seasonId,
from: params.from,
@@ -118,6 +185,11 @@ export class CommunityStatsController {
championId: this.toNumber(params.championId),
cursor: this.toNumber(params.cursor),
limit: this.toNumber(params.limit),
query: params.query?.trim(),
format: params.format,
playerId: params.playerId,
cursorMatchId: params.cursorMatchId,
lane: params.lane as CommunityStatsFilters['lane'],
};
}
@@ -1,4 +1,4 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { RiotModule } from '../riot/riot.module';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller';
@@ -8,7 +8,7 @@ import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
@Module({
imports: [RiotModule],
imports: [forwardRef(() => RiotModule)],
controllers: [CommunityStatsController],
providers: [
CommunityStatsService,
@@ -86,6 +86,246 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
}
describe('CommunityStatsService', () => {
it('reads the official result again on a filtered page cache hit and excludes games from stale revisions', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const playerId = new mongoose.Types.ObjectId().toString();
const scheduledAt = new Date('2026-06-18T12:00:00Z');
const matchCard = {
matchId: matchId.toString(),
scheduledAt: scheduledAt.toISOString(),
games: [{ gameNumber: 1, winnerTeamIndex: 1 }],
};
const findMatchPage = jest.fn().mockResolvedValue([
{
matchId,
scheduledAt,
matchCard,
gameDetails: [{ gameNumber: 1, gameCreation: 1000 }],
sourceCompetitionId: competitionId,
sourceRevision: 4,
},
{ matchId: new mongoose.Types.ObjectId() },
]);
const source = {
_id: competitionId,
matchId,
communityId,
revision: 4,
createdAt: scheduledAt,
updatedAt: scheduledAt,
teams: [],
projection: {
phase: 'completed',
formatType: 'double-elimination',
series: [],
outcome: { type: 'double-elimination', championTeamId: 'winner' },
},
};
const find = jest.fn().mockReturnValue({
select: () => ({ lean: () => ({ exec: async () => [source] }) }),
});
let cachedPage: unknown = null;
const service = new CommunityStatsService(
{
getModel: async (name: string) =>
name === 'community'
? { findById: () => ({ exec: async () => ({ _id: communityId }) }) }
: { find },
} as unknown as ConnectionService,
{
get: async () => cachedPage,
set: async (_key: unknown, page: unknown) => {
cachedPage = JSON.parse(JSON.stringify(page));
},
} as unknown as CommunityStatsCacheService,
{ findMatchPage } as unknown as MatchStatsRepository,
{} as MatchStatsService,
);
jest
.spyOn(
service as unknown as {
repairCommunityFragments: () => Promise<number>;
},
'repairCommunityFragments',
)
.mockResolvedValue(0);
const params = {
communityId,
filters: {
seasonId: 'all',
query: '결승',
format: 'tournament' as const,
playerId,
limit: 1,
},
};
const initial = await service.getMatches(params);
expect(initial.matches[0]).toMatchObject({
games: [{ gameNumber: 1 }],
resultPresentation: {
type: 'official',
phase: 'completed',
sourceRevision: 4,
outcome: { championTeamId: 'winner' },
},
});
Object.assign(source, {
revision: 5,
projection: {
...source.projection,
phase: 'running',
outcome: undefined,
},
});
const result = await service.getMatches(params);
expect(findMatchPage).toHaveBeenCalledWith(
expect.objectContaining({
query: '결승',
format: 'tournament',
playerId,
limit: 2,
}),
);
expect(find).toHaveBeenCalledWith({
communityId,
matchId: { $in: [matchId] },
});
expect(findMatchPage).toHaveBeenCalledTimes(1);
expect(find).toHaveBeenCalledTimes(2);
expect(result.matches[0]).toMatchObject({
games: [],
resultPresentation: {
type: 'official',
competitionId: competitionId.toString(),
sourceRevision: 5,
phase: 'running',
},
});
expect(result.nextCursor).toBe(scheduledAt.getTime());
expect(result.nextCursorMatchId).toBe(matchId.toString());
});
it.each(['legacy', 'riot', 'unlinked'] as const)(
'preserves the scoreboard without retrying a missing Riot archive for %s evidence',
async (type) => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = { matchId: matchId.toString() };
const participant = record(matchId);
const matchKey = type === 'legacy' ? 'legacy-reference' : 'KR_1';
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const set = jest.fn();
const setDetail = jest.fn();
const service = new CommunityStatsService(
{
getModel: async () => ({
exists: () => ({ exec: async () => null }),
}),
} as unknown as ConnectionService,
{
get: async () => null,
set,
setDetail,
} as unknown as CommunityStatsCacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
);
jest
.spyOn(
service as unknown as { getDetailRevision: () => Promise<string> },
'getDetailRevision',
)
.mockResolvedValue('revision-1');
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
jest.fn().mockResolvedValue({
matches: [match],
detailsByMatchId: new Map([
[
match.matchId,
[
{
gameNumber: 1,
riotMatchId: matchKey,
gameCreation: 1000,
gameDuration: 1800,
rawAvailable: false,
timelineLoaded: false,
teams: [
{
teamIndex: 1,
side: 'blue',
win: true,
objectives: objectives(),
participants: [participant],
},
],
},
],
],
]),
competition:
type === 'unlinked'
? undefined
: {
projection: {
games: [
{
id: 'game-1',
seriesId: 'series-1',
gameSlotId: 'slot-1',
ordinal: 1,
displayNumber: 1,
evidence:
type === 'legacy'
? { type, legacyReference: matchKey }
: { type, riotMatchId: matchKey },
},
],
},
},
});
const response = await service.getMatchDetail({ communityId, matchId });
const afterCacheMiss = await service.getMatchDetail({
communityId,
matchId,
});
expect(response.games).toHaveLength(1);
expect(response.games).toMatchObject([
{
...(type === 'unlinked' ? {} : { gameId: 'game-1' }),
analysisAvailability: 'missing',
teams: [
{
win: true,
participants: [
{
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
championId: participant.championId,
},
],
},
],
},
]);
expect(afterCacheMiss).toEqual(response);
expect(buildAndUpsert).not.toHaveBeenCalled();
expect(set).not.toHaveBeenCalled();
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
response,
);
},
);
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
@@ -222,7 +462,13 @@ describe('CommunityStatsService', () => {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
{} as ConnectionService,
{
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService,
{} as MatchStatsRepository,
matchStatsService,
@@ -284,7 +530,7 @@ describe('CommunityStatsService', () => {
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
invalidCheckpointResponse,
);
});
@@ -309,6 +555,7 @@ describe('CommunityStatsService', () => {
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
rawAvailable: true,
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
@@ -361,7 +608,13 @@ describe('CommunityStatsService', () => {
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const service = new CommunityStatsService(
{} as ConnectionService,
{
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{ buildAndUpsert } as unknown as MatchStatsService,
@@ -378,9 +631,13 @@ describe('CommunityStatsService', () => {
const backedOff = await service.getMatchDetail({ communityId, matchId });
expect(backedOff).toBe(fallback);
expect(fallback.games[0].analysisAvailability).toBe('available');
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
includeTimeline: true,
});
expect(set).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
fallback,
60,
);
@@ -392,7 +649,7 @@ describe('CommunityStatsService', () => {
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenCalledTimes(1);
expect(setDetail).toHaveBeenCalledWith(
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
recovered,
);
});
@@ -459,7 +716,13 @@ describe('CommunityStatsService', () => {
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
const service = new CommunityStatsService(
{} as ConnectionService,
{
getModel: jest.fn().mockResolvedValue({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as unknown as ConnectionService,
cacheService,
{} as MatchStatsRepository,
{} as MatchStatsService,
@@ -557,6 +820,73 @@ describe('CommunityStatsService', () => {
);
});
it('returns independent recent-20 lane windows and counts from records before pagination', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const records = Array.from({ length: 60 }, (_, index) => ({
...record(matchId),
userId: userId.toString(),
gameNumber: index + 1,
riotMatchId: `KR_${index}`,
gameCreation: index * 1000,
teamPosition: index < 25 ? 'MIDDLE' : 'TOP',
}));
const repository = {
findUserRecordFragments: jest
.fn()
.mockResolvedValue([
{ matchId, builderVersion: MATCH_STATS_BUILDER_VERSION, records },
]),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const cache = {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
} as unknown as CommunityStatsCacheService;
const service = new CommunityStatsService(
{} as ConnectionService,
cache,
repository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: { id: 'all', label: '전체', startedAt: null, endedAt: null },
from: null,
to: null,
});
const mid = await service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 20, lane: 'MIDDLE', includePositionCounts: true },
});
expect(mid.matches).toHaveLength(20);
expect(mid.matches[0].matchId).toBe('KR_24');
expect(mid.matches[19].matchId).toBe('KR_5');
expect(mid.matches[0].damageShare).toBe(30);
expect(mid.positionCounts).toEqual({
ALL: 20,
TOP: 20,
JUNGLE: 0,
MIDDLE: 20,
BOTTOM: 0,
UTILITY: 0,
});
expect(repository.findUserRecordFragments).toHaveBeenCalledWith(
expect.objectContaining({ limit: 0 }),
);
const all = await service.getUserInternalHistory({
communityId,
userId,
filters: { limit: 20, includePositionCounts: true },
});
expect(all.matches.every((game) => game.teamPosition === 'TOP')).toBe(true);
expect(all.positionCounts).toEqual(mid.positionCounts);
});
it('coalesces concurrent user internal history cache misses', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
File diff suppressed because it is too large. Load diff
@@ -1,3 +1,12 @@
import type {
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
SeriesProjection,
} from '@lolympus/contracts';
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
@@ -13,17 +22,24 @@ import type {
} from '../match-history/match-history.types';
export interface CommunityStatsFilters {
includePositionCounts?: boolean;
seasonId?: string;
from?: string;
to?: string;
championId?: number;
cursor?: number;
limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
cursorMatchId?: string;
lane?: RiotLane;
}
export interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
nextCursorMatchId?: string;
season: HistorySeasonDto;
}
@@ -34,6 +50,9 @@ export interface InternalMatchCardView {
status: 'finished' | 'in-progress';
gameCount: number;
winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
/** Official series only. Historical opponent pairs are not inferred rounds. */
series?: SeriesProjection[];
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
@@ -43,6 +62,9 @@ export interface InternalMatchCardView {
}>;
games: Array<{
gameNumber: number;
seriesId?: string;
ordinal?: number;
analysisAvailability?: GameAnalysisAvailability | 'pending';
riotMatchId: string | null;
blueTeamIndex: number;
redTeamIndex: number;
@@ -52,6 +74,7 @@ export interface InternalMatchCardView {
}>;
teams: Array<{
teamIndex: number;
teamId?: string;
name: string;
members: Array<{
userId: string;
@@ -63,12 +86,15 @@ export interface InternalMatchCardView {
export interface LeaderboardResponse {
rows: LeaderboardRow[];
lane?: RiotLane;
season: HistorySeasonDto;
matchedUserIds?: string[];
}
export interface LeaderboardRow {
userId: string;
summonerName: string;
tagLine?: string;
profileIconId: number;
games: number;
wins: number;
@@ -95,16 +121,25 @@ export interface LeaderHighlight {
summonerName: string;
championId?: number;
matchId?: string;
internalMatchId?: string;
gameNumber?: number;
isSingleGame: boolean;
}
export interface TeamInsightsResponse {
season: HistorySeasonDto;
totals: {
matches: number;
games: number;
analyzedGames: number;
players: number;
};
sideWinRate: {
blue: number;
red: number;
bluePicks: number;
redPicks: number;
confirmed: { sampleSize: number; blue: number; red: number };
};
topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null;
@@ -116,8 +151,14 @@ export interface TeamInsightsResponse {
export interface InternalMatchDetailResponse {
match: InternalMatchCardView;
competition?: InternalMatchCompetition;
games: Array<{
gameNumber: number;
gameId?: GameId;
analysisAvailability?: GameAnalysisAvailability;
gameSlotId?: GameSlotId;
seriesId?: SeriesId;
ordinal?: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
@@ -191,7 +232,9 @@ export interface InternalMatchDetailResponse {
}
export interface UserInternalHistoryResponse {
positionCounts?: Record<string, number>;
season: HistorySeasonDto;
playerStats?: LeaderboardRow | null;
championStats: LeaderboardChampionStats;
summary: {
windowSize: number;
@@ -0,0 +1,378 @@
import { BadRequestException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import type { Server } from 'node:http';
import mongoose from 'mongoose';
import { CommunityStatsService } from './community-stats.service';
import { CommunityStatsController } from './community-stats.controller';
import { ConnectionService } from '../global/database/connection.service';
import { CommunityStatsCacheService } from './community-stats-cache.service';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import {
MATCH_STATS_BUILDER_VERSION,
type InternalRecord,
} from './match-stats.types';
import { presentStatsCard, statsDate } from './internal-stats-presentation';
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const start = Date.parse('2026-06-18T12:00:00Z');
function record(
gameNumber: number,
values: Partial<InternalRecord> = {},
): InternalRecord {
return {
matchId: matchId.toString(),
title: '여름 내전',
scheduledAt: new Date(start),
gameNumber,
riotMatchId: `KR_${gameNumber}`,
gameCreation: start + gameNumber * 1800000,
gameDuration: 1800,
userId: userId.toString(),
summonerName: '선수',
tagLine: 'KR1',
profileIconId: 1,
teamIndex: 1,
side: 'blue',
championId: 1,
teamPosition: 'TOP',
kills: 8,
deaths: 2,
assists: 4,
win: true,
cs: 240,
csPerMin: 8,
gold: 12000,
gpm: 400,
killParticipation: 60,
damageShare: 30,
visionScore: 12,
damageDealtToChampions: 18000,
...values,
} as InternalRecord;
}
function fixture() {
const records = [
record(1),
record(2, {
teamPosition: 'JUNGLE',
championId: 2,
kills: 2,
deaths: 4,
assists: 6,
win: false,
csPerMin: 4,
gpm: 300,
killParticipation: 40,
}),
record(3, { kills: 99 }),
record(3, { userId: new mongoose.Types.ObjectId().toString() }),
];
const fragment = {
matchId,
builderVersion: MATCH_STATS_BUILDER_VERSION,
records,
gameDetails: [1, 2, 3].map((gameNumber) => ({
gameNumber,
gameCreation: start + gameNumber * 1800000,
winnerSide: gameNumber === 2 ? 'red' : 'blue',
rawAvailable: gameNumber !== 3,
})),
};
const cache = new Map<string, unknown>();
const repository = {
findSeasonStats: jest.fn().mockResolvedValue([fragment]),
findUserRecordFragments: jest.fn().mockResolvedValue([fragment]),
findDetailsByMatches: jest.fn().mockResolvedValue([]),
};
const service = new CommunityStatsService(
{
getModel: async () => ({
findById: () => ({
exec: async () => ({
seasons: [
{
id: 'june',
label: '6월',
startedAt: new Date('2026-06-01T00:00:00+09:00'),
endedAt: new Date('2026-06-30T23:59:59.999+09:00'),
},
],
}),
}),
}),
} as unknown as ConnectionService,
{
get: async (key: unknown) => cache.get(JSON.stringify(key)),
set: async (key: unknown, value: unknown) => {
cache.set(JSON.stringify(key), value);
},
} as unknown as CommunityStatsCacheService,
repository as unknown as MatchStatsRepository,
{} as MatchStatsService,
);
jest
.spyOn(
service as unknown as { repairCommunityFragments: () => Promise<number> },
'repairCommunityFragments',
)
.mockResolvedValue(0);
return { service, repository };
}
describe('internal stats API contract', () => {
it('serves the scoped player and leaderboard contracts through the HTTP routes', async () => {
const { service } = fixture();
const module = await Test.createTestingModule({
controllers: [CommunityStatsController],
providers: [{ provide: CommunityStatsService, useValue: service }],
}).compile();
const app = module.createNestApplication();
await app.init();
const server: Server = app.getHttpServer();
try {
const base = `/communities/${communityId.toString()}`;
const leaderboard = await request(server)
.get(`${base}/internal-stats/leaderboard?seasonId=all&lane=TOP`)
.expect(200);
expect(leaderboard.body).toMatchObject({
lane: 'TOP',
rows: [{ games: 1, kda: 6 }],
});
const player = await request(server)
.get(
`${base}/users/${userId.toString()}/internal-history?seasonId=all&lane=JUNGLE`,
)
.expect(200);
expect(player.body).toMatchObject({
playerStats: { games: 1, kda: 2 },
matches: [{ gameNumber: 2 }],
});
await request(server)
.get(`${base}/internal-stats/leaderboard?lane=invalid`)
.expect(400);
await request(server)
.get(`${base}/internal-stats/leaderboard?from=2026-02-30`)
.expect(400);
await request(server)
.get('/communities/invalid/internal-stats/leaderboard')
.expect(400);
} finally {
await app.close();
}
});
it('searches escaped text across title, team and player without losing date or cursor constraints', async () => {
const chain = {
select: jest.fn().mockReturnThis(),
sort: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue([]),
};
const find = jest.fn().mockReturnValue(chain);
const repository = new MatchStatsRepository({
getModel: async () => ({ find }),
} as unknown as ConnectionService);
await repository.findMatchPage({
communityId,
query: '팀.*',
from: start,
cursor: start + 1000,
cursorMatchId: matchId.toString(),
limit: 4,
});
expect(find).toHaveBeenCalledWith(
expect.objectContaining({
communityId,
$and: expect.arrayContaining([
{
$or: [
'matchCard.title',
'matchCard.teams.name',
'matchCard.teams.members.summonerName',
].map((field) => ({
[field]: { $regex: '팀\\.\\*', $options: 'i' },
})),
},
]),
}),
);
expect(chain.limit).toHaveBeenCalledWith(4);
expect(chain.select).toHaveBeenCalledWith(
expect.objectContaining({ 'gameDetails.rawAvailable': 1 }),
);
});
it('recalculates every metric per lane, isolates cached scopes and excludes missing raw data', async () => {
const { service } = fixture();
const all = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all' },
});
const top = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all', lane: 'TOP' },
});
const jungle = await service.getLeaderboard({
communityId,
filters: { seasonId: 'all', lane: 'JUNGLE' },
});
expect(all.rows).toHaveLength(1);
expect(all.rows[0]).toMatchObject({
games: 2,
totalKills: 10,
winRate: 50,
avgGoldPerMin: 350,
avgCsPerMin: 6,
avgKillParticipation: 50,
});
expect(top).toMatchObject({
lane: 'TOP',
rows: [
{
games: 1,
kda: 6,
winRate: 100,
avgGoldPerMin: 400,
avgCsPerMin: 8,
avgKillParticipation: 60,
},
],
});
expect(jungle).toMatchObject({
lane: 'JUNGLE',
rows: [{ games: 1, kda: 2, winRate: 0, avgGoldPerMin: 300 }],
});
expect(
await service.getLeaderboard({
communityId,
filters: { seasonId: 'all' },
}),
).toEqual(all);
const insight = await service.getTeamInsights({
communityId,
filters: { seasonId: 'all' },
});
expect(insight.totals).toEqual({
matches: 1,
games: 3,
analyzedGames: 2,
players: 2,
});
expect(insight.topTeamGpm).toMatchObject({
internalMatchId: matchId.toString(),
gameNumber: 1,
metric: 400,
});
});
it('keeps player summary and matches in the same scope while retaining champion choices', async () => {
const { service } = fixture();
const history = await service.getUserInternalHistory({
communityId,
userId,
filters: { seasonId: 'all', championId: 1 },
});
expect(history.playerStats).toMatchObject({ games: 1, kda: 6 });
expect(history.matches).toHaveLength(1);
expect(history.matches[0]).toMatchObject({
internalMatchId: matchId.toString(),
internalMatchTitle: '여름 내전',
gameNumber: 1,
});
expect(history.championStats.champions).toHaveLength(2);
});
it('intersects custom dates with the season and accepts inclusive KST calendar dates', async () => {
const { service, repository } = fixture();
await service.getLeaderboard({
communityId,
filters: { seasonId: 'june', from: '2026-05-01', to: '2026-07-31' },
});
expect(repository.findSeasonStats).toHaveBeenCalledWith({
communityId,
from: Date.parse('2026-05-31T15:00:00Z'),
to: Date.parse('2026-06-30T14:59:59.999Z'),
});
expect(statsDate('2026-06-18', false)?.toISOString()).toBe(
'2026-06-17T15:00:00.000Z',
);
expect(statsDate('2026-06-18', true)?.toISOString()).toBe(
'2026-06-18T14:59:59.999Z',
);
await expect(
service.getLeaderboard({ communityId, filters: { from: '2026-02-30' } }),
).rejects.toBeInstanceOf(BadRequestException);
await expect(
service.getLeaderboard({
communityId,
filters: { from: '2026-06-20', to: '2026-06-19' },
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('rejects unsupported lanes at the HTTP controller boundary', () => {
const controller = new CommunityStatsController(
{} as CommunityStatsService,
);
expect(() =>
(
controller as unknown as {
toFilters: (params: { lane: string }) => unknown;
}
).toFilters({ lane: 'SUPPORT' }),
).toThrow(BadRequestException);
});
it('uses official evidence to distinguish rematches and does not invent round identities', () => {
type Card = Parameters<typeof presentStatsCard>[0];
type Competition = NonNullable<Parameters<typeof presentStatsCard>[1]>;
const card = {
games: [
{ gameNumber: 1, riotMatchId: 'KR_1' },
{ gameNumber: 2, riotMatchId: 'KR_2' },
{ gameNumber: 3, riotMatchId: 'old' },
],
teams: [{ teamIndex: 1 }],
} as Card;
const competition = {
teams: [{ displayOrder: 1, teamId: 'a' }],
projection: {
games: [
{
displayNumber: 1,
ordinal: 1,
seriesId: 'upper',
evidence: { type: 'riot', riotMatchId: 'KR_1' },
},
{
displayNumber: 2,
ordinal: 1,
seriesId: 'final',
evidence: { type: 'riot', riotMatchId: 'KR_2' },
},
{
displayNumber: 3,
ordinal: 2,
seriesId: 'final',
evidence: { type: 'riot', riotMatchId: 'replacement' },
},
],
series: [
{ seriesId: 'upper' },
{ seriesId: 'final' },
{ seriesId: 'other', status: 'scheduled' },
],
},
} as unknown as Competition;
const result = presentStatsCard(card, competition);
expect(result.games.map((game) => game.seriesId)).toEqual([
'upper',
'final',
undefined,
]);
expect(result.series?.map((series) => series.seriesId)).toEqual([
'upper',
'final',
]);
expect(result.teams[0].teamId).toBe('a');
});
});
@@ -0,0 +1,59 @@
import type { InternalMatchCompetition } from '@lolympus/contracts';
import type { InternalMatchCardView } from './community-stats.types';
/** Attach official identities without merging rematches between the same teams. */
export function presentStatsCard(
card: InternalMatchCardView,
competition?: Pick<InternalMatchCompetition, 'teams' | 'projection'>,
): InternalMatchCardView {
if (!competition) return card;
const officialGames = competition.projection.games ?? [];
const games = card.games.map((game) => {
const official = officialGames.find(
(candidate) =>
candidate.displayNumber === game.gameNumber &&
(candidate.evidence.type === 'riot'
? candidate.evidence.riotMatchId
: candidate.evidence.legacyReference) === game.riotMatchId,
);
return official
? { ...game, seriesId: official.seriesId, ordinal: official.ordinal }
: game;
});
const visible = new Set(games.map((game) => game.seriesId));
return {
...card,
games,
teams: card.teams?.map((team) => ({
...team,
teamId: competition.teams.find((t) => t.displayOrder === team.teamIndex)
?.teamId,
})),
series: (competition.projection.series ?? []).filter(
(series) =>
visible.has(series.seriesId) ||
(series.status === 'completed' && series.outcome.type !== 'played'),
),
};
}
/** Date-only inputs are inclusive Korean calendar days; ISO timestamps remain supported. */
export function statsDate(
value: string | undefined,
end: boolean,
): Date | null {
if (!value) return null;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
const date = new Date(
`${value}T${end ? '23:59:59.999' : '00:00:00.000'}+09:00`,
);
const midnight = new Date(`${value}T00:00:00.000Z`);
if (
!Number.isFinite(midnight.getTime()) ||
midnight.toISOString().slice(0, 10) !== value
)
return new Date(NaN);
return date;
}
return new Date(value);
}
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { readMultiKills } from '../riot/riot-multi-kill';
import mongoose from 'mongoose';
import type {
MatchDocument,
@@ -183,6 +184,7 @@ export class MatchStatsFragmentBuilder {
winnerSide: game.winnerSide,
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
timelineLoaded: Boolean(usableTimeline),
rawAvailable: true,
objectiveEvents,
timelineEvents,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
@@ -253,6 +255,7 @@ export class MatchStatsFragmentBuilder {
winnerSide: game.winnerSide,
timeline: [],
timelineLoaded: false,
rawAvailable: false,
objectiveEvents: [],
timelineEvents: [],
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
@@ -349,6 +352,8 @@ export class MatchStatsFragmentBuilder {
rawParticipant?.individualPosition ||
'',
kills: participant.kills,
multiKills: readMultiKills(rawParticipant),
tier: snapshot?.tier,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
@@ -5,8 +5,12 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick<
MatchStats,
'matchId' | 'records'
>;
'matchId' | 'records' | 'builderVersion'
> & {
gameDetails?: Array<
Pick<MatchStats['gameDetails'][number], 'gameNumber' | 'rawAvailable'>
>;
};
export type MatchStatsDetailFragment = Pick<
MatchStats,
@@ -152,6 +156,119 @@ export class MatchStatsRepository {
return MatchStatsModel.findOne({ matchId }).exec();
}
public async findByRiotMatchIds(riotMatchIds: string[]) {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.find({
'gameDetails.riotMatchId': { $in: riotMatchIds },
})
.select({
matchId: 1,
communityId: 1,
'gameDetails.riotMatchId': 1,
'gameDetails.rawAvailable': 1,
})
.lean()
.exec();
}
public async findMatchPage(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
championId?: number;
cursor?: number;
cursorMatchId?: string;
limit: number;
}) {
const model = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = { communityId: params.communityId };
const conditions: Array<Record<string, unknown>> = [];
const gameCreation = {
...(params.from === undefined ? {} : { $gte: params.from }),
...(params.to === undefined ? {} : { $lte: params.to }),
};
if (Object.keys(gameCreation).length > 0) {
conditions.push({
$or: [
{ gameDetails: { $elemMatch: { gameCreation } } },
{
'gameDetails.0': { $exists: false },
gameCreationMin: gameCreation,
},
],
});
}
if (params.from !== undefined)
filter.gameCreationMax = { $gte: params.from };
if (params.to !== undefined) filter.gameCreationMin = { $lte: params.to };
if (params.championId) {
filter.records = {
$elemMatch: {
championId: params.championId,
...(Object.keys(gameCreation).length > 0 ? { gameCreation } : {}),
},
};
}
if (params.query) {
const search = {
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
$options: 'i',
};
conditions.push({
$or: [
{ 'matchCard.title': search },
{ 'matchCard.teams.name': search },
{ 'matchCard.teams.members.summonerName': search },
],
});
}
if (params.format) {
filter['matchCard.teams.1'] = { $exists: true };
filter['matchCard.teams.2'] = { $exists: params.format === 'tournament' };
}
if (params.playerId) {
filter['matchCard.teams.members.userId'] = params.playerId;
}
if (params.cursor !== undefined) {
const cursor = new Date(params.cursor);
if (params.cursorMatchId) {
conditions.push({
$or: [
{ scheduledAt: { $lt: cursor } },
{
scheduledAt: cursor,
matchId: {
$lt: new mongoose.Types.ObjectId(params.cursorMatchId),
},
},
],
});
} else {
filter.scheduledAt = { $lt: cursor };
}
}
if (conditions.length > 0) filter.$and = conditions;
return model
.find(filter)
.select({
matchId: 1,
scheduledAt: 1,
matchCard: 1,
sourceCompetitionId: 1,
sourceRevision: 1,
'gameDetails.gameNumber': 1,
'gameDetails.gameCreation': 1,
'gameDetails.rawAvailable': 1,
})
.sort({ scheduledAt: -1, matchId: -1 })
.limit(params.limit)
.lean()
.exec();
}
public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId;
fromGameCreation?: number;
@@ -175,6 +292,54 @@ export class MatchStatsRepository {
.exec();
}
public async findSeasonStats(params: {
communityId: mongoose.Types.ObjectId;
from?: number;
to?: number;
}) {
const model = await this.connectionService.getModel('matchStats');
return model
.find({
communityId: params.communityId,
...(params.from === undefined
? {}
: { gameCreationMax: { $gte: params.from } }),
...(params.to === undefined
? {}
: { gameCreationMin: { $lte: params.to } }),
})
.select({
_id: 0,
matchId: 1,
scheduledAt: 1,
'records.userId': 1,
'records.summonerName': 1,
'records.tagLine': 1,
'records.profileIconId': 1,
'records.gameCreation': 1,
'records.gameNumber': 1,
'records.matchId': 1,
'records.championId': 1,
'records.teamPosition': 1,
'records.win': 1,
'records.kills': 1,
'records.deaths': 1,
'records.assists': 1,
'records.gpm': 1,
'records.csPerMin': 1,
'records.killParticipation': 1,
'records.visionScore': 1,
'records.damageShare': 1,
'gameDetails.gameCreation': 1,
'gameDetails.gameNumber': 1,
'gameDetails.winnerSide': 1,
'gameDetails.rawAvailable': 1,
})
.sort({ scheduledAt: -1 })
.lean()
.exec();
}
public async findByUser(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
@@ -202,7 +367,14 @@ export class MatchStatsRepository {
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.select({ _id: 0, matchId: 1, records: 1 })
.select({
_id: 0,
matchId: 1,
records: 1,
builderVersion: 1,
'gameDetails.gameNumber': 1,
'gameDetails.rawAvailable': 1,
})
.lean<MatchStatsUserRecordFragment[]>()
.exec();
}
@@ -47,7 +47,7 @@ export class MatchStatsService {
? competitionStatsSource(match, competition)
: undefined;
const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) {
if (!this.isEligible(sourceMatch) && competition?.phase !== 'completed') {
if (competitionSource) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: competitionSource.sourceCompetitionId,
@@ -4,7 +4,7 @@ import type {
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 10;
export const MATCH_STATS_BUILDER_VERSION = 11;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
@@ -5,6 +5,7 @@ import {
CompetitionBootstrapService,
type CompetitionBootstrapMatch,
} from './competition-bootstrap.service';
import type { SeriesDefinition } from './domain/series-graph';
describe('CompetitionBootstrapService', () => {
it('creates a deterministic paired-Series Competition and immutable snapshots', async () => {
@@ -210,6 +211,40 @@ describe('CompetitionBootstrapService', () => {
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('gives a configured BO3 grand final three slots without changing the other stage rules', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(harness.connectionService);
const match = matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 5,
});
match.doubleElimination = {
teamCount: 4,
resetFinalEnabled: true,
grandFinalGameCount: 3,
seeds: [1, 2, 3, 4].map((teamIndex) => ({
seedNumber: teamIndex,
teamIndex,
})),
};
await service.bootstrap(match);
const { format, seriesGraph } = harness.insertedPayloads[0];
expect(format).toMatchObject({
rules: {
upper: { maxGames: 5, winsRequired: 3 },
lower: { maxGames: 1, winsRequired: 1 },
grandFinal: { maxGames: 3, winsRequired: 2 },
resetFinal: { maxGames: 1, winsRequired: 1 },
},
});
expect(
seriesGraph.find(({ code }) => code === 'GF')?.gameSlots,
).toHaveLength(3);
});
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
@@ -451,7 +486,7 @@ interface InsertPayload {
legacyTeamIndex: number;
seedNumber: number;
}>;
seriesGraph: Array<{ code?: string; rule: unknown }>;
seriesGraph: SeriesDefinition[];
[key: string]: any;
}
@@ -41,6 +41,7 @@ export interface CompetitionBootstrapMatch {
doubleElimination?: {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
seeds: Array<{ seedNumber: number; teamIndex: number }>;
};
}
@@ -514,6 +515,8 @@ function mapMatchFormat(
winsRequired: 1,
maxGames: 1,
};
const grandFinalGameCount =
match.doubleElimination?.grandFinalGameCount ?? 1;
return {
type: 'double-elimination',
teamCount: teams.length,
@@ -525,7 +528,11 @@ function mapMatchFormat(
maxGames: match.gameCount,
},
lower: { ...bestOfOne },
grandFinal: { ...bestOfOne },
grandFinal: {
type: 'first-to',
winsRequired: Math.floor(grandFinalGameCount / 2) + 1,
maxGames: grandFinalGameCount,
},
resetFinal: { ...bestOfOne },
},
};
@@ -821,7 +821,7 @@ function buildOutbox(
};
}
function factForProjection(
export function factForProjection(
fact: Readonly<Record<string, unknown>>,
): Readonly<Record<string, unknown>> {
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
@@ -13,6 +13,7 @@ export const COMPETITION_FACT_TYPES = [
'game-voided',
'series-adjudicated',
'adjudication-reversed',
'grand-final-rule-corrected',
] as const;
export type CompetitionFactType = (typeof COMPETITION_FACT_TYPES)[number];
@@ -200,6 +201,7 @@ export interface CompetitionFact {
adjudicationFactId?: mongoose.Types.ObjectId;
decision?: Record<string, unknown>;
reason?: string;
ruleCorrection?: { previousMaxGames: 1; nextMaxGames: 3 };
createdAt: Date;
updatedAt: Date;
}
@@ -339,6 +341,7 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
adjudicationFactId: { type: Schema.Types.ObjectId },
decision: { type: Schema.Types.Mixed },
reason: { type: String },
ruleCorrection: { type: Schema.Types.Mixed },
},
{ timestamps: true, collection: 'competition_fact' },
);
@@ -131,7 +131,12 @@ export interface CompetitionProjection {
export function projectCompetition(
input: ProjectCompetitionInput,
): CompetitionProjection {
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
// The repair commits the corrected graph and its audit fact together. The
// audit fact occupies a revision but is not a game or adjudication.
const resultFacts = input.facts.filter(
(fact) => !isRecord(fact) || fact.type !== 'grand-final-rule-corrected',
);
assertPrimaryFactTargetsGraph(input.seriesGraph, resultFacts);
const teamBySeed = new Map<number, string>();
const knownTeams = new Set<string>();
for (const team of input.teams) {
@@ -169,7 +174,7 @@ export function projectCompetition(
teamBySeed,
projectedById,
),
facts: input.facts,
facts: resultFacts,
active: false,
}),
);
@@ -188,7 +193,7 @@ export function projectCompetition(
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
facts: resultFacts,
}),
);
remaining.delete(seriesId);
@@ -211,7 +216,7 @@ export function projectCompetition(
projectSeries({
definition: asProjectorDefinition(definition),
participants,
facts: input.facts,
facts: resultFacts,
...(definition.activation ? { active: false } : {}),
}),
);
@@ -221,7 +226,7 @@ export function projectCompetition(
const gameProjection = projectGamesAndSlots(
input.seriesGraph,
series,
input.facts,
resultFacts,
);
const common = {
competitionId: input.competitionId,
@@ -88,6 +88,7 @@ export interface DoubleEliminationEvent {
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
@@ -98,6 +99,7 @@ export interface DoubleEliminationBracket {
export interface BuildDoubleEliminationBracketOptions {
resetFinalEnabled: boolean;
winnerBracketGameCount?: number;
grandFinalGameCount?: 1 | 3 | 5;
}
export interface DoubleEliminationSeriesRule {
@@ -146,6 +148,9 @@ export function buildDoubleEliminationBracket(
const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length,
resetFinalEnabled: options.resetFinalEnabled,
...(options.grandFinalGameCount === undefined
? {}
: { grandFinalGameCount: options.grandFinalGameCount }),
resetFinalCreated: false,
seeds,
bracketMatches:
@@ -171,11 +176,17 @@ export function resolveDoubleEliminationSeriesRule(
bracketMatchId: string;
roundNumber: number;
},
options: { winnerBracketGameCount?: number } = {},
options: Pick<
BuildDoubleEliminationBracketOptions,
'winnerBracketGameCount' | 'grandFinalGameCount'
> = {},
): DoubleEliminationSeriesRule {
if (params.bracketSide === 'winner') {
return seriesRule(options.winnerBracketGameCount ?? 3);
}
if (params.bracketSide === 'grand-final') {
return seriesRule(options.grandFinalGameCount ?? 1);
}
return seriesRule(1);
}
@@ -431,6 +442,7 @@ function rebuildWithSeeds(
): DoubleEliminationBracket {
const next = buildDoubleEliminationBracket(teamIndexes, {
resetFinalEnabled: bracket.resetFinalEnabled,
grandFinalGameCount: bracket.grandFinalGameCount,
});
next.events = [
...bracket.events,
@@ -7,6 +7,7 @@ import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import type {
Community,
MatchGameResult,
MatchParticipant,
MatchSeriesResult,
@@ -250,16 +251,17 @@ async function main() {
);
}
const match = await MatchModel.create(payload);
console.log(`[temp result seed] created=${match._id.toString()}`);
console.log(`[temp result seed] route=/match/${match._id.toString()}`);
const matchId = new mongoose.Types.ObjectId();
await MatchModel.create({ ...payload, _id: matchId });
console.log(`[temp result seed] created=${matchId.toString()}`);
console.log(`[temp result seed] route=/match/${matchId.toString()}`);
} finally {
await app.close();
}
}
async function resolveCommunity(
CommunityModel: mongoose.Model<unknown>,
CommunityModel: mongoose.Model<Community>,
communityId?: string,
): Promise<CommunityLean> {
const community = communityId
@@ -316,11 +318,11 @@ function buildMatchPayload(
description:
'결과 페이지 검증용으로 생성된 30명, 6팀, 15경기 완료 임시 데이터입니다.',
mapId: 11,
status: 'finished',
status: 'finished' as const,
scheduledAt: options.scheduledAt,
maxParticipants: TOTAL_PLAYERS,
gameCount: GAME_COUNT_PER_SERIES_GROUP,
gameMode: 'round-robin',
gameMode: 'round-robin' as const,
tournamentCodeIds: [],
teamBuiltAt: new Date(options.scheduledAt.getTime() - 30 * 60000),
participants,
@@ -335,10 +337,10 @@ function buildMatchPayload(
resultPollState: {
startedAt: new Date(options.scheduledAt.getTime() + 2 * 60 * 60 * 1000),
lastPolledAt: now,
lastPollOutcome: 'matched',
lastPollOutcome: 'matched' as const,
matchedCount: games.length,
expandedToAllPuuids: true,
state: 'complete',
state: 'complete' as const,
},
legacyImported: true,
legacyImportSource: {
@@ -0,0 +1,4 @@
export const MATCH_STATS_RIOT_MATCH_INDEX = {
key: { 'gameDetails.riotMatchId': 1 as const },
options: { name: 'gameDetails.riotMatchId_1' },
};
@@ -0,0 +1,47 @@
import type { mongo } from 'mongoose';
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
import { parseMatchStatsIndexOptions } from './run-match-stats-raw-index';
it('defaults to a read-only plan and validates the target environment', async () => {
expect(parseMatchStatsIndexOptions(['--env', 'prod']).dryRun).toBe(true);
expect(() => parseMatchStatsIndexOptions(['--env', 'unknown'])).toThrow();
const createIndex = jest.fn();
await migrateMatchStatsRawIndex(database([], createIndex));
expect(createIndex).not.toHaveBeenCalled();
});
it('adds only the lookup index and accepts an identical existing index', async () => {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const createIndex = jest.fn();
const result = await migrateMatchStatsRawIndex(
database([{ key, ...options }], createIndex),
{ dryRun: false },
);
expect(result.alreadyPresent).toBe(true);
expect(createIndex).toHaveBeenCalledWith(key, options);
});
it('rejects an incompatible existing index without dropping or recreating it', async () => {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const createIndex = jest.fn();
await expect(
migrateMatchStatsRawIndex(
database([{ key, ...options, unique: true }], createIndex),
{ dryRun: false },
),
).rejects.toThrow('different definition');
expect(createIndex).not.toHaveBeenCalled();
});
function database(indexes: unknown[], createIndex: jest.Mock): mongo.Db {
return {
collection: (name: string) => {
expect(name).toBe('match_stats');
return {
listIndexes: () => ({ toArray: async () => indexes }),
createIndex,
};
},
} as unknown as mongo.Db;
}
@@ -0,0 +1,38 @@
import type { mongo } from 'mongoose';
import { MATCH_STATS_RIOT_MATCH_INDEX } from '../match-stats-raw-index';
/** Adds the lookup index without dropping indexes or modifying game records. */
export async function migrateMatchStatsRawIndex(
db: mongo.Db,
{ dryRun = true }: { dryRun?: boolean } = {},
) {
const { key, options } = MATCH_STATS_RIOT_MATCH_INDEX;
const collection = db.collection('match_stats');
const indexes = await collection
.listIndexes()
.toArray()
.catch((error: unknown) => {
if (error instanceof Error && 'code' in error && error.code === 26)
return [];
throw error;
});
const existing = indexes.find((index) => index.name === options.name);
if (
existing &&
(JSON.stringify(existing.key) !== JSON.stringify(key) ||
existing.unique === true ||
existing.sparse === true ||
existing.hidden === true ||
existing.partialFilterExpression !== undefined)
) {
throw new Error(
`Index ${options.name} already exists with a different definition.`,
);
}
if (!dryRun) await collection.createIndex(key, options);
return {
dryRun,
alreadyPresent: Boolean(existing),
index: { key, ...options },
};
}
@@ -0,0 +1,293 @@
import mongoose from 'mongoose';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import { generateSeriesGraph } from '../../../competition/domain/series-graph';
import {
parseGrandFinalRepairOptions,
planGrandFinalBo3Repair,
repairGrandFinalBo3,
} from './repair-grand-final-bo3';
describe('grand final BO3 repair', () => {
it.each([false, true])(
'keeps game 28 and finishes only after two wins (split: %s)',
(split) => {
const input = finishedTournament();
const plan = planGrandFinalBo3Repair(input);
expect(plan.before.phase).toBe('completed');
expect(plan.preservedGame).toBe(28);
expect(plan.newGameNumbers).toEqual([29, 30]);
expect(plan.projection.games).toEqual(plan.before.games);
expect(plan.projection).toMatchObject({
phase: 'running',
placements: [],
});
expect(plan.projection).not.toHaveProperty('outcome');
expect(
plan.projection.series.find(
({ seriesId }) => seriesId === plan.seriesId,
),
).toMatchObject({
status: 'in-progress',
entries: [
{ slot: 'A', gameWins: 1 },
{ slot: 'B', gameWins: 0 },
],
});
const facts = [
...input.facts,
{
id: 'rule-audit',
type: 'grand-final-rule-corrected',
seriesId: plan.seriesId,
revision: plan.projection.sourceRevision,
ordinalWithinRevision: 1,
},
];
const replay = () =>
projectCompetition({
...input,
facts,
revision: facts.length,
format: plan.format,
seriesGraph: plan.seriesGraph,
});
expect(replay()).toEqual(plan.projection);
const second = replay().gameSlots.find(
({ displayNumber }) => displayNumber === 29,
)!;
facts.push(acceptedGame(second, facts.length + 1, split ? 'B' : 'A'));
if (split) {
expect(replay().phase).toBe('running');
const third = replay().gameSlots.find(
({ displayNumber }) => displayNumber === 30,
)!;
expect(third.status).toBe('ready');
facts.push(acceptedGame(third, facts.length + 1, 'A'));
}
const completed = replay();
expect(completed.phase).toBe('completed');
expect(
completed.gameSlots.find(({ displayNumber }) => displayNumber === 30)
?.status,
).toBe(split ? 'completed' : 'inactive');
expect(completed.games.at(-1)?.displayNumber).toBe(split ? 30 : 29);
},
);
it('refuses to reopen a bracket that enables a reset final', () => {
const input = finishedTournament();
expect(() =>
planGrandFinalBo3Repair({
...input,
format: { ...input.format, resetFinalEnabled: true },
}),
).toThrow('no reset or later series');
});
it('requires a target and a reviewed revision before applying', () => {
const target = ['--match-id', '000000000000000000000001', '--env', 'prod'];
expect(parseGrandFinalRepairOptions(target)).toMatchObject({
apply: false,
});
expect(() => parseGrandFinalRepairOptions(['--apply', ...target])).toThrow(
'--expected-revision',
);
expect(
parseGrandFinalRepairOptions([
'--apply',
...target,
'--expected-revision',
'23',
]),
).toMatchObject({ apply: true, expectedRevision: 23 });
});
it('previews without writes and applies the graph, match status and audit in one transaction', async () => {
const input = finishedTournament();
const competitionId = new mongoose.Types.ObjectId(input.competitionId);
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
competitionId,
communityId,
gameMode: 'double-elimination',
status: 'finished',
teamBuiltAt: new Date(),
doubleElimination: { resetFinalEnabled: false },
resultPollState: { state: 'complete' },
};
const competition = {
...input,
_id: competitionId,
schemaVersion: 1,
phase: 'completed',
teams: input.teams.map((team) => ({
...team,
teamId: new mongoose.Types.ObjectId(team.teamId),
})),
projection: projectCompetition(input),
};
const query = (value: unknown) => ({
session: jest.fn().mockReturnThis(),
lean: jest.fn().mockReturnThis(),
sort: jest.fn().mockReturnThis(),
exec: jest.fn().mockResolvedValue(value),
});
const update = () => jest.fn(() => query({ matchedCount: 1 }));
const models = {
match: { findById: jest.fn(() => query(match)), updateOne: update() },
competition: {
findOne: jest.fn(() => query(competition)),
updateOne: update(),
},
competitionFact: {
find: jest.fn(() => query(input.facts)),
insertMany: jest.fn(),
},
competitionOutbox: { insertMany: jest.fn() },
};
const session = {
withTransaction: jest.fn((run: () => unknown) => run()),
endSession: jest.fn(),
};
const connections = {
getModel: jest.fn((name: keyof typeof models) => models[name]),
createSession: jest.fn().mockResolvedValue(session),
} as never;
const options = { matchId, nodeEnv: 'prod', apply: false };
const preview = await repairGrandFinalBo3(connections, options);
expect(preview).toMatchObject({
mode: 'dry-run',
preservedGame: 28,
newGameNumbers: [29, 30],
});
expect(models.match.updateOne).not.toHaveBeenCalled();
expect(models.competition.updateOne).not.toHaveBeenCalled();
expect(models.competitionFact.insertMany).not.toHaveBeenCalled();
expect(models.competitionOutbox.insertMany).not.toHaveBeenCalled();
await expect(
repairGrandFinalBo3(connections, {
...options,
apply: true,
expectedRevision: preview.revisionBefore,
}),
).resolves.toMatchObject({
mode: 'applied',
phase: 'completed -> running',
});
expect(session.withTransaction).toHaveBeenCalledTimes(1);
expect(models.match.updateOne).toHaveBeenCalledWith(
{ _id: matchId, status: 'finished', competitionId },
{
$set: expect.objectContaining({
status: 'in-progress',
'resultPollState.state': 'polling',
}),
},
{ session, runValidators: true },
);
expect(models.competition.updateOne).toHaveBeenCalledWith(
{ _id: competitionId, revision: preview.revisionBefore },
{
$set: expect.objectContaining({
phase: 'running',
revision: preview.revisionAfter,
}),
},
{ session, runValidators: true },
);
expect(models.competitionFact.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'grand-final-rule-corrected',
revision: preview.revisionAfter,
}),
],
{ session },
);
expect(models.competitionOutbox.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'competition.projection-updated',
revision: preview.revisionAfter,
}),
],
{ session },
);
});
});
function finishedTournament() {
const competitionId = '000000000000000000000001';
const teams = Array.from({ length: 8 }, (_, index) => ({
teamId: (index + 1).toString(16).padStart(24, '0'),
displayOrder: index + 1,
seedNumber: index + 1,
}));
const bo1 = { type: 'first-to', maxGames: 1, winsRequired: 1 } as const;
const format = {
type: 'double-elimination' as const,
teamCount: 8 as const,
resetFinalEnabled: false,
rules: {
upper: { ...bo1, maxGames: 3, winsRequired: 2 },
lower: bo1,
grandFinal: bo1,
resetFinal: bo1,
},
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const facts: Record<string, unknown>[] = [];
const input = {
competitionId,
teams,
format,
seriesGraph,
facts,
projectorVersion: 1,
revision: 0,
};
for (let index = 0; index < 28; index += 1) {
const slot = projectCompetition(input).gameSlots.find(
({ status }) => status === 'ready',
);
if (!slot) break;
facts.push(acceptedGame(slot, index + 1, 'A'));
input.revision += 1;
}
return input;
}
function acceptedGame(
slot: ReturnType<typeof projectCompetition>['gameSlots'][number],
revision: number,
winner: 'A' | 'B',
): Record<string, unknown> {
const [a, b] = slot.entries;
const recordedAt = new Date(Date.UTC(2026, 6, 26, 0, revision)).toISOString();
return {
id: `fact-${revision}`,
type: 'game-accepted',
revision,
ordinalWithinRevision: 1,
gameId: `game-${revision}`,
seriesId: slot.seriesId,
gameSlotId: slot.id,
ordinal: slot.ordinal,
recordedAt,
occurredAt: recordedAt,
evidence: { type: 'riot', riotMatchId: `KR_${revision}` },
mapping: {
blueTeamId: a.teamId,
redTeamId: b.teamId,
winnerTeamId: winner === 'A' ? a.teamId : b.teamId,
participantAssignments: [],
},
};
}
@@ -0,0 +1,410 @@
import 'reflect-metadata';
import { ConfigService } from '@nestjs/config';
import mongoose from 'mongoose';
import { createHash } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { factForProjection } from '../../../competition/competition-command.service';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import {
generateSeriesGraph,
type CompetitionGraphFormat,
type CompetitionGraphTeam,
type SeriesDefinition,
} from '../../../competition/domain/series-graph';
import { SecretService } from '../../secret/secret.service';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
const CORRECTION_TYPE = 'grand-final-rule-corrected' as const;
const BO3 = { type: 'first-to', winsRequired: 2, maxGames: 3 } as const;
interface RepairInput {
competitionId: string;
revision: number;
projectorVersion: number;
teams: readonly CompetitionGraphTeam[];
format: CompetitionGraphFormat;
seriesGraph: readonly SeriesDefinition[];
facts: readonly Record<string, unknown>[];
}
export function planGrandFinalBo3Repair(input: RepairInput) {
const { format, seriesGraph, facts } = input;
const final = seriesGraph.find(({ stage }) => stage.type === 'grand-final');
if (
format.type !== 'double-elimination' ||
format.resetFinalEnabled ||
format.rules.grandFinal.type !== 'first-to' ||
format.rules.grandFinal.maxGames !== 1 ||
format.rules.grandFinal.winsRequired !== 1 ||
!final ||
!isDeepStrictEqual(final.rule, format.rules.grandFinal) ||
final.gameSlots.length !== 1 ||
seriesGraph.some(
({ stage }) => stage.displayOrder > final.stage.displayOrder,
)
) {
throw new Error(
'Expected a BO1 grand final with no reset or later series.',
);
}
const before = projectCompetition(input);
const previousFinal = before.series.find(
({ seriesId }) => seriesId === final.id,
);
const finalGames = before.games.filter(
({ seriesId }) => seriesId === final.id,
);
const firstGame = finalGames[0];
if (
before.phase !== 'completed' ||
previousFinal?.status !== 'completed' ||
previousFinal.outcome.type !== 'played' ||
finalGames.length !== 1 ||
firstGame.ordinal !== 1 ||
firstGame.evidence.type !== 'riot' ||
facts.filter((fact) => fact.seriesId === final.id).length !== 1
) {
throw new Error(
'Expected exactly one Riot result and no other final facts.',
);
}
const correctedFormat = {
...format,
rules: { ...format.rules, grandFinal: BO3 },
};
const generatedFinal = generateSeriesGraph({
competitionId: input.competitionId,
teams: input.teams,
format: correctedFormat,
}).find(({ stage }) => stage.type === 'grand-final');
if (
generatedFinal?.id !== final.id ||
!isDeepStrictEqual(generatedFinal.gameSlots[0], final.gameSlots[0])
) {
throw new Error(
'The existing grand final does not match its stable slot identity.',
);
}
const correctedGraph = seriesGraph.map((series) =>
series.id === final.id
? { ...series, rule: BO3, gameSlots: generatedFinal.gameSlots }
: series,
);
const projection = projectCompetition({
...input,
revision: input.revision + 1,
format: correctedFormat,
seriesGraph: correctedGraph,
});
const readySlots = projection.gameSlots.filter(
({ status }) => status === 'ready',
);
if (
projection.phase !== 'running' ||
!isDeepStrictEqual(projection.games, before.games) ||
readySlots.length !== 2 ||
readySlots.some(
(slot, index) =>
slot.seriesId !== final.id ||
slot.ordinal !== index + 2 ||
slot.displayNumber !== firstGame.displayNumber + index + 1,
) ||
!isDeepStrictEqual(
projection.series.filter(({ seriesId }) => seriesId !== final.id),
before.series.filter(({ seriesId }) => seriesId !== final.id),
)
) {
throw new Error(
'Repair would change existing results or fail to reopen the final.',
);
}
return {
before,
format: correctedFormat,
seriesGraph: correctedGraph,
projection,
seriesId: final.id,
preservedGame: firstGame.displayNumber,
newGameNumbers: readySlots.map(({ displayNumber }) => displayNumber),
};
}
interface CliOptions {
matchId: mongoose.Types.ObjectId;
nodeEnv: string;
expectedRevision?: number;
apply: boolean;
}
export function parseGrandFinalRepairOptions(argv: string[]): CliOptions {
let matchId: mongoose.Types.ObjectId | undefined;
let nodeEnv = 'dev';
let expectedRevision: number | undefined;
let apply = false;
for (let index = 0; index < argv.length; index += 1) {
switch (argv[index]) {
case '--':
break;
case '--apply':
apply = true;
break;
case '--match-id': {
const value = argv[++index];
if (!/^[a-f\d]{24}$/i.test(value ?? '')) {
throw new Error('--match-id must be a 24-character ObjectId.');
}
matchId = new mongoose.Types.ObjectId(value);
break;
}
case '--env':
nodeEnv = argv[++index];
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
break;
case '--expected-revision': {
const value = argv[++index];
expectedRevision = Number(value);
if (
!/^\d+$/.test(value ?? '') ||
!Number.isSafeInteger(expectedRevision)
) {
throw new Error('--expected-revision must be a nonnegative integer.');
}
break;
}
default:
throw new Error(`Unknown argument: ${argv[index]}`);
}
}
if (!matchId || (apply && expectedRevision === undefined)) {
throw new Error(
'--match-id is required; --apply also requires --expected-revision from the dry run.',
);
}
return { matchId, nodeEnv, expectedRevision, apply };
}
export async function repairGrandFinalBo3(
connectionService: ConnectionService,
options: CliOptions,
) {
if (options.apply && options.expectedRevision === undefined) {
throw new Error('An expected revision is required to apply the repair.');
}
const [Match, Competition, Fact, Outbox] = await Promise.all([
connectionService.getModel('match'),
connectionService.getModel('competition'),
connectionService.getModel('competitionFact'),
connectionService.getModel('competitionOutbox'),
]);
async function run(session: mongoose.ClientSession | null) {
const match = await Match.findById(options.matchId)
.session(session)
.lean()
.exec();
if (
!match?.competitionId ||
match.gameMode !== 'double-elimination' ||
match.status !== 'finished' ||
!match.teamBuiltAt ||
!match.doubleElimination
) {
throw new Error(
'Expected a finished double-elimination Match with a linked Competition.',
);
}
const competition = await Competition.findOne({
_id: match.competitionId,
matchId: match._id,
communityId: match.communityId,
})
.session(session)
.lean()
.exec();
if (!competition || competition.phase !== 'completed') {
throw new Error('Expected a completed Competition linked to this Match.');
}
if (
options.expectedRevision !== undefined &&
competition.revision !== options.expectedRevision
) {
throw new Error(
`Competition revision is ${competition.revision}; run the preview again.`,
);
}
const facts = await Fact.find({ competitionId: competition._id })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec();
const plan = planGrandFinalBo3Repair({
competitionId: competition._id.toHexString(),
revision: competition.revision,
projectorVersion: competition.projectorVersion,
teams: competition.teams.map(({ teamId, displayOrder, seedNumber }) => ({
teamId: teamId.toHexString(),
displayOrder,
seedNumber,
})),
format: competition.format as unknown as CompetitionGraphFormat,
seriesGraph: competition.seriesGraph as unknown as SeriesDefinition[],
facts: facts.map((fact) => factForProjection({ ...fact })),
});
if (!isDeepStrictEqual(plan.before, competition.projection)) {
throw new Error(
'The fact ledger does not reproduce the stored projection.',
);
}
const revision = plan.projection.sourceRevision;
if (session) {
const now = new Date();
const idempotencyKey = `repair:grand-final-bo3:${competition._id.toHexString()}`;
const requestHash = createHash('sha256')
.update(idempotencyKey)
.digest('hex');
const commandId = `cmpcmd_${requestHash.slice(0, 32)}`;
const receipt = {
competitionId: competition._id,
revision,
commandId,
idempotencyKey,
requestHash,
};
const factId = new mongoose.Types.ObjectId();
const competitionWrite = await Competition.updateOne(
{ _id: competition._id, revision: competition.revision },
{
$set: {
revision,
format: plan.format,
seriesGraph: plan.seriesGraph,
projection: plan.projection,
phase: plan.projection.phase,
},
},
{ session, runValidators: true },
).exec();
const matchWrite = await Match.updateOne(
{ _id: match._id, status: 'finished', competitionId: competition._id },
{
$set: {
status: 'in-progress',
'doubleElimination.grandFinalGameCount': 3,
...(match.resultPollState
? {
'resultPollState.state': 'polling',
'resultPollState.matchedCount': plan.projection.games.length,
}
: {}),
},
},
{ session, runValidators: true },
).exec();
if (
competitionWrite.matchedCount !== 1 ||
matchWrite.matchedCount !== 1
) {
throw new Error(
'Match or Competition changed during repair; run the preview again.',
);
}
await Fact.insertMany(
[
{
...receipt,
_id: factId,
type: CORRECTION_TYPE,
ordinalWithinRevision: 1,
schemaVersion: competition.schemaVersion,
actor: { type: 'system' },
seriesId: new mongoose.Types.ObjectId(plan.seriesId),
occurredAt: now,
recordedAt: now,
reason:
'Restore the intended BO3 grand final without voiding the first game.',
ruleCorrection: { previousMaxGames: 1, nextMaxGames: 3 },
},
],
{ session },
);
await Outbox.insertMany(
[
{
...receipt,
eventId: `${commandId}:competition-projected`,
type: 'competition.projection-updated',
payload: {
competitionId: competition._id.toHexString(),
sourceRevision: revision,
factIds: [factId.toHexString()],
projection: plan.projection,
phase: plan.projection.phase,
updatedAt: now,
},
state: 'pending',
availableAt: now,
},
],
{ session },
);
}
return {
mode: session ? 'applied' : 'dry-run',
database: resolveMongoDbName(options.nodeEnv),
matchId: match._id.toHexString(),
competitionId: competition._id.toHexString(),
revisionBefore: competition.revision,
revisionAfter: revision,
phase: `${competition.phase} -> ${plan.projection.phase}`,
preservedGame: plan.preservedGame,
totalPreservedGames: plan.projection.games.length,
newGameNumbers: plan.newGameNumbers,
};
}
if (!options.apply) return run(null);
const session = await connectionService.createSession();
if (!session) throw new Error('Repair requires a MongoDB transaction.');
try {
return await session.withTransaction(() => run(session));
} finally {
await session.endSession();
}
}
async function main() {
const args = process.argv.slice(2);
if (args.includes('--help')) {
process.stdout.write(
'Usage: pnpm --filter api competition:repair-grand-final --env <dev|staging|prod> --match-id <id> [--expected-revision <n> --apply]\n',
);
return;
}
const options = parseGrandFinalRepairOptions(args);
process.env.NODE_ENV = options.nodeEnv;
process.env.MONGODB_AUTO_INDEX = 'false';
const connections = new ConnectionService(
new SecretService(new ConfigService()),
);
const connection = await connections.getConnection();
try {
process.stdout.write(
`${JSON.stringify(await repairGrandFinalBo3(connections, options), null, 2)}\n`,
);
} finally {
await connection.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
process.stderr.write(
`${error instanceof Error ? error.message : String(error)}\n`,
);
process.exitCode = 1;
});
}
@@ -0,0 +1,102 @@
import 'reflect-metadata';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { readFile } from 'node:fs/promises';
import { resolve } from 'node:path';
import { ConnectionService, resolveMongoDbName } from '../connection.service';
import { SecretModule } from '../../secret/secret.module';
import { migrateMatchStatsRawIndex } from './20261111-match-stats-raw-index';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [
resolve(__dirname, '../../../../../../project.env'),
resolve(process.cwd(), '../project.env'),
resolve(process.cwd(), 'apps/project.env'),
resolve(process.cwd(), 'project.env'),
],
}),
SecretModule,
],
providers: [ConnectionService],
})
class MigrationModule {}
export function parseMatchStatsIndexOptions(argv: string[]) {
let dryRun = true;
let help = false;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index++) {
const argument = argv[index];
if (argument === '--') continue;
if (argument === '--apply') dryRun = false;
else if (argument === '--dry-run') dryRun = true;
else if (argument === '--help' || argument === '-h') help = true;
else if (argument === '--env') nodeEnv = argv[++index] ?? '';
else if (argument.startsWith('--env=')) nodeEnv = argument.slice(6);
else throw new Error(`Unknown argument: ${argument}`);
}
if (!help && !['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, help, nodeEnv };
}
async function main(): Promise<void> {
const options = parseMatchStatsIndexOptions(process.argv.slice(2));
if (options.help) {
console.log(`Usage:
pnpm --filter api stats:indexes -- --env staging --dry-run
pnpm --filter api stats:indexes -- --env prod --apply
Defaults to dry-run. --env accepts dev, staging, or prod (NODE_ENV or dev by default).
Creates the internal stats Riot match ID index; does not modify documents.`);
return;
}
// Use the same optional machine environment as the existing migration runners.
const machineHome = process.env.HOME ?? process.env.USERPROFILE;
if (machineHome) {
const contents = await readFile(
resolve(machineHome, 'source/global-env-vars.txt'),
'utf8',
).catch(() => '');
for (const line of contents.split(/\r?\n/)) {
const match = line.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
if (match) process.env[match[1]] = match[2].replace(/^["']|["']$/g, '');
}
}
process.env.NODE_ENV = options.nodeEnv;
// Even a dry-run with auto-index enabled in the environment must not write.
process.env.MONGODB_AUTO_INDEX = 'false';
const app = await NestFactory.createApplicationContext(MigrationModule, {
logger: ['warn', 'error'],
});
try {
const connection = await app.get(ConnectionService).getConnection();
if (!connection.db) throw new Error('MongoDB connection has no db handle.');
const result = await migrateMatchStatsRawIndex(connection.db, options);
console.log(
JSON.stringify(
{
env: options.nodeEnv,
db: resolveMongoDbName(options.nodeEnv),
...result,
},
null,
2,
),
);
} finally {
await app.close();
}
}
if (require.main === module) {
void main().catch((error: unknown) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
}
+29 -1
View File
@@ -1,4 +1,5 @@
import mongoose, { Schema, HydratedDocument } from 'mongoose';
import type { MatchEventType } from '@lolympus/contracts';
import type {
RiotPlatformRoute,
RiotRegionalRoute,
@@ -13,6 +14,7 @@ import {
} from '../../competition/competition.schema';
import { ModelDefinition } from './types';
import { AUCTION_CANCELLATION_CLEANUP_INDEX } from './auction-cancellation-index';
import { MATCH_STATS_RIOT_MATCH_INDEX } from './match-stats-raw-index';
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
@@ -38,6 +40,11 @@ export const MATCH_STATUSES: MatchStatus[] = [
'finished',
];
export const MATCH_EVENT_TYPES = [
'inhouse',
'tournament',
] as const satisfies readonly MatchEventType[];
export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
@@ -644,6 +651,7 @@ export interface DoubleEliminationEvent {
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
grandFinalGameCount?: 1 | 3 | 5;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
@@ -685,6 +693,7 @@ export interface Match extends MongooseTimestamps {
competitionId?: mongoose.Types.ObjectId;
shortCode?: string;
title: string;
eventType?: MatchEventType;
description: string;
mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등)
status: MatchStatus;
@@ -848,6 +857,8 @@ export const AuctionBidRecordSchema = new Schema<AuctionBidRecord>(
export interface AuctionChatMessage {
id: string;
clientMessageId?: string;
senderRole?: 'operator';
userId?: mongoose.Types.ObjectId;
displayName: string;
message: string;
@@ -1014,6 +1025,14 @@ export interface MatchStatsRecord {
championLevel: number;
teamPosition: string;
kills: number;
multiKills?: {
doubleKills: number;
tripleKills: number;
quadraKills: number;
pentaKills: number;
largestMultiKill: number;
};
tier?: TierInfo;
deaths: number;
assists: number;
win: boolean;
@@ -1046,6 +1065,7 @@ export interface MatchStatsGameDetail {
gameCreation: number;
gameDuration: number;
gameVersion?: string;
rawAvailable?: boolean;
winnerSide: TeamSide;
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
@@ -1850,6 +1870,7 @@ const DoubleEliminationBracketSubSchema = new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
grandFinalGameCount: { type: Number, enum: [1, 3, 5] },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
@@ -1952,6 +1973,7 @@ export const MatchSchema = new Schema<Match>(
maxlength: 6,
},
title: { type: String, required: true },
eventType: { type: String, enum: MATCH_EVENT_TYPES, default: 'inhouse' },
description: { type: String, required: false, default: '' },
mapId: { type: Number, required: true, default: 11 },
status: {
@@ -2235,6 +2257,8 @@ const AuctionBidHistoryEntrySubSchema = new Schema<AuctionBidHistoryEntry>(
const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
{
id: { type: String, required: true },
clientMessageId: { type: String, required: false },
senderRole: { type: String, enum: ['operator'], required: false },
userId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
displayName: { type: String, required: true },
message: { type: String, required: true },
@@ -2528,7 +2552,7 @@ export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
{ timestamps: true, collection: 'match_stats' },
) as mongoose.Schema<MatchStats>;
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1, matchId: -1 });
MatchStatsSchema.index({
communityId: 1,
gameCreationMin: 1,
@@ -2537,6 +2561,10 @@ MatchStatsSchema.index({
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, userIds: 1, scheduledAt: -1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
MatchStatsSchema.index(
MATCH_STATS_RIOT_MATCH_INDEX.key,
MATCH_STATS_RIOT_MATCH_INDEX.options,
);
export const tournamentModelDefinitions: Array<
ModelDefinition & { name: keyof TournamentModelTypes }
@@ -1,6 +1,5 @@
import { Module } from '@nestjs/common';
import { connect } from 'nats';
import type { NatsConnection } from 'nats';
import { connect, type NatsConnection } from '@nats-io/transport-node';
import { SecretModule } from '../secret/secret.module';
import { SecretService } from '../secret/secret.service';
import { NATS_CLIENT } from './nats.constants';
@@ -2,20 +2,21 @@ import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
import {
AckPolicy,
DeliverPolicy,
nanos,
jetstream,
jetstreamManager,
ReplayPolicy,
RetentionPolicy,
StorageType,
StringCodec,
} from 'nats';
import type {
ConsumerMessages,
JsMsg,
Msg,
NatsConnection,
PubAck,
Subscription,
} from 'nats';
type ConsumerMessages,
type JsMsg,
type PubAck,
} from '@nats-io/jetstream';
import {
nanos,
type Msg,
type NatsConnection,
type Subscription,
} from '@nats-io/transport-node';
import { NATS_CLIENT } from './nats.constants';
export type NatsMessageHandler<T = unknown> = (
@@ -64,7 +65,6 @@ const JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS = 1_000;
@Injectable()
export class NatsService implements OnModuleDestroy {
private readonly logger = new Logger(NatsService.name);
private readonly stringCodec = StringCodec();
private readonly subscriptions = new Set<Subscription>();
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
private isDestroying = false;
@@ -108,10 +108,7 @@ export class NatsService implements OnModuleDestroy {
}
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
this.natsClient.publish(
subject,
this.stringCodec.encode(JSON.stringify(data)),
);
this.natsClient.publish(subject, JSON.stringify(data));
await this.natsClient.flush();
}
@@ -133,19 +130,16 @@ export class NatsService implements OnModuleDestroy {
data: T,
options?: { messageId?: string; timeoutMs?: number },
): Promise<PubAck> {
const ack = await this.natsClient
.jetstream()
.publish(subject, this.stringCodec.encode(JSON.stringify(data)), {
msgID: options?.messageId,
timeout: options?.timeoutMs ?? 5000,
});
return ack;
return jetstream(this.natsClient).publish(subject, JSON.stringify(data), {
msgID: options?.messageId,
timeout: options?.timeoutMs ?? 5000,
});
}
public async ensureJetStreamStream(
options: JetStreamStreamOptions,
): Promise<void> {
const manager = await this.natsClient.jetstreamManager();
const manager = await jetstreamManager(this.natsClient);
const config = {
name: options.name,
subjects: options.subjects,
@@ -173,7 +167,7 @@ export class NatsService implements OnModuleDestroy {
public async ensureJetStreamConsumer(
options: JetStreamConsumerOptions,
): Promise<void> {
const manager = await this.natsClient.jetstreamManager();
const manager = await jetstreamManager(this.natsClient);
const config = {
durable_name: options.durable,
name: options.durable,
@@ -206,9 +200,10 @@ export class NatsService implements OnModuleDestroy {
): Promise<void> {
while (!this.isDestroying) {
try {
const consumer = await this.natsClient
.jetstream()
.consumers.get(options.stream, options.durable);
const consumer = await jetstream(this.natsClient).consumers.get(
options.stream,
options.durable,
);
const messages = await consumer.consume({
max_messages: options.maxMessages ?? 10,
expires: options.expiresMs ?? 30000,
@@ -263,8 +258,7 @@ export class NatsService implements OnModuleDestroy {
): Promise<void> {
let data: T;
try {
const decoded = this.stringCodec.decode(msg.data);
data = JSON.parse(decoded) as T;
data = msg.json<T>();
} catch (err) {
this.logger.warn(
`Failed to decode NATS message on subject="${msg.subject}": ${
@@ -292,7 +286,7 @@ export class NatsService implements OnModuleDestroy {
): Promise<void> {
let data: T;
try {
data = JSON.parse(msg.string()) as T;
data = msg.json<T>();
} catch (err) {
this.logger.warn(
`Terminating undecodable JetStream message subject="${msg.subject}" stream="${options.stream}": ${
@@ -389,6 +389,7 @@ describe('Legacy import Competition result cutover', () => {
}),
} as unknown as ConnectionService;
const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({
@@ -642,6 +643,7 @@ function createService(
{} as RiotMatchService,
options.communityStatsService ??
({
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as CommunityStatsService),
options.matchStatsService ?? ({} as MatchStatsService),
@@ -977,6 +979,7 @@ function createBulkDeleteFailureHarness(options: {
}),
} as unknown as ConnectionService;
const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(0),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ connectionService, communityStatsService });
@@ -59,6 +59,7 @@ describe('LegacyImportService member job completion', () => {
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
} as unknown as jest.Mocked<DistributedLockService>;
const communityStatsService = {
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = new LegacyImportService(
@@ -797,7 +797,9 @@ export class LegacyImportService {
'evidence.type': 'riot',
'evidence.riotMatchId': riotMatchId,
});
if (existing) return 'duplicate';
if (existing) {
return 'duplicate';
}
const detail = await this.ensureRiotMatchPersisted(
riotMatchId,
@@ -930,7 +932,9 @@ export class LegacyImportService {
const stored = await RiotMatchModel.findOne({
matchId: riotMatchId,
}).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
if (isRiotMatchDto(stored?.raw)) {
return stored.raw;
}
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
@@ -948,6 +952,13 @@ export class LegacyImportService {
{ $set: payload },
{ upsert: true },
).exec();
await this.communityStatsService
.refreshForRiotMatches([dto.metadata.matchId])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after saving ${dto.metadata.matchId}: ${String(error)}`,
);
});
return dto;
}
@@ -56,6 +56,7 @@ export class MatchHistoryController {
@Query('seasonId') seasonId?: string,
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('lane') lane?: string,
) {
return this.matchHistoryService.getRecentSummary({
communityId,
@@ -66,6 +67,7 @@ export class MatchHistoryController {
seasonId,
championId: this.toNumber(championId),
limit: this.toNumber(limit),
lane,
},
});
}
@@ -82,6 +84,8 @@ export class MatchHistoryController {
@Query('championId') championId?: string,
@Query('limit') limit?: string,
@Query('cursor') cursor?: string,
@Query('lane') lane?: string,
@Query('includePositionCounts') includePositionCounts?: string,
) {
return this.matchHistoryService.getRecentMatches({
communityId,
@@ -93,6 +97,8 @@ export class MatchHistoryController {
championId: this.toNumber(championId),
limit: this.toNumber(limit),
cursor: this.toNumber(cursor),
lane,
includePositionCounts: includePositionCounts === 'true',
},
});
}
@@ -5,6 +5,72 @@ import { MatchHistoryService } from './match-history.service';
const SEASON_START = Date.parse('2026-01-01T00:00:00Z');
describe('MatchHistoryService champion filtering', () => {
it('selects a lane before limiting and uses only the requested participant, including legacy individualPosition', async () => {
const { service, scope, find } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: { rank: 'solo', lane: 'MIDDLE', limit: 20 },
});
expect(result.matches.map((game) => game.matchId)).toEqual([
'KR_3',
'KR_2',
'KR_1',
]);
expect(result.matches.every((game) => game.teamPosition === 'MIDDLE')).toBe(
true,
);
expect(result.matches[0].damageShare).toBe(100);
expect(find.mock.calls[0][0]['raw.info.participants']?.$elemMatch).toEqual({
puuid: 'player',
$or: [
{ teamPosition: 'MIDDLE' },
{ teamPosition: { $in: ['', null] }, individualPosition: 'MIDDLE' },
],
});
});
it('combines champion and lane filtering and rejects invalid lanes', async () => {
const { service, scope } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: { rank: 'solo', championId: 1, lane: 'MIDDLE', limit: 20 },
});
expect(result.matches).toEqual([]);
await expect(
service.getRecentMatches({ ...scope, filters: { lane: 'unknown' } }),
).rejects.toThrow('Invalid lane');
});
it('counts independent lane windows across the season and caps each at twenty', async () => {
const { service, scope, aggregate } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: {
rank: 'solo',
lane: 'MIDDLE',
limit: 20,
includePositionCounts: true,
},
});
expect(result.positionCounts).toEqual({
ALL: 20,
TOP: 20,
JUNGLE: 0,
MIDDLE: 3,
BOTTOM: 0,
UTILITY: 0,
});
expect(aggregate.mock.calls[0][0][0]).toEqual({
$match: {
participantPuuids: 'player',
queueId: { $in: [420] },
gameCreation: { $gte: SEASON_START },
},
});
expect(JSON.stringify(aggregate.mock.calls[0][0])).toContain('$$p.puuid');
expect(JSON.stringify(aggregate.mock.calls[0][0])).not.toContain('$limit');
});
it('paginates matching games beyond 120 newer games and excludes opponents using the champion', async () => {
const harness = createHarness();
const filters = { championId: 99, rank: 'solo', limit: 2 };
@@ -18,6 +84,11 @@ describe('MatchHistoryService champion filtering', () => {
'KR_2',
]);
expect(first.nextCursor).toBe(SEASON_START + 2_000);
expect(first.matches[0].largestMultiKill).toBe(3);
expect(first.matches[0].teams[0].participants[0].tier).toMatchObject({
tier: 'GOLD',
rank: 'II',
});
const second = await harness.service.getRecentMatches({
...harness.scope,
filters: { ...filters, cursor: first.nextCursor! },
@@ -72,7 +143,14 @@ interface HistoryQuery {
queueId: { $in: number[] };
gameCreation?: { $gte?: number; $lt?: number };
'raw.info.participants'?: {
$elemMatch: { puuid: string; championId: number };
$elemMatch: {
puuid: string;
championId?: number;
$or?: Array<{
teamPosition: string | { $in: (string | null)[] };
individualPosition?: string;
}>;
};
};
}
@@ -117,7 +195,18 @@ function createHarness() {
row.raw.info.participants.some(
(entry) =>
entry.puuid === participant.puuid &&
entry.championId === participant.championId,
(participant.championId === undefined ||
entry.championId === participant.championId) &&
(!participant.$or ||
participant.$or.some((condition) =>
typeof condition.teamPosition === 'string'
? entry.teamPosition === condition.teamPosition
: condition.teamPosition.$in.includes(
entry.teamPosition ?? null,
) &&
entry.individualPosition ===
condition.individualPosition,
)),
)),
)
.sort((a, b) => b.gameCreation - a.gameCreation)
@@ -128,8 +217,45 @@ function createHarness() {
};
return query;
});
const aggregate = jest.fn<
{ exec: () => Promise<Array<{ _id: string; count: number }>> },
[unknown[]]
>(() => ({
exec: async () => [
{ _id: 'TOP', count: 127 },
{ _id: 'MIDDLE', count: 3 },
],
}));
const models = {
user: {
find: () => ({
select: () => ({
lean: () => ({
exec: async () => [
{
riotAccounts: [
{
puuid: 'player',
tierHistory: [
{
queueType: 'RANKED_SOLO_5x5',
tier: 'PLATINUM',
recordedAt: new Date(SEASON_START + 4_000),
},
{
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'II',
recordedAt: new Date(SEASON_START),
},
],
},
],
},
],
}),
}),
}),
findById: () => ({
exec: async () => ({
_id: userId,
@@ -146,7 +272,7 @@ function createHarness() {
}),
}),
},
riotMatch: { find },
riotMatch: { find, aggregate },
};
const connection = {
getModel: async (name: keyof typeof models) => models[name],
@@ -157,6 +283,7 @@ function createHarness() {
find,
select,
returnedCounts,
aggregate,
};
}
@@ -165,9 +292,13 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
const participant = {
puuid: 'player',
championId,
teamPosition:
sequence === 2 ? undefined : championId === 99 ? 'MIDDLE' : 'TOP',
individualPosition: championId === 99 ? 'MIDDLE' : 'TOP',
teamId: 100,
win: true,
kills: 5,
tripleKills: 1,
deaths: 2,
assists: 3,
totalMinionsKilled: 100,
@@ -195,6 +326,7 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
puuid: 'opponent',
teamId: 200,
championId: 99,
teamPosition: 'MIDDLE',
win: false,
},
],
@@ -21,6 +21,7 @@ import {
type RiotRankFilter,
} from '../riot/riot-queue.constants';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import { readMultiKills } from '../riot/riot-multi-kill';
import type {
ChampionStatsResponse,
ChampionStatsRow,
@@ -52,6 +53,8 @@ interface MatchFilters {
championId?: number;
limit?: number;
cursor?: number;
lane?: string;
includePositionCounts?: boolean;
}
interface AggregatedChampion {
@@ -182,6 +185,7 @@ export class MatchHistoryService {
context,
queueIds,
championId: params.filters.championId,
lane: params.filters.lane,
limit,
});
const views = docs
@@ -211,6 +215,7 @@ export class MatchHistoryService {
context,
queueIds,
championId: params.filters.championId,
lane: params.filters.lane,
limit: limit + 1,
cursor: params.filters.cursor,
});
@@ -218,9 +223,19 @@ export class MatchHistoryService {
.map((doc) => this.toRecentMatchView(doc, context.account.puuid))
.filter((view): view is RecentMatchView => Boolean(view));
const page = views.slice(0, limit);
await this.attachRecordedRanks(params.communityId, page);
return {
matches: page,
...(params.filters.includePositionCounts
? {
positionCounts: await this.getPositionCounts(
context,
queueIds,
params.filters.championId,
),
}
: {}),
nextCursor:
views.length > limit
? (page[page.length - 1]?.gameCreation ?? null)
@@ -230,6 +245,64 @@ export class MatchHistoryService {
};
}
private async attachRecordedRanks(
communityId: mongoose.Types.ObjectId,
page: RecentMatchView[],
) {
const ranked = page.filter(
(game) => game.queueId === 420 || game.queueId === 440,
);
const puuids = new Set(
ranked.flatMap((game) =>
game.teams.flatMap((team) =>
team.participants.map(({ puuid }) => puuid),
),
),
);
if (puuids.size === 0) return;
const UserModel = await this.connectionService.getModel('user');
const users = await UserModel.find({
communityId,
'riotAccounts.puuid': { $in: [...puuids] },
})
.select({ 'riotAccounts.puuid': 1, 'riotAccounts.tierHistory': 1 })
.lean()
.exec();
const history = new Map(
users.flatMap(({ riotAccounts }) =>
riotAccounts
.filter(({ puuid }) => puuids.has(puuid))
.map(({ puuid, tierHistory }) => [puuid, tierHistory ?? []] as const),
),
);
for (const game of ranked) {
const queueType =
game.queueId === 420 ? 'RANKED_SOLO_5x5' : 'RANKED_FLEX_SR';
for (const participant of game.teams.flatMap(
(team) => team.participants,
)) {
const snapshot = history
.get(participant.puuid)
?.filter(
(entry) =>
entry.queueType === queueType &&
entry.recordedAt.getTime() <= game.gameCreation,
)
.sort(
(left, right) =>
right.recordedAt.getTime() - left.recordedAt.getTime(),
)[0];
if (snapshot)
participant.tier = {
tier: snapshot.tier,
rank: snapshot.rank,
leaguePoints: snapshot.leaguePoints,
fetchedAt: snapshot.recordedAt.toISOString(),
};
}
}
}
private async resolveContext(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
@@ -334,7 +407,14 @@ export class MatchHistoryService {
limit: number;
cursor?: number;
championId?: number;
lane?: string;
}): Promise<RiotMatchDocument[]> {
if (
params.lane &&
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
) {
throw new BadRequestException('Invalid lane.');
}
if (params.queueIds.length === 0) return [];
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const gameCreation: Record<string, number> = {};
@@ -348,12 +428,25 @@ export class MatchHistoryService {
queueId: { $in: params.queueIds },
};
if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation;
if (params.championId !== undefined) {
if (params.championId !== undefined || params.lane) {
// Both conditions must match the same participant, before pagination.
query['raw.info.participants'] = {
$elemMatch: {
puuid: params.context.account.puuid,
championId: params.championId,
...(params.championId !== undefined
? { championId: params.championId }
: {}),
...(params.lane
? {
$or: [
{ teamPosition: params.lane },
{
teamPosition: { $in: ['', null] },
individualPosition: params.lane,
},
],
}
: {}),
},
};
}
@@ -365,6 +458,74 @@ export class MatchHistoryService {
.exec();
}
/** Counts independent position windows, without transferring full match payloads. */
private async getPositionCounts(
context: HistoryContext,
queueIds: number[],
championId?: number,
): Promise<Record<string, number>> {
const model = await this.connectionService.getModel('riotMatch');
const rows = await model
.aggregate<{ _id: string; count: number }>([
{
$match: {
participantPuuids: context.account.puuid,
queueId: { $in: queueIds },
...(context.seasonStartedAt
? { gameCreation: { $gte: context.seasonStartedAt.getTime() } }
: {}),
},
},
{
$project: {
participant: {
$first: {
$filter: {
input: '$raw.info.participants',
as: 'p',
cond: { $eq: ['$$p.puuid', context.account.puuid] },
},
},
},
},
},
{
$match: {
participant: { $ne: null },
...(championId !== undefined
? { 'participant.championId': championId }
: {}),
},
},
{
$group: {
_id: {
$cond: [
{ $in: [{ $ifNull: ['$participant.teamPosition', ''] }, ['']] },
'$participant.individualPosition',
'$participant.teamPosition',
],
},
count: { $sum: 1 },
},
},
])
.exec();
const counts: Record<string, number> = {
ALL: Math.min(
20,
rows.reduce((sum, row) => sum + row.count, 0),
),
};
for (const lane of ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY']) {
counts[lane] = Math.min(
20,
rows.find((row) => row._id === lane)?.count ?? 0,
);
}
return counts;
}
private async aggregateChampionStats(params: {
context: HistoryContext;
queueIds: number[];
@@ -593,6 +754,7 @@ export class MatchHistoryService {
championLevel: participant.champLevel,
teamPosition: participant.teamPosition || participant.individualPosition,
kills: participant.kills,
largestMultiKill: readMultiKills(participant)?.largestMultiKill,
deaths: participant.deaths,
assists: participant.assists,
kda: this.resolveKda(
@@ -615,6 +777,7 @@ export class MatchHistoryService {
wardsPlaced: participant.wardsPlaced,
wardsKilled: participant.wardsKilled,
damageDealtToChampions: participant.totalDamageDealtToChampions,
damageShare: damageShare * 100,
damageTaken: participant.totalDamageTaken,
goldEarned: participant.goldEarned,
items: [
@@ -1,4 +1,5 @@
import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema';
import type { RecentMatchParticipantRank } from '@lolympus/contracts';
import type {
RiotQueueGroup,
RiotRankFilter,
@@ -102,6 +103,8 @@ export interface RecentSummaryResponse {
}
export interface RecentMatchesResponse {
/** Available games in each independent recent-20 window. */
positionCounts?: Record<string, number>;
matches: RecentMatchView[];
nextCursor: number | null;
lastFetchedAt: string | null;
@@ -115,6 +118,7 @@ export interface RecentMatchTeamParticipantView {
championId: number;
championLevel: number;
teamPosition: string;
tier?: RecentMatchParticipantRank;
kills: number;
deaths: number;
assists: number;
@@ -134,8 +138,11 @@ export interface RecentMatchTeamParticipantView {
}
export interface RecentMatchView {
/** Player champion damage / team champion damage, as a percentage. */
damageShare?: number;
matchId: string;
internalMatchId?: string;
internalMatchTitle?: string;
gameNumber?: number;
queueId: number;
queueLabel: string;
@@ -147,6 +154,7 @@ export interface RecentMatchView {
championLevel: number;
teamPosition: string;
kills: number;
largestMultiKill?: number;
deaths: number;
assists: number;
kda: number;
@@ -3,7 +3,11 @@ import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import mongoose from 'mongoose';
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
import {
CreateMatchDto,
JoinMatchDto,
UpdateMatchDto,
} from './create-match.dto';
describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => {
@@ -61,3 +65,53 @@ describe('JoinMatchDto self-join boundary', () => {
}
});
});
describe('Grand final format validation', () => {
it('allows BO3 on creation and rejects an even game count on update', () => {
const create = plainToInstance(CreateMatchDto, {
title: 'Competition',
scheduledAt: '2026-07-13T10:00:00.000Z',
gameMode: 'double-elimination',
doubleEliminationGrandFinalGameCount: 3,
});
expect(validateSync(create)).toEqual([]);
const update = plainToInstance(UpdateMatchDto, {
doubleEliminationGrandFinalGameCount: 2,
});
expect(validateSync(update)).toEqual([
expect.objectContaining({
property: 'doubleEliminationGrandFinalGameCount',
}),
]);
});
});
describe('Match event type validation', () => {
it.each(['inhouse', 'tournament', undefined])(
'accepts %s in create and update requests',
(eventType) => {
expect(
validateSync(
plainToInstance(CreateMatchDto, {
title: 'Competition',
scheduledAt: '2026-07-13T10:00:00.000Z',
eventType,
}),
),
).toEqual([]);
expect(
validateSync(plainToInstance(UpdateMatchDto, { eventType })),
).toEqual([]);
},
);
it.each(['double-elimination', null])(
'rejects %s as an event type',
(eventType) => {
const dto = plainToInstance(UpdateMatchDto, { eventType });
expect(validateSync(dto)).toEqual([
expect.objectContaining({ property: 'eventType' }),
]);
},
);
});
@@ -1,3 +1,4 @@
import type { GrandFinalGameCount, MatchEventType } from '@lolympus/contracts';
import { Type } from 'class-transformer';
import {
ArrayMaxSize,
@@ -14,11 +15,12 @@ import {
MaxLength,
Min,
MinLength,
ValidateIf,
ValidateNested,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { POSITIONS } from '../../global/database/schema';
import { MATCH_EVENT_TYPES, POSITIONS } from '../../global/database/schema';
import type { MatchGameMode, Position } from '../../global/database/schema';
const LIVE_MATCH_GAME_MODES = [
@@ -82,6 +84,10 @@ export class CreateMatchDto {
@MaxLength(128)
title!: string;
@ValidateIf((_object, value) => value !== undefined)
@IsIn(MATCH_EVENT_TYPES)
eventType?: MatchEventType;
@IsOptional()
@IsString()
@MaxLength(2048)
@@ -119,6 +125,10 @@ export class CreateMatchDto {
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsIn([1, 3, 5])
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -145,6 +155,10 @@ export class UpdateMatchDto {
@MaxLength(128)
title?: string;
@ValidateIf((_object, value) => value !== undefined)
@IsIn(MATCH_EVENT_TYPES)
eventType?: MatchEventType;
@IsOptional()
@IsString()
@MaxLength(2048)
@@ -183,6 +197,10 @@ export class UpdateMatchDto {
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional()
@IsIn([1, 3, 5])
doubleEliminationGrandFinalGameCount?: GrandFinalGameCount;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -0,0 +1,168 @@
import mongoose from 'mongoose';
import {
summarizeMatchHistoryResult,
type HistoryCompetition,
} from './match-history-result';
const firstId = new mongoose.Types.ObjectId();
const secondId = new mongoose.Types.ObjectId();
const thirdId = new mongoose.Types.ObjectId();
const teams = [
{
teamId: firstId,
name: '첫 팀',
displayOrder: 1,
seedNumber: 1,
members: [],
},
{
teamId: secondId,
name: '둘째 팀',
displayOrder: 2,
seedNumber: 2,
members: [],
},
{
teamId: thirdId,
name: '셋째 팀',
displayOrder: 3,
seedNumber: 3,
members: [],
},
];
const finishedMatch = {
status: 'finished' as const,
competitionId: new mongoose.Types.ObjectId(),
teams: [],
};
const singleSeries = {
status: 'completed',
entries: [
{ teamId: secondId.toString(), gameWins: 2 },
{ teamId: firstId.toString(), gameWins: 1 },
],
outcome: { type: 'played', winnerTeamId: secondId.toString() },
};
describe('summarizeMatchHistoryResult', () => {
it('shows played scores only for one completed series between two teams', () => {
const competition: HistoryCompetition = {
teams: teams.slice(0, 2),
projection: {
series: [singleSeries],
outcome: { type: 'paired-series' },
},
};
expect(summarizeMatchHistoryResult(finishedMatch, competition)).toEqual({
type: 'score',
teamAWins: 2,
teamBWins: 1,
teamAName: '둘째 팀',
teamBName: '첫 팀',
winnerTeamName: '둘째 팀',
});
expect(
summarizeMatchHistoryResult(
{ ...finishedMatch, status: 'in-progress' },
competition,
),
).toBeUndefined();
expect(
summarizeMatchHistoryResult(finishedMatch, {
...competition,
projection: {
...competition.projection,
series: [singleSeries, singleSeries],
},
}),
).toBeUndefined();
});
it('shows adjudication without a score even if some games were played', () => {
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams: teams.slice(0, 2),
projection: {
series: [
{
...singleSeries,
outcome: { ...singleSeries.outcome, type: 'forfeit' },
},
],
outcome: { type: 'paired-series' },
},
}),
).toEqual({
type: 'decision',
decision: 'forfeit',
winnerTeamName: '둘째 팀',
});
});
it('uses the tournament winner or joint leaders instead of a series score', () => {
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams,
projection: {
series: [singleSeries],
outcome: {
type: 'double-elimination',
championTeamId: thirdId.toString(),
},
},
}),
).toEqual({ type: 'winners', teamNames: ['셋째 팀'] });
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams,
projection: {
series: [singleSeries],
outcome: {
type: 'round-robin',
leaderTeamIds: [firstId.toString(), secondId.toString()],
},
},
}),
).toEqual({ type: 'winners', teamNames: ['첫 팀', '둘째 팀'] });
});
it('uses collected games for legacy two-team records without a Competition', () => {
const match = {
status: 'finished' as const,
teams: [
{ teamIndex: 2, name: '둘째 팀', members: [] },
{ teamIndex: 1, name: '첫 팀', members: [] },
],
result: {
winnerTeamIndex: 2,
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 2,
winnerSide: 'red' as const,
gameCreation: 0,
gameDuration: 1800,
participants: [],
},
],
},
};
expect(summarizeMatchHistoryResult(match)).toEqual({
type: 'score',
teamAWins: 0,
teamBWins: 1,
teamAName: '첫 팀',
teamBName: '둘째 팀',
winnerTeamName: '둘째 팀',
});
expect(
summarizeMatchHistoryResult({ ...match, competitionId: firstId }),
).toBeUndefined();
});
});
@@ -0,0 +1,121 @@
import type { MatchHistoryResult } from '@lolympus/contracts';
import type { Competition } from '../competition/competition.schema';
import type { CompetitionProjection } from '../competition/domain/competition-projector';
import type { Match } from '../global/database/schema';
type HistoryMatch = Pick<
Match,
'status' | 'competitionId' | 'teams' | 'result' | 'doubleElimination'
>;
export type HistoryCompetition = Pick<Competition, 'projection' | 'teams'>;
export function summarizeMatchHistoryResult(
match: HistoryMatch,
competition?: HistoryCompetition,
): MatchHistoryResult | undefined {
if (match.status !== 'finished') return;
if (!match.competitionId) return summarizeLegacyResult(match);
if (!competition) return;
const { series, outcome } = competition.projection as Pick<
CompetitionProjection,
'series' | 'outcome'
>;
if (!outcome) return;
const teamName = (teamId: string | null) => {
const team = competition.teams.find(
(item) => String(item.teamId) === teamId,
);
return team && (team.name.trim() || `${team.displayOrder}팀`);
};
const singleSeries = series?.length === 1 ? series[0] : undefined;
if (competition.teams.length === 2 && singleSeries?.status === 'completed') {
const decision = singleSeries.outcome;
const winnerTeamName =
decision.type === 'draw' ? undefined : teamName(decision.winnerTeamId);
if (
decision.type === 'played' ||
(decision.type === 'draw' && decision.basis.type === 'played')
) {
const [teamA, teamB] = singleSeries.entries;
return {
type: 'score',
teamAWins: teamA.gameWins,
teamBWins: teamB.gameWins,
teamAName: teamName(teamA.teamId),
teamBName: teamName(teamB.teamId),
winnerTeamName,
};
}
return { type: 'decision', decision: decision.type, winnerTeamName };
}
const winnerIds =
outcome.type === 'double-elimination'
? [outcome.championTeamId]
: outcome.type === 'round-robin'
? outcome.leaderTeamIds
: [];
const teamNames = winnerIds.map(teamName);
if (teamNames.length > 0 && teamNames.every((name) => name !== undefined)) {
return { type: 'winners', teamNames };
}
}
function summarizeLegacyResult(
match: HistoryMatch,
): MatchHistoryResult | undefined {
const placement = match.doubleElimination?.placements.firstTeamIndex;
if (placement !== undefined) {
const champion = match.teams.find((team) => team.teamIndex === placement);
if (champion) {
return {
type: 'winners',
teamNames: [champion.name.trim() || `${placement}팀`],
};
}
}
if (match.teams.length !== 2 || !match.result?.games.length) return;
const [teamA, teamB] = [...match.teams].sort(
(a, b) => a.teamIndex - b.teamIndex,
);
const { games } = match.result;
const teamIndices = new Set([teamA.teamIndex, teamB.teamIndex]);
if (
games.some(
({ blueTeamIndex, redTeamIndex }) =>
blueTeamIndex === redTeamIndex ||
!teamIndices.has(blueTeamIndex) ||
!teamIndices.has(redTeamIndex),
)
)
return;
const teamAWins = games.filter(
(game) => game.winnerTeamIndex === teamA.teamIndex,
).length;
const teamBWins = games.filter(
(game) => game.winnerTeamIndex === teamB.teamIndex,
).length;
if (teamAWins + teamBWins !== games.length) return;
const winner = match.teams.find(
(team) => team.teamIndex === match.result?.winnerTeamIndex,
);
if (
winner &&
(teamAWins === teamBWins ||
winner.teamIndex !==
(teamAWins > teamBWins ? teamA.teamIndex : teamB.teamIndex))
)
return;
return {
type: 'score',
teamAWins,
teamBWins,
teamAName: teamA.name.trim() || `${teamA.teamIndex}팀`,
teamBName: teamB.name.trim() || `${teamB.teamIndex}팀`,
winnerTeamName: winner && (winner.name.trim() || `${winner.teamIndex}팀`),
};
}
@@ -75,6 +75,7 @@ describe('presentPublicMatch', () => {
communityId: oid('2').toString(),
competitionId: oid('3').toString(),
title: '내전',
eventType: 'inhouse',
doubleEliminationResetFinalEnabled: false,
scheduledAt: '2026-07-12T10:00:00.000Z',
participants: [
@@ -1,4 +1,8 @@
import type { MatchDetailResponse, MatchTierView } from '@lolympus/contracts';
import type {
MatchDetailResponse,
MatchEventType,
MatchTierView,
} from '@lolympus/contracts';
import type {
MatchGameMode,
MatchStatus,
@@ -13,6 +17,7 @@ interface PublicMatchSource {
competitionId?: IdLike;
shortCode?: string;
title: string;
eventType?: MatchEventType;
description: string;
mapId: number;
status: MatchStatus;
@@ -21,7 +26,10 @@ interface PublicMatchSource {
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleElimination?: { resetFinalEnabled?: boolean };
doubleElimination?: {
resetFinalEnabled?: boolean;
grandFinalGameCount?: 1 | 3 | 5;
};
hostUserId?: IdLike;
participants: Array<{
userId: IdLike;
@@ -67,6 +75,7 @@ export function presentPublicMatch(
: {}),
...(source.shortCode ? { shortCode: source.shortCode } : {}),
title: source.title,
eventType: source.eventType ?? 'inhouse',
description: source.description,
mapId: source.mapId,
status: source.status,
@@ -81,6 +90,8 @@ export function presentPublicMatch(
? {
doubleEliminationResetFinalEnabled:
source.doubleElimination?.resetFinalEnabled ?? false,
doubleEliminationGrandFinalGameCount:
source.doubleElimination?.grandFinalGameCount ?? 1,
}
: {}),
...(source.hostUserId
@@ -1,12 +1,89 @@
import 'reflect-metadata';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import mongoose from 'mongoose';
import { plainToInstance } from 'class-transformer';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { ROLES_KEY } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import type { UserDocument } from '../global/database/schema';
import { UpdateMatchDto } from './dto/create-match.dto';
import { MatchController } from './match.controller';
describe('MatchController history summaries', () => {
it('only attaches the page results when requested', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = { _id: new mongoose.Types.ObjectId() };
const summary = { _id: match._id.toString() };
const historyResult = { type: 'score', teamAWins: 2, teamBWins: 1 };
const matchService = {
listPage: jest
.fn()
.mockResolvedValue({ matches: [match], total: 1, page: 1, limit: 10 }),
serialize: jest.fn().mockReturnValue(summary),
getHistoryResults: jest
.fn()
.mockResolvedValue(new Map([[summary._id, historyResult]])),
};
const controller = new MatchController(matchService as never);
await expect(
controller.listMatches(undefined, communityId),
).resolves.toMatchObject({
matches: [summary],
});
expect(matchService.getHistoryResults).not.toHaveBeenCalled();
await expect(
controller.listMatches(
undefined,
communityId,
undefined,
'10',
'1',
undefined,
undefined,
undefined,
'desc',
'true',
'tournament',
),
).resolves.toMatchObject({ matches: [{ ...summary, historyResult }] });
expect(matchService.listPage).toHaveBeenLastCalledWith(
expect.objectContaining({ eventType: 'tournament' }),
);
expect(matchService.getHistoryResults).toHaveBeenCalledWith(communityId, [
match,
]);
});
});
describe('MatchController partial updates', () => {
it('passes only supplied fields when reclassifying a match', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const user = { _id: new mongoose.Types.ObjectId(), communityId };
const matchService = {
update: jest.fn().mockResolvedValue({ participants: [] }),
serialize: jest.fn(),
};
const controller = new MatchController(matchService as never);
const body = plainToInstance(UpdateMatchDto, { eventType: 'tournament' });
await controller.updateMatch(
user as UserDocument,
communityId,
matchId,
body,
);
expect(matchService.update).toHaveBeenCalledWith({
communityId,
matchId,
patch: { eventType: 'tournament' },
});
});
});
describe('MatchController participant access', () => {
function createController() {
const joinedMatch = { _id: new mongoose.Types.ObjectId() };
+92 -6
View File
@@ -1,6 +1,9 @@
import type {
HallOfFameResponse,
MatchDetailResponse,
MatchEventType,
MatchListResponse,
MatchListView,
} from '@lolympus/contracts';
import {
BadRequestException,
@@ -16,6 +19,7 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { isISO8601 } from 'class-validator';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -23,6 +27,7 @@ import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { MatchStatus, UserDocument } from '../global/database/schema';
import { MATCH_EVENT_TYPES } from '../global/database/schema';
import {
AddParticipantDto,
CreateMatchDto,
@@ -51,6 +56,7 @@ export class MatchController {
hostUserId: currentUser._id,
data: {
title: body.title,
eventType: body.eventType,
description: body.description ?? '',
mapId: body.mapId ?? 11,
scheduledAt: body.scheduledAt,
@@ -60,6 +66,8 @@ export class MatchController {
roundRobinMaxRounds: body.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
body.doubleEliminationResetFinalEnabled,
doubleEliminationGrandFinalGameCount:
body.doubleEliminationGrandFinalGameCount,
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
@@ -82,21 +90,63 @@ export class MatchController {
@Query('scheduledFrom') scheduledFrom?: string,
@Query('scheduledTo') scheduledTo?: string,
@Query('sort') sort?: 'asc' | 'desc',
@Query('includeResults') includeResults?: string,
@Query('eventType') eventType?: MatchEventType,
@Query('view') view?: MatchListView,
@Query('asOf') asOf?: string,
): Promise<MatchListResponse> {
if (eventType !== undefined && !MATCH_EVENT_TYPES.includes(eventType)) {
throw new BadRequestException('Invalid eventType.');
}
if (
view !== undefined &&
view !== 'active' &&
view !== 'upcoming' &&
view !== 'history'
) {
throw new BadRequestException('Invalid view.');
}
if (
view &&
(status !== undefined ||
scheduledFrom !== undefined ||
scheduledTo !== undefined)
) {
throw new BadRequestException(
'view cannot be combined with status or schedule filters.',
);
}
const asOfDate = this.toOptionalDate(asOf);
if (
asOf !== undefined &&
(typeof asOf !== 'string' ||
!isISO8601(asOf, { strict: true, strictSeparator: true }) ||
!asOfDate)
)
throw new BadRequestException('Invalid asOf.');
const result = await this.matchService.listPage({
communityId,
status,
eventType,
limit: this.toOptionalNumber(limit),
page: this.toOptionalNumber(page),
offset: this.toOptionalNumber(offset),
scheduledFrom: this.toOptionalDate(scheduledFrom),
scheduledTo: this.toOptionalDate(scheduledTo),
sort,
...(view ? { view, asOf: asOfDate } : {}),
});
const historyResults =
includeResults === 'true'
? await this.matchService.getHistoryResults(communityId, result.matches)
: undefined;
const eventProgress = view
? await this.matchService.getEventProgress(result.matches)
: undefined;
return {
...result,
matches: result.matches.map((match) =>
this.matchService.serialize(match, {
matches: result.matches.map((match) => {
const summary = this.matchService.serialize(match, {
...(currentUser
? {
joined: match.participants.some((participant) =>
@@ -104,11 +154,28 @@ export class MatchController {
),
}
: {}),
}),
),
});
const historyResult = historyResults?.get(summary._id);
return {
...summary,
...(historyResult ? { historyResult } : {}),
...(eventProgress
? { eventProgress: eventProgress.get(summary._id) }
: {}),
};
}),
};
}
@Get('hall-of-fame')
@AllowPublicAccess()
public getHallOfFame(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
): Promise<HallOfFameResponse> {
return this.matchService.getHallOfFame(communityId);
}
@Get(':matchId')
@AllowPublicAccess()
public async getMatch(
@@ -118,7 +185,7 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
): Promise<MatchDetailResponse> {
const match = await this.matchService.getById(matchId, communityId);
return this.matchService.serialize(match, {
const summary = this.matchService.serialize(match, {
joined: Boolean(
currentUser &&
match.participants.some((participant) =>
@@ -126,6 +193,8 @@ export class MatchController {
),
),
});
const progress = await this.matchService.getEventProgress([match]);
return { ...summary, eventProgress: progress.get(summary._id) };
}
@Patch(':matchId')
@@ -142,7 +211,7 @@ export class MatchController {
const match = await this.matchService.update({
matchId,
communityId,
patch: body,
patch: mongoose.omitUndefined({ ...body }),
});
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
@@ -241,6 +310,23 @@ export class MatchController {
}
// 관리자 전용 — 참가자 강제 제외.
@Delete(':matchId/participants')
@Roles('admin', 'owner', 'member')
@UseGuards(RolesGuard)
public async cancelJoin(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.cancelJoin({
matchId,
userId: currentUser._id,
});
return this.matchService.serialize(match, { joined: false });
}
@Delete(':matchId/participants/:userId')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
@@ -2,6 +2,104 @@ import mongoose from 'mongoose';
import { MatchService } from './match.service';
describe('MatchService', () => {
it('selects the official hall-of-fame roster by team ID when names repeat', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const championId = new mongoose.Types.ObjectId();
const captainUserId = new mongoose.Types.ObjectId();
const MatchModel = {
aggregate: jest.fn().mockReturnValue({
exec: async () => [
{
_id: matchId,
title: '멸망전',
official: [
{
projection: {
outcome: {
type: 'double-elimination',
championTeamId: championId.toString(),
},
},
teams: [
{
teamId: new mongoose.Types.ObjectId(),
name: '별무리',
members: [],
},
{
teamId: championId,
name: '별무리',
captainUserId,
members: [
{
userId: captainUserId,
assignedPosition: 'TOP',
gameName: '별빛',
},
],
},
],
},
],
},
],
}),
};
const CompetitionModel = { collection: { name: 'competition' } };
const service = new MatchService(
{
getModel: async (name: string) =>
name === 'match' ? MatchModel : CompetitionModel,
} as never,
{} as never,
{} as never,
{} as never,
);
await expect(service.getHallOfFame(communityId)).resolves.toMatchObject({
match: { id: matchId.toString(), title: '멸망전' },
teams: [
{
name: '별무리',
captainUserId: captainUserId.toString(),
members: [
{
userId: captainUserId.toString(),
position: 'TOP',
gameName: '별빛',
},
],
},
],
});
const [pipeline] = MatchModel.aggregate.mock.calls[0];
expect(pipeline[0]).toMatchObject({
$match: {
communityId,
eventType: 'tournament',
$or: [
{ competitionId: { $type: 'objectId' } },
expect.objectContaining({ competitionId: null, status: 'finished' }),
],
},
});
expect(pipeline[0].$match).not.toHaveProperty('status');
expect(pipeline[2]).toMatchObject({
$lookup: {
pipeline: [
expect.objectContaining({
$match: expect.objectContaining({
communityId,
phase: 'completed',
}),
}),
expect.anything(),
],
},
});
});
function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = {
@@ -195,7 +293,7 @@ describe('MatchService', () => {
expect(MatchModel.find).toHaveBeenCalledWith({ communityId });
expect(MatchModel.countDocuments).toHaveBeenCalledWith({ communityId });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
expect(skip).toHaveBeenCalledWith(5);
expect(limit).toHaveBeenCalledWith(5);
expect(page).toEqual({
@@ -254,7 +352,7 @@ describe('MatchService', () => {
communityId,
scheduledAt: { $gte: scheduledFrom },
});
expect(sort).toHaveBeenCalledWith({ scheduledAt: 1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: 1, _id: 1 });
});
it('filters past matches and keeps newest first for history sections', async () => {
@@ -277,9 +375,31 @@ describe('MatchService', () => {
communityId,
scheduledAt: { $lt: scheduledTo },
});
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
});
it.each([
['inhouse', { $in: ['inhouse', null] }],
['tournament', 'tournament'],
] as const)(
'filters both results and pagination totals for %s events',
async (eventType, expectedEventType) => {
const communityId = new mongoose.Types.ObjectId();
const scheduledTo = new Date('2026-06-08T12:00:00.000Z');
const { service, MatchModel } = createServiceWithListModel();
await service.listPage({ communityId, scheduledTo, eventType });
const expectedFilter = {
communityId,
scheduledAt: { $lt: scheduledTo },
eventType: expectedEventType,
};
expect(MatchModel.find).toHaveBeenCalledWith(expectedFilter);
expect(MatchModel.countDocuments).toHaveBeenCalledWith(expectedFilter);
},
);
it('uses saved user preferences when joining without explicit positions', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
@@ -531,6 +651,7 @@ describe('MatchService', () => {
gameCount: 5,
gameMode: 'double-elimination',
doubleEliminationResetFinalEnabled: true,
doubleEliminationGrandFinalGameCount: 3,
},
});
@@ -543,6 +664,7 @@ describe('MatchService', () => {
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
grandFinalGameCount: 3,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
@@ -635,6 +757,26 @@ describe('MatchService', () => {
expect(match.set).not.toHaveBeenCalled();
});
it('allows reclassifying a finished match without altering its competition settings', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'finished',
set: jest.fn(),
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { eventType: 'tournament' },
});
expect(match.set).toHaveBeenCalledWith({ eventType: 'tournament' });
expect(match.save).toHaveBeenCalledTimes(1);
});
it('rejects game count changes after recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
+304 -2
View File
@@ -1,3 +1,12 @@
import type {
HallOfFameResponse,
MatchEventStage,
MatchEventType,
MatchHistoryResult,
MatchId,
MatchListView,
UserId,
} from '@lolympus/contracts';
import {
BadRequestException,
ConflictException,
@@ -8,6 +17,7 @@ import {
import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import type { CompetitionProjection } from '../competition/domain/competition-projector';
import { ConnectionService } from '../global/database/connection.service';
import {
Match,
@@ -20,6 +30,10 @@ import {
} from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import {
summarizeMatchHistoryResult,
type HistoryCompetition,
} from './match-history-result';
import { presentPublicMatch } from './match-public.presenter';
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
@@ -32,6 +46,7 @@ const DEFAULT_DOUBLE_ELIMINATION_SERIES_GAME_COUNT = 3;
interface DoubleEliminationConfigInput {
doubleEliminationResetFinalEnabled?: boolean;
doubleEliminationGrandFinalGameCount?: 1 | 3 | 5;
}
interface CreateMatchParams {
@@ -51,10 +66,13 @@ interface UpdateMatchParams {
interface ListMatchesQuery {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
eventType?: MatchEventType;
limit?: number;
scheduledFrom?: Date;
scheduledTo?: Date;
sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: Date;
}
interface ListMatchesPageQuery extends ListMatchesQuery {
@@ -65,10 +83,15 @@ interface ListMatchesPageQuery extends ListMatchesQuery {
interface MatchListFilter {
communityId: mongoose.Types.ObjectId;
status?: MatchStatus;
eventType?: MatchEventType | { $in: (MatchEventType | null)[] };
scheduledAt?: {
$gte?: Date;
$lt?: Date;
};
$or?: Array<{
status: MatchStatus | { $in: MatchStatus[] };
scheduledAt?: { $lt: Date };
}>;
}
interface JoinMatchParams {
@@ -170,6 +193,244 @@ export class MatchService {
};
}
public async getHistoryResults(
communityId: mongoose.Types.ObjectId,
matches: readonly MatchDocument[],
): Promise<Map<string, MatchHistoryResult>> {
const finished = matches.filter((match) => match.status === 'finished');
const competitionIds = finished.flatMap((match) =>
match.competitionId ? [match.competitionId] : [],
);
const competitions = new Map<string, HistoryCompetition>();
if (competitionIds.length > 0) {
const CompetitionModel =
await this.connectionService.getModel('competition');
const completed = await CompetitionModel.find({
_id: { $in: competitionIds },
communityId,
phase: 'completed',
})
.select({
matchId: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
for (const competition of completed) {
competitions.set(competition.matchId.toString(), competition);
}
}
const results = new Map<string, MatchHistoryResult>();
for (const match of finished) {
const id = match._id.toString();
const result = summarizeMatchHistoryResult(match, competitions.get(id));
if (result) results.set(id, result);
}
return results;
}
public async getHallOfFame(
communityId: mongoose.Types.ObjectId,
): Promise<HallOfFameResponse> {
const [MatchModel, CompetitionModel] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const legacyChampion = {
competitionId: null,
status: 'finished',
'doubleElimination.placements.firstTeamIndex': { $type: 'number' },
};
const [match] = await MatchModel.aggregate<
Pick<Match, 'title' | 'teams' | 'participants' | 'doubleElimination'> & {
_id: mongoose.Types.ObjectId;
official: HistoryCompetition[];
}
>([
{
$match: {
communityId,
eventType: 'tournament',
$or: [{ competitionId: { $type: 'objectId' } }, legacyChampion],
},
},
{ $sort: { scheduledAt: -1, _id: -1 } },
{
$lookup: {
from: CompetitionModel.collection.name,
localField: 'competitionId',
foreignField: '_id',
let: { matchId: '$_id' },
pipeline: [
{
$match: {
communityId,
phase: 'completed',
$expr: { $eq: ['$matchId', '$$matchId'] },
$or: [
{ 'projection.outcome.type': 'double-elimination' },
{
'projection.outcome.type': 'round-robin',
'projection.outcome.leaderTeamIds.0': { $exists: true },
},
],
},
},
{ $project: { teams: 1, 'projection.outcome': 1 } },
],
as: 'official',
},
},
{
$match: { $or: [{ 'official.0': { $exists: true } }, legacyChampion] },
},
{ $limit: 1 },
{
$project: {
title: 1,
teams: 1,
participants: 1,
doubleElimination: 1,
official: 1,
},
},
]).exec();
if (!match) return { match: null, teams: [] };
const featuredMatch = {
id: match._id.toString() as MatchId,
title: match.title,
};
const [competition] = match.official;
if (competition) {
const { outcome } = competition.projection as Pick<
CompetitionProjection,
'outcome'
>;
const winnerIds =
outcome?.type === 'double-elimination'
? [outcome.championTeamId]
: outcome?.type === 'round-robin'
? outcome.leaderTeamIds
: [];
const teams = competition.teams
.filter((team) => winnerIds.includes(team.teamId.toString()))
.map((team) => ({
name: team.name.trim() || `${team.displayOrder}팀`,
captainUserId: team.captainUserId?.toString() as UserId | undefined,
members: team.members.map((member) => ({
userId: member.userId.toString() as UserId,
position: POSITIONS.find(
(position) => position === member.assignedPosition,
),
gameName: member.gameName,
tagLine: member.tagLine,
profileIconId: member.profileIconId,
})),
}));
return { match: featuredMatch, teams };
}
const placement = match.doubleElimination?.placements.firstTeamIndex;
const champion =
placement === undefined
? undefined
: match.teams.find((team) => team.teamIndex === placement);
if (!champion) return { match: featuredMatch, teams: [] };
const participants = new Map(
match.participants.map((participant) => [
participant.userId.toString(),
participant,
]),
);
return {
match: featuredMatch,
teams: [
{
name: champion.name.trim() || `${champion.teamIndex}팀`,
captainUserId: champion.captainUserId?.toString() as
| UserId
| undefined,
members: champion.members.map((member) => {
const userId = member.userId.toString() as UserId;
const participant = participants.get(userId);
return {
userId,
position: member.assignedPosition,
gameName: participant?.gameName,
tagLine: participant?.tagLine,
profileIconId: participant?.profileIconId,
};
}),
},
],
};
}
public async getEventProgress(matches: readonly MatchDocument[]) {
const teamBuilding = matches.filter(
(match) => match.status === 'team-built',
);
const byMatchId = new Map<string, MatchEventStage>();
if (teamBuilding.length > 0) {
const AuctionModel = await this.connectionService.getModel('auction');
const auctions = await AuctionModel.find({
matchId: { $in: teamBuilding.map(({ _id }) => _id) },
})
.select({
matchId: 1,
phase: 1,
auctionLifecycleId: 1,
startupCompleted: 1,
matchSideEffectStatus: 1,
})
.lean()
.exec();
for (const auction of auctions) {
const match = teamBuilding.find(({ _id }) =>
_id.equals(auction.matchId),
);
if (
!match ||
(auction.auctionLifecycleId &&
auction.auctionLifecycleId ===
match.lastCancelledAuctionLifecycleId)
)
continue;
if (
auction.matchSideEffectStatus === 'failed' ||
auction.startupCompleted === false ||
(auction.phase === 'complete' &&
(auction.matchSideEffectStatus === 'pending' ||
auction.matchSideEffectStatus === 'processing'))
) {
byMatchId.set(match._id.toString(), 'team-check');
} else if (auction.phase !== 'complete') {
byMatchId.set(match._id.toString(), 'auction');
}
}
}
return new Map(
matches.map((match) => {
const id = match._id.toString();
const stage: MatchEventStage =
match.status !== 'team-built'
? match.status
: (byMatchId.get(id) ??
(match.teams.length >= 2 &&
(match.competitionId || match.teamBuiltAt)
? 'team-ready'
: 'team-check'));
return [id, { stage }] as const;
}),
);
}
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
if (match.shortCode) return match;
@@ -232,6 +493,14 @@ export class MatchService {
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
}
if (
previousStatus !== 'recruiting' &&
'doubleEliminationGrandFinalGameCount' in params.patch
) {
throw new BadRequestException(
'Grand final game count can only be changed while recruiting.',
);
}
const patchToSet =
previousStatus === 'recruiting'
? this.normalizeMatchConfig({
@@ -246,6 +515,10 @@ export class MatchService {
params.patch.doubleEliminationResetFinalEnabled ??
params.patch.doubleElimination?.resetFinalEnabled ??
match.doubleElimination?.resetFinalEnabled,
doubleEliminationGrandFinalGameCount:
params.patch.doubleEliminationGrandFinalGameCount ??
params.patch.doubleElimination?.grandFinalGameCount ??
match.doubleElimination?.grandFinalGameCount,
})
: this.stripMatchConfigInput(params.patch);
match.set(patchToSet);
@@ -360,6 +633,9 @@ export class MatchService {
input.doubleEliminationResetFinalEnabled ??
input.doubleElimination?.resetFinalEnabled ??
false,
grandFinalGameCount:
input.doubleEliminationGrandFinalGameCount ??
input.doubleElimination?.grandFinalGameCount,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
@@ -381,6 +657,7 @@ export class MatchService {
>(input: T): Partial<Match> {
const patch = { ...input };
delete patch.doubleEliminationResetFinalEnabled;
delete patch.doubleEliminationGrandFinalGameCount;
return patch;
}
@@ -649,6 +926,27 @@ export class MatchService {
communityId: query.communityId,
};
if (query.status) filter.status = query.status;
if (query.view === 'history') filter.status = 'finished';
if (query.view === 'upcoming') {
filter.status = 'recruiting';
filter.scheduledAt = { $gte: query.asOf ?? new Date() };
}
if (query.view === 'active') {
filter.$or = [
{ status: { $in: ['team-built', 'in-progress'] } },
{
status: 'recruiting',
scheduledAt: { $lt: query.asOf ?? new Date() },
},
];
}
if (query.eventType) {
// MongoDB matches missing fields as well as explicit null values.
filter.eventType =
query.eventType === 'inhouse'
? { $in: ['inhouse', null] }
: query.eventType;
}
if (query.scheduledFrom || query.scheduledTo) {
filter.scheduledAt = {};
if (query.scheduledFrom) filter.scheduledAt.$gte = query.scheduledFrom;
@@ -657,8 +955,12 @@ export class MatchService {
return filter;
}
private buildListSort(sort?: 'asc' | 'desc'): { scheduledAt: 1 | -1 } {
return { scheduledAt: sort === 'asc' ? 1 : -1 };
private buildListSort(sort?: 'asc' | 'desc'): {
scheduledAt: 1 | -1;
_id: 1 | -1;
} {
const direction = sort === 'asc' ? 1 : -1;
return { scheduledAt: direction, _id: direction };
}
private normalizeListLimit(limit?: number): number {
@@ -0,0 +1,191 @@
import { Test } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import { RedisService } from '../global/redis/redis.service';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { RiotModule } from './riot.module';
import { RiotRecentMatchesService } from './riot-recent-matches.service';
import type { RiotMatchDto } from './riot.types';
const detail = {
metadata: { matchId: 'KR_1', participants: [] },
info: { participants: [], teams: [], queueId: 420 },
} as unknown as RiotMatchDto;
describe('Riot raw persistence recovery hooks', () => {
it('resolves the Riot and community stats providers without external connections', async () => {
const external = new Set<unknown>([
ConnectionService,
RedisService,
DistributedLockService,
ConfigService,
]);
const module = await Test.createTestingModule({ imports: [RiotModule] })
.useMocker((token) => (external.has(token) ? {} : undefined))
.compile();
expect(module.get(RiotRecentMatchesService)).toBeInstanceOf(
RiotRecentMatchesService,
);
expect(module.get(CommunityStatsService)).toBeInstanceOf(
CommunityStatsService,
);
await module.close();
});
it.each([
['legacy', false],
['legacy', true],
['tournament', false],
['tournament', true],
] as const)(
'returns saved %s raw data even if stats recovery fails (%s), without retrying stored raw',
async (kind, recoveryFails) => {
let stored: { raw: RiotMatchDto } | null = null;
const events: string[] = [];
const updateOne = jest.fn(() => ({
exec: async () => {
stored = { raw: detail };
events.push('save');
},
}));
const connection = {
getModel: async () => ({
findOne: () => ({ exec: async () => stored }),
updateOne,
}),
};
const getMatch = jest.fn().mockResolvedValue(detail);
const refreshForRiotMatches = jest.fn(async () => {
expect(stored?.raw).toBe(detail);
events.push('refresh');
if (recoveryFails) throw new Error('Stats unavailable');
});
const stats = { refreshForRiotMatches };
const service =
kind === 'legacy'
? new LegacyImportService(
connection as never,
{} as never,
{ getMatch } as never,
stats as never,
{} as never,
{} as never,
{} as never,
{} as never,
)
: new TournamentResultService(
connection as never,
{ getMatch } as never,
{} as never,
stats as never,
{} as never,
{} as never,
{} as never,
{} as never,
);
const archive = service as unknown as {
ensureRiotMatchPersisted: (
id: string,
region: string,
) => Promise<RiotMatchDto>;
};
expect(await archive.ensureRiotMatchPersisted('KR_1', 'asia')).toBe(
detail,
);
expect(await archive.ensureRiotMatchPersisted('KR_1', 'asia')).toBe(
detail,
);
expect(events).toEqual(['save', 'refresh']);
expect(getMatch).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledWith(['KR_1']);
},
);
it.each([false, true])(
'refreshes only newly fetched recent matches and tolerates recovery failure (%s)',
async (recoveryFails) => {
const stored = new Map<string, { matchId: string; raw: RiotMatchDto }>([
['KR_2', { matchId: 'KR_2', raw: detail }],
]);
const refreshForRiotMatches = jest.fn(async () => {
expect(stored.has('KR_1')).toBe(true);
if (recoveryFails) throw new Error('Stats unavailable');
});
const getMatch = jest.fn().mockResolvedValue(detail);
const service = new RiotRecentMatchesService(
{
getModel: async () => ({
find: () => query([...stored.values()]),
updateOne: () => ({
exec: async () => {
stored.set('KR_1', { matchId: 'KR_1', raw: detail });
},
}),
}),
} as never,
{ getMatchIdsByPuuid: async () => ['KR_1'], getMatch } as never,
{
runWithLock: async (
_options: unknown,
operation: () => Promise<unknown>,
) => operation(),
} as never,
{ refreshForRiotMatches } as never,
);
await service.syncRecentMatches({ puuid: 'player' });
await service.syncRecentMatches({ puuid: 'player' });
expect(getMatch).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledTimes(1);
expect(refreshForRiotMatches).toHaveBeenCalledWith(['KR_1']);
},
);
it('skips stats recovery for duplicate legacy import facts', async () => {
const refreshForRiotMatches = jest.fn();
const service = new LegacyImportService(
{ getModel: async () => ({ exists: async () => true }) } as never,
{} as never,
{} as never,
{ refreshForRiotMatches } as never,
{} as never,
{
runWithLock: async (
_options: unknown,
operation: () => Promise<unknown>,
) => operation(),
} as never,
{} as never,
{} as never,
);
const importer = service as unknown as {
importSingleMatch: (
id: string,
job: unknown,
users: unknown,
) => Promise<string>;
};
expect(await importer.importSingleMatch('KR_1', {}, {})).toBe('duplicate');
expect(refreshForRiotMatches).not.toHaveBeenCalled();
});
});
function query<T>(value: T) {
return {
select() {
return this;
},
lean() {
return this;
},
sort() {
return this;
},
limit() {
return this;
},
exec: async () => value,
};
}
@@ -0,0 +1,28 @@
import type { RiotMatchParticipantDto } from './riot.types';
export function readMultiKills(participant?: RiotMatchParticipantDto) {
if (!participant) return undefined;
const count = (key: string) => {
const value = participant[key];
return typeof value === 'number' && Number.isInteger(value) && value > 0
? value
: 0;
};
const doubleKills = count('doubleKills');
const tripleKills = count('tripleKills');
const quadraKills = count('quadraKills');
const pentaKills = count('pentaKills');
const largestMultiKill = Math.max(
count('largestMultiKill'),
pentaKills ? 5 : quadraKills ? 4 : tripleKills ? 3 : doubleKills ? 2 : 0,
);
return {
doubleKills,
tripleKills,
quadraKills,
pentaKills,
largestMultiKill,
};
}
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import type {
RiotMatchDocument,
RiotMatch as StoredRiotMatch,
@@ -23,6 +24,7 @@ export class RiotRecentMatchesService {
private readonly connectionService: ConnectionService,
private readonly matchService: RiotMatchService,
private readonly distributedLockService: DistributedLockService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async syncRecentMatches(params: {
@@ -34,6 +36,7 @@ export class RiotRecentMatchesService {
const region = params.region ?? DEFAULT_REGION;
const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT;
const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID;
const savedMatchIds = new Set<string>();
const result = await this.distributedLockService.runWithLock(
{
lockKey: `distributed-lock:riot-recent-matches:sync:puuid:${params.puuid}`,
@@ -57,6 +60,7 @@ export class RiotRecentMatchesService {
await this.connectionService.getModel('riotMatch');
const existingMatches = await RiotMatchModel.find({
matchId: { $in: matchIds },
'raw.info': { $exists: true },
})
.select({ matchId: 1 })
.lean()
@@ -94,9 +98,10 @@ export class RiotRecentMatchesService {
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ $set: payload },
{ upsert: true },
).exec();
savedMatchIds.add(dto.metadata.matchId);
} catch (error: unknown) {
this.logger.warn(
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
@@ -111,7 +116,19 @@ export class RiotRecentMatchesService {
},
);
return result ?? this.loadFromDb({ puuid: params.puuid, limit, queueId });
const matches =
result ??
(await this.loadFromDb({ puuid: params.puuid, limit, queueId }));
if (savedMatchIds.size > 0) {
await this.communityStatsService
.refreshForRiotMatches([...savedMatchIds])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after recent match sync: ${String(error)}`,
);
});
}
return matches;
}
public async ensureFreshForQueue(params: {
+3 -2
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { SecretModule } from '../global/secret/secret.module';
import { RiotAccountEnrichmentService } from './riot-account-enrichment.service';
import { RiotAccountService } from './riot-account.service';
@@ -15,7 +16,7 @@ import { RiotSummonerService } from './riot-summoner.service';
import { RiotWebhookController } from './riot-webhook.controller';
@Module({
imports: [SecretModule],
imports: [SecretModule, forwardRef(() => CommunityStatsModule)],
controllers: [RiotWebhookController, RiotDdragonController],
providers: [
RiotRateLimiterService,
@@ -540,7 +540,7 @@ export class TournamentCodeService {
): Promise<MatchDocument[]> {
const MatchModel = await this.connectionService.getModel('match');
const filter: {
status: { $in: string[] };
status: { $in: MatchDocument['status'][] };
communityId?: mongoose.Types.ObjectId;
} = {
status: { $in: ['team-built', 'in-progress'] },
@@ -975,6 +975,7 @@ export class TournamentCodeService {
shuffledTeamIndexes,
{
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
grandFinalGameCount: match.doubleElimination?.grandFinalGameCount,
winnerBracketGameCount:
match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
},
@@ -243,7 +243,7 @@ export class CompetitionOutboxProcessor
function leaseFilter(event: ClaimedOutboxEvent) {
return {
_id: event._id,
state: 'pending',
state: 'pending' as const,
attemptCount: event.attemptCount,
};
}
@@ -203,7 +203,10 @@ describe('TournamentResultService Competition cutover', () => {
connectionService as never,
{ getMatch: jest.fn().mockResolvedValue(detail) } as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as never,
{
runWithLock: jest.fn(),
runWithRenewedLock: jest.fn(),
@@ -312,7 +312,10 @@ function pollHarness(params: {
connectionService as never,
riotMatchService as never,
riotJobQueueService as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as never,
distributedLockService as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never,
@@ -717,7 +717,9 @@ export class TournamentResultService {
const stored = await RiotMatchModel.findOne({
matchId: riotMatchId,
}).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
if (isRiotMatchDto(stored?.raw)) {
return stored.raw;
}
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
@@ -732,9 +734,16 @@ export class TournamentResultService {
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ $set: payload },
{ upsert: true },
).exec();
await this.communityStatsService
.refreshForRiotMatches([dto.metadata.matchId])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after saving ${dto.metadata.matchId}: ${errorMessage(error)}`,
);
});
return dto;
}
@@ -1,3 +1,4 @@
import os from 'node:os';
import mongoose from 'mongoose';
import { AuctionService } from '../src/modules/auction/auction.service';
import { AuctionDurabilityScheduler } from '../src/modules/auction/auction-durability.scheduler';
@@ -16,7 +17,7 @@ import {
} from '../src/modules/global/database/schema';
let connection: mongoose.Connection;
let models: Record<string, mongoose.Model<any>>;
let models: ReturnType<typeof createModels>;
const redis = {
acquireTokenLock: async () => true,
releaseTokenLock: async () => true,
@@ -27,19 +28,8 @@ const redis = {
}),
};
beforeAll(async () => {
if (
process.env.MONGO_TEST_ISOLATED !== '1' ||
!process.env.MONGO_TEST_URL?.startsWith('mongodb://127.0.0.1:')
)
throw new Error('Use test:mongodb with an isolated local replica set.');
connection = await mongoose
.createConnection(process.env.MONGO_TEST_URL, {
autoIndex: false,
autoCreate: false,
})
.asPromise();
models = {
function createModels(connection: mongoose.Connection) {
return {
match: connection.model('match', MatchSchema),
auction: connection.model('auction', AuctionSchema),
auctionHistory: connection.model(
@@ -56,12 +46,29 @@ beforeAll(async () => {
AuctionBidRecordSchema,
),
};
}
beforeAll(async () => {
if (
process.env.MONGO_TEST_ISOLATED !== '1' ||
!process.env.MONGO_TEST_URL?.startsWith('mongodb://127.0.0.1:')
)
throw new Error('Use test:mongodb with an isolated local replica set.');
connection = await mongoose
.createConnection(process.env.MONGO_TEST_URL, {
autoIndex: false,
autoCreate: false,
// NODE-7832: the driver's default OS adapter breaks the Jest handshake.
runtimeAdapters: { os },
})
.asPromise();
models = createModels(connection);
await Promise.all(
Object.values(models).map((model) => model.createCollection()),
);
});
beforeEach(async () => {
await Promise.all(Object.values(models).map((model) => model.deleteMany({})));
await Promise.all(Object.values(models).map((model) => model.deleteMany()));
});
afterEach(() => jest.restoreAllMocks());
afterAll(async () => {
@@ -84,7 +91,6 @@ async function fixture(reserved: boolean) {
participants: [],
tournamentCodeIds: reserved ? [codeId] : [],
gameSchedule: [],
__v: 0,
});
await models.auction.collection.insertOne({
_id: auctionId,
@@ -104,7 +110,7 @@ async function fixture(reserved: boolean) {
matchId,
});
const database = {
getModel: async (name: string) => models[name],
getModel: async (name: keyof typeof models) => models[name],
createSession: () => connection.startSession(),
};
const codes = new TournamentCodeService(database as never, redis as never);
@@ -611,10 +617,7 @@ it('reads an uncommitted Match in the provided session when cancelling polling b
{ session },
);
expect(await models.match.findById(created._id)).toBeNull();
await f.results.cancelPolling(
created._id as mongoose.Types.ObjectId,
session,
);
await f.results.cancelPolling(created._id, session);
expect(
await models.match.findById(created._id).session(session),
).not.toBeNull();
@@ -0,0 +1 @@
* text eol=lf
+1
View File
@@ -0,0 +1 @@
results/
+13
View File
@@ -0,0 +1,13 @@
FROM node:26-bookworm-slim
RUN npm install --global pnpm@10.4.1
WORKDIR /workspace
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY packages/contracts ./packages/contracts
COPY apps/api/package.json ./apps/api/package.json
COPY apps/web/package.json ./apps/web/package.json
RUN pnpm install --frozen-lockfile --filter api --filter web --ignore-scripts
COPY apps/api ./apps/api
COPY apps/web/src/api ./apps/web/src/api
WORKDIR /workspace/apps/api
ENV NODE_ENV=test NEW_RELIC_ENABLED=false
CMD ["node", "-r", "ts-node/register/transpile-only", "test/auction-cluster/node.ts"]
@@ -0,0 +1,61 @@
x-app: &app
image: ${COMPOSE_PROJECT_NAME}-app
build:
context: ../../../..
dockerfile: apps/api/test/auction-cluster/Dockerfile
environment: &environment
MONGO_TEST_URL: mongodb://mongo:27017/auction_cluster?replicaSet=auction_cluster
REDIS_TEST_URL: redis://redis-proxy:6379
NODE_ENV: test
NEW_RELIC_ENABLED: 'false'
volumes:
- ./results:/results
networks: [cluster]
mem_limit: 1g
services:
redis:
image: redis:8-alpine
command: [redis-server, --save, '', --appendonly, 'no']
networks: [cluster]
mem_limit: 256m
mongo:
# MongoDB 8+ refuses the test host's Linux 7.0.0 kernel (SERVER-121912).
image: ${MONGO_TEST_IMAGE:-mongo:7.0}
command:
[
mongod,
--replSet,
auction_cluster,
--bind_ip_all,
--wiredTigerCacheSizeGB,
'0.25',
]
networks: [cluster]
mem_limit: 768m
redis-proxy:
<<: *app
command: [node, test/auction-cluster/fault-proxy.mjs]
mem_limit: 128m
api-a:
<<: *app
environment:
<<: *environment
CLUSTER_NODE: api-a
api-b:
<<: *app
environment:
<<: *environment
CLUSTER_NODE: api-b
lb:
image: nginx:stable-alpine
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
networks: [cluster]
mem_limit: 128m
runner:
<<: *app
command: [node, test/auction-cluster/run.mjs, verify]
networks:
cluster: {}
@@ -0,0 +1,60 @@
import { createServer as createTcpServer, connect } from 'node:net';
import { createServer as createHttpServer } from 'node:http';
// Real TCP connections; only connections issuing SUBSCRIBE/PSUBSCRIBE are cut.
// Redis commands, TIME and PUBLISH continue through the same proxy.
let blocked = false;
let dropped = 0;
const connections = new Set();
createTcpServer((socket) => {
const upstream = connect(6379, 'redis');
const connection = { socket, upstream, subscriber: false, prefix: '' };
connections.add(connection);
const close = () => {
socket.destroy();
upstream.destroy();
connections.delete(connection);
};
socket.on('error', close);
upstream.on('error', close);
socket.on('close', close);
upstream.on('close', close);
socket.on('data', (chunk) => {
connection.prefix = (connection.prefix + chunk.toString('utf8')).slice(
-4096,
);
if (/\r\n(?:p?subscribe|ssubscribe)\r\n/i.test(connection.prefix)) {
connection.subscriber = true;
}
if (blocked && connection.subscriber) {
dropped += 1;
close();
} else upstream.write(chunk);
});
upstream.on('data', (chunk) => socket.write(chunk));
}).listen(6379, '0.0.0.0');
createHttpServer((request, response) => {
if (request.method === 'POST' && request.url === '/block') {
blocked = true;
for (const connection of connections) {
if (!connection.subscriber) continue;
dropped += 1;
connection.socket.destroy();
connection.upstream.destroy();
}
} else if (request.method === 'POST' && request.url === '/restore') {
blocked = false;
} else if (request.url !== '/status') {
response.writeHead(404).end();
return;
}
response.setHeader('content-type', 'application/json');
response.end(
JSON.stringify({
blocked,
dropped,
subscribers: [...connections].filter((c) => c.subscriber).length,
}),
);
}).listen(8081, '0.0.0.0');
+18
View File
@@ -0,0 +1,18 @@
events {}
http {
upstream auction {
server api-a:3000;
server api-b:3000;
}
server {
listen 8080;
location / {
proxy_pass http://auction;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 120s;
add_header X-Cluster-Upstream $upstream_addr always;
}
}
}
+203
View File
@@ -0,0 +1,203 @@
import 'reflect-metadata';
import { readFile } from 'node:fs/promises';
import { Body, Controller, Get, Module, Post } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { createClient } from 'redis';
import type { Namespace } from 'socket.io';
import { RedisIoAdapter } from '../../src/redis-io.adapter';
import { AuctionController } from '../../src/modules/auction/auction.controller';
import { AuctionGateway } from '../../src/modules/auction/auction.gateway';
import { AuctionEventBusService } from '../../src/modules/auction/auction-event-bus.service';
import { AuctionService } from '../../src/modules/auction/auction.service';
import { AuctionBidArchiveService } from '../../src/modules/auction/auction-bid-archive.service';
import {
AuctionDurabilityScheduler,
type AuctionDurabilityPayload,
} from '../../src/modules/auction/auction-durability.scheduler';
import { AuctionRedisService } from '../../src/modules/auction/redis/auction-redis.service';
import { AuctionRedisCommandService } from '../../src/modules/auction/redis/auction-redis-command.service';
import { AuctionRedisStateReaderService } from '../../src/modules/auction/redis/auction-redis-state-reader.service';
import { AuthService } from '../../src/modules/auth/auth.service';
import { JwtService } from '../../src/modules/auth/jwt.service';
import { IdentityService } from '../../src/modules/auth/identity.service';
import { ConnectionService } from '../../src/modules/global/database/connection.service';
import {
AuctionSchema,
AuctionHistoryEntrySchema,
AuctionSideEffectApplicationSchema,
MatchSchema,
} from '../../src/modules/global/database/schema';
async function bootstrap() {
if (
!process.env.MONGO_TEST_URL?.startsWith(
'mongodb://mongo:27017/auction_cluster?',
) ||
process.env.REDIS_TEST_URL !== 'redis://redis-proxy:6379'
) {
throw new Error(
'This test node only accepts the isolated Compose services.',
);
}
const fixture = JSON.parse(
await readFile('/results/fixture.json', 'utf8'),
) as { communityId: string };
const connection = await mongoose
.createConnection(process.env.MONGO_TEST_URL, { autoIndex: false })
.asPromise();
const models = {
match: connection.model('match', MatchSchema),
auction: connection.model('auction', AuctionSchema),
auctionHistory: connection.model(
'auctionHistory',
AuctionHistoryEntrySchema,
),
auctionSideEffectApplication: connection.model(
'auctionSideEffectApplication',
AuctionSideEffectApplicationSchema,
),
};
let releaseCommit: (() => void) | undefined;
let commitGate: Promise<void> | undefined;
let commitsWaiting = 0;
const database = {
getModel: async (name: keyof typeof models) => {
if (!models[name]) throw new Error(`Unexpected test model: ${name}`);
return models[name];
},
createSession: async () => {
const session = await connection.startSession();
const commit = session.commitTransaction.bind(session);
session.commitTransaction = async () => {
if (commitGate) {
commitsWaiting += 1;
await commitGate;
commitsWaiting -= 1;
}
await commit();
};
return session;
},
};
const client = createClient({ url: process.env.REDIS_TEST_URL });
client.on('error', (error) =>
console.error('command-client:', error.message),
);
await client.connect();
const redis = new AuctionRedisService(client);
const commands = new AuctionRedisCommandService(redis);
const reader = new AuctionRedisStateReaderService(redis);
const bus = new AuctionEventBusService();
const service = new AuctionService(
database as never,
{} as never,
{} as never,
{} as never,
redis,
commands,
reader,
bus,
);
// Explicit draining lets the test hold real Mongo commits and reorder durable
// payloads; no in-memory database or fake Redis adapter is involved.
const scheduler = new AuctionDurabilityScheduler(
database as never,
redis,
undefined,
undefined,
undefined,
bus,
reader,
service,
);
@Controller('_cluster')
class ControlController {
@Get('health') health() {
const namespace = Reflect.get(gateway, 'server') as Namespace;
return {
node: process.env.CLUSTER_NODE,
sockets: [...namespace.sockets.keys()],
pid: process.pid,
commitsWaiting,
};
}
@Post('hold-commit') hold() {
if (commitGate) throw new Error('Commit already held');
commitGate = new Promise<void>((resolve) => {
releaseCommit = resolve;
});
return { held: true };
}
@Post('release-commit') release() {
releaseCommit?.();
commitGate = undefined;
releaseCommit = undefined;
return { released: true };
}
@Post('drain') drain() {
return scheduler.processDueDurabilityPayloads(100);
}
@Post('apply') async apply(@Body() payload: AuctionDurabilityPayload) {
await scheduler.applyDurabilityPayload(payload);
return { applied: true };
}
}
@Module({
controllers: [AuctionController, ControlController],
providers: [
AuctionGateway,
{ provide: AuctionService, useValue: service },
{ provide: ConnectionService, useValue: database },
{ provide: AuctionRedisService, useValue: redis },
{ provide: AuctionEventBusService, useValue: bus },
{ provide: AuctionBidArchiveService, useValue: {} },
{
provide: AuthService,
useValue: { resolveDevUserById: async () => null },
},
{ provide: JwtService, useValue: {} },
{ provide: IdentityService, useValue: {} },
],
})
class TestModule {}
const app = await NestFactory.create(TestModule, {
logger: ['error', 'warn'],
});
// Identity-provider authentication is outside this transport/durability test.
// The real controller's RolesGuard still checks this isolated fixture admin.
app.use(
(
request: { user?: unknown },
response: { setHeader(name: string, value: string): void },
next: () => void,
) => {
request.user = {
role: 'admin',
communityId: new mongoose.Types.ObjectId(fixture.communityId),
};
response.setHeader(
'X-Cluster-Node',
process.env.CLUSTER_NODE ?? 'unknown',
);
next();
},
);
const adapter = new RedisIoAdapter(app);
await adapter.connectToRedis();
app.useWebSocketAdapter(adapter);
const gateway = app.get(AuctionGateway);
await app.listen(3000, '0.0.0.0');
console.log(`cluster node ready: ${process.env.CLUSTER_NODE}`);
process.on('SIGTERM', () => {
void app
.close()
.then(() => connection.close())
.then(() => process.exit(0));
});
}
void bootstrap().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
+641
View File
@@ -0,0 +1,641 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFile, writeFile } from 'node:fs/promises';
import { request } from 'node:http';
import { setTimeout as delay } from 'node:timers/promises';
import { randomUUID } from 'node:crypto';
import mongoose from 'mongoose';
import { createClient } from 'redis';
const require = createRequire(import.meta.url);
require('ts-node/register/transpile-only');
const {
AuctionRedisService,
} = require('../../src/modules/auction/redis/auction-redis.service.ts');
const {
AuctionRedisCommandService,
} = require('../../src/modules/auction/redis/auction-redis-command.service.ts');
const {
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
} = require('../../src/modules/auction/redis/auction-redis.keys.ts');
const {
MatchSchema,
AuctionSchema,
AuctionHistoryEntrySchema,
AuctionSideEffectApplicationSchema,
} = require('../../src/modules/global/database/schema.ts');
const webRequire = createRequire(
new URL('../../../web/package.json', import.meta.url),
);
const { io } = webRequire('socket.io-client');
const { QueryClient, QueryObserver, environmentManager } = webRequire(
'@tanstack/react-query',
);
const {
createAuctionHeartbeatMonitor,
shouldApplyPolledAuctionState,
mergeAuctionState,
} = await import('../../../web/src/api/auction-state.ts');
const { createAuctionResyncRequester } =
await import('../../../web/src/api/auction-resync.ts');
const { AUCTION_SAFETY_POLL_INTERVAL_MS } =
await import('../../../web/src/api/auction-polling.ts');
if (
process.env.REDIS_TEST_URL !== 'redis://redis-proxy:6379' ||
!process.env.MONGO_TEST_URL?.startsWith(
'mongodb://mongo:27017/auction_cluster?',
)
) {
throw new Error('Only the isolated Compose services are allowed.');
}
const redis = createClient({ url: 'redis://redis:6379' });
redis.on('error', () => {});
await redis.connect();
const cleanup = [() => (redis.isOpen ? redis.quit() : undefined)];
const report = {
startedAt: new Date().toISOString(),
checks: [],
requests: [],
limitation:
'Real API processes, Nginx, Redis TCP faults and Mongo transactions; fixture identity replaces the external login provider. Client recovery uses production helpers and QueryObserver, without rendering the React page.',
};
async function until(check, description, timeout = 15_000) {
const deadline = Date.now() + timeout;
let lastError;
while (Date.now() < deadline) {
try {
const value = await check();
if (value) return value;
} catch (error) {
lastError = error;
}
await delay(50);
}
throw new Error(
`Timed out: ${description}${lastError ? `: ${lastError.message}` : ''}`,
);
}
async function http(url, body) {
const started = Date.now();
return new Promise((resolve, reject) => {
const req = request(
url,
{
method: body === undefined ? 'GET' : 'POST',
agent: false,
headers: { 'content-type': 'application/json' },
},
(res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
report.requests.push({
url,
node: res.headers['x-cluster-node'],
status: res.statusCode,
durationMS: Date.now() - started,
});
if (res.statusCode < 200 || res.statusCode >= 300)
return reject(new Error(`${url}: ${res.statusCode} ${data}`));
try {
resolve({
body: JSON.parse(data),
node: res.headers['x-cluster-node'],
});
} catch (error) {
reject(error);
}
});
},
);
req.setTimeout(10_000, () =>
req.destroy(new Error(`HTTP timeout: ${url}`)),
);
req.on('error', reject);
req.end(body === undefined ? undefined : JSON.stringify(body));
});
}
const pass = (name, details = {}) => {
report.checks.push({ name, passed: true, ...details });
console.log(`PASS ${name} ${JSON.stringify(details)}`);
};
async function initialize() {
const admin = new mongoose.mongo.MongoClient(
'mongodb://mongo:27017/?directConnection=true',
{ serverSelectionTimeoutMS: 1000 },
);
await until(
async () => {
await admin.connect();
return true;
},
'Mongo startup',
60_000,
);
await admin.db('admin').command({
replSetInitiate: {
_id: 'auction_cluster',
members: [{ _id: 0, host: 'mongo:27017' }],
},
});
await until(
async () =>
(await admin.db('admin').command({ hello: 1 })).isWritablePrimary,
'Mongo primary',
60_000,
);
const build = await admin.db('admin').command({ buildInfo: 1 });
await admin.close();
const connection = await mongoose
.createConnection(process.env.MONGO_TEST_URL, { autoIndex: false })
.asPromise();
try {
const models = {
match: connection.model('match', MatchSchema),
auction: connection.model('auction', AuctionSchema),
history: connection.model('auctionHistory', AuctionHistoryEntrySchema),
sideEffects: connection.model(
'auctionSideEffectApplication',
AuctionSideEffectApplicationSchema,
),
};
await Promise.all(
Object.values(models).map((model) => model.createCollection()),
);
await models.history.createIndexes();
const matchId = new mongoose.Types.ObjectId(),
communityId = new mongoose.Types.ObjectId(),
auctionId = new mongoose.Types.ObjectId();
const lifecycle = `cluster:${matchId}`;
const playerA = new mongoose.Types.ObjectId(),
playerB = new mongoose.Types.ObjectId(),
captain = new mongoose.Types.ObjectId();
const structure = {
auctionPlayerOrder: [
{ userId: playerA.toString() },
{ userId: playerB.toString() },
],
auctionTeams: [
{
teamIndex: 1,
captainUserId: captain.toString(),
remainingBidPointAmount: 1000,
members: [],
},
],
currentAuctionPlayerOrderIndex: 0,
currentAuctionRound: 1,
passedAuctionPlayerQueue: [],
maximumBidRoundDurationSeconds: 600,
bidRoundExtensionSeconds: 5,
initialTeamBidPointAmount: 1000,
topTierAuctionPriorityThreshold: 'NONE',
manualTopTierAuctionPriorityUserIds: [],
};
await models.match.collection.insertOne({
_id: matchId,
communityId,
title: 'Isolated cluster test',
participants: [],
teams: [],
status: 'team-building',
scheduledAt: new Date(),
});
await models.auction.collection.insertOne({
_id: auctionId,
matchId,
auctionEngineVersion: 'redis-v1',
auctionLifecycleId: lifecycle,
phase: 'presenting',
revision: 0,
currentAuctionHistorySequence: 0,
chatMessages: [],
...structure,
});
const commands = new AuctionRedisCommandService(
new AuctionRedisService(redis),
);
await commands.hydrateState(matchId.toString(), {
matchId: matchId.toString(),
auctionLifecycleId: lifecycle,
phase: 'presenting',
revision: 0,
auctionHistorySequence: 0,
maximumBidRoundDurationSeconds: 600,
structureStateJson: JSON.stringify(structure),
liveStatePatch: {
currentAuctionPlayerOrderIndex: 0,
currentBidRoundPlayerUserId: playerA.toString(),
currentBidRoundId: 'initial',
currentHighestBidPointAmount: 0,
currentHighestBidderTeamIndex: -1,
maximumBidRoundDurationSeconds: 600,
bidRoundExtensionSeconds: 5,
'team:1:captainUserId': captain.toString(),
'team:1:remainingBidPointAmount': 1000,
'team:1:assignedAuctionTeamMemberCount': 1,
},
});
const fixture = {
matchId: matchId.toString(),
communityId: communityId.toString(),
auctionId: auctionId.toString(),
lifecycle,
mongoVersion: build.version,
redisVersion: (await redis.info('server')).match(
/redis_version:([^\r\n]+)/,
)?.[1],
};
await writeFile('/results/fixture.json', JSON.stringify(fixture, null, 2));
console.log(
`Initialized isolated MongoDB ${build.version} and Redis ${fixture.redisVersion}`,
);
} finally {
await connection.close();
}
}
async function verify() {
const fixture = JSON.parse(await readFile('/results/fixture.json', 'utf8'));
report.versions = {
node: process.version,
mongo: fixture.mongoVersion,
redis: fixture.redisVersion,
};
const route = `/communities/${fixture.communityId}/matches/${fixture.matchId}/auction`;
const url = `http://lb:8080${route}`;
await until(
async () => (await http('http://api-a:3000/_cluster/health')).body.node,
'API A startup',
60_000,
);
await until(
async () => (await http('http://api-b:3000/_cluster/health')).body.node,
'API B startup',
60_000,
);
const routedNodes = new Set();
for (let i = 0; i < 4; i += 1) routedNodes.add((await http(url)).node);
assert.deepEqual([...routedNodes].sort(), ['api-a', 'api-b']);
pass('Nginx routes real HTTP requests to both API processes');
async function connectViewer() {
const socket = io('http://lb:8080/auction', {
transports: ['websocket'],
autoConnect: false,
reconnection: false,
});
const viewer = {
socket,
state: null,
states: [],
histories: [],
errors: [],
};
socket.on('state', (state) => {
viewer.state = state;
viewer.states.push(state);
});
socket.on('error', (error) => viewer.errors.push(error));
socket.on('connect_error', (error) => viewer.errors.push(error.message));
socket.on('history-updated', (event) => {
void http(`${url}/history`)
.then(({ body, node }) => viewer.histories.push({ event, body, node }))
.catch((error) => viewer.errors.push(error.message));
});
cleanup.push(() => socket.disconnect());
socket.connect();
await until(
() => socket.connected,
`socket connect: ${viewer.errors.join(',')}`,
);
const ack = await socket
.timeout(5000)
.emitWithAck('join', { matchId: fixture.matchId });
assert.equal(ack.ok, true);
assert.equal(viewer.state.matchId, fixture.matchId);
assert.equal(viewer.state.auctionEngineVersion, 'redis-v1');
const health = await Promise.all(
['api-a', 'api-b'].map((node) =>
http(`http://${node}:3000/_cluster/health`),
),
);
viewer.node = health.find((entry) =>
entry.body.sockets.includes(socket.id),
).body.node;
return viewer;
}
const one = await connectViewer(),
two = await connectViewer();
assert.notEqual(one.node, two.node);
const a = one.node === 'api-a' ? one : two;
const b = one.node === 'api-b' ? one : two;
const initialRevision = a.state.revision;
const revisionFor = (sequence) => initialRevision + sequence;
assert.equal(b.state.revision, initialRevision);
pass('WebSocket viewers join different nodes through Nginx', {
nodes: [one.node, two.node],
});
const sequences = async () =>
(await http(`${url}/history`)).body.map((entry) => entry.sequence);
const action = async (viewer, name) => {
const ack = await viewer.socket
.timeout(5000)
.emitWithAck(name, { auctionActionRequestId: randomUUID() });
assert.equal(ack.ok, true, JSON.stringify(ack));
};
for (let i = 0; i < 4; i += 1) assert.deepEqual(await sequences(), []);
await action(a, 'open-bidding');
await until(
() =>
a.state.revision === revisionFor(1) &&
b.state.revision === revisionFor(1),
'cross-node full state',
);
assert.equal(a.histories.length + b.histories.length, 0);
await http('http://api-a:3000/_cluster/hold-commit', {});
const pendingDrain = http('http://api-a:3000/_cluster/drain', {});
await until(
async () =>
(await http('http://api-a:3000/_cluster/health')).body.commitsWaiting ===
1,
'real Mongo commit barrier',
);
for (let i = 0; i < 4; i += 1) assert.deepEqual(await sequences(), []);
assert.equal(a.histories.length + b.histories.length, 0);
await http('http://api-a:3000/_cluster/release-commit', {});
assert.equal((await pendingDrain).body.applied, 1);
await until(
() => a.histories.length === 1 && b.histories.length === 1,
'post-commit history event on both nodes',
);
for (const viewer of [a, b])
assert.deepEqual(
viewer.histories[0].body.map((entry) => entry.sequence),
[1],
);
pass(
'History notification crosses nodes only after a real Mongo transaction commits',
);
await action(a, 'passed');
await action(b, 'next');
await until(
() =>
a.state.revision === revisionFor(3) &&
b.state.revision === revisionFor(3),
'state fanout in both directions',
);
const keys = await redis.zRange(AUCTION_DURABILITY_RETRY_QUEUE_KEY, 0, -1);
const queued = await Promise.all(
keys.map(async (key) => ({
key,
payload: JSON.parse(await redis.hGet(key, 'payloadJson')),
})),
);
const third = queued.find(
({ payload }) => payload.auctionHistorySequence === 3,
);
const second = queued.find(
({ payload }) => payload.auctionHistorySequence === 2,
);
assert.ok(third && second);
await http('http://api-b:3000/_cluster/apply', third.payload);
assert.deepEqual(await sequences(), [3, 1]);
const previousEvents = b.histories.length;
await http('http://api-a:3000/_cluster/apply', second.payload);
await until(
() =>
b.histories.length > previousEvents &&
b.histories.at(-1).body.some((entry) => entry.sequence === 2),
'late append history refresh',
);
assert.deepEqual(await sequences(), [3, 2, 1]);
for (const item of queued) {
await redis.zRem(AUCTION_DURABILITY_RETRY_QUEUE_KEY, item.key);
await redis.del(item.key);
}
pass(
'A delayed history append refreshes another node with the same maximum sequence',
{ maximumSequence: 3 },
);
const undo = await http(`${url}/undo`, {
sequence: 1,
auctionActionRequestId: randomUUID(),
});
assert.equal(undo.body.auctionEngineVersion, 'redis-v1');
assert.equal(undo.body.revision, revisionFor(4));
assert.deepEqual(await sequences(), [3, 2, 1]);
await http('http://api-b:3000/_cluster/drain', {});
await until(
async () => JSON.stringify(await sequences()) === '[4,1]',
'durable Undo history',
);
await until(
() => b.histories.at(-1)?.body[0]?.sequence === 4,
'Undo history event',
);
pass('Undo increases sequence and replaces history on every node', {
sequence: 4,
history: [4, 1],
});
await until(
async () =>
(await http('http://redis-proxy:8081/status')).body.subscribers >= 2,
'Redis subscriptions',
);
await http('http://redis-proxy:8081/block', {});
console.log(
'FAULT Pub/Sub TCP connections blocked; Redis commands and HTTP stay available',
);
await delay(500);
assert.equal(
(await http('http://api-a:3000/_cluster/health')).body.node,
'api-a',
);
assert.equal(
(await http('http://api-b:3000/_cluster/health')).body.node,
'api-b',
);
assert.equal(a.socket.connected && b.socket.connected, true);
const timestamp = await b.socket
.timeout(3000)
.emitWithAck('time-sync', { sequence: 1 });
assert.equal(timestamp.ok, true);
pass(
'Both API processes and socket clock sync survive Pub/Sub-only TCP disconnection',
);
environmentManager.setIsServer(() => false);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
});
cleanup.push(() => queryClient.clear());
let stateByHttp = b.state,
historyByHttp,
statePolls = 0,
historyPolls = 0;
const pollingStarted = Date.now();
const stateObserver = new QueryObserver(queryClient, {
queryKey: ['auction', fixture.matchId],
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
queryFn: async () => {
statePolls += 1;
return (await http(url)).body;
},
});
const historyObserver = new QueryObserver(queryClient, {
queryKey: ['auction-history', fixture.matchId],
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
queryFn: async () => {
historyPolls += 1;
return (await http(`${url}/history`)).body;
},
});
cleanup.push(
stateObserver.subscribe((result) => {
if (
result.data &&
shouldApplyPolledAuctionState(stateByHttp, result.data, fixture.matchId)
)
stateByHttp = mergeAuctionState(stateByHttp, result.data);
}),
);
cleanup.push(
historyObserver.subscribe((result) => {
if (result.data) historyByHttp = result.data;
}),
);
await until(
() =>
stateByHttp.revision === revisionFor(4) &&
historyByHttp?.[0]?.sequence === 4,
'baseline HTTP reads',
);
const beforeHistoryEvents = b.histories.length;
await action(a, 'open-bidding');
await http('http://api-a:3000/_cluster/drain', {});
await delay(250);
assert.equal(b.state.revision, revisionFor(4));
assert.equal(b.histories.length, beforeHistoryEvents);
assert.equal(a.state.revision, revisionFor(5));
// Do not run heartbeat recovery yet: verify the independent 30-second safety
// route even if the client identity checker fails to notice a missed event.
console.log(
'WAIT Real 30-second HTTP safety polling with Pub/Sub still blocked',
);
await until(
() =>
stateByHttp.revision === revisionFor(5) &&
historyByHttp?.[0]?.sequence === 5,
'30-second HTTP safety fallback',
35_000,
);
assert.ok(Date.now() - pollingStarted >= 29_000);
pass(
'Real 30-second HTTP polls repair missed state and history through Nginx',
{ elapsedMS: Date.now() - pollingStarted, statePolls, historyPolls },
);
const monitor = createAuctionHeartbeatMonitor();
const heartbeat = async (sequence) => {
const ack = await b.socket
.timeout(3000)
.emitWithAck('time-sync', { sequence });
assert.equal(ack.ok, true);
return monitor.inspect(b.state, ack.auctionState);
};
assert.equal((await heartbeat(2)).needsResync, false);
await delay(10_000);
assert.equal((await heartbeat(3)).needsResync, true);
let resyncs = 0;
const requester = createAuctionResyncRequester(
async () => {
resyncs += 1;
return b.socket.timeout(3000).emitWithAck('resync', {});
},
(state) => {
b.state = state;
},
);
await requester.request(revisionFor(5), fixture.lifecycle);
assert.equal(b.state.revision, revisionFor(5));
assert.equal(resyncs, 1);
pass(
'Two real heartbeats detect a persistent gap and private socket resync works during Pub/Sub outage',
{ resyncs },
);
await http('http://redis-proxy:8081/restore', {});
await until(
async () =>
(await http('http://redis-proxy:8081/status')).body.subscribers >= 2,
'Pub/Sub resubscription',
20_000,
);
await action(a, 'passed');
await http('http://api-a:3000/_cluster/drain', {});
await until(
() =>
b.state.revision === revisionFor(6) &&
b.histories.at(-1)?.body[0]?.sequence === 6,
'events after Pub/Sub restoration',
);
pass(
'Cross-node state and history events recover after restoring the TCP path',
);
const fault = (await http('http://redis-proxy:8081/status')).body;
report.fault = fault;
const previousId = b.socket.id;
b.socket.disconnect();
b.socket.connect();
await until(
() => b.socket.connected && b.socket.id !== previousId,
'socket reconnect through Nginx',
);
assert.equal(
(
await b.socket
.timeout(5000)
.emitWithAck('join', { matchId: fixture.matchId })
).ok,
true,
);
await until(
() => b.state.revision === revisionFor(6),
'reconnect full state',
);
pass('A reconnected viewer receives the latest snapshot through Nginx');
}
try {
if (process.argv[2] === 'init') await initialize();
else {
await verify();
report.passed = true;
}
} catch (error) {
report.passed = false;
report.failure = { message: error.message, stack: error.stack };
console.error(error);
process.exitCode = 1;
} finally {
if (process.argv[2] !== 'init') {
await http('http://redis-proxy:8081/restore', {}).catch(() => {});
report.finishedAt = new Date().toISOString();
await writeFile('/results/report.json', JSON.stringify(report, null, 2));
}
for (const close of cleanup.reverse()) {
try {
await close();
} catch {}
}
}
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# From the repository root: sh apps/api/test/auction-cluster/run.sh
# Requires Docker Compose. No host ports or production credentials are used.
# Results and container logs remain in this directory's ignored results/ folder.
# Authentication uses a fixture admin; client recovery uses the production
# helpers and QueryObserver without rendering React. MongoDB 7 is the default
# for the test host's kernel; set MONGO_TEST_IMAGE on a compatible host to match
# the production database version.
set -eu
cd "$(dirname "$0")"
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-lolympus-auction-cluster-$(date +%s)}"
case "$COMPOSE_PROJECT_NAME" in
lolympus-auction-cluster-*) ;;
*) echo 'Refusing to use a Compose project outside the auction-cluster test prefix.' >&2; exit 1 ;;
esac
mkdir -p results
cleanup() {
docker compose logs --no-color api-a api-b redis-proxy > results/containers.log 2>&1 || true
docker compose down --volumes --remove-orphans
}
trap cleanup EXIT INT TERM
docker compose build runner
docker compose up -d redis mongo redis-proxy
docker compose run --rm runner node test/auction-cluster/run.mjs init
docker compose up -d api-a api-b lb
docker compose run --rm runner node test/auction-cluster/run.mjs verify
@@ -324,7 +324,13 @@ describe('Community Hash response cache', () => {
it('does not share an old in-flight detail request after invalidation or overwrite the fresh response', async () => {
const service = new CommunityStatsService(
{} as never,
{
getModel: async () => ({
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => null }) }),
}),
}),
} as never,
cache,
{} as never,
{} as never,
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>내전 전적 개선 시안 · LOLYMPUS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/design-previews/internal-stats/main.tsx"></script>
</body>
</html>
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>선수 정보 시안 02 · LOLYMPUS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/design-previews/player-information-v2/main.tsx"></script>
</body>
</html>
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>선수 정보 개선 시안 · LOLYMPUS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/design-previews/player-information/main.tsx"></script>
</body>
</html>
+10
View File
@@ -19,5 +19,15 @@ export default defineConfig([
ecmaVersion: 2020,
globals: globals.browser,
},
rules: {
// Product policy: information stays visible; use sections, links and pagination.
'no-restricted-syntax': [
'error',
{
selector: 'JSXOpeningElement[name.name="details"], JSXOpeningElement[name.name="summary"]',
message: 'LOLYMPUS does not use disclosure/accordion UI. Keep content visible in a section, or use a dedicated route for a separate task.',
},
],
},
},
])
+11 -9
View File
@@ -19,10 +19,13 @@
"preview": "vite preview"
},
"dependencies": {
"@astryxdesign/core": "0.7.11",
"@astryxdesign/theme-neutral": "0.7.11",
"@azure/msal-browser": "^5.8.0",
"@azure/msal-react": "^5.3.1",
"@lolympus/contracts": "workspace:*",
"@newrelic/browser-agent": "^1.318.0",
"@newrelic/browser-agent": "^1.324.1",
"@stylexjs/stylex": "0.19.1",
"@tanstack/react-query": "^5.100.1",
"lucide-react": "^1.14.0",
"react": "^19.2.8",
@@ -32,21 +35,20 @@
"socket.io-client": "^4.8.3"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/vite": "^4.2.2",
"@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.3.5",
"@types/node": "^26.1.1",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"daisyui": "^5.5.19",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"@vitejs/plugin-react": "^6.3.0",
"eslint": "^10.14.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"tailwindcss": "^4.2.2",
"tailwindcss": "^4.3.5",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.1.5",
"vite": "^8.3.8",
"wrangler": "^4.114.0"
}
}
-1
View File
@@ -1 +0,0 @@
/* App-specific styles — currently using Tailwind + daisyUI */
+211 -66
View File
@@ -1,10 +1,18 @@
import { BrowserRouter, Link, Route, Routes } from "react-router";
import {
BrowserRouter,
Link,
matchPath,
Navigate,
Route,
Routes,
useLocation,
} from "react-router";
import type { ReactNode } from "react";
import { useMsal } from "@azure/msal-react";
import { Moon, Sun } from "lucide-react";
import { LogOut, Moon, Sun } from "lucide-react";
import DevAuthSwitcher from "./components/DevAuthSwitcher";
import { DEFAULT_COMMUNITY_ID, setTheme, useTheme } from "./config";
import { useCommunity } from "./api/hooks";
import { useCommunity, useMatch, useMe } from "./api/hooks";
import { isMsalConfigured } from "./lib/auth/msal.config";
import AuthCallbackPage from "./pages/AuthCallback";
import HomePage from "./pages/HomePage";
@@ -15,11 +23,18 @@ import MatchTeamProgressPage from "./pages/MatchTeamProgressPage";
import AuctionPage from "./pages/AuctionPage";
import UserHistoryPage from "./pages/UserHistoryPage";
import CommunityInternalStatsPage from "./pages/CommunityInternalStatsPage";
import CommunityInternalPlayerPage from "./pages/CommunityInternalPlayerPage";
import InternalMatchDetailPage from "./pages/InternalMatchDetailPage";
import LegacyImportPage from "./pages/admin/LegacyImportPage";
import LegacyMatchesPage from "./pages/admin/LegacyMatchesPage";
import MatchAdminPage from "./pages/admin/MatchAdminPage";
import TournamentCodesPage from "./pages/admin/TournamentCodesPage";
import { PlainPage, Tooltip, pageWidthClass } from "./ui";
import "./components/app-header.css";
const NAV_ICON_BUTTON_CLASS =
"lts-header-icon-button";
function MsalHeaderActions() {
const { accounts, instance } = useMsal();
@@ -28,7 +43,7 @@ function MsalHeaderActions() {
if (!account) {
return (
<Link
className="btn btn-ghost btn-sm px-2 text-base-content/60 hover:text-base-content"
className="inline-flex h-8 items-center whitespace-nowrap rounded-full border border-line px-3 text-[13px] font-medium text-content-muted transition-colors hover:bg-sunken hover:text-content"
to="/login"
>
로그인
@@ -36,15 +51,24 @@ function MsalHeaderActions() {
);
}
const name = account.name ?? account.username;
return (
<button
type="button"
className="btn btn-ghost btn-sm px-3 max-w-[45vw] sm:max-w-none"
onClick={() => void instance.logoutRedirect()}
>
<span className="truncate">{account.name ?? account.username}</span>
<span className="hidden shrink-0 sm:inline">로그아웃</span>
</button>
<div className="flex min-w-0 items-center gap-1">
<span className="hidden max-w-40 truncate text-sm font-medium text-content-muted lg:block">
{name}
</span>
<Tooltip content="로그아웃" placement="below">
<button
type="button"
className={NAV_ICON_BUTTON_CLASS}
aria-label={`${name} 로그아웃`}
onClick={() => void instance.logoutRedirect()}
>
<LogOut className="size-[18px]" aria-hidden="true" />
</button>
</Tooltip>
</div>
);
}
@@ -56,38 +80,141 @@ function ThemeToggle() {
const Icon = nextTheme === "dark" ? Moon : Sun;
return (
<span className="tooltip tooltip-bottom" data-tip={label}>
<Tooltip content={label} placement="below">
<button
type="button"
className="btn btn-ghost btn-sm btn-square text-base-content/60 hover:text-base-content"
className={`${NAV_ICON_BUTTON_CLASS} lts-header-theme-toggle`}
aria-label={label}
onClick={() => setTheme(nextTheme)}
>
<Icon className="size-4" aria-hidden="true" />
<Icon className="size-[18px]" aria-hidden="true" />
</button>
</span>
</Tooltip>
);
}
function PrimaryNavLink({
to,
sectionPaths = [],
children,
}: {
to: string;
sectionPaths?: string[];
children: ReactNode;
}) {
const { pathname } = useLocation();
const current = matchPath(to, pathname)
? "page"
: sectionPaths.some((pattern) => matchPath(pattern, pathname))
? "location"
: undefined;
return (
<Link
to={to}
aria-current={current}
className="lts-primary-nav-link"
>
{children}
</Link>
);
}
function AppHeader() {
const { pathname } = useLocation();
const matchId = matchPath("/match/:id/*", pathname)?.params.id;
const matchQuery = useMatch(matchId);
const isTournamentMatch = matchQuery.data?.eventType === "tournament";
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const meQuery = useMe();
const communityLabel = communityQuery.data?.name ?? "LOLYMPUS";
const role = meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user?.role;
const canManage = role === "owner" || role === "admin";
const statsPath = `/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`;
const adminPath = `/admin/communities/${DEFAULT_COMMUNITY_ID}`;
return (
<header
className={`lts-app-header${DEFAULT_COMMUNITY_ID ? "" : " lts-app-header--without-nav"}`}
>
<div className="lts-app-header-inner">
<Link
className="lts-header-brand"
to="/"
aria-label={`${communityLabel} 홈`}
>
<span className="lts-header-brand-name">{communityLabel}</span>
<span className="lts-header-brand-tagline">TOURNAMENT</span>
</Link>
{DEFAULT_COMMUNITY_ID && (
<nav aria-label="주 메뉴" className="lts-primary-nav">
<PrimaryNavLink to="/">홈</PrimaryNavLink>
<PrimaryNavLink
to="/inhouse"
sectionPaths={isTournamentMatch ? undefined : ["/match/*"]}
>
내전
</PrimaryNavLink>
<PrimaryNavLink
to="/tournaments"
sectionPaths={isTournamentMatch ? ["/match/*"] : undefined}
>
멸망전
</PrimaryNavLink>
<PrimaryNavLink
to={statsPath}
sectionPaths={[`${statsPath}/*`, "/users/:userId/history"]}
>
전적
</PrimaryNavLink>
{canManage && (
<PrimaryNavLink
to={`${adminPath}/matches`}
sectionPaths={[`${adminPath}/*`]}
>
운영
</PrimaryNavLink>
)}
</nav>
)}
<div className="lts-header-actions">
<ThemeToggle />
{isMsalConfigured && <MsalHeaderActions />}
</div>
</div>
</header>
);
}
function AppFooter() {
return (
<footer className="border-t border-base-content/10 bg-base-100">
<div className="max-w-5xl mx-auto px-4 sm:px-6 py-8 text-xs text-base-content/35">
<nav className="flex items-center gap-4 mb-4 font-semibold text-base-content/45">
<Link to="/terms" className="hover:text-base-content">
<footer className="border-t border-line">
<div
className={`${pageWidthClass("xl")} flex flex-col items-center gap-4 py-10 text-center text-xs text-content-subtle sm:py-12`}
>
<nav
aria-label="정책"
className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2 font-semibold text-content-muted"
>
<Link to="/terms" className="inline-flex min-h-8 items-center hover:text-content">
서비스 이용약관
</Link>
<Link to="/privacy" className="hover:text-base-content">
<Link to="/privacy" className="inline-flex min-h-8 items-center font-bold hover:text-content">
개인정보처리방침
</Link>
</nav>
<p className="leading-relaxed max-w-4xl">
© 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and does not
reflect the views or opinions of Riot Games or anyone officially
involved in producing or managing League of Legends. League of Legends
and Riot Games are trademarks or registered trademarks of Riot Games,
Inc. League of Legends © Riot Games, Inc.
</p>
<div className="w-full max-w-4xl space-y-1 leading-relaxed">
<p className="text-balance">
LOLYMPUS is not endorsed by Riot Games and does not reflect the views
or opinions of Riot Games or anyone officially involved in producing
or managing League of Legends. League of Legends and Riot Games are
trademarks or registered trademarks of Riot Games, Inc. League of
Legends © Riot Games, Inc.
</p>
<p>© 2026 LOLYMPUS.</p>
</div>
</div>
</footer>
);
@@ -101,55 +228,71 @@ function LegalPage({
children: ReactNode;
}) {
return (
<main className="max-w-3xl mx-auto px-4 sm:px-6 py-12">
<Link
to="/"
className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5"
>
← 홈으로
</Link>
<h1 className="text-2xl font-black text-base-content">{title}</h1>
<div className="mt-6 space-y-4 text-sm leading-7 text-base-content/60">
<PlainPage width="md" className="py-12">
<h1 className="text-2xl font-extrabold">{title}</h1>
<div className="lts-panel mt-6 space-y-4 p-6 text-sm leading-7 text-content-muted">
{children}
</div>
</main>
</PlainPage>
);
}
function App() {
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
const communityLabel = communityQuery.data?.name ?? "LOLYMPUS";
function NotFoundPage() {
return (
<PlainPage width="md" className="py-24 text-center">
<p className="tabular text-5xl font-extrabold text-content-disabled">
404
</p>
<h1 className="mt-4 text-xl font-bold">
페이지를 찾을 수 없습니다
</h1>
<p className="mt-2 text-sm text-content-muted">
주소가 바뀌었거나 삭제된 내전일 수 있습니다.
</p>
<Link
to="/inhouse"
className="mt-6 inline-flex h-10 items-center rounded-field bg-primary px-5 text-sm font-bold text-primary-content"
>
내전 목록으로
</Link>
</PlainPage>
);
}
function HomeRoute() {
const { search, hash } = useLocation();
const params = new URLSearchParams(search);
if (params.get("history") === "all") {
params.delete("history");
return (
<Navigate
replace
to={{ pathname: "/inhouse", search: params.toString(), hash }}
/>
);
}
return <HomePage />;
}
function App() {
return (
<BrowserRouter>
<div className="min-h-screen bg-base-100 flex flex-col">
<nav className="bg-base-100 border-b border-base-content/10 sticky top-0 z-50">
<div className="max-w-5xl mx-auto px-4 sm:px-6 flex items-center justify-between h-12">
<Link
className="text-base font-bold tracking-tight text-base-content"
to="/"
>
{communityLabel}
</Link>
<div className="flex items-center gap-3">
{/* {DEFAULT_COMMUNITY_ID ? (
<span className="text-xs uppercase tracking-wider text-base-content/25">
API Live
</span>
) : (
<span className="text-xs uppercase tracking-wider text-amber-500/70">
Set `VITE_DEFAULT_COMMUNITY_ID`
</span>
)} */}
<ThemeToggle />
{isMsalConfigured && <MsalHeaderActions />}
</div>
</div>
</nav>
<div
className={`lts-app-shell flex min-h-screen flex-col bg-body ${DEFAULT_COMMUNITY_ID ? "" : "lts-app-shell--without-nav"}`}
>
<AppHeader />
<div className="flex-1">
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/" element={<HomeRoute />} />
<Route
path="/inhouse"
element={<HomePage key="inhouse" eventType="inhouse" />}
/>
<Route
path="/tournaments"
element={<HomePage key="tournament" eventType="tournament" />}
/>
<Route path="/login" element={<LoginPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} />
@@ -167,6 +310,7 @@ function App() {
path="/communities/:cid/internal-stats"
element={<CommunityInternalStatsPage />}
/>
<Route path="/communities/:cid/internal-stats/players/:userId" element={<CommunityInternalPlayerPage />} />
<Route
path="/communities/:cid/internal-stats/match/:matchId"
element={<InternalMatchDetailPage />}
@@ -226,6 +370,7 @@ function App() {
</LegalPage>
}
/>
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
<AppFooter />
+31
View File
@@ -0,0 +1,31 @@
import type { ApiAuctionChatMessage } from "./types.ts";
export interface ChatMessagePayload {
displayName?: string;
message: string;
clientMessageId: string;
}
export interface ChatMessageReply {
ok?: boolean;
message?: ApiAuctionChatMessage | string;
}
export async function sendAuctionChatMessage(
send: (() => Promise<ChatMessageReply>) | undefined,
): Promise<ApiAuctionChatMessage> {
if (!send) throw new Error("연결이 끊겼습니다. 연결 후 다시 보내 주세요.");
let reply: ChatMessageReply;
try {
reply = await send();
} catch {
throw new Error("전송을 확인하지 못했습니다. 다시 보내 주세요.");
}
if (reply?.ok && typeof reply.message === "object" && reply.message?.id) {
return reply.message;
}
if (reply?.message === "Chat message must be 300 characters or less.") {
throw new Error("메시지는 300자까지 보낼 수 있습니다.");
}
throw new Error("메시지를 보내지 못했습니다. 다시 보내 주세요.");
}
+12
View File
@@ -0,0 +1,12 @@
export const AUCTION_SAFETY_POLL_INTERVAL_MS = 30_000;
/** Supplements the fixed safety poll without restarting its timer. */
export function startAuctionRecoveryPolling(
refetch: () => void,
isVisible = () => document.visibilityState === 'visible',
): () => void {
const timer = setInterval(() => {
if (isVisible()) refetch();
}, 5000);
return () => clearInterval(timer);
}
+81
View File
@@ -0,0 +1,81 @@
import type {
AuctionReactionEvent,
AuctionReactionKind,
AuctionReactionReply,
} from "@lolympus/contracts";
export const AUCTION_REACTIONS: Record<
AuctionReactionKind,
{ emoji: string; label: string }
> = {
"thumbs-up": { emoji: "👍", label: "좋아요" },
heart: { emoji: "❤️", label: "하트" },
clap: { emoji: "👏", label: "박수" },
laugh: { emoji: "😂", label: "웃음" },
wow: { emoji: "😮", label: "놀람" },
sad: { emoji: "😢", label: "아쉬움" },
fire: { emoji: "🔥", label: "불꽃" },
celebrate: { emoji: "🎉", label: "축하" },
eyes: { emoji: "👀", label: "관심" },
thinking: { emoji: "🤔", label: "고민" },
"skull-crossbones": { emoji: "☠️", label: "해골과 뼈" },
poop: { emoji: "💩", label: "똥" },
pray: { emoji: "🙏", label: "간절함" },
"sweat-smile": { emoji: "😅", label: "식은땀" },
money: { emoji: "💸", label: "플렉스" },
trophy: { emoji: "🏆", label: "우승각" },
};
export const REACTION_LIFETIME_MS = 3200;
export const MAX_VISIBLE_REACTIONS = 16;
export type ActiveAuctionReaction = AuctionReactionEvent & {
receivedAt: number;
};
export function isAuctionReaction(
value: unknown,
): value is AuctionReactionEvent {
if (!value || typeof value !== "object") return false;
const reaction = value as Partial<AuctionReactionEvent>;
return (
typeof reaction.id === "string" &&
reaction.id.length > 0 &&
reaction.id.length <= 100 &&
typeof reaction.kind === "string" &&
Object.hasOwn(AUCTION_REACTIONS, reaction.kind) &&
typeof reaction.displayName === "string" &&
reaction.displayName.length <= 160 &&
typeof reaction.sentAt === "number" &&
Number.isFinite(reaction.sentAt)
);
}
export function appendAuctionReaction(
current: ActiveAuctionReaction[],
incoming: AuctionReactionEvent,
now = Date.now(),
): ActiveAuctionReaction[] {
const active = current.filter(
(reaction) => now - reaction.receivedAt < REACTION_LIFETIME_MS,
);
if (active.some((reaction) => reaction.id === incoming.id)) return active;
return [...active, { ...incoming, receivedAt: now }].slice(
-MAX_VISIBLE_REACTIONS,
);
}
export async function sendAuctionReaction(
send: (() => Promise<AuctionReactionReply>) | undefined,
): Promise<AuctionReactionEvent> {
if (!send) throw new Error("연결되면 반응을 보낼 수 있습니다.");
let reply: AuctionReactionReply;
try {
reply = await send();
} catch {
throw new Error("반응을 보내지 못했습니다. 잠시 후 다시 눌러 주세요.");
}
if (reply?.ok && isAuctionReaction(reply.reaction)) return reply.reaction;
if (reply?.code === "REACTION_RATE_LIMITED")
throw new Error("조금만 기다렸다가 다시 눌러 주세요.");
throw new Error("반응을 보내지 못했습니다. 잠시 후 다시 눌러 주세요.");
}
+2
View File
@@ -27,6 +27,7 @@ export function createAuctionResyncRequester(
fetchState: () => Promise<AuctionResyncReply>,
applyState: (state: ApiAuction) => void,
wait = waitForRetry,
onFailure?: () => void,
) {
let pending: Promise<void> | undefined;
let controller = new AbortController();
@@ -67,6 +68,7 @@ export function createAuctionResyncRequester(
}
if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal);
}
if (!signal.aborted) onFailure?.();
})().finally(() => {
if (!signal.aborted) pending = undefined;
});
+65
View File
@@ -1,4 +1,69 @@
import type { ApiAuction } from "./types";
import type { AuctionStateIdentity } from "@lolympus/contracts";
export function resolveCurrentBidPointAmount(auction: ApiAuction): number {
const amount = Number(
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
);
return Number.isFinite(amount) ? Math.max(0, amount) : 0;
}
export function shouldResyncForAuctionIdentity(
current: ApiAuction | null,
identity: AuctionStateIdentity | null,
): boolean {
if (!current) return true;
// Completed runtimes expire while their archived Mongo state remains valid.
if (!identity) {
return (
current.auctionEngineVersion === "redis-v1" &&
current.phase !== "complete"
);
}
if (identity.auctionLifecycleId !== current.auctionLifecycleId) return true;
if ((identity.revision ?? -1) > (current.revision ?? -1)) return true;
// A delayed heartbeat must not undo a newer state already received by socket.
if ((identity.revision ?? -1) < (current.revision ?? -1)) return false;
return (
(identity.matchSideEffectRevision ?? -1) >
(current.matchSideEffectRevision ?? -1)
);
}
export function createAuctionHeartbeatMonitor() {
let pendingIdentity: AuctionStateIdentity | null | undefined;
let consecutiveFailures = 0;
return {
reset() {
pendingIdentity = undefined;
consecutiveFailures = 0;
},
recordFailure(): boolean {
pendingIdentity = undefined;
consecutiveFailures += 1;
return consecutiveFailures >= 2;
},
inspect(
current: ApiAuction | null,
identity: AuctionStateIdentity | null | undefined,
) {
consecutiveFailures = 0;
const previousIdentity = pendingIdentity;
const isCurrent =
identity === undefined ||
!shouldResyncForAuctionIdentity(current, identity);
pendingIdentity = undefined;
if (isCurrent) return { isCurrent: true, needsResync: false };
// Bids received since the first heartbeat may have closed that gap, even
// when this heartbeat observes another newer bid still in transit.
const needsResync =
previousIdentity !== undefined &&
shouldResyncForAuctionIdentity(current, previousIdentity);
if (!needsResync) pendingIdentity = identity;
return { isCurrent: false, needsResync };
},
};
}
export interface BidDeltaPayload {
currentBidRoundId?: string;
+75 -9
View File
@@ -5,8 +5,11 @@ import type {
CompetitionCommandResponse,
CompetitionDetailResponse,
CreateSeriesAdjudicationRequest,
HallOfFameResponse,
MatchDetailResponse,
MatchEventType,
MatchLifecycleStatus,
MatchListView,
MatchListResponse,
ReverseSeriesResultRequest,
SeriesId,
@@ -32,6 +35,7 @@ import type {
ApiCommunity,
ApiCommunityUserSearchCandidate,
ApiEnqueueRefreshResult,
ApiHistorySeason,
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
ApiLeaderboardResponse,
@@ -52,6 +56,7 @@ import type {
MeResponse,
RiotQueueGroup,
RiotRankFilter,
RiotLane,
RebuildLegacyMatchesResponse,
TournamentCodeBulkUploadResponse,
TournamentCodeListResponse,
@@ -64,15 +69,23 @@ const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
interface MatchesQueryOptions {
status?: MatchLifecycleStatus;
eventType?: MatchEventType;
limit?: number;
page?: number;
offset?: number;
scheduledFrom?: string;
scheduledTo?: string;
sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: string;
}
interface MatchesPageQueryOptions extends MatchesQueryOptions {
includeResults?: boolean;
}
export interface UserHistoryFilters {
lane?: RiotLane;
queueGroup?: RiotQueueGroup;
rank?: RiotRankFilter;
seasonId?: string;
@@ -80,19 +93,24 @@ export interface UserHistoryFilters {
}
export interface CommunityInternalStatsFilters {
lane?: RiotLane;
seasonId?: string;
from?: string;
to?: string;
championId?: number;
limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
}
function createMatchesPath(
communityId: string,
options: MatchesQueryOptions = {},
options: MatchesPageQueryOptions = {},
) {
const searchParams = new URLSearchParams();
if (options.status) searchParams.set('status', options.status);
if (options.eventType) searchParams.set('eventType', options.eventType);
if (options.limit) searchParams.set('limit', String(options.limit));
if (options.page) searchParams.set('page', String(options.page));
if (options.offset) searchParams.set('offset', String(options.offset));
@@ -100,6 +118,9 @@ function createMatchesPath(
searchParams.set('scheduledFrom', options.scheduledFrom);
if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo);
if (options.sort) searchParams.set('sort', options.sort);
if (options.includeResults) searchParams.set('includeResults', 'true');
if (options.view) searchParams.set('view', options.view);
if (options.asOf) searchParams.set('asOf', options.asOf);
const queryString = searchParams.toString();
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`;
@@ -153,6 +174,17 @@ export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) {
});
}
export function useHallOfFame(communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({
queryKey: ['hall-of-fame', communityId],
queryFn: () => apiFetch<HallOfFameResponse>(
`/communities/${communityId}/matches/hall-of-fame`,
{ auth: 'none' },
),
enabled: Boolean(communityId),
});
}
export function useMatches(
options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID,
@@ -171,6 +203,9 @@ export function useMatches(
options.scheduledFrom ?? null,
options.scheduledTo ?? null,
options.sort ?? null,
options.eventType ?? null,
options.view ?? null,
options.asOf ?? null,
],
queryFn: async () => {
const response = await authScope.fetch<MatchListResponse>(
@@ -183,7 +218,7 @@ export function useMatches(
}
export function useMatchesPage(
options: MatchesQueryOptions,
options: MatchesPageQueryOptions,
communityId = DEFAULT_COMMUNITY_ID,
) {
const authScope = useOptionalAuthQueryScope();
@@ -200,6 +235,10 @@ export function useMatchesPage(
options.scheduledFrom ?? null,
options.scheduledTo ?? null,
options.sort ?? null,
options.includeResults ?? false,
options.eventType ?? null,
options.view ?? null,
options.asOf ?? null,
],
queryFn: () =>
authScope.fetch<MatchListResponse>(
@@ -384,10 +423,10 @@ export function useAuction(
) {
return useQuery({
queryKey: ['auction', communityId, matchId ?? null],
queryFn: () =>
queryFn: ({ signal }) =>
apiFetch<ApiAuction>(
`/communities/${communityId}/matches/${matchId}/auction`,
{ auth: 'none' },
{ auth: 'none', signal },
),
enabled: Boolean(communityId && matchId),
retry: false,
@@ -402,9 +441,10 @@ export function useAuctionHistory(
) {
return useQuery({
queryKey: ['auction-history', communityId, matchId ?? null],
queryFn: () =>
queryFn: ({ signal }) =>
apiFetch<ApiAuctionHistoryEntry[]>(
`/communities/${communityId}/matches/${matchId}/auction/history`,
{ signal },
),
enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
retry: false,
@@ -523,6 +563,7 @@ function createUserHistoryPath(
const searchParams = new URLSearchParams();
if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup);
if (filters.rank) searchParams.set('rank', filters.rank);
if (filters.lane) searchParams.set('lane', filters.lane);
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
if (filters.championId)
searchParams.set('championId', String(filters.championId));
@@ -533,7 +574,8 @@ function createUserHistoryPath(
}
const queryString = searchParams.toString();
return `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`;
const path = `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`;
return path;
}
export function useUserHistoryProfile(
@@ -659,12 +701,16 @@ function createCommunityInternalStatsPath(
extra: Record<string, string | number | null | undefined> = {},
) {
const searchParams = new URLSearchParams();
if (filters.lane) searchParams.set('lane', filters.lane);
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
if (filters.from) searchParams.set('from', filters.from);
if (filters.to) searchParams.set('to', filters.to);
if (filters.championId)
searchParams.set('championId', String(filters.championId));
if (filters.limit) searchParams.set('limit', String(filters.limit));
if (filters.query) searchParams.set('q', filters.query);
if (filters.format) searchParams.set('format', filters.format);
if (filters.playerId) searchParams.set('playerId', filters.playerId);
for (const [key, value] of Object.entries(extra)) {
if (value !== null && value !== undefined && value !== '') {
searchParams.set(key, String(value));
@@ -689,16 +735,22 @@ export function useCommunityInternalStatsMatches(
filters.to ?? null,
filters.championId ?? null,
filters.limit ?? null,
filters.query ?? null,
filters.format ?? null,
filters.playerId ?? null,
],
queryFn: ({ pageParam }) =>
apiFetch<ApiInternalMatchListResponse>(
createCommunityInternalStatsPath(communityId, 'matches', filters, {
cursor: pageParam,
cursor: pageParam?.cursor,
cursorMatchId: pageParam?.matchId,
}),
{ auth: 'none' },
),
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
initialPageParam: null as { cursor: number; matchId?: string } | null,
getNextPageParam: (lastPage) => lastPage.nextCursor === null
? null
: { cursor: lastPage.nextCursor, matchId: lastPage.nextCursorMatchId },
enabled: Boolean(communityId && enabled),
});
}
@@ -712,10 +764,12 @@ export function useCommunityLeaderboard(
queryKey: [
'community-internal-stats-leaderboard',
communityId,
filters.lane ?? null,
filters.seasonId ?? null,
filters.from ?? null,
filters.to ?? null,
filters.championId ?? null,
filters.query ?? null,
],
queryFn: () =>
apiFetch<ApiLeaderboardResponse>(
@@ -728,6 +782,17 @@ export function useCommunityLeaderboard(
});
}
export function useCommunityStatsSeasons(communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({
queryKey: ['community-stats-seasons', communityId],
queryFn: () => apiFetch<{ seasons: ApiHistorySeason[] }>(
`/communities/${communityId}/internal-stats/seasons`,
{ auth: 'none' },
),
enabled: Boolean(communityId),
});
}
export function useTeamInsights(
filters: CommunityInternalStatsFilters,
communityId = DEFAULT_COMMUNITY_ID,
@@ -781,6 +846,7 @@ export function useUserInternalHistory(
queryKey: [
'user-internal-history',
communityId,
filters.lane ?? null,
userId ?? null,
filters.seasonId ?? null,
filters.championId ?? null,
+11 -7
View File
@@ -81,6 +81,7 @@ export interface AuctionTeamView {
name: string;
captainUserId: string;
captainName: string;
captain?: ParticipantView;
points: number;
members: (AuctionPlayerView & {
assignedPosition: Position;
@@ -253,13 +254,16 @@ function mapAuctionTeamToView(
playerLookup: Map<string, AuctionPlayerView>,
participantLookup: Map<string, ParticipantView>,
): AuctionTeamView {
const captain =
participantLookup.get(team.captainUserId) ??
playerLookup.get(team.captainUserId);
return {
teamIndex: team.teamIndex,
name: teamIndexLabel(team.teamIndex),
captainUserId: team.captainUserId,
captainName:
participantLookup.get(team.captainUserId)?.summonerName ??
`User ${team.captainUserId.slice(-4)}`,
captainName: captain?.summonerName ?? `User ${team.captainUserId.slice(-4)}`,
captain,
points: team.points,
members: team.members.map((member) => {
const participant = participantLookup.get(member.userId);
@@ -354,15 +358,15 @@ export function formatTierLabel(tier?: ApiTierInfo) {
export function getTierColorToken(tier?: ApiTierInfo) {
switch (tier?.tier) {
case "CHALLENGER":
return "text-amber-400";
return "text-gold";
case "GRANDMASTER":
return "text-red-400";
return "text-loss";
case "MASTER":
return "text-fuchsia-400";
case "DIAMOND":
return "text-cyan-400";
case "EMERALD":
return "text-emerald-400";
return "text-leaf";
case "PLATINUM":
return "text-teal-300";
case "GOLD":
@@ -370,7 +374,7 @@ export function getTierColorToken(tier?: ApiTierInfo) {
case "SILVER":
return "text-gray-300";
case "BRONZE":
return "text-amber-700";
return "text-gold";
case "IRON":
return "text-stone-400";
default:
Loaded 100 of 351 files, more files were not shown because too many files have changed in this diff. Show more