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.
This commit is contained in:
dahyeon committed 2026-11-11 02:00:35 +09:00
1 parent 20e1e6ec04
commit 0d7617e2d2
70 files changed
+3739 -1793

No files matched your search

+33
View File
@@ -117,6 +117,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.
+1
View File
@@ -11,6 +11,7 @@
"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",
@@ -80,7 +80,7 @@ export class AuctionController {
return this.auctionService.getStateByMatchId(matchId);
}
// 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전).
// 공개 입찰 기록 조회.
@Get('bids/history')
@AllowPublicAccess()
public async getBidHistory(
@@ -106,14 +106,20 @@ export class AuctionController {
}
@Post('bids')
@AllowPublicAccess()
@Roles('admin', 'owner', 'member')
@UseGuards(RolesGuard)
@HttpCode(HttpStatus.OK)
public async placeBid(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: PlaceBidDto,
) {
this.assertSameCommunity(currentUser, communityId);
return this.auctionService.placeBid({
matchId,
bidderUserId: currentUser._id,
teamIndex: body.bidderTeamIndex,
amount: body.bidPointAmount,
bidRequestId: body.bidRequestId,
@@ -78,6 +78,8 @@ describe('AuctionGateway', () => {
expect(broadcast).not.toHaveBeenCalled();
});
const bidderUserId = new mongoose.Types.ObjectId();
function createGateway(params?: {
getCurrentRedisTimestampMS?: jest.Mock;
placeBidDelta?: jest.Mock;
@@ -112,6 +114,23 @@ describe('AuctionGateway', () => {
};
}
it('requires an authenticated user before forwarding a bid', async () => {
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('broadcasts a bid delta and acknowledges the matching bid request', async () => {
const matchId = new mongoose.Types.ObjectId().toString();
const auctionBidHistoryEntry = {
@@ -133,7 +152,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 +169,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 +223,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 +273,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,
@@ -318,7 +347,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 +391,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) {
@@ -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 {
@@ -86,6 +86,7 @@ interface AuctionSocketData {
identity?: IdentityDocument;
matchId?: string;
user?: UserDocument;
devUser?: UserDocument;
}
type AuctionSocket = Socket<
@@ -114,6 +115,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 +135,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(
@@ -153,11 +160,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
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),
);
@@ -240,11 +249,17 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
}
try {
const bidderUserId = this.resolveSocketUserId(socket);
if (!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,
@@ -573,14 +588,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 +636,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({
@@ -1,5 +1,6 @@
import {
BadRequestException,
ForbiddenException,
ConflictException,
Injectable,
InternalServerErrorException,
@@ -795,6 +796,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 +812,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 +932,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 +1012,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 +2917,15 @@ export class AuctionService {
return auction.teams.find((team) => team.teamIndex === teamIndex);
}
private assertBidderIsCaptain(
bidderUserId: mongoose.Types.ObjectId | undefined,
captainUserId: string,
) {
if (bidderUserId && bidderUserId.toString() !== captainUserId) {
throw new ForbiddenException('해당 팀의 팀장만 입찰할 수 있습니다.');
}
}
private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000);
}
@@ -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,11 @@ export class CommunityStatsController {
@Query('from') from?: string,
@Query('to') to?: string,
@Query('championId') championId?: string,
@Query('q') query?: string,
) {
return this.communityStatsService.getLeaderboard({
communityId,
filters: this.toFilters({ seasonId, from, to, championId }),
filters: this.toFilters({ seasonId, from, to, championId, query }),
});
}
@@ -110,7 +153,17 @@ export class CommunityStatsController {
championId?: string;
cursor?: string;
limit?: string;
query?: string;
format?: CommunityStatsFilters['format'];
playerId?: string;
cursorMatchId?: string;
}): CommunityStatsFilters {
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 +171,10 @@ 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,
};
}
@@ -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,244 @@ 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(':r8:') }),
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 +460,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 +528,7 @@ describe('CommunityStatsService', () => {
expect(setDetail).toHaveBeenCalledTimes(2);
expect(setDetail).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ field: expect.stringContaining(':r4:') }),
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
invalidCheckpointResponse,
);
});
@@ -309,6 +553,7 @@ describe('CommunityStatsService', () => {
gameCreation: 1_000,
gameDuration: 1_800,
winnerSide: 'blue',
rawAvailable: true,
timelineLoaded: false,
timeline: [],
objectiveEvents: [],
@@ -361,7 +606,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 +629,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(':r8:') }),
fallback,
60,
);
@@ -392,7 +647,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(':r8:') }),
recovered,
);
});
@@ -459,7 +714,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,
@@ -1,3 +1,9 @@
import type {
CompetitionGameView,
GameAnalysisAvailability,
InternalMatchCompetition,
InternalMatchResultPresentation,
} from '@lolympus/contracts';
import {
BadRequestException,
Injectable,
@@ -5,8 +11,14 @@ import {
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { presentCompetitionDetail } from '../competition/competition.presenter';
import type { Competition } from '../competition/competition.schema';
import { ConnectionService } from '../global/database/connection.service';
import type { CommunityDocument, RiotLane } from '../global/database/schema';
import type {
CommunityDocument,
MatchStatsDocument,
RiotLane,
} from '../global/database/schema';
import type {
HistorySeasonDto,
RecentMatchView,
@@ -43,7 +55,7 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 8;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext {
@@ -58,6 +70,15 @@ interface BaseDataset {
matches: InternalMatchCardView[];
records: InternalRecord[];
detailsByMatchId: Map<string, InternalGameDetail[]>;
competition?: InternalMatchCompetition;
}
interface CachedMatchPage extends Omit<InternalMatchListResponse, 'matches'> {
cards: Array<{
card: InternalMatchCardView;
sourceCompetitionId?: string;
sourceRevision?: number;
}>;
}
@Injectable()
@@ -71,6 +92,8 @@ export class CommunityStatsService {
string,
Promise<UserInternalHistoryResponse>
>();
private readonly fragmentRepairs = new Map<string, Promise<number>>();
private readonly rawRecoveryRetryAfter = new Map<string, number>();
constructor(
private readonly connectionService: ConnectionService,
@@ -84,67 +107,141 @@ export class CommunityStatsService {
filters: CommunityStatsFilters;
}): Promise<InternalMatchListResponse> {
const key = this.cacheKey('matches', params.communityId, params.filters);
const cached = await this.cacheService.get<InternalMatchListResponse>(key);
if (cached) return cached;
const cached = await this.cacheService.get<CachedMatchPage>(key);
const page =
cached ?? (await this.loadMatchPage(params.communityId, params.filters));
if (!cached) await this.cacheService.set(key, page);
const { cards, ...pagination } = page;
if (cards.length === 0) return { ...pagination, matches: [] };
const matchIds = cards.map(
({ card }) => new mongoose.Types.ObjectId(card.matchId),
);
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions = await CompetitionModel.find({
communityId: params.communityId,
matchId: { $in: matchIds },
})
.select({
matchId: 1,
communityId: 1,
schemaVersion: 1,
revision: 1,
phase: 1,
format: 1,
createdAt: 1,
updatedAt: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.phase': 1,
'projection.formatType': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
const official = new Map(
competitions.map((competition) => [
competition.matchId.toString(),
this.presentOfficialResult(competition),
]),
);
return {
...pagination,
matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => {
const resultPresentation = official.get(card.matchId) ?? {
type: sourceCompetitionId
? ('unavailable' as const)
: ('legacy' as const),
};
const canUseGames =
resultPresentation.type === 'legacy' ||
(resultPresentation.type === 'official' &&
sourceCompetitionId === resultPresentation.competitionId &&
sourceRevision === resultPresentation.sourceRevision);
return {
...(canUseGames ? card : this.adjustCardForRange(card, [])),
resultPresentation,
};
}),
};
}
private async loadMatchPage(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<CachedMatchPage> {
const limit = this.clampLimit(
params.filters.limit,
filters.limit,
DEFAULT_LIST_LIMIT,
MAX_LIST_LIMIT,
);
const dataset = await this.buildBaseDataset(
params.communityId,
params.filters,
);
const filtered = params.filters.championId
? dataset.matches.filter((match) =>
dataset.records.some(
(record) =>
record.matchId === match.matchId &&
record.championId === params.filters.championId,
),
)
: dataset.matches;
const cursor = params.filters.cursor;
const page = filtered
.filter(
(match) => !cursor || new Date(match.scheduledAt).getTime() < cursor,
)
.slice(0, limit + 1);
const context = await this.resolveContext(communityId, filters);
await this.repairCommunityFragments(communityId);
const page = await this.matchStatsRepository.findMatchPage({
...filters,
communityId,
from: context.from?.getTime(),
to: context.to?.getTime(),
limit: limit + 1,
});
const visible = page.slice(0, limit);
const response: InternalMatchListResponse = {
matches: visible,
nextCursor:
page.length > limit
? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime()
: null,
season: dataset.season,
const last = page.length > limit ? visible.at(-1) : undefined;
return {
cards: visible.map((fragment) => ({
card: this.adjustCardForRange(
fragment.matchCard as unknown as InternalMatchCardView,
(fragment.gameDetails ?? []).filter((game) =>
this.isGameInRange(game.gameCreation, context),
),
),
sourceCompetitionId: fragment.sourceCompetitionId?.toString(),
sourceRevision: fragment.sourceRevision,
})),
nextCursor: last?.scheduledAt.getTime() ?? null,
nextCursorMatchId: last?.matchId.toString(),
season: context.season,
};
await this.cacheService.set(key, response);
return response;
}
public async getSeasons(communityId: mongoose.Types.ObjectId) {
const { community } = await this.resolveContext(communityId, {});
return { seasons: this.resolveSeasons(community) };
}
public async getLeaderboard(params: {
communityId: mongoose.Types.ObjectId;
filters: CommunityStatsFilters;
}): Promise<LeaderboardResponse> {
const key = this.cacheKey(
'leaderboard',
params.communityId,
params.filters,
);
const cached = await this.cacheService.get<LeaderboardResponse>(key);
if (cached) return cached;
const dataset = await this.buildBaseDataset(
params.communityId,
params.filters,
);
const records = this.applyChampionFilter(dataset.records, params.filters);
const rows = this.buildLeaderboardRows(records);
const response = { rows, season: dataset.season };
await this.cacheService.set(key, response);
return response;
const { query, ...filters } = params.filters;
const key = this.cacheKey('leaderboard', params.communityId, filters);
let response = await this.cacheService.get<LeaderboardResponse>(key);
if (!response) {
const dataset = await this.buildSeasonDataset(
params.communityId,
filters,
);
const records = this.applyChampionFilter(dataset.records, filters);
response = {
rows: this.buildLeaderboardRows(records),
season: dataset.season,
};
await this.cacheService.set(key, response);
}
const keyword = query?.toLocaleLowerCase('ko-KR');
if (!keyword) return response;
return {
...response,
matchedUserIds: response.rows
.filter(({ summonerName, tagLine }) =>
(tagLine ? summonerName + '#' + tagLine : summonerName)
.toLocaleLowerCase('ko-KR')
.includes(keyword),
)
.map(({ userId }) => userId),
};
}
public async getTeamInsights(params: {
@@ -159,13 +256,13 @@ export class CommunityStatsService {
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
if (cached) return cached;
const dataset = await this.buildBaseDataset(
const dataset = await this.buildSeasonDataset(
params.communityId,
params.filters,
);
const records = this.applyChampionFilter(dataset.records, params.filters);
const rows = this.buildLeaderboardRows(records);
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
const gameDetails = dataset.gameDetails;
const blueGames = gameDetails.length;
const redGames = gameDetails.length;
const blueWins = gameDetails.filter(
@@ -174,6 +271,7 @@ export class CommunityStatsService {
const redWins = gameDetails.filter(
(game) => game.winnerSide === 'red',
).length;
const confirmedGames = blueWins + redWins;
const response: TeamInsightsResponse = {
season: dataset.season,
@@ -182,6 +280,11 @@ export class CommunityStatsService {
red: this.percent(redWins, redGames),
bluePicks: blueGames,
redPicks: redGames,
confirmed: {
sampleSize: confirmedGames,
blue: this.percent(blueWins, confirmedGames),
red: this.percent(redWins, confirmedGames),
},
},
topKda: this.toHighlight(
rows
@@ -222,29 +325,56 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> {
const revision = await this.getDetailRevision(
params.communityId,
params.matchId,
);
const key = new CommunityStatsCacheKey(
params.communityId.toString(),
'matchDetail',
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}`,
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}:${revision}`,
);
const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
if (
cached &&
isCompleteMatchDetailResponse(cached) &&
(!this.canRetryRawRecovery(key) ||
!(await this.hasArchivedMissingRaw(cached.games, cached.competition)))
) {
return cached;
}
const inFlight = this.matchDetailInFlight.get(key.identity);
const identity = key.identity;
const inFlight = this.matchDetailInFlight.get(identity);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key.identity, promise);
this.matchDetailInFlight.set(identity, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key.identity) === promise) {
this.matchDetailInFlight.delete(key.identity);
if (this.matchDetailInFlight.get(identity) === promise) {
this.matchDetailInFlight.delete(identity);
}
}
}
private async getDetailRevision(
communityId: mongoose.Types.ObjectId,
matchId: mongoose.Types.ObjectId,
): Promise<string> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const source = await CompetitionModel.findOne({ communityId, matchId })
.select({ _id: 1, revision: 1, projectorVersion: 1 })
.lean()
.exec();
return source
? `${source._id.toString()}:${source.revision}:${source.projectorVersion}`
: 'legacy';
}
private async buildMatchDetailResponse(
params: {
communityId: mongoose.Types.ObjectId;
@@ -252,27 +382,101 @@ export class CommunityStatsService {
},
key: CommunityStatsCacheKey,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
const match = dataset.matches.find(
let dataset = await this.buildBaseDataset(
params.communityId,
{
seasonId: 'all',
},
params.matchId,
);
let match = dataset.matches.find(
(item) => item.matchId === params.matchId.toString(),
);
if (!match) throw new NotFoundException('Internal match not found.');
let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? [];
if (gameDetails.some((game) => game.timelineLoaded !== true)) {
let games = linkDetailGames(dataset, match.matchId);
const missingBefore = new Set(
games
.filter(
({ analysisAvailability }) => analysisAvailability === 'missing',
)
.map(({ game }) => game.riotMatchId),
);
const rawRestored =
this.canRetryRawRecovery(key) &&
(await this.hasArchivedMissingRaw(
games.map(({ game, official, analysisAvailability }) => ({
riotMatchId: game.riotMatchId,
gameId: official?.id,
analysisAvailability,
})),
dataset.competition,
));
let canCacheResponse = true;
if (rawRestored || games.some(needsDetailHydration)) {
if (rawRestored) this.deferRawRecovery(key);
await this.matchStatsService.buildAndUpsert(params.matchId, {
includeTimeline: true,
});
const refreshedDataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? [];
const refreshedDataset = await this.buildBaseDataset(
params.communityId,
{
seasonId: 'all',
},
params.matchId,
);
const refreshedMatch = refreshedDataset.matches.find(
(item) => item.matchId === params.matchId.toString(),
);
if (!refreshedMatch)
throw new NotFoundException('Internal match not found.');
dataset = refreshedDataset;
match = refreshedMatch;
games = linkDetailGames(dataset, match.matchId);
const rawImproved = games.some(
({ game, analysisAvailability }) =>
missingBefore.has(game.riotMatchId) &&
analysisAvailability === 'available',
);
if (rawImproved) {
canCacheResponse = await this.cacheService.invalidateCommunityWithRetry(
params.communityId.toString(),
);
if (canCacheResponse) {
try {
// Read the new generation before caching the rebuilt response.
await this.cacheService.get(key);
} catch (error) {
canCacheResponse = false;
this.logger.warn(
`Stats detail cache refresh failed: ${String(error)}`,
);
}
}
}
if (
!games.some(
({ game, analysisAvailability }) =>
missingBefore.has(game.riotMatchId) &&
analysisAvailability === 'missing',
)
) {
this.rawRecoveryRetryAfter.delete(key.field);
}
}
const response: InternalMatchDetailResponse = {
match,
games: gameDetails.map((game) => ({
competition: dataset.competition,
games: games.map(({ game, official, analysisAvailability }) => ({
gameNumber: game.gameNumber,
analysisAvailability,
...(official
? {
gameId: official.id,
gameSlotId: official.gameSlotId,
seriesId: official.seriesId,
ordinal: official.ordinal,
}
: {}),
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
@@ -325,7 +529,12 @@ export class CommunityStatsService {
})),
})),
};
if (gameDetails.every((game) => game.timelineLoaded === true)) {
if (!canCacheResponse) return response;
if (
!games.some(needsDetailHydration) &&
(!dataset.competition ||
response.games.length === dataset.competition.projection.games.length)
) {
await this.cacheService.setDetail(key, response);
} else {
await this.cacheService.set(
@@ -367,65 +576,260 @@ export class CommunityStatsService {
}
}
public async refreshForRiotMatches(riotMatchIds: string[]): Promise<void> {
if (riotMatchIds.length === 0) return;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const archived = await RiotMatchModel.find({
matchId: { $in: [...new Set(riotMatchIds)] },
'raw.info': { $exists: true },
})
.select({ matchId: 1 })
.lean()
.exec();
const ids = new Set(archived.map((match) => match.matchId));
if (ids.size === 0) return;
const fragments = await this.matchStatsRepository.findByRiotMatchIds([
...ids,
]);
const communityIds = new Map<string, mongoose.Types.ObjectId>();
for (const fragment of fragments) {
const missingIds = new Set(
fragment.gameDetails
.filter(
(game) => ids.has(game.riotMatchId) && game.rawAvailable === false,
)
.map((game) => game.riotMatchId),
);
if (missingIds.size === 0) continue;
try {
// Raw enrichment must run even when the Competition revision is current.
await this.matchStatsService.buildAndUpsert(fragment.matchId);
} catch (error) {
this.logger.warn(
`Stats recovery failed for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
try {
// A builder can return without writing, or fail during post-write checks.
// Only actual enrichment should cause a community-wide invalidation.
const updated = await this.matchStatsRepository.findByMatch(
fragment.matchId,
);
if (
updated?.gameDetails.some(
(game) =>
missingIds.has(game.riotMatchId) && game.rawAvailable === true,
)
) {
communityIds.set(
fragment.communityId.toString(),
fragment.communityId,
);
}
} catch (error) {
this.logger.warn(
`Could not verify stats recovery for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
}
for (const communityId of communityIds.values()) {
await this.cacheService.invalidateCommunityWithRetry(
communityId.toString(),
);
}
}
private canRetryRawRecovery(key: CommunityStatsCacheKey): boolean {
return (this.rawRecoveryRetryAfter.get(key.field) ?? 0) <= Date.now();
}
private deferRawRecovery(key: CommunityStatsCacheKey): void {
const now = Date.now();
for (const [field, retryAt] of this.rawRecoveryRetryAfter) {
if (retryAt <= now) this.rawRecoveryRetryAfter.delete(field);
}
if (this.rawRecoveryRetryAfter.size >= 1000) {
this.rawRecoveryRetryAfter.delete(
this.rawRecoveryRetryAfter.keys().next().value!,
);
}
this.rawRecoveryRetryAfter.set(
key.field,
now + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS * 1000,
);
}
private async hasArchivedMissingRaw(
games: Array<
Pick<
InternalMatchDetailResponse['games'][number],
'riotMatchId' | 'gameId' | 'analysisAvailability'
>
>,
competition?: InternalMatchCompetition,
): Promise<boolean> {
const officialById = new Map(
competition?.projection.games.map((game) => [game.id, game]),
);
const ids = games
.filter(
(game) =>
game.analysisAvailability === 'missing' &&
(!competition ||
(game.gameId &&
officialById.get(game.gameId)?.evidence.type === 'riot')),
)
.map((game) => game.riotMatchId);
if (ids.length === 0) return false;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
return Boolean(
await RiotMatchModel.exists({
matchId: { $in: ids },
'raw.info': { $exists: true },
}).exec(),
);
}
public invalidateCommunity(
communityId: mongoose.Types.ObjectId,
): Promise<number> {
return this.cacheService.invalidateCommunity(communityId.toString());
}
private async buildBaseDataset(
private async buildSeasonDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<BaseDataset> {
) {
const context = await this.resolveContext(communityId, filters);
let fragments = await this.matchStatsRepository.findByCommunity({
await this.repairCommunityFragments(communityId);
const fragments = await this.matchStatsRepository.findSeasonStats({
communityId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
from: context.from?.getTime(),
to: context.to?.getTime(),
});
const rebuilt = await this.rebuildMissingOrStaleFragments(communityId);
if (rebuilt > 0) {
fragments = await this.matchStatsRepository.findByCommunity({
communityId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
}
const cards: InternalMatchCardView[] = [];
const gameDetails: Array<Pick<InternalGameDetail, 'winnerSide'>> = [];
const records: InternalRecord[] = [];
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) {
const filteredGames = fragment.gameDetails
.filter((game) => this.isGameInRange(game.gameCreation, context))
.sort((left, right) => left.gameNumber - right.gameNumber);
if (filteredGames.length === 0) continue;
const card = this.adjustCardForRange(
fragment.matchCard as unknown as InternalMatchCardView,
filteredGames,
);
cards.push(card);
detailsByMatchId.set(fragment.matchId.toString(), filteredGames);
const allowedGameNumbers = new Set(
filteredGames.map((game) => game.gameNumber),
const games = fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context),
);
const gameNumbers = new Set(games.map(({ gameNumber }) => gameNumber));
gameDetails.push(...games);
records.push(
...fragment.records.filter((record) =>
allowedGameNumbers.has(record.gameNumber),
...fragment.records.filter(({ gameNumber }) =>
gameNumbers.has(gameNumber),
),
);
}
return { season: context.season, records, gameDetails };
}
private async buildBaseDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
matchId: mongoose.Types.ObjectId,
): Promise<BaseDataset> {
const context = await this.resolveContext(communityId, filters);
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({ _id: matchId, communityId })
.lean()
.exec();
if (!match) throw new NotFoundException('Internal match not found.');
const CompetitionModel =
await this.connectionService.getModel('competition');
const [source, stored] = await Promise.all([
CompetitionModel.findOne({ matchId, communityId }).lean().exec(),
this.matchStatsRepository.findByMatch(matchId),
]);
const isCurrent = (fragment: MatchStatsDocument | null) =>
Boolean(
fragment?.communityId.equals(communityId) &&
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
(source
? fragment.sourceCompetitionId?.equals(source._id) &&
fragment.sourceRevision === source.revision &&
fragment.projectorVersion === source.projectorVersion
: !fragment.sourceCompetitionId && !match.competitionId),
);
let fragment = stored;
if (!isCurrent(fragment) && (source || match.result?.games.length)) {
await this.matchStatsService.buildAndUpsert(matchId);
fragment = await this.matchStatsRepository.findByMatch(matchId);
}
if (!isCurrent(fragment)) fragment = null;
if (!fragment && !source && !match.competitionId) {
throw new NotFoundException('Internal match not found.');
}
const competition =
source &&
presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({
...team,
members: team.members.map((member) => ({ ...member })),
})),
});
const resultPresentation: InternalMatchResultPresentation = source
? this.presentOfficialResult(source)
: { type: match.competitionId ? 'unavailable' : 'legacy' };
const card = (fragment?.matchCard as unknown as
| InternalMatchCardView
| undefined) ?? {
matchId: matchId.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
status: match.status === 'finished' ? 'finished' : 'in-progress',
gameCount: match.gameCount,
seriesResults: [],
games: [],
teams: match.teams.map(({ teamIndex, name }) => ({
teamIndex,
name,
members: [],
})),
};
return {
season: context.season,
matches: cards,
records,
detailsByMatchId,
matches: [{ ...card, resultPresentation }],
records: fragment?.records ?? [],
detailsByMatchId: new Map([
[matchId.toString(), fragment?.gameDetails ?? []],
]),
competition: competition
? {
id: competition.id,
revision: competition.revision,
teams: competition.teams,
projection: competition.projection,
}
: undefined,
};
}
private presentOfficialResult(
source: Competition & { _id: mongoose.Types.ObjectId },
): InternalMatchResultPresentation {
const competition = presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({ ...team, members: [] })),
});
const { projection } = competition;
return {
type: 'official',
competitionId: competition.id,
sourceRevision: competition.revision,
phase: projection.phase,
formatType: projection.formatType,
teams: competition.teams.map(({ teamId, name }) => ({ teamId, name })),
completedSeriesCount: projection.series.filter(
({ status }) => status === 'completed',
).length,
outcome: projection.outcome,
singleSeries:
projection.formatType === 'paired-series' &&
projection.series.length === 1
? projection.series[0]
: undefined,
};
}
@@ -442,13 +846,25 @@ export class CommunityStatsService {
params.filters,
);
const userId = params.userId.toString();
const fragments = await this.matchStatsRepository.findUserRecordFragments({
const fragmentQuery = {
communityId: params.communityId,
userId: params.userId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
};
let fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
const stale = fragments.filter(
(fragment) => fragment.builderVersion < MATCH_STATS_BUILDER_VERSION,
);
if (stale.length > 0) {
for (const { matchId } of stale) {
await this.matchStatsService.buildAndUpsert(matchId);
}
fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
}
const allUserRecords = this.extractUserRecords(fragments, userId, context);
const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50);
@@ -621,9 +1037,22 @@ export class CommunityStatsService {
return rebuilt;
}
private repairCommunityFragments(communityId: mongoose.Types.ObjectId) {
const key = communityId.toString();
const inFlight = this.fragmentRepairs.get(key);
if (inFlight) return inFlight;
const repair = this.rebuildMissingOrStaleFragments(communityId).finally(
() => {
this.fragmentRepairs.delete(key);
},
);
this.fragmentRepairs.set(key, repair);
return repair;
}
private adjustCardForRange(
card: InternalMatchCardView,
filteredGames: InternalGameDetail[],
filteredGames: Pick<InternalGameDetail, 'gameNumber'>[],
): InternalMatchCardView {
const allowedGameNumbers = new Set(
filteredGames.map((game) => game.gameNumber),
@@ -706,13 +1135,20 @@ export class CommunityStatsService {
: season.startedAt
? new Date(season.startedAt)
: null;
const to = filters.to ? new Date(filters.to) : null;
const to = filters.to
? new Date(filters.to)
: season.endedAt
? new Date(season.endedAt)
: null;
if (from && Number.isNaN(from.getTime())) {
throw new BadRequestException('Invalid from date.');
}
if (to && Number.isNaN(to.getTime())) {
throw new BadRequestException('Invalid to date.');
}
if (from && to && from.getTime() > to.getTime()) {
throw new BadRequestException('Invalid date range.');
}
return { community, season, from, to };
}
@@ -761,7 +1197,9 @@ export class CommunityStatsService {
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
const byUser = new Map<string, InternalRecord[]>();
for (const record of records) {
byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]);
const rows = byUser.get(record.userId);
if (rows) rows.push(record);
else byUser.set(record.userId, [record]);
}
return [...byUser.entries()]
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
@@ -816,6 +1254,7 @@ export class CommunityStatsService {
return {
userId,
summonerName: first?.summonerName ?? 'Unknown',
tagLine: first?.tagLine || undefined,
profileIconId: first?.profileIconId ?? 0,
games: records.length,
wins,
@@ -907,10 +1346,22 @@ export class CommunityStatsService {
totalKills: kills,
totalDeaths: deaths,
totalAssists: assists,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
doubleKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.doubleKills ?? 0),
0,
),
tripleKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.tripleKills ?? 0),
0,
),
quadraKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.quadraKills ?? 0),
0,
),
pentaKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.pentaKills ?? 0),
0,
),
avgCs: this.average(this.sum(rows, 'cs'), rows.length),
avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes),
};
@@ -980,6 +1431,7 @@ export class CommunityStatsService {
championLevel: record.championLevel,
teamPosition: record.teamPosition,
kills: record.kills,
largestMultiKill: record.multiKills?.largestMultiKill,
deaths: record.deaths,
assists: record.assists,
kda: this.kda(record.kills, record.deaths, record.assists),
@@ -1006,6 +1458,14 @@ export class CommunityStatsService {
puuid: participant.userId,
gameName: participant.summonerName,
tagLine: '',
tier: participant.tier
? {
tier: participant.tier.tier,
rank: participant.tier.rank,
leaguePoints: participant.tier.leaguePoints,
fetchedAt: new Date(participant.tier.fetchedAt).toISOString(),
}
: undefined,
championId: participant.championId,
championLevel: participant.championLevel,
teamPosition: participant.teamPosition,
@@ -1161,13 +1621,18 @@ export class CommunityStatsService {
communityId.toString(),
cacheScope,
JSON.stringify([
scope,
MATCH_STATS_BUILDER_VERSION,
scope === 'matches' ? 'matches-page-v1' : scope,
filters.seasonId ?? 'current',
filters.from ?? '',
filters.to ?? '',
filters.championId ?? '',
filters.cursor ?? '',
filters.limit ?? '',
filters.query ?? '',
filters.format ?? '',
filters.playerId ?? '',
filters.cursorMatchId ?? '',
]),
);
}
@@ -1210,6 +1675,46 @@ export class CommunityStatsService {
}
}
interface LinkedDetailGame {
game: InternalGameDetail;
official?: CompetitionGameView;
analysisAvailability: GameAnalysisAvailability;
}
function linkDetailGames(
dataset: BaseDataset,
matchId: string,
): LinkedDetailGame[] {
const officialByEvidence = new Map<string, CompetitionGameView | null>();
for (const game of dataset.competition?.projection.games ?? []) {
const evidence =
game.evidence.type === 'riot'
? game.evidence.riotMatchId
: game.evidence.legacyReference;
const key = JSON.stringify([game.displayNumber, evidence]);
officialByEvidence.set(key, officialByEvidence.has(key) ? null : game);
}
return (dataset.detailsByMatchId.get(matchId) ?? []).flatMap((game) => {
const official = officialByEvidence.get(
JSON.stringify([game.gameNumber, game.riotMatchId]),
);
if (dataset.competition && !official) return [];
// A Riot ID is evidence, not a pending raw fetch. Detail hydration only
// fetches timelines for matches whose raw data is already archived.
const analysisAvailability: GameAnalysisAvailability =
game.rawAvailable === false ? 'missing' : 'available';
return [{ game, official: official ?? undefined, analysisAvailability }];
});
}
function needsDetailHydration({
game,
analysisAvailability,
}: LinkedDetailGame) {
return analysisAvailability === 'available' && game.timelineLoaded !== true;
}
function isCompleteMatchDetailResponse(
response: InternalMatchDetailResponse,
): boolean {
@@ -1,3 +1,11 @@
import type {
GameAnalysisAvailability,
GameId,
GameSlotId,
InternalMatchCompetition,
InternalMatchResultPresentation,
SeriesId,
} from '@lolympus/contracts';
import type {
MatchStatsParticipantCheckpoints,
MatchStatsItemBuildEvent,
@@ -19,11 +27,16 @@ export interface CommunityStatsFilters {
championId?: number;
cursor?: number;
limit?: number;
query?: string;
format?: 'pair' | 'tournament';
playerId?: string;
cursorMatchId?: string;
}
export interface InternalMatchListResponse {
matches: InternalMatchCardView[];
nextCursor: number | null;
nextCursorMatchId?: string;
season: HistorySeasonDto;
}
@@ -34,6 +47,7 @@ export interface InternalMatchCardView {
status: 'finished' | 'in-progress';
gameCount: number;
winnerTeamIndex?: number;
resultPresentation?: InternalMatchResultPresentation;
seriesResults: Array<{
teamAIndex: number;
teamBIndex: number;
@@ -64,11 +78,13 @@ export interface InternalMatchCardView {
export interface LeaderboardResponse {
rows: LeaderboardRow[];
season: HistorySeasonDto;
matchedUserIds?: string[];
}
export interface LeaderboardRow {
userId: string;
summonerName: string;
tagLine?: string;
profileIconId: number;
games: number;
wins: number;
@@ -105,6 +121,7 @@ export interface TeamInsightsResponse {
red: number;
bluePicks: number;
redPicks: number;
confirmed: { sampleSize: number; blue: number; red: number };
};
topKda: LeaderHighlight | null;
mostKills: LeaderHighlight | null;
@@ -116,8 +133,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;
@@ -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,7 +5,7 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
export type MatchStatsUserRecordFragment = Pick<
MatchStats,
'matchId' | 'records'
'matchId' | 'records' | 'builderVersion'
>;
export type MatchStatsDetailFragment = Pick<
@@ -152,6 +152,111 @@ 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) {
filter['matchCard.title'] = {
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
$options: 'i',
};
}
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,
})
.sort({ scheduledAt: -1, matchId: -1 })
.limit(params.limit)
.lean()
.exec();
}
public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId;
fromGameCreation?: number;
@@ -175,6 +280,51 @@ 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,
'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,
})
.sort({ scheduledAt: -1 })
.lean()
.exec();
}
public async findByUser(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
@@ -202,7 +352,7 @@ 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 })
.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;
@@ -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,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;
});
}
+12 -1
View File
@@ -14,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'];
@@ -1019,6 +1020,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;
@@ -1051,6 +1060,7 @@ export interface MatchStatsGameDetail {
gameCreation: number;
gameDuration: number;
gameVersion?: string;
rawAvailable?: boolean;
winnerSide: TeamSide;
timeline: MatchStatsTimelinePoint[];
timelineLoaded?: boolean;
@@ -2535,7 +2545,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,
@@ -2544,6 +2554,7 @@ 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 }
@@ -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;
}
@@ -18,6 +18,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! },
@@ -130,6 +135,34 @@ function createHarness() {
});
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,
@@ -168,6 +201,7 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
teamId: 100,
win: true,
kills: 5,
tripleKills: 1,
deaths: 2,
assists: 3,
totalMinionsKilled: 100,
@@ -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,
@@ -218,6 +219,7 @@ 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,
@@ -230,6 +232,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;
@@ -593,6 +653,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(
@@ -1,4 +1,5 @@
import type { MatchStatsRunePerks, RiotLane } from '../global/database/schema';
import type { RecentMatchParticipantRank } from '@lolympus/contracts';
import type {
RiotQueueGroup,
RiotRankFilter,
@@ -115,6 +116,7 @@ export interface RecentMatchTeamParticipantView {
championId: number;
championLevel: number;
teamPosition: string;
tier?: RecentMatchParticipantRank;
kills: number;
deaths: number;
assists: number;
@@ -147,6 +149,7 @@ export interface RecentMatchView {
championLevel: number;
teamPosition: string;
kills: number;
largestMultiKill?: number;
deaths: number;
assists: number;
kda: number;
+71 -2
View File
@@ -1,7 +1,9 @@
import type {
HallOfFameResponse,
MatchDetailResponse,
MatchEventType,
MatchListResponse,
MatchListView,
} from '@lolympus/contracts';
import {
BadRequestException,
@@ -17,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';
@@ -89,10 +92,38 @@ export class MatchController {
@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,
@@ -103,11 +134,15 @@ export class MatchController {
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) => {
@@ -121,11 +156,26 @@ export class MatchController {
: {}),
});
const historyResult = historyResults?.get(summary._id);
return historyResult ? { ...summary, historyResult } : summary;
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(
@@ -135,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) =>
@@ -143,6 +193,8 @@ export class MatchController {
),
),
});
const progress = await this.matchService.getEventProgress([match]);
return { ...summary, eventProgress: progress.get(summary._id) };
}
@Patch(':matchId')
@@ -258,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,7 +375,7 @@ describe('MatchService', () => {
communityId,
scheduledAt: { $lt: scheduledTo },
});
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 });
expect(sort).toHaveBeenCalledWith({ scheduledAt: -1, _id: -1 });
});
it.each([
+236 -4
View File
@@ -1,4 +1,12 @@
import type { MatchEventType, MatchHistoryResult } from '@lolympus/contracts';
import type {
HallOfFameResponse,
MatchEventStage,
MatchEventType,
MatchHistoryResult,
MatchId,
MatchListView,
UserId,
} from '@lolympus/contracts';
import {
BadRequestException,
ConflictException,
@@ -9,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,
@@ -62,6 +71,8 @@ interface ListMatchesQuery {
scheduledFrom?: Date;
scheduledTo?: Date;
sort?: 'asc' | 'desc';
view?: MatchListView;
asOf?: Date;
}
interface ListMatchesPageQuery extends ListMatchesQuery {
@@ -77,6 +88,10 @@ interface MatchListFilter {
$gte?: Date;
$lt?: Date;
};
$or?: Array<{
status: MatchStatus | { $in: MatchStatus[] };
scheduledAt?: { $lt: Date };
}>;
}
interface JoinMatchParams {
@@ -219,6 +234,203 @@ export class MatchService {
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;
@@ -714,10 +926,26 @@ 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;
query.eventType === 'inhouse'
? { $in: ['inhouse', null] }
: query.eventType;
}
if (query.scheduledFrom || query.scheduledTo) {
filter.scheduledAt = {};
@@ -727,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,
@@ -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;
}