refactor: rebuild stats from competition revision

This commit is contained in:
dahyeon committed 2026-07-12 19:28:04 +00:00
1 parent 28e9ac1529
commit e6e434d13f
4 files changed
+412 -7

No files matched your search

@@ -0,0 +1,59 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { MatchStats } from '../global/database/schema';
import { MatchStatsRepository } from './match-stats.repository';
describe('MatchStatsRepository', () => {
it('only updates a Competition projection when its revision is not stale', async () => {
const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
const fragment = statsFragment(12);
await repository.upsert(fragment);
expect(updateOne).toHaveBeenCalledWith(
{
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: 12 } },
],
},
],
},
{ $set: fragment },
{ upsert: false },
);
});
});
function statsFragment(sourceRevision: number) {
return {
matchId: new Types.ObjectId(),
communityId: new Types.ObjectId(),
sourceCompetitionId: new Types.ObjectId(),
sourceRevision,
projectorVersion: 3,
scheduledAt: new Date(),
gameCreationMin: 1,
gameCreationMax: 2,
userIds: [],
championIds: [],
matchCard: {},
records: [],
gameDetails: [],
builtAt: new Date(),
builderVersion: 9,
} satisfies Omit<MatchStats, 'createdAt' | 'updatedAt'>;
}
@@ -21,9 +21,44 @@ export class MatchStatsRepository {
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>, fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
): Promise<void> { ): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats'); const MatchStatsModel = await this.connectionService.getModel('matchStats');
if (
!fragment.sourceCompetitionId ||
fragment.sourceRevision === undefined
) {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $set: fragment },
{ upsert: true },
).exec();
return;
}
const updated = await MatchStatsModel.updateOne(
{
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: fragment.sourceRevision } },
],
},
],
},
{ $set: fragment },
{ upsert: false },
).exec();
if (updated.matchedCount > 0) return;
// If no read model exists, insert it. If a newer revision won the race,
// this filter matches it and $setOnInsert intentionally changes nothing.
await MatchStatsModel.updateOne( await MatchStatsModel.updateOne(
{ matchId: fragment.matchId }, { matchId: fragment.matchId },
{ $set: fragment }, { $setOnInsert: fragment },
{ upsert: true }, { upsert: true },
).exec(); ).exec();
} }
@@ -17,6 +17,7 @@ describe('MatchStatsService', () => {
const connectionService = { const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => { getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById }; if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return {}; if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`); throw new Error(`Unexpected model: ${name}`);
}), }),
@@ -73,6 +74,7 @@ describe('MatchStatsService', () => {
const connectionService = { const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => { getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById }; if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return { find: riotFind }; if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`); throw new Error(`Unexpected model: ${name}`);
}), }),
@@ -118,4 +120,149 @@ describe('MatchStatsService', () => {
}), }),
); );
}); });
it('builds from the Competition projection and records its source revision', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const userAId = new mongoose.Types.ObjectId();
const userBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: { games: [{ riotMatchId: 'KR_LEGACY_MUST_NOT_BE_USED' }] },
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 8, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 3, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
displayNumber: 4,
evidence: { type: 'riot', riotMatchId: 'KR_COMPETITION' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
startedAt: '2026-07-12T10:00:00.000Z',
durationSeconds: 1800,
participants: [
participant(userAId, teamAId, 'blue', true),
participant(userBId, teamBId, 'red', false),
],
},
],
},
};
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest
.fn()
.mockResolvedValue([{ matchId: 'KR_COMPETITION', raw: {} }]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match')
return { findById: () => queryResult(match, false) };
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
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: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
expect(riotFind).toHaveBeenCalledWith({
matchId: { $in: ['KR_COMPETITION'] },
});
expect(builder.buildFragment).toHaveBeenCalledWith(
expect.objectContaining({
match: expect.objectContaining({
result: expect.objectContaining({
riotMatchIds: ['KR_COMPETITION'],
games: [
expect.objectContaining({
gameNumber: 4,
blueTeamIndex: 8,
redTeamIndex: 3,
winnerTeamIndex: 8,
}),
],
}),
}),
}),
);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
sourceCompetitionId: competitionId,
sourceRevision: 12,
projectorVersion: 3,
}),
);
});
}); });
function participant(
userId: mongoose.Types.ObjectId,
teamId: mongoose.Types.ObjectId,
side: 'blue' | 'red',
win: boolean,
) {
return {
userId: userId.toString(),
teamId: teamId.toString(),
side,
summonerName: 'player',
tagLine: 'KR1',
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win,
};
}
function queryResult<T>(value: T, lean = true) {
const query = {
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.lean.mockReturnValue(query);
return lean ? query : { exec: query.exec };
}
@@ -29,15 +29,24 @@ export class MatchStatsService {
options: { includeTimeline?: boolean } = {}, options: { includeTimeline?: boolean } = {},
): Promise<void> { ): Promise<void> {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const CompetitionModel =
await this.connectionService.getModel('competition');
const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const match = await MatchModel.findById(matchId).exec(); const match = await MatchModel.findById(matchId).exec();
if (!match) return; if (!match) return;
if (!this.isEligible(match)) { const competition = await CompetitionModel.findOne({ matchId })
.lean()
.exec();
const competitionSource = competition
? competitionStatsSource(match, competition)
: undefined;
const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) {
await this.repository.deleteByMatch(matchId); await this.repository.deleteByMatch(matchId);
return; return;
} }
const riotIds = [ const riotIds = competitionSource?.riotMatchIds ?? [
...new Set( ...new Set(
(match.result?.games ?? []) (match.result?.games ?? [])
.map((game) => game.riotMatchId) .map((game) => game.riotMatchId)
@@ -93,7 +102,7 @@ export class MatchStatsService {
} }
const fragment = this.builder.buildFragment({ const fragment = this.builder.buildFragment({
match, match: sourceMatch,
rawByRiotMatchId, rawByRiotMatchId,
timelineByRiotMatchId, timelineByRiotMatchId,
timelineLoadAttempted: options.includeTimeline === true, timelineLoadAttempted: options.includeTimeline === true,
@@ -112,6 +121,13 @@ export class MatchStatsService {
gameDetails: fragment.gameDetails, gameDetails: fragment.gameDetails,
builtAt: new Date(), builtAt: new Date(),
builderVersion: MATCH_STATS_BUILDER_VERSION, builderVersion: MATCH_STATS_BUILDER_VERSION,
...(competitionSource
? {
sourceCompetitionId: competitionSource.sourceCompetitionId,
sourceRevision: competitionSource.sourceRevision,
projectorVersion: competitionSource.projectorVersion,
}
: {}),
}); });
} }
@@ -173,9 +189,7 @@ export class MatchStatsService {
} }
} }
function isRiotMatchTimelineDto( function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
value: unknown,
): value is RiotMatchTimelineDto {
if (!isRecord(value) || !isRecord(value.info)) return false; if (!isRecord(value) || !isRecord(value.info)) return false;
return Array.isArray(value.info.frames); return Array.isArray(value.info.frames);
} }
@@ -183,3 +197,153 @@ function isRiotMatchTimelineDto(
function isRecord(value: unknown): value is Record<string, unknown> { function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null; return typeof value === 'object' && value !== null;
} }
function competitionStatsSource(
match: MatchDocument,
competition: {
_id: mongoose.Types.ObjectId;
revision: number;
projectorVersion: number;
teams: unknown[];
projection: Record<string, unknown>;
},
): {
match: MatchDocument;
riotMatchIds: string[];
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
projectorVersion: number;
} {
const teamIndexById = new Map<string, number>();
for (const rawTeam of competition.teams) {
if (!isRecord(rawTeam)) continue;
const teamId = identifier(rawTeam.teamId);
const legacyTeamIndex = finiteNumber(rawTeam.legacyTeamIndex);
const displayOrder = finiteNumber(rawTeam.displayOrder);
if (teamId && (legacyTeamIndex ?? displayOrder)) {
teamIndexById.set(teamId, legacyTeamIndex ?? displayOrder!);
}
}
const rawGames = Array.isArray(competition.projection.games)
? competition.projection.games
: [];
const riotMatchIds = new Set<string>();
const games = rawGames.flatMap((rawGame, gameIndex) => {
if (!isRecord(rawGame)) return [];
const teams = isRecord(rawGame.teams) ? rawGame.teams : undefined;
const blue = teams && isRecord(teams.blue) ? teams.blue : undefined;
const red = teams && isRecord(teams.red) ? teams.red : undefined;
const blueTeamId = identifier(blue?.teamId);
const redTeamId = identifier(red?.teamId);
const winnerTeamId = identifier(rawGame.winnerTeamId);
const blueTeamIndex = blueTeamId
? teamIndexById.get(blueTeamId)
: undefined;
const redTeamIndex = redTeamId ? teamIndexById.get(redTeamId) : undefined;
const winnerTeamIndex = winnerTeamId
? teamIndexById.get(winnerTeamId)
: undefined;
if (!blueTeamIndex || !redTeamIndex || !winnerTeamIndex) return [];
const evidence = isRecord(rawGame.evidence) ? rawGame.evidence : undefined;
const riotMatchId =
evidence?.type === 'riot' && typeof evidence.riotMatchId === 'string'
? evidence.riotMatchId
: typeof evidence?.legacyReference === 'string'
? evidence.legacyReference
: `competition:${identifier(rawGame.id) ?? 'game'}`;
if (evidence?.type === 'riot') riotMatchIds.add(riotMatchId);
const participantValues = Array.isArray(rawGame.participants)
? rawGame.participants
: [];
const participants = participantValues.flatMap((rawParticipant) => {
if (!isRecord(rawParticipant)) return [];
const userId = identifier(rawParticipant.userId);
const teamId = identifier(rawParticipant.teamId);
const teamIndex = teamId ? teamIndexById.get(teamId) : undefined;
const side = rawParticipant.side;
if (
!userId ||
!mongoose.isValidObjectId(userId) ||
!teamIndex ||
(side !== 'blue' && side !== 'red')
) {
return [];
}
return [
{
userId: new mongoose.Types.ObjectId(userId),
teamIndex,
side,
championId: finiteNumber(rawParticipant.championId) ?? 0,
kills: finiteNumber(rawParticipant.kills) ?? 0,
deaths: finiteNumber(rawParticipant.deaths) ?? 0,
assists: finiteNumber(rawParticipant.assists) ?? 0,
win: teamId === winnerTeamId,
},
];
});
const startedAt = new Date(String(rawGame.startedAt ?? ''));
return [
{
gameNumber: finiteNumber(rawGame.displayNumber) ?? gameIndex + 1,
riotMatchId,
blueTeamIndex,
redTeamIndex,
winnerTeamIndex,
winnerSide:
winnerTeamIndex === blueTeamIndex
? ('blue' as const)
: ('red' as const),
gameCreation: Number.isNaN(startedAt.getTime())
? 0
: startedAt.getTime(),
gameDuration: finiteNumber(rawGame.durationSeconds) ?? 0,
participants,
},
];
});
const base =
typeof match.toObject === 'function' ? match.toObject() : { ...match };
return {
match: {
...base,
status:
competition.projection.phase === 'completed'
? 'finished'
: games.length > 0
? 'in-progress'
: match.status,
result: {
riotMatchIds: games.map(({ riotMatchId }) => riotMatchId),
games,
seriesResults: [],
},
} as unknown as MatchDocument,
riotMatchIds: [...riotMatchIds],
sourceCompetitionId: competition._id,
sourceRevision: competition.revision,
projectorVersion: competition.projectorVersion,
};
}
function identifier(value: unknown): string | undefined {
if (typeof value === 'string' && value.length > 0) return value;
if (
typeof value === 'object' &&
value !== null &&
'toString' in value &&
typeof value.toString === 'function'
) {
const result = value.toString();
return result === '[object Object]' ? undefined : result;
}
return undefined;
}
function finiteNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}