This commit is contained in:
dahyeon committed 2026-05-03 20:42:26 -07:00
1 parent 3b3c564075
commit 00448c94f3
16 files changed
+1529 -510

No files matched your search

@@ -1,7 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'; import { Injectable, Logger } from '@nestjs/common';
import { GarnetService } from '../global/garnet/garnet.service'; import { GarnetService } from '../global/garnet/garnet.service';
const COMMUNITY_STATS_TTL_SECONDS = 60 * 60; const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
@Injectable() @Injectable()
@@ -2,10 +2,19 @@ import { Module } from '@nestjs/common';
import { CommunityStatsCacheService } from './community-stats-cache.service'; import { CommunityStatsCacheService } from './community-stats-cache.service';
import { CommunityStatsController } from './community-stats.controller'; import { CommunityStatsController } from './community-stats.controller';
import { CommunityStatsService } from './community-stats.service'; import { CommunityStatsService } from './community-stats.service';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
@Module({ @Module({
controllers: [CommunityStatsController], controllers: [CommunityStatsController],
providers: [CommunityStatsService, CommunityStatsCacheService], providers: [
exports: [CommunityStatsService], CommunityStatsService,
CommunityStatsCacheService,
MatchStatsFragmentBuilder,
MatchStatsRepository,
MatchStatsService,
],
exports: [CommunityStatsService, MatchStatsService],
}) })
export class CommunityStatsModule {} export class CommunityStatsModule {}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,98 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
function makeMatch(): MatchDocument {
const userId = new mongoose.Types.ObjectId();
return {
_id: new mongoose.Types.ObjectId(),
communityId: new mongoose.Types.ObjectId(),
title: '내전',
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
status: 'finished',
gameCount: 1,
participants: [
{
userId,
puuid: 'puuid-1',
gameName: 'Player',
profileIconId: 7,
},
],
teams: [
{
teamIndex: 1,
name: 'A',
members: [{ userId, assignedPosition: 'TOP' }],
},
{ teamIndex: 2, name: 'B', members: [] },
],
result: {
winnerTeamIndex: 1,
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
winnerSide: 'blue',
gameCreation: 1_000,
gameDuration: 1_800,
participants: [
{
userId,
teamIndex: 1,
side: 'blue',
championId: 266,
kills: 5,
deaths: 1,
assists: 7,
win: true,
},
],
},
],
seriesResults: [
{
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 1,
teamBWins: 0,
winnerTeamIndex: 1,
},
],
},
} as unknown as MatchDocument;
}
describe('MatchStatsFragmentBuilder', () => {
it('builds a fallback fragment without raw Riot match data', () => {
const builder = new MatchStatsFragmentBuilder();
const match = makeMatch();
const fragment = builder.buildFragment({
match,
rawByRiotMatchId: new Map(),
});
expect(fragment.matchCard.matchId).toBe(match._id.toString());
expect(fragment.gameCreationMin).toBe(1_000);
expect(fragment.gameCreationMax).toBe(1_000);
expect(fragment.userIds.map((id) => id.toString())).toEqual([
match.participants[0].userId.toString(),
]);
expect(fragment.championIds).toEqual([266]);
expect(fragment.records).toHaveLength(1);
expect(fragment.records[0]).toMatchObject({
summonerName: 'Player',
championId: 266,
kills: 5,
deaths: 1,
assists: 7,
win: true,
});
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1);
});
});
@@ -0,0 +1,367 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import type {
MatchDocument,
MatchGameResultParticipant,
TeamSide,
} from '../global/database/schema';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
import type { InternalMatchCardView } from './community-stats.types';
import type {
InternalGameDetail,
InternalRecord,
MatchStatsFragment,
} from './match-stats.types';
@Injectable()
export class MatchStatsFragmentBuilder {
public buildFragment(params: {
match: MatchDocument;
rawByRiotMatchId: Map<string, RiotMatchDto>;
}): MatchStatsFragment {
const games = [...(params.match.result?.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
);
const matchCard = this.toMatchCard(params.match, games);
const gameDetails = games.map((game) => {
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
return raw
? this.toGameDetail(params.match, game, raw)
: this.toFallbackGameDetail(params.match, game);
});
const records = gameDetails.flatMap((detail) =>
detail.teams.flatMap((team) => team.participants),
);
const gameCreations = gameDetails.map((detail) => detail.gameCreation);
return {
matchCard,
records,
gameDetails,
userIds: [
...new Map(
records
.filter((record) => mongoose.isValidObjectId(record.userId))
.map((record) => [
record.userId,
new mongoose.Types.ObjectId(record.userId),
]),
).values(),
],
championIds: [...new Set(records.map((record) => record.championId))],
gameCreationMin:
gameCreations.length > 0
? Math.min(...gameCreations)
: params.match.scheduledAt.getTime(),
gameCreationMax:
gameCreations.length > 0
? Math.max(...gameCreations)
: params.match.scheduledAt.getTime(),
};
}
private toMatchCard(
match: MatchDocument,
games: NonNullable<MatchDocument['result']>['games'],
): InternalMatchCardView {
const participantById = new Map(
match.participants.map((participant) => [
participant.userId.toString(),
participant,
]),
);
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
status: match.status === 'finished' ? 'finished' : 'in-progress',
gameCount: match.gameCount,
winnerTeamIndex: match.result?.winnerTeamIndex,
seriesResults: match.result?.seriesResults ?? [],
games: games.map((game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId ?? null,
blueTeamIndex: game.blueTeamIndex,
redTeamIndex: game.redTeamIndex,
winnerTeamIndex: game.winnerTeamIndex ?? null,
winnerSide: game.winnerSide ?? null,
gameDuration: game.gameDuration,
})),
teams: match.teams.map((team) => ({
teamIndex: team.teamIndex,
name: team.name,
members: team.members.map((member) => {
const participant = participantById.get(member.userId.toString());
return {
userId: member.userId.toString(),
summonerName: participant?.gameName ?? 'Unknown',
profileIconId: participant?.profileIconId ?? 0,
};
}),
})),
};
}
private toGameDetail(
match: MatchDocument,
game: NonNullable<MatchDocument['result']>['games'][number],
raw: RiotMatchDto,
): InternalGameDetail {
const puuidByUserId = new Map(
match.participants
.filter((participant) => participant.puuid)
.map((participant) => [
participant.userId.toString(),
participant.puuid as string,
]),
);
const rawByPuuid = new Map(
raw.info.participants.map((participant) => [
participant.puuid,
participant,
]),
);
const rawTeamIdBySide = new Map<TeamSide, number>();
for (const participant of game.participants) {
const puuid = puuidByUserId.get(participant.userId.toString());
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
if (rawParticipant) {
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
}
}
return {
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
winnerSide: game.winnerSide,
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
const teamIndex =
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
const rawTeamId = rawTeamIdBySide.get(side);
const rawTeam = raw.info.teams.find(
(team) => team.teamId === rawTeamId,
);
const teamRawParticipants = raw.info.participants.filter(
(participant) => participant.teamId === rawTeamId,
);
const teamKills = teamRawParticipants.reduce(
(sum, participant) => sum + participant.kills,
0,
);
const teamDamage = teamRawParticipants.reduce(
(sum, participant) => sum + participant.totalDamageDealtToChampions,
0,
);
return {
teamIndex,
side,
win: game.winnerSide === side,
objectives: {
baron: rawTeam?.objectives?.baron?.kills ?? 0,
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
tower: rawTeam?.objectives?.tower?.kills ?? 0,
},
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
this.toRecord({
match,
game,
participant,
rawParticipant: rawByPuuid.get(
puuidByUserId.get(participant.userId.toString()) ?? '',
),
teamKills,
teamDamage,
}),
),
};
}),
};
}
private toFallbackGameDetail(
match: MatchDocument,
game: NonNullable<MatchDocument['result']>['games'][number],
): InternalGameDetail {
return {
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
winnerSide: game.winnerSide,
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
side,
win: game.winnerSide === side,
objectives: { baron: 0, dragon: 0, tower: 0 },
participants: game.participants
.filter((participant) => participant.side === side)
.map((participant) =>
this.toRecord({
match,
game,
participant,
teamKills: 0,
teamDamage: 0,
}),
),
})),
};
}
private toRecord(params: {
match: MatchDocument;
game: NonNullable<MatchDocument['result']>['games'][number];
participant: MatchGameResultParticipant;
rawParticipant?: RiotMatchParticipantDto;
teamKills: number;
teamDamage: number;
}): InternalRecord {
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
params;
const snapshot = match.participants.find((item) =>
item.userId.equals(participant.userId),
);
const minutes = Math.max(
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
1,
);
const cs = rawParticipant
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
: 0;
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
const killParticipation = percent(
participant.kills + participant.assists,
teamKills,
);
const damageShare = percent(damage, teamDamage);
const rating = this.resolveRating({
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
killParticipation,
csPerMin: average(cs, minutes),
damageShare,
visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes),
});
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt,
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
userId: participant.userId.toString(),
summonerName:
snapshot?.gameName ??
rawParticipant?.riotIdGameName ??
rawParticipant?.summonerName ??
'Unknown',
profileIconId: snapshot?.profileIconId ?? 0,
teamIndex: participant.teamIndex,
side: participant.side,
championId: participant.championId,
championLevel: rawParticipant?.champLevel ?? 0,
teamPosition:
rawParticipant?.teamPosition ||
rawParticipant?.individualPosition ||
'',
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
cs,
csPerMin: average(cs, minutes),
gold: rawParticipant?.goldEarned ?? 0,
gpm: average(rawParticipant?.goldEarned ?? 0, minutes),
damageDealtToChampions: damage,
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
damageShare,
killParticipation,
visionScore: rawParticipant?.visionScore ?? 0,
controlWardsBought: numberField(
rawParticipant,
'visionWardsBoughtInGame',
),
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
wardsKilled: rawParticipant?.wardsKilled ?? 0,
items: [
rawParticipant?.item0 ?? 0,
rawParticipant?.item1 ?? 0,
rawParticipant?.item2 ?? 0,
rawParticipant?.item3 ?? 0,
rawParticipant?.item4 ?? 0,
rawParticipant?.item5 ?? 0,
],
trinket: rawParticipant?.item6 ?? 0,
summonerSpells: [
rawParticipant?.summoner1Id ?? 0,
rawParticipant?.summoner2Id ?? 0,
],
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
rating,
};
}
private resolvePerks(participant: RiotMatchParticipantDto) {
const primary = participant.perks.styles.find(
(style) => style.description === 'primaryStyle',
);
const sub = participant.perks.styles.find(
(style) => style.description === 'subStyle',
);
return {
primaryStyle: primary?.style,
subStyle: sub?.style,
keystone: primary?.selections[0]?.perk,
};
}
private resolveRating(params: {
kills: number;
deaths: number;
assists: number;
killParticipation: number;
csPerMin: number;
damageShare: number;
visionPerMin: number;
}): number {
const kdaScore = kda(params.kills, params.deaths, params.assists);
const score =
Math.min(kdaScore / 6, 1) * 4 +
Math.min(params.killParticipation / 100, 1) * 2 +
Math.min(params.csPerMin / 9, 1) * 2 +
Math.min(params.damageShare / 35, 1) +
Math.min(params.visionPerMin / 2, 1);
return round(score);
}
}
function kda(kills: number, deaths: number, assists: number): number {
return deaths === 0 ? kills + assists : round((kills + assists) / deaths);
}
function percent(value: number, total: number): number {
return total > 0 ? Math.round((value / total) * 100) : 0;
}
function average(value: number, total: number): number {
return total > 0 ? round(value / total) : 0;
}
function round(value: number): number {
return Math.round(value * 10) / 10;
}
function numberField(
participant: RiotMatchParticipantDto | undefined,
key: string,
): number {
const value = participant?.[key];
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
@@ -0,0 +1,84 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
@Injectable()
export class MatchStatsRepository {
constructor(private readonly connectionService: ConnectionService) {}
public async upsert(
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $set: fragment },
{ upsert: true },
).exec();
}
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({ matchId }).exec();
}
public async deleteByMatches(
matchIds: mongoose.Types.ObjectId[],
): Promise<void> {
if (matchIds.length === 0) return;
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
}
public async findByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<MatchStatsDocument | null> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
return MatchStatsModel.findOne({ matchId }).exec();
}
public async findByCommunity(params: {
communityId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
limit?: number;
}): Promise<MatchStatsDocument[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = {
communityId: params.communityId,
};
if (params.fromGameCreation !== undefined) {
filter.gameCreationMax = { $gte: params.fromGameCreation };
}
if (params.toGameCreation !== undefined) {
filter.gameCreationMin = { $lte: params.toGameCreation };
}
return MatchStatsModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(params.limit ?? 300)
.exec();
}
public async findByUser(params: {
communityId: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
fromGameCreation?: number;
toGameCreation?: number;
}): Promise<MatchStatsDocument[]> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
const filter: Record<string, unknown> = {
communityId: params.communityId,
userIds: params.userId,
};
if (params.fromGameCreation !== undefined) {
filter.gameCreationMax = { $gte: params.fromGameCreation };
}
if (params.toGameCreation !== undefined) {
filter.gameCreationMin = { $lte: params.toGameCreation };
}
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
}
}
@@ -0,0 +1,104 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
describe('MatchStatsService', () => {
it('deletes an existing fragment when the match is no longer eligible', async () => {
const matchId = new mongoose.Types.ObjectId();
const findById = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: matchId,
status: 'recruiting',
result: undefined,
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
);
await service.buildAndUpsert(matchId);
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
expect(repository.upsert).not.toHaveBeenCalled();
});
it('upserts a fragment for eligible matches', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const scheduledAt = new Date('2026-05-03T00:00:00.000Z');
const match = {
_id: matchId,
communityId,
scheduledAt,
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const findById = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(match),
});
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
);
await service.buildAndUpsert(matchId);
expect(builder.buildFragment).toHaveBeenCalledWith({
match,
rawByRiotMatchId: expect.any(Map),
});
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
communityId,
scheduledAt,
gameCreationMin: 1_000,
gameCreationMax: 2_000,
builderVersion: 1,
}),
);
});
});
@@ -0,0 +1,104 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
import { MatchStatsRepository } from './match-stats.repository';
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
@Injectable()
export class MatchStatsService {
constructor(
private readonly connectionService: ConnectionService,
private readonly repository: MatchStatsRepository,
private readonly builder: MatchStatsFragmentBuilder,
) {}
public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise<void> {
const MatchModel = await this.connectionService.getModel('match');
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const match = await MatchModel.findById(matchId).exec();
if (!match) return;
if (!this.isEligible(match)) {
await this.repository.deleteByMatch(matchId);
return;
}
const riotIds = [
...new Set(
(match.result?.games ?? [])
.map((game) => game.riotMatchId)
.filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)),
),
];
const riotDocs =
riotIds.length > 0
? await RiotMatchModel.find({ matchId: { $in: riotIds } })
.lean()
.exec()
: [];
const rawByRiotMatchId = new Map(
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
);
const fragment = this.builder.buildFragment({ match, rawByRiotMatchId });
await this.repository.upsert({
matchId: match._id,
communityId: match.communityId,
scheduledAt: match.scheduledAt,
gameCreationMin: fragment.gameCreationMin,
gameCreationMax: fragment.gameCreationMax,
userIds: fragment.userIds,
championIds: fragment.championIds,
matchCard: fragment.matchCard as unknown as Record<string, unknown>,
records: fragment.records,
gameDetails: fragment.gameDetails,
builtAt: new Date(),
builderVersion: MATCH_STATS_BUILDER_VERSION,
});
}
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
await this.repository.deleteByMatch(matchId);
}
public async removeByMatches(
matchIds: mongoose.Types.ObjectId[],
): Promise<void> {
await this.repository.deleteByMatches(matchIds);
}
public async backfillCommunity(
communityId: mongoose.Types.ObjectId,
): Promise<{ processed: number; failed: number }> {
const MatchModel = await this.connectionService.getModel('match');
const matches = await MatchModel.find({
communityId,
status: { $in: ['finished', 'in-progress'] },
'result.games.0': { $exists: true },
})
.sort({ scheduledAt: -1 })
.select({ _id: 1 })
.exec();
let processed = 0;
let failed = 0;
for (const match of matches) {
try {
await this.buildAndUpsert(match._id);
processed += 1;
} catch {
failed += 1;
}
}
return { processed, failed };
}
private isEligible(match: MatchDocument): boolean {
return (
(match.status === 'finished' || match.status === 'in-progress') &&
Boolean(match.result?.games?.length)
);
}
}
@@ -0,0 +1,20 @@
import type {
MatchStatsGameDetail,
MatchStatsRecord,
} from '../global/database/schema';
import type { InternalMatchCardView } from './community-stats.types';
export const MATCH_STATS_BUILDER_VERSION = 1;
export type InternalRecord = MatchStatsRecord;
export type InternalGameDetail = MatchStatsGameDetail;
export interface MatchStatsFragment {
matchCard: InternalMatchCardView;
records: InternalRecord[];
gameDetails: InternalGameDetail[];
userIds: import('mongoose').Types.ObjectId[];
championIds: number[];
gameCreationMin: number;
gameCreationMax: number;
}
@@ -0,0 +1,102 @@
import { NestFactory } from '@nestjs/core';
import mongoose from 'mongoose';
import { AppModule } from '../../../../app.module';
import { ConnectionService } from '../connection.service';
import { MatchStatsService } from '../../../community-stats/match-stats.service';
interface Options {
communityId?: mongoose.Types.ObjectId;
dryRun: boolean;
force: boolean;
}
async function main() {
const options = parseArgs(process.argv.slice(2));
const app = await NestFactory.createApplicationContext(AppModule, {
logger: ['log', 'warn', 'error'],
});
try {
const connectionService = app.get(ConnectionService);
const matchStatsService = app.get(MatchStatsService);
const MatchModel = await connectionService.getModel('match');
const MatchStatsModel = await connectionService.getModel('matchStats');
const filter: Record<string, unknown> = {
status: { $in: ['finished', 'in-progress'] },
'result.games.0': { $exists: true },
};
if (options.communityId) filter.communityId = options.communityId;
const matches = await MatchModel.find(filter)
.sort({ scheduledAt: -1 })
.select({ _id: 1 })
.exec();
console.log(`match_stats backfill target=${matches.length}`);
let processed = 0;
let skipped = 0;
let failed = 0;
for (const match of matches) {
if (!options.force) {
const existing = await MatchStatsModel.exists({ matchId: match._id });
if (existing) {
skipped += 1;
continue;
}
}
if (options.dryRun) {
processed += 1;
continue;
}
try {
await matchStatsService.buildAndUpsert(match._id);
processed += 1;
} catch (error) {
failed += 1;
console.warn(
`failed ${match._id.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
}
if ((processed + skipped + failed) % 50 === 0) {
console.log(
`progress processed=${processed} skipped=${skipped} failed=${failed}`,
);
}
}
console.log(
`done processed=${processed} skipped=${skipped} failed=${failed}`,
);
} finally {
await app.close();
}
}
function parseArgs(args: string[]): Options {
const options: Options = { dryRun: false, force: false };
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === '--dry-run') options.dryRun = true;
if (arg === '--force') options.force = true;
if (arg === '--community-id') {
const value = args[index + 1];
if (!value || !mongoose.isValidObjectId(value)) {
throw new Error('--community-id requires a valid ObjectId');
}
options.communityId = new mongoose.Types.ObjectId(value);
index += 1;
}
}
return options;
}
void main().catch((error) => {
console.error(error);
process.exit(1);
});
+134 -6
View File
@@ -65,7 +65,11 @@ export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [
]; ];
export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed'; export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed';
export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed'; export type MatchResultPollStateValue =
| 'polling'
| 'complete'
| 'expired'
| 'failed';
export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [ export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [
'polling', 'polling',
'complete', 'complete',
@@ -562,8 +566,79 @@ export interface AuctionHistoryEntry extends MongooseTimestamps {
takenAt: Date; takenAt: Date;
} }
export type AuctionHistoryEntryDocument = export type AuctionHistoryEntryDocument = HydratedDocument<AuctionHistoryEntry>;
HydratedDocument<AuctionHistoryEntry>;
// ===== MatchStats (precomputed internal stats fragment) =====
export interface MatchStatsRecord {
matchId: string;
title: string;
scheduledAt: Date;
gameNumber: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
userId: string;
summonerName: string;
profileIconId: number;
teamIndex: number;
side: TeamSide;
championId: number;
championLevel: number;
teamPosition: string;
kills: number;
deaths: number;
assists: number;
win: boolean;
cs: number;
csPerMin: number;
gold: number;
gpm: number;
damageDealtToChampions: number;
damageTaken: number;
damageShare: number;
killParticipation: number;
visionScore: number;
controlWardsBought: number;
wardsPlaced: number;
wardsKilled: number;
items: number[];
trinket: number;
summonerSpells: [number, number];
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
rating: number;
}
export interface MatchStatsGameDetail {
gameNumber: number;
riotMatchId: string;
gameCreation: number;
gameDuration: number;
winnerSide: TeamSide;
teams: Array<{
teamIndex: number;
side: TeamSide;
win: boolean;
objectives: { baron: number; dragon: number; tower: number };
participants: MatchStatsRecord[];
}>;
}
export interface MatchStats extends MongooseTimestamps {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
scheduledAt: Date;
gameCreationMin: number;
gameCreationMax: number;
userIds: mongoose.Types.ObjectId[];
championIds: number[];
matchCard: Record<string, unknown>;
records: MatchStatsRecord[];
gameDetails: MatchStatsGameDetail[];
builtAt: Date;
builderVersion: number;
}
export type MatchStatsDocument = HydratedDocument<MatchStats>;
// ===== Sub-schemas ===== // ===== Sub-schemas =====
const PositionPreferenceSubSchema = new Schema<PositionPreference>( const PositionPreferenceSubSchema = new Schema<PositionPreference>(
@@ -1068,7 +1143,9 @@ const MatchScheduleItemSubSchema = new Schema<MatchScheduleItem>(
{ _id: false }, { _id: false },
); );
const MatchLegacyImportSourceSubSchema = new Schema<NonNullable<Match['legacyImportSource']>>( const MatchLegacyImportSourceSubSchema = new Schema<
NonNullable<Match['legacyImportSource']>
>(
{ {
importedAt: { type: Date, required: true }, importedAt: { type: Date, required: true },
importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true }, importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
@@ -1109,7 +1186,8 @@ export const MatchSchema = new Schema<Match>(
default: 10, default: 10,
min: 10, min: 10,
validate: { validate: {
validator: (value: number) => Number.isInteger(value) && value % 10 === 0, validator: (value: number) =>
Number.isInteger(value) && value % 10 === 0,
message: 'maxParticipants must be a multiple of 10.', message: 'maxParticipants must be a multiple of 10.',
}, },
}, },
@@ -1379,7 +1457,15 @@ const AuctionHistoryEntrySchema = new Schema<AuctionHistoryEntry>(
sequence: { type: Number, required: true, min: 1 }, sequence: { type: Number, required: true, min: 1 },
action: { action: {
type: String, type: String,
enum: ['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete'], enum: [
'start',
'open-bidding',
'bid',
'sold',
'passed',
'next',
'complete',
],
required: true, required: true,
}, },
actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false }, actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
@@ -1394,6 +1480,42 @@ const AuctionHistoryEntrySchema = new Schema<AuctionHistoryEntry>(
AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 }); AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 });
export const MatchStatsSchema: mongoose.Schema<MatchStats> = new Schema(
{
matchId: {
type: Schema.Types.ObjectId,
ref: 'match',
required: true,
unique: true,
},
communityId: {
type: Schema.Types.ObjectId,
ref: 'community',
required: true,
},
scheduledAt: { type: Date, required: true },
gameCreationMin: { type: Number, required: true },
gameCreationMax: { type: Number, required: true },
userIds: { type: [Schema.Types.ObjectId], required: true, default: [] },
championIds: { type: [Number], required: true, default: [] },
matchCard: { type: Schema.Types.Mixed, required: true },
records: { type: [Schema.Types.Mixed], required: true, default: [] },
gameDetails: { type: [Schema.Types.Mixed], required: true, default: [] },
builtAt: { type: Date, required: true, default: Date.now },
builderVersion: { type: Number, required: true, default: 1 },
} as mongoose.SchemaDefinition,
{ timestamps: true, collection: 'match_stats' },
) as mongoose.Schema<MatchStats>;
MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 });
MatchStatsSchema.index({
communityId: 1,
gameCreationMin: 1,
gameCreationMax: 1,
});
MatchStatsSchema.index({ communityId: 1, userIds: 1 });
MatchStatsSchema.index({ communityId: 1, championIds: 1 });
export const tournamentModelDefinitions: ModelDefinition[] = [ export const tournamentModelDefinitions: ModelDefinition[] = [
{ name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'identity', schema: IdentitySchema, schemaName: 'identity' },
{ name: 'community', schema: CommunitySchema, schemaName: 'community' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' },
@@ -1416,6 +1538,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
schema: AuctionHistoryEntrySchema, schema: AuctionHistoryEntrySchema,
schemaName: 'auctionHistory', schemaName: 'auctionHistory',
}, },
{
name: 'matchStats',
schema: MatchStatsSchema,
schemaName: 'matchStats',
},
]; ];
export interface TournamentModelTypes { export interface TournamentModelTypes {
@@ -1428,4 +1555,5 @@ export interface TournamentModelTypes {
match: Match; match: Match;
auction: Auction; auction: Auction;
auctionHistory: AuctionHistoryEntry; auctionHistory: AuctionHistoryEntry;
matchStats: MatchStats;
} }
@@ -7,6 +7,7 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type {
@@ -55,6 +56,7 @@ export class LegacyImportService {
private readonly garnetService: GarnetService, private readonly garnetService: GarnetService,
private readonly riotMatchService: RiotMatchService, private readonly riotMatchService: RiotMatchService,
private readonly communityStatsService: CommunityStatsService, private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
) {} ) {}
public async previewMembers(params: { public async previewMembers(params: {
@@ -107,8 +109,12 @@ export class LegacyImportService {
]), ]),
); );
const windows = users const windows = users
.map((user) => this.resolveMemberWindow(user, windowStart, windowEnd, overrides)) .map((user) =>
.filter((window) => window.startTime.getTime() <= window.endTime.getTime()); this.resolveMemberWindow(user, windowStart, windowEnd, overrides),
)
.filter(
(window) => window.startTime.getTime() <= window.endTime.getTime(),
);
const LegacyImportJobModel = const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob'); await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.create({ await LegacyImportJobModel.create({
@@ -174,7 +180,9 @@ export class LegacyImportService {
}): Promise<{ jobs: LegacyImportJobDocument[] }> { }): Promise<{ jobs: LegacyImportJobDocument[] }> {
const LegacyImportJobModel = const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob'); await this.connectionService.getModel('legacyImportJob');
const jobs = await LegacyImportJobModel.find({ communityId: params.communityId }) const jobs = await LegacyImportJobModel.find({
communityId: params.communityId,
})
.sort({ startedAt: -1 }) .sort({ startedAt: -1 })
.limit(Math.min(params.limit ?? 10, 50)) .limit(Math.min(params.limit ?? 10, 50))
.exec(); .exec();
@@ -210,7 +218,8 @@ export class LegacyImportService {
{ $set: { state: 'cancelled', completedAt: new Date() } }, { $set: { state: 'cancelled', completedAt: new Date() } },
{ returnDocument: 'after' }, { returnDocument: 'after' },
).exec(); ).exec();
if (!job) throw new NotFoundException('Running legacy import job not found.'); if (!job)
throw new NotFoundException('Running legacy import job not found.');
await this.garnetService.delete(this.communityLockKey(params.communityId)); await this.garnetService.delete(this.communityLockKey(params.communityId));
return job; return job;
} }
@@ -284,7 +293,9 @@ export class LegacyImportService {
.map((match) => match.result?.games[0]?.riotMatchId) .map((match) => match.result?.games[0]?.riotMatchId)
.filter((matchId): matchId is string => Boolean(matchId)); .filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) const rawDocs = await RiotMatchModel.find({
matchId: { $in: riotMatchIds },
})
.lean() .lean()
.exec(); .exec();
const rawById = new Map( const rawById = new Map(
@@ -314,7 +325,7 @@ export class LegacyImportService {
}), }),
nextCursor: nextCursor:
matches.length > limit matches.length > limit
? visible[visible.length - 1]?.scheduledAt.getTime() ?? null ? (visible[visible.length - 1]?.scheduledAt.getTime() ?? null)
: null, : null,
}; };
} }
@@ -328,11 +339,22 @@ export class LegacyImportService {
.map((id) => new mongoose.Types.ObjectId(id)); .map((id) => new mongoose.Types.ObjectId(id));
if (ids.length === 0) return { deleted: 0 }; if (ids.length === 0) return { deleted: 0 };
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const result = await MatchModel.deleteMany({ const targets = await MatchModel.find({
_id: { $in: ids }, _id: { $in: ids },
communityId: params.communityId, communityId: params.communityId,
legacyImported: true, legacyImported: true,
})
.select({ _id: 1 })
.exec();
const targetIds = targets.map((match) => match._id);
if (targetIds.length === 0) return { deleted: 0 };
const result = await MatchModel.deleteMany({
_id: { $in: targetIds },
communityId: params.communityId,
legacyImported: true,
}).exec(); }).exec();
await this.matchStatsService.removeByMatches(targetIds);
await this.communityStatsService.invalidateCommunity(params.communityId); await this.communityStatsService.invalidateCommunity(params.communityId);
return { deleted: result.deletedCount ?? 0 }; return { deleted: result.deletedCount ?? 0 };
} }
@@ -348,12 +370,15 @@ export class LegacyImportService {
const riotMatchIds = matches const riotMatchIds = matches
.map( .map(
(match) => (match) =>
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0], match.result?.games[0]?.riotMatchId ??
match.result?.riotMatchIds?.[0],
) )
.filter((matchId): matchId is string => Boolean(matchId)); .filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) const rawDocs = await RiotMatchModel.find({
matchId: { $in: riotMatchIds },
})
.lean() .lean()
.exec(); .exec();
const rawById = new Map<string, RiotMatchDto>(); const rawById = new Map<string, RiotMatchDto>();
@@ -387,7 +412,11 @@ export class LegacyImportService {
if (!raw || !riotMatchId) { if (!raw || !riotMatchId) {
result.skippedMissingRaw += 1; result.skippedMissingRaw += 1;
if (Object.keys(update).length > 0) { if (Object.keys(update).length > 0) {
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec(); await MatchModel.updateOne(
{ _id: match._id },
{ $set: update },
).exec();
await this.matchStatsService.buildAndUpsert(match._id);
} }
continue; continue;
} }
@@ -397,7 +426,11 @@ export class LegacyImportService {
if (!gameResult || participants.length === 0) { if (!gameResult || participants.length === 0) {
result.skippedNoKnownParticipants += 1; result.skippedNoKnownParticipants += 1;
if (Object.keys(update).length > 0) { if (Object.keys(update).length > 0) {
await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec(); await MatchModel.updateOne(
{ _id: match._id },
{ $set: update },
).exec();
await this.matchStatsService.buildAndUpsert(match._id);
} }
continue; continue;
} }
@@ -429,6 +462,7 @@ export class LegacyImportService {
}, },
{ $set: update }, { $set: update },
).exec(); ).exec();
await this.matchStatsService.buildAndUpsert(match._id);
result.rebuilt += 1; result.rebuilt += 1;
} }
@@ -439,7 +473,9 @@ export class LegacyImportService {
return result; return result;
} }
private async collectMatchIds(job: LegacyImportMemberJob): Promise<Set<string>> { private async collectMatchIds(
job: LegacyImportMemberJob,
): Promise<Set<string>> {
const matchIds = new Set<string>(); const matchIds = new Set<string>();
let start = 0; let start = 0;
while (true) { while (true) {
@@ -478,7 +514,10 @@ export class LegacyImportService {
}); });
if (existing) return 'duplicate'; if (existing) return 'duplicate';
const detail = await this.ensureRiotMatchPersisted(riotMatchId, job.region); const detail = await this.ensureRiotMatchPersisted(
riotMatchId,
job.region,
);
if (!detail.info.tournamentCode) return 'skipped'; if (!detail.info.tournamentCode) return 'skipped';
const counts = countKnownParticipants(detail, userByPuuid); const counts = countKnownParticipants(detail, userByPuuid);
if (counts.total === 0) return 'skipped'; if (counts.total === 0) return 'skipped';
@@ -527,7 +566,8 @@ export class LegacyImportService {
notices: [], notices: [],
schedule: [], schedule: [],
}; };
await MatchModel.create(matchPayload); const match = await MatchModel.create(matchPayload);
await this.matchStatsService.buildAndUpsert(match._id);
return 'imported'; return 'imported';
} catch (error) { } catch (error) {
await this.recordError(job.parentJobId, { await this.recordError(job.parentJobId, {
@@ -546,7 +586,9 @@ export class LegacyImportService {
region: RiotRegionalRoute, region: RiotRegionalRoute,
): Promise<RiotMatchDto> { ): Promise<RiotMatchDto> {
const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec(); 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 dto = await this.riotMatchService.getMatch(riotMatchId, { region });
@@ -588,7 +630,9 @@ export class LegacyImportService {
const average = const average =
current.averageMemberSeconds === undefined current.averageMemberSeconds === undefined
? stats.elapsedSeconds ? stats.elapsedSeconds
: Math.round(current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3); : Math.round(
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
);
const nextProcessed = current.processedMembers + 1; const nextProcessed = current.processedMembers + 1;
const completed = nextProcessed >= current.totalMembers; const completed = nextProcessed >= current.totalMembers;
@@ -631,7 +675,8 @@ export class LegacyImportService {
jobId: job.parentJobId, jobId: job.parentJobId,
}).exec(); }).exec();
if (!legacyJob || legacyJob.state === 'cancelled') return null; if (!legacyJob || legacyJob.state === 'cancelled') return null;
if (legacyJob.state === 'completed' || legacyJob.state === 'failed') return null; if (legacyJob.state === 'completed' || legacyJob.state === 'failed')
return null;
return legacyJob; return legacyJob;
} }
@@ -686,7 +731,12 @@ export class LegacyImportService {
windowStart: Date, windowStart: Date,
windowEnd: Date, windowEnd: Date,
): LegacyImportMemberWindowView { ): LegacyImportMemberWindowView {
const resolved = this.resolveMemberWindow(user, windowStart, windowEnd, new Map()); const resolved = this.resolveMemberWindow(
user,
windowStart,
windowEnd,
new Map(),
);
const account = const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ?? user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0]; user.riotAccounts[0];
@@ -731,10 +781,7 @@ export class LegacyImportService {
}; };
} }
private resolveWindow(params: { private resolveWindow(params: { windowStart?: string; windowEnd?: string }) {
windowStart?: string;
windowEnd?: string;
}) {
const windowStart = const windowStart =
this.parseOptionalDate(params.windowStart) ?? this.parseOptionalDate(params.windowStart) ??
new Date(LEGACY_IMPORT_DEFAULT_START_ISO); new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
@@ -755,7 +802,9 @@ export class LegacyImportService {
} }
private minDate(...values: Array<Date | undefined>): Date { private minDate(...values: Array<Date | undefined>): Date {
return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime()))); return new Date(
Math.min(...values.filter(Boolean).map((date) => date!.getTime())),
);
} }
private normalizeLegacyTitle(title: string, gameCreation: number): string { private normalizeLegacyTitle(title: string, gameCreation: number): string {
@@ -782,8 +831,8 @@ export class LegacyImportService {
function isRiotMatchDto(value: unknown): value is RiotMatchDto { function isRiotMatchDto(value: unknown): value is RiotMatchDto {
return Boolean( return Boolean(
value && value &&
typeof value === 'object' && typeof value === 'object' &&
'metadata' in value && 'metadata' in value &&
'info' in value, 'info' in value,
); );
} }
@@ -19,14 +19,20 @@ describe('MatchService', () => {
const communityStatsService = { const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined), invalidateCommunity: jest.fn().mockResolvedValue(undefined),
}; };
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
removeByMatch: jest.fn().mockResolvedValue(undefined),
};
return { return {
service: new MatchService( service: new MatchService(
connectionService as never, connectionService as never,
tournamentCodeService as never, tournamentCodeService as never,
communityStatsService as never, communityStatsService as never,
matchStatsService as never,
), ),
tournamentCodeService, tournamentCodeService,
matchStatsService,
}; };
} }
@@ -49,7 +55,8 @@ describe('MatchService', () => {
}), }),
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
}; };
const { service, tournamentCodeService } = createService(match); const { service, tournamentCodeService, matchStatsService } =
createService(match);
await service.update({ await service.update({
matchId: new mongoose.Types.ObjectId(), matchId: new mongoose.Types.ObjectId(),
@@ -64,6 +71,7 @@ describe('MatchService', () => {
expect(match.result).toBeUndefined(); expect(match.result).toBeUndefined();
expect(match.resultPollState).toBeUndefined(); expect(match.resultPollState).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1); expect(match.save).toHaveBeenCalledTimes(1);
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
}); });
it('releases reserved codes when returning a built match to recruiting', async () => { it('releases reserved codes when returning a built match to recruiting', async () => {
@@ -5,6 +5,7 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { import {
@@ -59,6 +60,7 @@ export class MatchService {
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly tournamentCodeService: TournamentCodeService, private readonly tournamentCodeService: TournamentCodeService,
private readonly communityStatsService: CommunityStatsService, private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
) {} ) {}
public async create(params: CreateMatchParams): Promise<MatchDocument> { public async create(params: CreateMatchParams): Promise<MatchDocument> {
@@ -172,6 +174,13 @@ export class MatchService {
match.resultPollState = undefined; match.resultPollState = undefined;
} }
await match.save(); await match.save();
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
await this.matchStatsService.removeByMatch(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
} else if (match.result?.games?.length) {
await this.matchStatsService.buildAndUpsert(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
}
return match; return match;
} }
@@ -186,6 +195,7 @@ export class MatchService {
throw new BadRequestException('Match does not belong to this community.'); throw new BadRequestException('Match does not belong to this community.');
} }
await this.tournamentCodeService.releaseFromMatch(match); await this.tournamentCodeService.releaseFromMatch(match);
await this.matchStatsService.removeByMatch(match._id);
await match.deleteOne(); await match.deleteOne();
await this.communityStatsService.invalidateCommunity(params.communityId); await this.communityStatsService.invalidateCommunity(params.communityId);
} }
@@ -17,6 +17,7 @@ function createService() {
{} as never, {} as never,
{} as never, {} as never,
{} as never, {} as never,
{} as never,
) as unknown as TournamentResultServiceInternals; ) as unknown as TournamentResultServiceInternals;
} }
@@ -189,6 +190,7 @@ describe('TournamentResultService manual result collection', () => {
riotMatchService as never, riotMatchService as never,
{} as never, {} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
); );
return { return {
@@ -5,6 +5,7 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type {
@@ -55,6 +56,7 @@ export class TournamentResultService {
private readonly riotMatchService: RiotMatchService, private readonly riotMatchService: RiotMatchService,
private readonly riotJobQueueService: RiotJobQueueService, private readonly riotJobQueueService: RiotJobQueueService,
private readonly communityStatsService: CommunityStatsService, private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
) {} ) {}
public async scheduleInitialPoll( public async scheduleInitialPoll(
@@ -98,7 +100,9 @@ export class TournamentResultService {
} }
const result = await this.scheduleInitialPoll(match, 'high'); const result = await this.scheduleInitialPoll(match, 'high');
if (!result) { if (!result) {
throw new BadRequestException('Tournament result polling is not available.'); throw new BadRequestException(
'Tournament result polling is not available.',
);
} }
return result; return result;
} }
@@ -119,7 +123,10 @@ export class TournamentResultService {
const region = await this.resolveRiotRegion(match); const region = await this.resolveRiotRegion(match);
const lookup = await this.buildPuuidLookup(match); const lookup = await this.buildPuuidLookup(match);
const puuids = this.collectPollingPuuids(collectMatchUserIds(match), lookup); const puuids = this.collectPollingPuuids(
collectMatchUserIds(match),
lookup,
);
const startTime = Math.floor(params.startTime.getTime() / 1000); const startTime = Math.floor(params.startTime.getTime() / 1000);
const endTime = Math.floor(params.endTime.getTime() / 1000); const endTime = Math.floor(params.endTime.getTime() / 1000);
const riotMatchIds = new Set<string>(); const riotMatchIds = new Set<string>();
@@ -240,7 +247,9 @@ export class TournamentResultService {
if (checkedRiotMatchIds.has(riotMatchId)) continue; if (checkedRiotMatchIds.has(riotMatchId)) continue;
checkedRiotMatchIds.add(riotMatchId); checkedRiotMatchIds.add(riotMatchId);
const alreadyMatched = await TournamentCodeModel.exists({ riotMatchId }); const alreadyMatched = await TournamentCodeModel.exists({
riotMatchId,
});
if (alreadyMatched) continue; if (alreadyMatched) continue;
let detail: RiotMatchDto; let detail: RiotMatchDto;
@@ -309,7 +318,9 @@ export class TournamentResultService {
} }
code.state = 'used'; code.state = 'used';
code.usedAt = new Date(detail.info.gameEndTimestamp ?? detail.info.gameCreation); code.usedAt = new Date(
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
);
code.riotMatchId = detail.metadata.matchId; code.riotMatchId = detail.metadata.matchId;
await code.save(); await code.save();
@@ -318,6 +329,7 @@ export class TournamentResultService {
match.status = 'in-progress'; match.status = 'in-progress';
} }
await match.save(); await match.save();
await this.rebuildMatchStatsSafe(match);
return true; return true;
} }
@@ -346,7 +358,11 @@ export class TournamentResultService {
} }
this.upsertGameResult(match, gameResult); this.upsertGameResult(match, gameResult);
await this.markTournamentCodeUsedForManualResult(match, gameResult, detail); await this.markTournamentCodeUsedForManualResult(
match,
gameResult,
detail,
);
appliedRiotMatchIds.push(detail.metadata.matchId); appliedRiotMatchIds.push(detail.metadata.matchId);
appliedGameNumbers.push(gameResult.gameNumber); appliedGameNumbers.push(gameResult.gameNumber);
} }
@@ -356,6 +372,9 @@ export class TournamentResultService {
} }
this.updateManualCollectionState(match, appliedRiotMatchIds.length); this.updateManualCollectionState(match, appliedRiotMatchIds.length);
await match.save(); await match.save();
if (appliedRiotMatchIds.length > 0) {
await this.rebuildMatchStatsSafe(match);
}
if (this.hasAllRequiredGameResults(match)) { if (this.hasAllRequiredGameResults(match)) {
await this.finishMatchFromManualResults(match); await this.finishMatchFromManualResults(match);
} }
@@ -393,6 +412,7 @@ export class TournamentResultService {
state: 'complete', state: 'complete',
}; };
await match.save(); await match.save();
await this.rebuildMatchStatsSafe(match);
void this.communityStatsService void this.communityStatsService
.invalidateCommunity(match.communityId) .invalidateCommunity(match.communityId)
.catch((error) => { .catch((error) => {
@@ -419,7 +439,8 @@ export class TournamentResultService {
lastPolledAt: pollState?.lastPolledAt, lastPolledAt: pollState?.lastPolledAt,
lastPollOutcome: pollState?.lastPollOutcome, lastPollOutcome: pollState?.lastPollOutcome,
matchedCount: match.result?.games?.length ?? 0, matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids: pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, expandedToAllPuuids:
pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids,
state: 'expired', state: 'expired',
}; };
await match.save(); await match.save();
@@ -431,7 +452,8 @@ export class TournamentResultService {
const expandedToAllPuuids = const expandedToAllPuuids =
job.expandedToAllPuuids || job.expandedToAllPuuids ||
(elapsedMs >= EXPAND_AFTER_MS && (match.result?.games?.length ?? 0) === 0); (elapsedMs >= EXPAND_AFTER_MS &&
(match.result?.games?.length ?? 0) === 0);
await this.riotJobQueueService.enqueueTournamentResultPoll({ await this.riotJobQueueService.enqueueTournamentResultPoll({
matchId: match._id.toString(), matchId: match._id.toString(),
attempt: job.attempt + 1, attempt: job.attempt + 1,
@@ -446,7 +468,9 @@ export class TournamentResultService {
region: RiotRegionalRoute, region: RiotRegionalRoute,
): Promise<RiotMatchDto> { ): Promise<RiotMatchDto> {
const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec(); 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 dto = await this.riotMatchService.getMatch(riotMatchId, { region });
@@ -491,7 +515,9 @@ export class TournamentResultService {
return details; return details;
} }
private async buildPuuidLookup(match: MatchDocument): Promise<MatchPuuidLookup> { private async buildPuuidLookup(
match: MatchDocument,
): Promise<MatchPuuidLookup> {
const puuidByUserId = new Map<string, string>(); const puuidByUserId = new Map<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>(); const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
@@ -651,6 +677,7 @@ export class TournamentResultService {
state: 'complete', state: 'complete',
}; };
await match.save(); await match.save();
await this.rebuildMatchStatsSafe(match);
void this.communityStatsService void this.communityStatsService
.invalidateCommunity(match.communityId) .invalidateCommunity(match.communityId)
.catch((error) => { .catch((error) => {
@@ -662,6 +689,18 @@ export class TournamentResultService {
}); });
} }
private async rebuildMatchStatsSafe(match: MatchDocument): Promise<void> {
try {
await this.matchStatsService.buildAndUpsert(match._id);
} catch (error) {
this.logger.warn(
`Failed to rebuild match stats for ${match._id.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
private async markTournamentCodeUsedForManualResult( private async markTournamentCodeUsedForManualResult(
match: MatchDocument, match: MatchDocument,
gameResult: MatchGameResult, gameResult: MatchGameResult,
@@ -705,14 +744,12 @@ export class TournamentResultService {
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`; const key = `${teamAIndex}:${teamBIndex}`;
const current = const current = bySeries.get(key) ?? {
bySeries.get(key) ?? teamAIndex,
{ teamBIndex,
teamAIndex, teamAWins: 0,
teamBIndex, teamBWins: 0,
teamAWins: 0, };
teamBWins: 0,
};
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
current.winnerTeamIndex = current.winnerTeamIndex =
@@ -750,10 +787,12 @@ export class TournamentResultService {
const perSeries = match.gameCount || 1; const perSeries = match.gameCount || 1;
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
return roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? { return (
teamAIndex: 1, roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
teamBIndex: 2, teamAIndex: 1,
}; teamBIndex: 2,
}
);
} }
const perSeries = match.gameCount || 1; const perSeries = match.gameCount || 1;
@@ -832,9 +871,9 @@ export class TournamentResultService {
private isReadyToPoll(match: MatchDocument): boolean { private isReadyToPoll(match: MatchDocument): boolean {
return Boolean( return Boolean(
match.teamBuiltAt && match.teamBuiltAt &&
match.tournamentCodeIds.length > 0 && match.tournamentCodeIds.length > 0 &&
match.teams.length >= 2 && match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0), match.teams.every((team) => team.members.length > 0),
); );
} }
@@ -855,8 +894,8 @@ export class TournamentResultService {
private hasBuiltTeams(match: MatchDocument): boolean { private hasBuiltTeams(match: MatchDocument): boolean {
return Boolean( return Boolean(
match.teamBuiltAt && match.teamBuiltAt &&
match.teams.length >= 2 && match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0), match.teams.every((team) => team.members.length > 0),
); );
} }
@@ -887,8 +926,8 @@ export class TournamentResultService {
function isRiotMatchDto(value: unknown): value is RiotMatchDto { function isRiotMatchDto(value: unknown): value is RiotMatchDto {
return Boolean( return Boolean(
value && value &&
typeof value === 'object' && typeof value === 'object' &&
'metadata' in value && 'metadata' in value &&
'info' in value, 'info' in value,
); );
} }