This commit is contained in:
dahyeon committed 2026-05-03 04:33:47 -07:00
1 parent 6767a9f61b
commit 5df3ea67e7
8 files changed
+785 -16

No files matched your search

@@ -0,0 +1,19 @@
import { Type } from 'class-transformer';
import { IsDate, IsString, MaxLength, MinLength } from 'class-validator';
export class CollectTournamentResultWindowDto {
@IsDate()
@Type(() => Date)
startTime!: Date;
@IsDate()
@Type(() => Date)
endTime!: Date;
}
export class CollectTournamentResultRiotMatchDto {
@IsString()
@MinLength(1)
@MaxLength(96)
riotMatchId!: string;
}
@@ -1,5 +1,6 @@
import {
BadRequestException,
Body,
Controller,
Param,
Post,
@@ -11,6 +12,10 @@ import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import {
CollectTournamentResultRiotMatchDto,
CollectTournamentResultWindowDto,
} from './dto/manual-result-collection.dto';
import { TournamentResultService } from './tournament-result.service';
@Controller('communities/:communityId/matches/:matchId/poll-tournament-result')
@@ -36,4 +41,41 @@ export class TournamentResultController {
communityId,
});
}
@Post('collect-by-window')
public async collectByWindow(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: CollectTournamentResultWindowDto,
) {
if (!currentUser.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
return this.tournamentResultService.collectManualByWindow({
matchId,
communityId,
startTime: body.startTime,
endTime: body.endTime,
});
}
@Post('collect-by-riot-match')
public async collectByRiotMatch(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: CollectTournamentResultRiotMatchDto,
) {
if (!currentUser.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
return this.tournamentResultService.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: body.riotMatchId,
});
}
}
@@ -1,4 +1,6 @@
import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { TournamentResultService } from './tournament-result.service';
type TournamentResultServiceInternals = TournamentResultService & {
@@ -81,3 +83,179 @@ describe('TournamentResultService round-robin scheduling', () => {
});
});
});
describe('TournamentResultService manual result collection', () => {
function createManualFixture() {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `puuid-${index + 1}`,
}));
const match = {
_id: matchId,
communityId,
gameCount: 1,
gameMode: 'pair',
teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'),
status: 'team-built',
tournamentCodeIds: [],
gameSchedule: [],
participants: users.map((user) => ({
userId: user.userId,
puuid: user.puuid,
excluded: false,
})),
teams: [
{
teamIndex: 1,
members: users.slice(0, 5).map((user) => ({ userId: user.userId })),
},
{
teamIndex: 2,
members: users.slice(5).map((user) => ({ userId: user.userId })),
},
],
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & {
save: jest.Mock;
result?: MatchDocument['result'];
};
const detail = {
metadata: {
matchId: 'KR_1234567890',
participants: users.map((user) => user.puuid),
},
info: {
gameCreation: Date.parse('2026-05-03T10:30:00.000Z'),
gameDuration: 1800,
participants: users.map((user, index) => ({
puuid: user.puuid,
teamId: index < 5 ? 100 : 200,
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win: index < 5,
})),
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
} as unknown as RiotMatchDto;
const communityFindById = jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }),
}),
}),
});
const riotMatchFindOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
});
const riotMatchUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
});
const tournamentCodeUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: jest.fn().mockResolvedValue(match) };
}
if (name === 'community') {
return { findById: communityFindById };
}
if (name === 'riotMatch') {
return {
findOne: riotMatchFindOne,
updateOne: riotMatchUpdateOne,
};
}
if (name === 'tournamentCode') {
return { updateOne: tournamentCodeUpdateOne };
}
return {};
}),
};
const riotMatchService = {
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']),
getMatch: jest.fn().mockResolvedValue(detail),
};
const service = new TournamentResultService(
connectionService as never,
riotMatchService as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
);
return {
service,
match,
communityId,
matchId,
riotMatchService,
tournamentCodeUpdateOne,
};
}
it('collects by time window without setting Riot match type', async () => {
const { service, match, communityId, matchId, riotMatchService } =
createManualFixture();
const result = await service.collectManualByWindow({
matchId,
communityId,
startTime: new Date('2026-05-03T10:00:00.000Z'),
endTime: new Date('2026-05-03T11:00:00.000Z'),
});
expect(result).toMatchObject({
scanned: 1,
matched: 1,
gameNumbers: [1],
riotMatchIds: ['KR_1234567890'],
});
expect(riotMatchService.getMatchIdsByPuuid).toHaveBeenCalledWith(
'puuid-1',
expect.not.objectContaining({ type: expect.anything() }),
);
expect(match.result?.games).toHaveLength(1);
expect(match.status).toBe('finished');
});
it('collects directly by Riot match id', async () => {
const {
service,
match,
communityId,
matchId,
riotMatchService,
tournamentCodeUpdateOne,
} = createManualFixture();
const result = await service.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: ' KR_1234567890 ',
});
expect(result.matched).toBe(1);
expect(riotMatchService.getMatchIdsByPuuid).not.toHaveBeenCalled();
expect(riotMatchService.getMatch).toHaveBeenCalledWith('KR_1234567890', {
region: 'asia',
});
expect(tournamentCodeUpdateOne).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
gameNumber: 1,
}),
expect.objectContaining({
$set: expect.objectContaining({ riotMatchId: 'KR_1234567890' }),
}),
);
expect(match.result?.games[0].winnerTeamIndex).toBe(1);
});
});
@@ -30,6 +30,7 @@ import {
} from './team-mapping.util';
import type {
EnqueueTournamentResultPollResult,
ManualTournamentResultCollectResponse,
PollTournamentResultJob,
} from './tournament-result.types';
@@ -39,6 +40,12 @@ const POLL_EXPIRY_MS = 24 * 60 * 60_000;
const EXPAND_AFTER_MS = 60 * 60_000;
const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
interface ManualGameAssignment {
gameNumber: number;
teamAIndex: number;
teamBIndex: number;
}
@Injectable()
export class TournamentResultService {
private readonly logger = new Logger(TournamentResultService.name);
@@ -96,6 +103,75 @@ export class TournamentResultService {
return result;
}
public async collectManualByWindow(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
startTime: Date;
endTime: Date;
}): Promise<ManualTournamentResultCollectResponse> {
const match = await this.loadMatch(params.matchId);
this.assertManualCollectionAllowed(match, params.communityId);
if (params.startTime.getTime() > params.endTime.getTime()) {
throw new BadRequestException(
'startTime must be less than or equal to endTime.',
);
}
const region = await this.resolveRiotRegion(match);
const lookup = await this.buildPuuidLookup(match);
const puuids = this.collectPollingPuuids(collectMatchUserIds(match), lookup);
const startTime = Math.floor(params.startTime.getTime() / 1000);
const endTime = Math.floor(params.endTime.getTime() / 1000);
const riotMatchIds = new Set<string>();
for (const puuid of puuids) {
try {
const ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, {
region,
startTime,
endTime,
count: 100,
});
ids.forEach((id) => riotMatchIds.add(id));
} catch (error) {
this.logger.warn(
`Manual result match id lookup failed for ${puuid}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
const details = await this.loadRiotMatchDetails(
[...riotMatchIds],
region,
'Manual result detail fetch failed',
);
return this.applyManualRiotMatches(match, details, lookup);
}
public async collectManualByRiotMatch(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
riotMatchId: string;
}): Promise<ManualTournamentResultCollectResponse> {
const match = await this.loadMatch(params.matchId);
this.assertManualCollectionAllowed(match, params.communityId);
const normalizedRiotMatchId = params.riotMatchId.trim();
if (!normalizedRiotMatchId) {
throw new BadRequestException('riotMatchId is required.');
}
const region = await this.resolveRiotRegion(match);
const lookup = await this.buildPuuidLookup(match);
const detail = await this.ensureRiotMatchPersisted(
normalizedRiotMatchId,
region,
);
return this.applyManualRiotMatches(match, [detail], lookup);
}
public async cancelPolling(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> {
@@ -245,6 +321,54 @@ export class TournamentResultService {
return true;
}
private async applyManualRiotMatches(
match: MatchDocument,
details: RiotMatchDto[],
lookup: MatchPuuidLookup,
): Promise<ManualTournamentResultCollectResponse> {
const sortedDetails = [...details].sort(
(left, right) => left.info.gameCreation - right.info.gameCreation,
);
const appliedRiotMatchIds: string[] = [];
const appliedGameNumbers: number[] = [];
let skipped = 0;
for (const detail of sortedDetails) {
if (this.hasResultForRiotMatch(match, detail.metadata.matchId)) {
skipped += 1;
continue;
}
const gameResult = this.computeManualGameResult(match, detail, lookup);
if (!gameResult) {
skipped += 1;
continue;
}
this.upsertGameResult(match, gameResult);
await this.markTournamentCodeUsedForManualResult(match, gameResult, detail);
appliedRiotMatchIds.push(detail.metadata.matchId);
appliedGameNumbers.push(gameResult.gameNumber);
}
if (appliedRiotMatchIds.length > 0 && match.status === 'team-built') {
match.status = 'in-progress';
}
this.updateManualCollectionState(match, appliedRiotMatchIds.length);
await match.save();
if (this.hasAllRequiredGameResults(match)) {
await this.finishMatchFromManualResults(match);
}
return {
scanned: sortedDetails.length,
matched: appliedRiotMatchIds.length,
skipped,
riotMatchIds: appliedRiotMatchIds,
gameNumbers: appliedGameNumbers,
};
}
private async advanceMatchIfReady(
match: MatchDocument,
codes: TournamentCodeDocument[],
@@ -344,6 +468,29 @@ export class TournamentResultService {
return dto;
}
private async loadRiotMatchDetails(
riotMatchIds: string[],
region: RiotRegionalRoute,
logPrefix: string,
): Promise<RiotMatchDto[]> {
const details: RiotMatchDto[] = [];
const checked = new Set<string>();
for (const riotMatchId of riotMatchIds) {
if (checked.has(riotMatchId)) continue;
checked.add(riotMatchId);
try {
details.push(await this.ensureRiotMatchPersisted(riotMatchId, region));
} catch (error) {
this.logger.warn(
`${logPrefix} ${riotMatchId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
return details;
}
private async buildPuuidLookup(match: MatchDocument): Promise<MatchPuuidLookup> {
const puuidByUserId = new Map<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
@@ -413,6 +560,133 @@ export class TournamentResultService {
};
}
private computeManualGameResult(
match: MatchDocument,
detail: RiotMatchDto,
lookup: MatchPuuidLookup,
): MatchGameResult | null {
for (const assignment of this.resolveOpenManualGameAssignments(match)) {
const gameResult = computeGameResult({
match,
detail,
gameNumber: assignment.gameNumber,
lookup,
teamAIndex: assignment.teamAIndex,
teamBIndex: assignment.teamBIndex,
});
if (gameResult) return gameResult;
}
return null;
}
private resolveOpenManualGameAssignments(
match: MatchDocument,
): ManualGameAssignment[] {
const usedGameNumbers = new Set(
(match.result?.games ?? []).map((game) => game.gameNumber),
);
const assignments: ManualGameAssignment[] = [];
const requiredSlots = this.resolveRequiredGameSlots(match);
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
if (usedGameNumbers.has(gameNumber)) continue;
assignments.push({
gameNumber,
...this.resolveSeriesRefForGameNumber(match, gameNumber),
});
}
return assignments;
}
private hasResultForRiotMatch(
match: MatchDocument,
riotMatchId: string,
): boolean {
return Boolean(
match.result?.games?.some((game) => game.riotMatchId === riotMatchId),
);
}
private hasAllRequiredGameResults(match: MatchDocument): boolean {
const requiredSlots = this.resolveRequiredGameSlots(match);
if (requiredSlots <= 0) return false;
const resultGameNumbers = new Set(
(match.result?.games ?? []).map((game) => game.gameNumber),
);
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
if (!resultGameNumbers.has(gameNumber)) return false;
}
return true;
}
private updateManualCollectionState(
match: MatchDocument,
matchedCount: number,
): void {
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: new Date(),
lastPollOutcome: matchedCount > 0 ? 'matched' : 'not-found',
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids: true,
state: 'polling',
};
}
private async finishMatchFromManualResults(
match: MatchDocument,
): Promise<void> {
match.status = 'finished';
if (match.result) {
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
match.result.seriesResults ?? [],
);
}
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: new Date(),
lastPollOutcome: 'matched',
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids: true,
state: 'complete',
};
await match.save();
void this.communityStatsService
.invalidateCommunity(match.communityId)
.catch((error) => {
this.logger.warn(
`Failed to invalidate community stats cache for ${match.communityId.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
});
}
private async markTournamentCodeUsedForManualResult(
match: MatchDocument,
gameResult: MatchGameResult,
detail: RiotMatchDto,
): Promise<void> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
await TournamentCodeModel.updateOne(
{
matchId: match._id,
gameNumber: gameResult.gameNumber,
state: { $in: ['reserved', 'released'] },
},
{
$set: {
state: 'used',
usedAt: new Date(
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
),
riotMatchId: detail.metadata.matchId,
},
},
).exec();
}
private buildSeriesResults(
games: MatchGameResult[],
): NonNullable<MatchDocument['result']>['seriesResults'] {
@@ -564,6 +838,39 @@ export class TournamentResultService {
);
}
private assertManualCollectionAllowed(
match: MatchDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!match.communityId.equals(communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if (!this.hasBuiltTeams(match)) {
throw new BadRequestException(
'Match needs built teams before manual result collection.',
);
}
}
private hasBuiltTeams(match: MatchDocument): boolean {
return Boolean(
match.teamBuiltAt &&
match.teams.length >= 2 &&
match.teams.every((team) => team.members.length > 0),
);
}
private async resolveRiotRegion(
match: MatchDocument,
): Promise<RiotRegionalRoute> {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(match.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
return community?.riotRegion ?? 'asia';
}
private async loadMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<MatchDocument> {
@@ -19,6 +19,14 @@ export interface EnqueueTournamentResultPollResult {
expandedToAllPuuids: boolean;
}
export interface ManualTournamentResultCollectResponse {
scanned: number;
matched: number;
skipped: number;
riotMatchIds: string[];
gameNumbers: number[];
}
export interface ComputedGameParticipant {
userId: string;
teamIndex: number;