fix(api): correct champion history and deduplicate stats builds

Apply participant and champion filters before pagination and exclude timeline payloads. Route result statistics through the durable outbox, reuse current fragments, and serialize projection effects without spending retries on contention.

Validated with 716 API tests, 32 isolated Redis integration tests, API typecheck and build, and lint on changed files.
This commit is contained in:
dahyeon committed 2026-11-09 18:40:51 +09:00
1 parent ef141a13d0
commit f2eec479d9
14 files changed
+704 -47

No files matched your search

@@ -0,0 +1,208 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { MatchHistoryService } from './match-history.service';
const SEASON_START = Date.parse('2026-01-01T00:00:00Z');
describe('MatchHistoryService champion filtering', () => {
it('paginates matching games beyond 120 newer games and excludes opponents using the champion', async () => {
const harness = createHarness();
const filters = { championId: 99, rank: 'solo', limit: 2 };
const first = await harness.service.getRecentMatches({
...harness.scope,
filters,
});
expect(first.matches.map((match) => match.matchId)).toEqual([
'KR_3',
'KR_2',
]);
expect(first.nextCursor).toBe(SEASON_START + 2_000);
const second = await harness.service.getRecentMatches({
...harness.scope,
filters: { ...filters, cursor: first.nextCursor! },
});
expect(second.matches.map((match) => match.matchId)).toEqual(['KR_1']);
expect(second.nextCursor).toBeNull();
expect(harness.returnedCounts).toEqual([3, 1]);
expect(harness.find).toHaveBeenLastCalledWith({
participantPuuids: 'player',
queueId: { $in: [420] },
gameCreation: { $gte: SEASON_START, $lt: first.nextCursor },
'raw.info.participants': {
$elemMatch: { puuid: 'player', championId: 99 },
},
});
});
it('summarizes matching games across the former scan boundary', async () => {
const { service, scope, returnedCounts } = createHarness();
const summary = await service.getRecentSummary({
...scope,
filters: { championId: 99, rank: 'solo', limit: 20 },
});
expect(summary).toMatchObject({ windowSize: 3, wins: 3, losses: 0 });
expect(summary.topChampions).toEqual([
expect.objectContaining({ championId: 99, games: 3 }),
]);
expect(returnedCounts).toEqual([3]);
});
it('keeps unfiltered pagination and does not transfer timeline payloads', async () => {
const { service, scope, find, select, returnedCounts } = createHarness();
const result = await service.getRecentMatches({
...scope,
filters: { rank: 'solo', limit: 2 },
});
expect(result.matches.map((match) => match.matchId)).toEqual([
'KR_130',
'KR_129',
]);
expect(result.nextCursor).toBe(SEASON_START + 129_000);
expect(find.mock.calls[0][0]['raw.info.participants']).toBeUndefined();
expect(select).toHaveBeenCalledWith({ timeline: 0 });
expect(returnedCounts).toEqual([3]);
});
});
interface HistoryQuery {
participantPuuids: string;
queueId: { $in: number[] };
gameCreation?: { $gte?: number; $lt?: number };
'raw.info.participants'?: {
$elemMatch: { puuid: string; championId: number };
};
}
function createHarness() {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
// In the newer games only the opponent played champion 99.
const rows = [
...Array.from({ length: 127 }, (_, index) => storedMatch(index + 4, 1)),
storedMatch(3, 99),
storedMatch(2, 99),
storedMatch(1, 99),
storedMatch(131, 99, 450), // Wrong queue.
storedMatch(-1, 99), // Before the season.
];
const returnedCounts: number[] = [];
const select = jest.fn();
const find = jest.fn((filter: HistoryQuery) => {
let limit = rows.length;
const query = {
sort: jest.fn().mockReturnThis(),
limit: (value: number) => {
limit = value;
return query;
},
select: (projection: unknown) => {
select(projection);
return query;
},
exec: async () => {
const participant = filter['raw.info.participants']?.$elemMatch;
const result = rows
.filter(
(row) =>
row.participantPuuids.includes(filter.participantPuuids) &&
filter.queueId.$in.includes(row.queueId) &&
(filter.gameCreation?.$gte === undefined ||
row.gameCreation >= filter.gameCreation.$gte) &&
(filter.gameCreation?.$lt === undefined ||
row.gameCreation < filter.gameCreation.$lt) &&
(!participant ||
row.raw.info.participants.some(
(entry) =>
entry.puuid === participant.puuid &&
entry.championId === participant.championId,
)),
)
.sort((a, b) => b.gameCreation - a.gameCreation)
.slice(0, limit);
returnedCounts.push(result.length);
return result;
},
};
return query;
});
const models = {
user: {
findById: () => ({
exec: async () => ({
_id: userId,
communityId,
riotAccounts: [{ puuid: 'player', isPrimary: true }],
}),
}),
},
community: {
findById: () => ({
exec: async () => ({
_id: communityId,
seasonStartedAt: new Date(SEASON_START),
}),
}),
},
riotMatch: { find },
};
const connection = {
getModel: async (name: keyof typeof models) => models[name],
} as unknown as ConnectionService;
return {
service: new MatchHistoryService(connection),
scope: { communityId, userId },
find,
select,
returnedCounts,
};
}
function storedMatch(sequence: number, championId: number, queueId = 420) {
const gameCreation = SEASON_START + sequence * 1_000;
const participant = {
puuid: 'player',
championId,
teamId: 100,
win: true,
kills: 5,
deaths: 2,
assists: 3,
totalMinionsKilled: 100,
neutralMinionsKilled: 20,
goldEarned: 10_000,
totalDamageDealtToChampions: 10_000,
totalDamageTaken: 5_000,
perks: { styles: [] },
};
return {
gameCreation,
queueId,
participantPuuids: ['player', 'opponent'],
fetchedAt: new Date(),
raw: {
metadata: { matchId: `KR_${sequence}` },
info: {
gameCreation,
queueId,
gameDuration: 1_800,
participants: [
participant,
{
...participant,
puuid: 'opponent',
teamId: 200,
championId: 99,
win: false,
},
],
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
},
};
}