fix: close competition cutover integrity gaps
This commit is contained in:
1 parent
7ea2002975
commit
683d602d63
57 files changed
+4805
-1582
No files matched your search
@@ -8,7 +8,11 @@ import type {
|
||||
} from './community-stats.types';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
import type { InternalGameDetail, InternalRecord } from './match-stats.types';
|
||||
import {
|
||||
MATCH_STATS_BUILDER_VERSION,
|
||||
type InternalGameDetail,
|
||||
type InternalRecord,
|
||||
} from './match-stats.types';
|
||||
|
||||
function objectives() {
|
||||
return {
|
||||
@@ -219,8 +223,9 @@ describe('CommunityStatsService', () => {
|
||||
matchStatsRepository,
|
||||
{} as MatchStatsService,
|
||||
);
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
|
||||
jest.fn().mockResolvedValue({
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
community: {},
|
||||
season: {
|
||||
id: 'all',
|
||||
@@ -275,7 +280,12 @@ describe('CommunityStatsService', () => {
|
||||
participant.userId = userId.toString();
|
||||
|
||||
let resolveFragments:
|
||||
| ((fragments: Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>) => void)
|
||||
| ((
|
||||
fragments: Array<{
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
records: InternalRecord[];
|
||||
}>,
|
||||
) => void)
|
||||
| undefined;
|
||||
const fragmentsPromise = new Promise<
|
||||
Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>
|
||||
@@ -296,8 +306,9 @@ describe('CommunityStatsService', () => {
|
||||
matchStatsRepository,
|
||||
{} as MatchStatsService,
|
||||
);
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
|
||||
jest.fn().mockResolvedValue({
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
community: {},
|
||||
season: {
|
||||
id: 'all',
|
||||
@@ -329,4 +340,83 @@ describe('CommunityStatsService', () => {
|
||||
);
|
||||
expect(cacheService.set).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('self-heals Competition fragments when their source revision is stale', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const competitionId = new mongoose.Types.ObjectId();
|
||||
const matches = [{ _id: matchId, competitionId }];
|
||||
const MatchModel = {
|
||||
find: jest.fn().mockReturnValue({
|
||||
sort: jest.fn().mockReturnValue({
|
||||
limit: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(matches),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const CompetitionModel = {
|
||||
find: jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue([
|
||||
{
|
||||
_id: competitionId,
|
||||
revision: 7,
|
||||
projectorVersion: 3,
|
||||
},
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation((name: string) => {
|
||||
if (name === 'match') return Promise.resolve(MatchModel);
|
||||
if (name === 'competition') return Promise.resolve(CompetitionModel);
|
||||
throw new Error(`Unexpected model ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const matchStatsRepository = {
|
||||
findByCommunity: jest.fn().mockResolvedValue([
|
||||
{
|
||||
matchId,
|
||||
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||
sourceCompetitionId: competitionId,
|
||||
sourceRevision: 6,
|
||||
projectorVersion: 3,
|
||||
},
|
||||
]),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const matchStatsService = {
|
||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<MatchStatsService>;
|
||||
const service = new CommunityStatsService(
|
||||
connectionService,
|
||||
{} as CommunityStatsCacheService,
|
||||
matchStatsRepository,
|
||||
matchStatsService,
|
||||
);
|
||||
|
||||
const rebuilt = await (
|
||||
service as unknown as {
|
||||
rebuildMissingOrStaleFragments(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<number>;
|
||||
}
|
||||
).rebuildMissingOrStaleFragments(communityId);
|
||||
|
||||
expect(MatchModel.find).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
$or: [
|
||||
{ competitionId: { $exists: true } },
|
||||
{ 'result.games.0': { $exists: true } },
|
||||
],
|
||||
});
|
||||
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId);
|
||||
expect(rebuilt).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -238,58 +238,56 @@ export class CommunityStatsService {
|
||||
}
|
||||
const response: InternalMatchDetailResponse = {
|
||||
match,
|
||||
games: gameDetails.map(
|
||||
(game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
gameVersion: game.gameVersion,
|
||||
timeline: game.timeline ?? [],
|
||||
objectiveEvents: game.objectiveEvents ?? [],
|
||||
teams: game.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
side: team.side,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
bans: team.bans ?? [],
|
||||
participants: team.participants.map((record) => ({
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
tagLine: record.tagLine,
|
||||
teamIndex: record.teamIndex,
|
||||
side: record.side,
|
||||
teamPosition: record.teamPosition,
|
||||
championId: record.championId,
|
||||
championLevel: record.championLevel,
|
||||
kills: record.kills,
|
||||
deaths: record.deaths,
|
||||
assists: record.assists,
|
||||
cs: record.cs,
|
||||
csPerMin: record.csPerMin,
|
||||
gold: record.gold,
|
||||
gpm: record.gpm,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageTaken: record.damageTaken,
|
||||
damageShare: record.damageShare,
|
||||
killParticipation: record.killParticipation,
|
||||
visionScore: record.visionScore,
|
||||
wardsPlaced: record.wardsPlaced,
|
||||
wardsKilled: record.wardsKilled,
|
||||
controlWardsBought: record.controlWardsBought,
|
||||
firstBloodKill: record.firstBloodKill ?? false,
|
||||
firstBloodAssist: record.firstBloodAssist ?? false,
|
||||
items: record.items,
|
||||
trinket: record.trinket,
|
||||
summonerSpells: record.summonerSpells,
|
||||
perks: record.perks,
|
||||
itemBuild: record.itemBuild ?? [],
|
||||
skillBuild: record.skillBuild ?? [],
|
||||
win: record.win,
|
||||
})),
|
||||
games: gameDetails.map((game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
gameVersion: game.gameVersion,
|
||||
timeline: game.timeline ?? [],
|
||||
objectiveEvents: game.objectiveEvents ?? [],
|
||||
teams: game.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
side: team.side,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
bans: team.bans ?? [],
|
||||
participants: team.participants.map((record) => ({
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
tagLine: record.tagLine,
|
||||
teamIndex: record.teamIndex,
|
||||
side: record.side,
|
||||
teamPosition: record.teamPosition,
|
||||
championId: record.championId,
|
||||
championLevel: record.championLevel,
|
||||
kills: record.kills,
|
||||
deaths: record.deaths,
|
||||
assists: record.assists,
|
||||
cs: record.cs,
|
||||
csPerMin: record.csPerMin,
|
||||
gold: record.gold,
|
||||
gpm: record.gpm,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageTaken: record.damageTaken,
|
||||
damageShare: record.damageShare,
|
||||
killParticipation: record.killParticipation,
|
||||
visionScore: record.visionScore,
|
||||
wardsPlaced: record.wardsPlaced,
|
||||
wardsKilled: record.wardsKilled,
|
||||
controlWardsBought: record.controlWardsBought,
|
||||
firstBloodKill: record.firstBloodKill ?? false,
|
||||
firstBloodAssist: record.firstBloodAssist ?? false,
|
||||
items: record.items,
|
||||
trinket: record.trinket,
|
||||
summonerSpells: record.summonerSpells,
|
||||
perks: record.perks,
|
||||
itemBuild: record.itemBuild ?? [],
|
||||
skillBuild: record.skillBuild ?? [],
|
||||
win: record.win,
|
||||
})),
|
||||
}),
|
||||
),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
await this.cacheService.setDetail(key, response);
|
||||
return response;
|
||||
@@ -357,7 +355,7 @@ export class CommunityStatsService {
|
||||
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
|
||||
|
||||
for (const fragment of fragments) {
|
||||
const filteredGames = (fragment.gameDetails as InternalGameDetail[])
|
||||
const filteredGames = fragment.gameDetails
|
||||
.filter((game) => this.isGameInRange(game.gameCreation, context))
|
||||
.sort((left, right) => left.gameNumber - right.gameNumber);
|
||||
if (filteredGames.length === 0) continue;
|
||||
@@ -373,7 +371,7 @@ export class CommunityStatsService {
|
||||
filteredGames.map((game) => game.gameNumber),
|
||||
);
|
||||
records.push(
|
||||
...(fragment.records as InternalRecord[]).filter((record) =>
|
||||
...fragment.records.filter((record) =>
|
||||
allowedGameNumbers.has(record.gameNumber),
|
||||
),
|
||||
);
|
||||
@@ -407,11 +405,7 @@ export class CommunityStatsService {
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
});
|
||||
const allUserRecords = this.extractUserRecords(
|
||||
fragments,
|
||||
userId,
|
||||
context,
|
||||
);
|
||||
const allUserRecords = this.extractUserRecords(fragments, userId, context);
|
||||
const records = this.applyChampionFilter(allUserRecords, params.filters);
|
||||
const limit = this.clampLimit(params.filters.limit, 30, 50);
|
||||
const cursor = params.filters.cursor;
|
||||
@@ -457,7 +451,7 @@ export class CommunityStatsService {
|
||||
): InternalRecord[] {
|
||||
return fragments
|
||||
.flatMap((fragment) =>
|
||||
(fragment.records as InternalRecord[]).filter(
|
||||
fragment.records.filter(
|
||||
(record) =>
|
||||
record.userId === userId &&
|
||||
this.isGameInRange(record.gameCreation, context),
|
||||
@@ -493,7 +487,7 @@ export class CommunityStatsService {
|
||||
for (const fragment of fragments) {
|
||||
detailsByMatchId.set(
|
||||
fragment.matchId.toString(),
|
||||
(fragment.gameDetails as InternalGameDetail[]).filter((game) =>
|
||||
fragment.gameDetails.filter((game) =>
|
||||
this.isGameInRange(game.gameCreation, context),
|
||||
),
|
||||
);
|
||||
@@ -509,11 +503,14 @@ export class CommunityStatsService {
|
||||
MatchModel.find({
|
||||
communityId,
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
'result.games.0': { $exists: true },
|
||||
$or: [
|
||||
{ competitionId: { $exists: true } },
|
||||
{ 'result.games.0': { $exists: true } },
|
||||
],
|
||||
})
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(MAX_MATCH_SCAN)
|
||||
.select({ _id: 1 })
|
||||
.select({ _id: 1, competitionId: 1 })
|
||||
.exec(),
|
||||
this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
@@ -523,11 +520,45 @@ export class CommunityStatsService {
|
||||
const fragmentByMatchId = new Map(
|
||||
fragments.map((fragment) => [fragment.matchId.toString(), fragment]),
|
||||
);
|
||||
const competitionIds = matches.flatMap((match) =>
|
||||
match.competitionId ? [match.competitionId] : [],
|
||||
);
|
||||
const CompetitionModel =
|
||||
await this.connectionService.getModel('competition');
|
||||
const competitions =
|
||||
competitionIds.length > 0
|
||||
? await CompetitionModel.find({ _id: { $in: competitionIds } })
|
||||
.select({ _id: 1, revision: 1, projectorVersion: 1 })
|
||||
.lean()
|
||||
.exec()
|
||||
: [];
|
||||
const competitionById = new Map(
|
||||
competitions.map((competition) => [
|
||||
competition._id.toString(),
|
||||
competition,
|
||||
]),
|
||||
);
|
||||
let rebuilt = 0;
|
||||
|
||||
for (const match of matches) {
|
||||
const fragment = fragmentByMatchId.get(match._id.toString());
|
||||
if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) {
|
||||
const competition = match.competitionId
|
||||
? competitionById.get(match.competitionId.toString())
|
||||
: undefined;
|
||||
const sourceIsCurrent = match.competitionId
|
||||
? Boolean(
|
||||
competition &&
|
||||
fragment?.sourceCompetitionId?.toString() ===
|
||||
competition._id.toString() &&
|
||||
(fragment.sourceRevision ?? -1) >= competition.revision &&
|
||||
(fragment.projectorVersion ?? -1) >= competition.projectorVersion,
|
||||
)
|
||||
: true;
|
||||
if (
|
||||
fragment &&
|
||||
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
|
||||
sourceIsCurrent
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,47 @@ import type { MatchStats } from '../global/database/schema';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
|
||||
describe('MatchStatsRepository', () => {
|
||||
it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => {
|
||||
const fragment = {
|
||||
...statsFragment(12),
|
||||
sourceCompetitionId: undefined,
|
||||
sourceRevision: undefined,
|
||||
projectorVersion: undefined,
|
||||
};
|
||||
const updateOne = jest
|
||||
.fn()
|
||||
.mockReturnValueOnce({
|
||||
exec: jest.fn().mockResolvedValue({ matchedCount: 0 }),
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
exec: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
|
||||
});
|
||||
const connection = {
|
||||
getModel: jest.fn().mockResolvedValue({ updateOne }),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = new MatchStatsRepository(connection);
|
||||
|
||||
await repository.upsert(fragment);
|
||||
|
||||
expect(updateOne).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
{
|
||||
matchId: fragment.matchId,
|
||||
sourceCompetitionId: { $exists: false },
|
||||
},
|
||||
{ $set: fragment },
|
||||
{ upsert: false },
|
||||
);
|
||||
expect(updateOne).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
{ matchId: fragment.matchId },
|
||||
{ $setOnInsert: fragment },
|
||||
{ upsert: true },
|
||||
);
|
||||
});
|
||||
|
||||
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 }),
|
||||
@@ -36,6 +77,122 @@ describe('MatchStatsRepository', () => {
|
||||
{ upsert: false },
|
||||
);
|
||||
});
|
||||
|
||||
it('converges concurrent initial upserts to the highest Competition revision', async () => {
|
||||
const older = statsFragment(12);
|
||||
const newer = {
|
||||
...statsFragment(13),
|
||||
matchId: older.matchId,
|
||||
sourceCompetitionId: older.sourceCompetitionId,
|
||||
};
|
||||
let stored: ReturnType<typeof statsFragment> | undefined;
|
||||
let initialGuardCount = 0;
|
||||
let releaseInitialGuards!: () => void;
|
||||
const initialGuardsReady = new Promise<void>((resolve) => {
|
||||
releaseInitialGuards = resolve;
|
||||
});
|
||||
let releaseOlderInsert!: () => void;
|
||||
const olderInserted = new Promise<void>((resolve) => {
|
||||
releaseOlderInsert = resolve;
|
||||
});
|
||||
const updateOne = jest.fn(
|
||||
(
|
||||
_filter: Record<string, unknown>,
|
||||
update: {
|
||||
$set?: ReturnType<typeof statsFragment>;
|
||||
$setOnInsert?: ReturnType<typeof statsFragment>;
|
||||
},
|
||||
) => ({
|
||||
exec: async () => {
|
||||
const fragment = update.$set ?? update.$setOnInsert!;
|
||||
if (update.$set && !stored && initialGuardCount < 2) {
|
||||
initialGuardCount += 1;
|
||||
if (initialGuardCount === 2) releaseInitialGuards();
|
||||
await initialGuardsReady;
|
||||
return { matchedCount: 0, upsertedCount: 0 };
|
||||
}
|
||||
|
||||
if (update.$setOnInsert) {
|
||||
if (fragment.sourceRevision === 13) await olderInserted;
|
||||
const existed = stored !== undefined;
|
||||
if (!stored) stored = fragment;
|
||||
if (fragment.sourceRevision === 12) releaseOlderInsert();
|
||||
return {
|
||||
matchedCount: existed ? 1 : 0,
|
||||
upsertedCount: existed ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
stored &&
|
||||
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) &&
|
||||
stored.sourceRevision! <= fragment.sourceRevision!
|
||||
) {
|
||||
stored = fragment;
|
||||
return { matchedCount: 1, upsertedCount: 0 };
|
||||
}
|
||||
return { matchedCount: 0, upsertedCount: 0 };
|
||||
},
|
||||
}),
|
||||
);
|
||||
const connection = {
|
||||
getModel: jest.fn().mockResolvedValue({ updateOne }),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = new MatchStatsRepository(connection);
|
||||
|
||||
await Promise.all([repository.upsert(older), repository.upsert(newer)]);
|
||||
|
||||
expect(stored?.sourceRevision).toBe(13);
|
||||
});
|
||||
|
||||
it('guards a zero-game delete so an observed revision cannot remove newer stats', async () => {
|
||||
const matchId = new Types.ObjectId();
|
||||
const sourceCompetitionId = new Types.ObjectId();
|
||||
const deleteOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
|
||||
});
|
||||
const connection = {
|
||||
getModel: jest.fn().mockResolvedValue({ deleteOne }),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = new MatchStatsRepository(connection);
|
||||
|
||||
await repository.deleteByMatch(matchId, {
|
||||
sourceCompetitionId,
|
||||
sourceRevision: 12,
|
||||
});
|
||||
|
||||
expect(deleteOne).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
$or: [
|
||||
{ sourceCompetitionId: { $exists: false } },
|
||||
{
|
||||
sourceCompetitionId,
|
||||
$or: [
|
||||
{ sourceRevision: { $exists: false } },
|
||||
{ sourceRevision: { $lte: 12 } },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes only non-Competition stats during legacy source cleanup', async () => {
|
||||
const matchId = new Types.ObjectId();
|
||||
const deleteOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
|
||||
});
|
||||
const connection = {
|
||||
getModel: jest.fn().mockResolvedValue({ deleteOne }),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = new MatchStatsRepository(connection);
|
||||
|
||||
await repository.deleteLegacyByMatch(matchId);
|
||||
|
||||
expect(deleteOne).toHaveBeenCalledWith({
|
||||
matchId,
|
||||
sourceCompetitionId: { $exists: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function statsFragment(sourceRevision: number) {
|
||||
|
||||
@@ -13,6 +13,11 @@ export type MatchStatsDetailFragment = Pick<
|
||||
'matchId' | 'gameDetails'
|
||||
>;
|
||||
|
||||
export interface MatchStatsDeleteGuard {
|
||||
sourceCompetitionId: mongoose.Types.ObjectId;
|
||||
sourceRevision: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsRepository {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
@@ -25,30 +30,33 @@ export class MatchStatsRepository {
|
||||
!fragment.sourceCompetitionId ||
|
||||
fragment.sourceRevision === undefined
|
||||
) {
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
const updated = await MatchStatsModel.updateOne(
|
||||
{
|
||||
matchId: fragment.matchId,
|
||||
sourceCompetitionId: { $exists: false },
|
||||
},
|
||||
{ $set: fragment },
|
||||
{ upsert: true },
|
||||
{ upsert: false },
|
||||
).exec();
|
||||
if (updated.matchedCount > 0) return;
|
||||
|
||||
// A legacy builder must never overwrite a Competition-backed fragment
|
||||
// that appeared while the legacy source was being read.
|
||||
try {
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
{ $setOnInsert: fragment },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
} catch (error) {
|
||||
if (!isDuplicateKeyError(error)) throw error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const revisionGuard = competitionRevisionGuard(fragment);
|
||||
const updated = await MatchStatsModel.updateOne(
|
||||
{
|
||||
matchId: fragment.matchId,
|
||||
$or: [
|
||||
{ sourceCompetitionId: { $exists: false } },
|
||||
{ sourceCompetitionId: fragment.sourceCompetitionId },
|
||||
],
|
||||
$and: [
|
||||
{
|
||||
$or: [
|
||||
{ sourceRevision: { $exists: false } },
|
||||
{ sourceRevision: { $lte: fragment.sourceRevision } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
revisionGuard,
|
||||
{ $set: fragment },
|
||||
{ upsert: false },
|
||||
).exec();
|
||||
@@ -56,16 +64,48 @@ export class MatchStatsRepository {
|
||||
|
||||
// If no read model exists, insert it. If a newer revision won the race,
|
||||
// this filter matches it and $setOnInsert intentionally changes nothing.
|
||||
try {
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
{ $setOnInsert: fragment },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
} catch (error) {
|
||||
if (!isDuplicateKeyError(error)) throw error;
|
||||
}
|
||||
|
||||
// A lower revision can win the initial insert between the guarded miss and
|
||||
// the upsert. Re-run the monotonic CAS so every concurrent builder converges
|
||||
// to the highest source revision; a newer winner simply does not match.
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
{ $setOnInsert: fragment },
|
||||
{ upsert: true },
|
||||
revisionGuard,
|
||||
{ $set: fragment },
|
||||
{ upsert: false },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
public async deleteByMatch(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
guard?: MatchStatsDeleteGuard,
|
||||
): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteOne({ matchId }).exec();
|
||||
await MatchStatsModel.deleteOne(
|
||||
guard
|
||||
? {
|
||||
matchId,
|
||||
$or: [
|
||||
{ sourceCompetitionId: { $exists: false } },
|
||||
{
|
||||
sourceCompetitionId: guard.sourceCompetitionId,
|
||||
$or: [
|
||||
{ sourceRevision: { $exists: false } },
|
||||
{ sourceRevision: { $lte: guard.sourceRevision } },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
: { matchId },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatches(
|
||||
@@ -76,6 +116,16 @@ export class MatchStatsRepository {
|
||||
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
|
||||
}
|
||||
|
||||
public async deleteLegacyByMatch(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteOne({
|
||||
matchId,
|
||||
sourceCompetitionId: { $exists: false },
|
||||
}).exec();
|
||||
}
|
||||
|
||||
public async findByMatch(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchStatsDocument | null> {
|
||||
@@ -173,3 +223,32 @@ export class MatchStatsRepository {
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
|
||||
function competitionRevisionGuard(
|
||||
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
|
||||
) {
|
||||
return {
|
||||
matchId: fragment.matchId,
|
||||
$or: [
|
||||
{ sourceCompetitionId: { $exists: false } },
|
||||
{ sourceCompetitionId: fragment.sourceCompetitionId },
|
||||
],
|
||||
$and: [
|
||||
{
|
||||
$or: [
|
||||
{ sourceRevision: { $exists: false } },
|
||||
{ sourceRevision: { $lte: fragment.sourceRevision } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function isDuplicateKeyError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
error.code === 11_000
|
||||
);
|
||||
}
|
||||
@@ -39,6 +39,57 @@ describe('MatchStatsService', () => {
|
||||
expect(repository.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('revision-guards deletion when a Competition reversal leaves zero games', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const competitionId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
|
||||
status: 'in-progress',
|
||||
teams: [],
|
||||
result: undefined,
|
||||
};
|
||||
const competition = {
|
||||
_id: competitionId,
|
||||
revision: 12,
|
||||
projectorVersion: 3,
|
||||
teams: [],
|
||||
projection: { phase: 'ready', games: [] },
|
||||
};
|
||||
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 {};
|
||||
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,
|
||||
{ getMatchTimeline: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
|
||||
|
||||
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
|
||||
sourceCompetitionId: competitionId,
|
||||
sourceRevision: 12,
|
||||
});
|
||||
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();
|
||||
@@ -237,6 +288,92 @@ describe('MatchStatsService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('removes a fragment written after its Competition Match was deleted', 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 match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
|
||||
status: 'in-progress',
|
||||
teams: [],
|
||||
result: undefined,
|
||||
};
|
||||
const competition = {
|
||||
_id: competitionId,
|
||||
revision: 12,
|
||||
projectorVersion: 3,
|
||||
teams: [
|
||||
{ teamId: teamAId, legacyTeamIndex: 1, displayOrder: 1 },
|
||||
{ teamId: teamBId, legacyTeamIndex: 2, displayOrder: 2 },
|
||||
],
|
||||
projection: {
|
||||
phase: 'running',
|
||||
games: [
|
||||
{
|
||||
id: new mongoose.Types.ObjectId(),
|
||||
displayNumber: 1,
|
||||
evidence: { type: 'legacy', legacyReference: 'legacy:1' },
|
||||
teams: {
|
||||
blue: { teamId: teamAId.toString() },
|
||||
red: { teamId: teamBId.toString() },
|
||||
},
|
||||
winnerTeamId: teamAId.toString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const findById = jest
|
||||
.fn()
|
||||
.mockReturnValueOnce(queryResult(match, false))
|
||||
.mockReturnValueOnce(queryResult(null, false));
|
||||
const findCompetition = jest.fn().mockReturnValue(queryResult(competition));
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return { findById };
|
||||
if (name === 'competition') return { findOne: findCompetition };
|
||||
if (name === 'riotMatch') return {};
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = {
|
||||
upsert: jest.fn().mockResolvedValue(undefined),
|
||||
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||
deleteLegacyByMatch: 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, { sourceRevision: 12 });
|
||||
|
||||
expect(repository.upsert).toHaveBeenCalled();
|
||||
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
|
||||
sourceCompetitionId: competitionId,
|
||||
sourceRevision: 12,
|
||||
});
|
||||
expect(repository.upsert.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
repository.deleteByMatch.mock.invocationCallOrder[0],
|
||||
);
|
||||
});
|
||||
|
||||
it('does not rebuild before the requested Competition revision is visible', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const riotFind = jest.fn();
|
||||
|
||||
@@ -48,7 +48,14 @@ export class MatchStatsService {
|
||||
: undefined;
|
||||
const sourceMatch = competitionSource?.match ?? match;
|
||||
if (!this.isEligible(sourceMatch)) {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
if (competitionSource) {
|
||||
await this.repository.deleteByMatch(matchId, {
|
||||
sourceCompetitionId: competitionSource.sourceCompetitionId,
|
||||
sourceRevision: competitionSource.sourceRevision,
|
||||
});
|
||||
} else {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -135,6 +142,11 @@ export class MatchStatsService {
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
// Source reads and the read-model write are intentionally separated by
|
||||
// Riot/timeline work. Revalidate after the write so a concurrent aggregate
|
||||
// deletion cannot resurrect MatchStats after the delete transaction.
|
||||
await this.removeFragmentIfSourceChanged(matchId, competitionSource);
|
||||
}
|
||||
|
||||
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
@@ -196,6 +208,49 @@ export class MatchStatsService {
|
||||
? (region as RiotRegionalRoute)
|
||||
: 'asia';
|
||||
}
|
||||
|
||||
private async removeFragmentIfSourceChanged(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
source:
|
||||
| {
|
||||
sourceCompetitionId: mongoose.Types.ObjectId;
|
||||
sourceRevision: number;
|
||||
}
|
||||
| undefined,
|
||||
): Promise<void> {
|
||||
const [MatchModel, CompetitionModel] = await Promise.all([
|
||||
this.connectionService.getModel('match'),
|
||||
this.connectionService.getModel('competition'),
|
||||
]);
|
||||
const [currentMatch, currentCompetition] = await Promise.all([
|
||||
MatchModel.findById(matchId).exec(),
|
||||
CompetitionModel.findOne({
|
||||
matchId,
|
||||
...(source
|
||||
? {
|
||||
_id: source.sourceCompetitionId,
|
||||
revision: source.sourceRevision,
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.lean()
|
||||
.exec(),
|
||||
]);
|
||||
|
||||
if (source) {
|
||||
if (!currentMatch || !currentCompetition) {
|
||||
await this.repository.deleteByMatch(matchId, {
|
||||
sourceCompetitionId: source.sourceCompetitionId,
|
||||
sourceRevision: source.sourceRevision,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentMatch || currentCompetition) {
|
||||
await this.repository.deleteLegacyByMatch(matchId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
|
||||
|
||||
Reference in new issue
Block a user