feat(api): collect tournament results
This commit is contained in:
1 parent
06c190a41f
commit
3447162aa5
4 files changed
+1291
No files matched your search
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Param,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
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')
|
||||
@Roles('owner', 'admin')
|
||||
@UseGuards(RolesGuard)
|
||||
export class TournamentResultController {
|
||||
constructor(
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
public async poll(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
if (!currentUser.communityId.equals(communityId)) {
|
||||
throw new BadRequestException('Different community.');
|
||||
}
|
||||
return this.tournamentResultService.scheduleManualPoll({
|
||||
matchId,
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { CommunityStatsModule } from '../community-stats/community-stats.module';
|
||||
import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { TournamentResultController } from './tournament-result.controller';
|
||||
import { TournamentResultService } from './tournament-result.service';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)],
|
||||
controllers: [TournamentResultController],
|
||||
providers: [TournamentResultService],
|
||||
exports: [TournamentResultService],
|
||||
})
|
||||
export class TournamentResultModule {}
|
||||
@@ -0,0 +1,263 @@
|
||||
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 & {
|
||||
resolveRequiredGameSlots(match: MatchDocument): number;
|
||||
resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { teamAIndex: number; teamBIndex: number };
|
||||
};
|
||||
|
||||
function createService() {
|
||||
return new TournamentResultService(
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
) as unknown as TournamentResultServiceInternals;
|
||||
}
|
||||
|
||||
interface MatchOverrides {
|
||||
gameCount?: number;
|
||||
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||
participants?: Array<{ excluded?: boolean }>;
|
||||
teams?: Array<{ teamIndex: number }>;
|
||||
gameSchedule?: Array<{
|
||||
gameNumber: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||
return {
|
||||
gameCount: 1,
|
||||
gameMode: 'pair',
|
||||
participants: [],
|
||||
teams: [],
|
||||
gameSchedule: [],
|
||||
...overrides,
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
|
||||
describe('TournamentResultService round-robin scheduling', () => {
|
||||
it('calculates required slots for round-robin polling', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({
|
||||
gameMode: 'round-robin',
|
||||
gameCount: 1,
|
||||
teams: Array.from({ length: 6 }, (_, index) => ({
|
||||
teamIndex: index + 1,
|
||||
})),
|
||||
});
|
||||
|
||||
expect(service.resolveRequiredGameSlots(match)).toBe(15);
|
||||
});
|
||||
|
||||
it('uses persisted round-robin schedule when mapping a game number', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({
|
||||
gameMode: 'round-robin',
|
||||
gameSchedule: [
|
||||
{ gameNumber: 1, teamAIndex: 3, teamBIndex: 6 },
|
||||
{ gameNumber: 2, teamAIndex: 1, teamBIndex: 5 },
|
||||
],
|
||||
});
|
||||
|
||||
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 5,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps pair game number mapping unchanged', () => {
|
||||
const service = createService();
|
||||
const match = createMatch({ gameCount: 3 });
|
||||
|
||||
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
|
||||
teamAIndex: 3,
|
||||
teamBIndex: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
{ buildAndUpsert: 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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,933 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
RiotMatch as StoredRiotMatch,
|
||||
TournamentCodeDocument,
|
||||
} from '../global/database/schema';
|
||||
import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service';
|
||||
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
|
||||
import { RiotMatchService } from '../riot/riot-match.service';
|
||||
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
|
||||
import {
|
||||
resolveRoundRobinTeamCount,
|
||||
roundRobinPairCount,
|
||||
roundRobinPairs,
|
||||
} from '../tournament-code/round-robin.util';
|
||||
import {
|
||||
collectCaptainUserIds,
|
||||
collectMatchUserIds,
|
||||
computeGameResult,
|
||||
type MatchPuuidLookup,
|
||||
} from './team-mapping.util';
|
||||
import type {
|
||||
EnqueueTournamentResultPollResult,
|
||||
ManualTournamentResultCollectResponse,
|
||||
PollTournamentResultJob,
|
||||
} from './tournament-result.types';
|
||||
|
||||
const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000;
|
||||
const LATER_POLL_DELAY_MS = 60 * 60_000;
|
||||
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);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly riotMatchService: RiotMatchService,
|
||||
private readonly riotJobQueueService: RiotJobQueueService,
|
||||
private readonly communityStatsService: CommunityStatsService,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
) {}
|
||||
|
||||
public async scheduleInitialPoll(
|
||||
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||
priority: RiotJobPriority = 'high',
|
||||
): Promise<EnqueueTournamentResultPollResult | null> {
|
||||
const match = await this.loadMatch(matchOrId);
|
||||
if (match.status === 'finished') return null;
|
||||
if (!this.isReadyToPoll(match)) return null;
|
||||
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
lastPolledAt: match.resultPollState?.lastPolledAt,
|
||||
lastPollOutcome: match.resultPollState?.lastPollOutcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids: false,
|
||||
state: 'polling',
|
||||
};
|
||||
await match.save();
|
||||
|
||||
return this.riotJobQueueService.enqueueTournamentResultPoll({
|
||||
matchId: match._id.toString(),
|
||||
attempt: 1,
|
||||
expandedToAllPuuids: false,
|
||||
priority,
|
||||
});
|
||||
}
|
||||
|
||||
public async scheduleManualPoll(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<EnqueueTournamentResultPollResult> {
|
||||
const match = await this.loadMatch(params.matchId);
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
if (!this.isReadyToPoll(match)) {
|
||||
throw new BadRequestException(
|
||||
'Match needs built teams, teamBuiltAt, and tournament codes before polling.',
|
||||
);
|
||||
}
|
||||
const result = await this.scheduleInitialPoll(match, 'high');
|
||||
if (!result) {
|
||||
throw new BadRequestException(
|
||||
'Tournament result polling is not available.',
|
||||
);
|
||||
}
|
||||
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> {
|
||||
const match = await this.loadMatch(matchOrId);
|
||||
match.resultPollState = undefined;
|
||||
await match.save();
|
||||
}
|
||||
|
||||
public async processPollJob(job: PollTournamentResultJob): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const match = await MatchModel.findById(job.matchId);
|
||||
if (!match || match.status === 'finished') return;
|
||||
if (!this.isReadyToPoll(match)) {
|
||||
await this.updatePollState(match, 'failed', job.expandedToAllPuuids);
|
||||
return;
|
||||
}
|
||||
|
||||
const codes = await TournamentCodeModel.find({ matchId: match._id })
|
||||
.sort({ gameNumber: 1 })
|
||||
.exec();
|
||||
const unmatched = codes.filter(
|
||||
(code) => code.state === 'reserved' && !code.riotMatchId,
|
||||
);
|
||||
if (unmatched.length === 0) {
|
||||
await this.advanceMatchIfReady(match, codes);
|
||||
return;
|
||||
}
|
||||
|
||||
const community = await CommunityModel.findById(match.communityId)
|
||||
.select({ riotRegion: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
const region = community?.riotRegion ?? 'asia';
|
||||
const lookup = await this.buildPuuidLookup(match);
|
||||
const puuids = job.expandedToAllPuuids
|
||||
? this.collectPollingPuuids(collectMatchUserIds(match), lookup)
|
||||
: this.collectPollingPuuids(collectCaptainUserIds(match), lookup);
|
||||
|
||||
const matchedGameNumbers = new Set<number>();
|
||||
const checkedRiotMatchIds = new Set<string>();
|
||||
const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code]));
|
||||
|
||||
for (const puuid of puuids) {
|
||||
let ids: string[];
|
||||
try {
|
||||
ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, {
|
||||
region,
|
||||
type: 'tourney',
|
||||
startTime: this.resolveStartTime(match),
|
||||
endTime: Math.floor(Date.now() / 1000),
|
||||
count: 100,
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Tournament result match id lookup failed for ${puuid}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const riotMatchId of ids) {
|
||||
if (checkedRiotMatchIds.has(riotMatchId)) continue;
|
||||
checkedRiotMatchIds.add(riotMatchId);
|
||||
|
||||
const alreadyMatched = await TournamentCodeModel.exists({
|
||||
riotMatchId,
|
||||
});
|
||||
if (alreadyMatched) continue;
|
||||
|
||||
let detail: RiotMatchDto;
|
||||
try {
|
||||
detail = await this.ensureRiotMatchPersisted(riotMatchId, region);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Tournament result detail fetch failed for ${riotMatchId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase();
|
||||
if (!tournamentCode) continue;
|
||||
|
||||
const code = unmatchedByCode.get(tournamentCode);
|
||||
if (!code) continue;
|
||||
|
||||
const applied = await this.applyMatchToGameSlot({
|
||||
match,
|
||||
code,
|
||||
detail,
|
||||
lookup,
|
||||
});
|
||||
if (applied) {
|
||||
matchedGameNumbers.add(code.gameNumber ?? 0);
|
||||
unmatchedByCode.delete(tournamentCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id })
|
||||
.sort({ gameNumber: 1 })
|
||||
.exec();
|
||||
const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found';
|
||||
await this.updatePollState(match, outcome, job.expandedToAllPuuids);
|
||||
const completed = await this.advanceMatchIfReady(match, reloadedCodes);
|
||||
if (!completed) {
|
||||
await this.scheduleNextPoll(match, job);
|
||||
}
|
||||
}
|
||||
|
||||
private async applyMatchToGameSlot(params: {
|
||||
match: MatchDocument;
|
||||
code: TournamentCodeDocument;
|
||||
detail: RiotMatchDto;
|
||||
lookup: MatchPuuidLookup;
|
||||
}): Promise<boolean> {
|
||||
const { match, code, detail, lookup } = params;
|
||||
if (code.state !== 'reserved' || code.riotMatchId) return false;
|
||||
if (!code.gameNumber) return false;
|
||||
|
||||
const gameResult = computeGameResult({
|
||||
match,
|
||||
detail,
|
||||
gameNumber: code.gameNumber,
|
||||
lookup,
|
||||
...this.resolveSeriesRefForGameNumber(match, code.gameNumber),
|
||||
});
|
||||
if (!gameResult) {
|
||||
this.logger.warn(
|
||||
`Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
code.state = 'used';
|
||||
code.usedAt = new Date(
|
||||
detail.info.gameEndTimestamp ?? detail.info.gameCreation,
|
||||
);
|
||||
code.riotMatchId = detail.metadata.matchId;
|
||||
await code.save();
|
||||
|
||||
this.upsertGameResult(match, gameResult);
|
||||
if (match.status === 'team-built') {
|
||||
match.status = 'in-progress';
|
||||
}
|
||||
await match.save();
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
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 (appliedRiotMatchIds.length > 0) {
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
}
|
||||
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[],
|
||||
): Promise<boolean> {
|
||||
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
|
||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex(
|
||||
match.result.seriesResults ?? [],
|
||||
);
|
||||
}
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
lastPolledAt: match.resultPollState?.lastPolledAt,
|
||||
lastPollOutcome: match.resultPollState?.lastPollOutcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false,
|
||||
state: 'complete',
|
||||
};
|
||||
await match.save();
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
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
|
||||
}`,
|
||||
);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private async scheduleNextPoll(
|
||||
match: MatchDocument,
|
||||
job: PollTournamentResultJob,
|
||||
): Promise<void> {
|
||||
const pollState = match.resultPollState;
|
||||
const startedAt = pollState?.startedAt ?? new Date();
|
||||
const elapsedMs = Date.now() - startedAt.getTime();
|
||||
const delayMs = this.nextPollDelayMs(elapsedMs);
|
||||
if (delayMs === null) {
|
||||
match.resultPollState = {
|
||||
startedAt,
|
||||
lastPolledAt: pollState?.lastPolledAt,
|
||||
lastPollOutcome: pollState?.lastPollOutcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids:
|
||||
pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids,
|
||||
state: 'expired',
|
||||
};
|
||||
await match.save();
|
||||
this.logger.warn(
|
||||
`Tournament result polling expired for match ${match._id.toString()}.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const expandedToAllPuuids =
|
||||
job.expandedToAllPuuids ||
|
||||
(elapsedMs >= EXPAND_AFTER_MS &&
|
||||
(match.result?.games?.length ?? 0) === 0);
|
||||
await this.riotJobQueueService.enqueueTournamentResultPoll({
|
||||
matchId: match._id.toString(),
|
||||
attempt: job.attempt + 1,
|
||||
expandedToAllPuuids,
|
||||
priority: 'low',
|
||||
deferUntilMs: Date.now() + delayMs,
|
||||
});
|
||||
}
|
||||
|
||||
private async ensureRiotMatchPersisted(
|
||||
riotMatchId: string,
|
||||
region: RiotRegionalRoute,
|
||||
): Promise<RiotMatchDto> {
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const stored = await RiotMatchModel.findOne({
|
||||
matchId: riotMatchId,
|
||||
}).exec();
|
||||
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
||||
|
||||
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
||||
const payload: Partial<StoredRiotMatch> = {
|
||||
matchId: dto.metadata.matchId,
|
||||
gameCreation: dto.info.gameCreation,
|
||||
gameDuration: dto.info.gameDuration,
|
||||
gameVersion: dto.info.gameVersion,
|
||||
queueId: dto.info.queueId,
|
||||
participantPuuids: dto.metadata.participants,
|
||||
raw: dto as unknown as Record<string, unknown>,
|
||||
fetchedAt: new Date(),
|
||||
};
|
||||
await RiotMatchModel.updateOne(
|
||||
{ matchId: dto.metadata.matchId },
|
||||
{ $setOnInsert: payload },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
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>();
|
||||
|
||||
for (const participant of match.participants) {
|
||||
if (!participant.puuid) continue;
|
||||
const userId = participant.userId.toString();
|
||||
puuidByUserId.set(userId, participant.puuid);
|
||||
userIdByPuuid.set(participant.puuid, participant.userId);
|
||||
}
|
||||
|
||||
const missingUserIds = collectMatchUserIds(match).filter(
|
||||
(userId) => !puuidByUserId.has(userId.toString()),
|
||||
);
|
||||
if (missingUserIds.length > 0) {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const users = await UserModel.find({ _id: { $in: missingUserIds } })
|
||||
.select({ riotAccounts: 1 })
|
||||
.exec();
|
||||
for (const user of users) {
|
||||
const primary =
|
||||
user.riotAccounts.find((account) => account.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
if (!primary) continue;
|
||||
puuidByUserId.set(user._id.toString(), primary.puuid);
|
||||
userIdByPuuid.set(primary.puuid, user._id);
|
||||
}
|
||||
}
|
||||
|
||||
return { puuidByUserId, userIdByPuuid };
|
||||
}
|
||||
|
||||
private collectPollingPuuids(
|
||||
userIds: mongoose.Types.ObjectId[],
|
||||
lookup: MatchPuuidLookup,
|
||||
): string[] {
|
||||
return [
|
||||
...new Set(
|
||||
userIds
|
||||
.map((userId) => lookup.puuidByUserId.get(userId.toString()))
|
||||
.filter((puuid): puuid is string => Boolean(puuid)),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
private upsertGameResult(
|
||||
match: MatchDocument,
|
||||
gameResult: MatchGameResult,
|
||||
): void {
|
||||
const currentGames = match.result?.games ?? [];
|
||||
const games = [
|
||||
...currentGames.filter(
|
||||
(game) =>
|
||||
game.gameNumber !== gameResult.gameNumber &&
|
||||
game.riotMatchId !== gameResult.riotMatchId,
|
||||
),
|
||||
gameResult,
|
||||
].sort((left, right) => left.gameNumber - right.gameNumber);
|
||||
const seriesResults = this.buildSeriesResults(games);
|
||||
|
||||
match.result = {
|
||||
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults),
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
seriesResults,
|
||||
};
|
||||
}
|
||||
|
||||
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();
|
||||
await this.rebuildMatchStatsSafe(match);
|
||||
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 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(
|
||||
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'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}
|
||||
>();
|
||||
|
||||
for (const game of games) {
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current = bySeries.get(key) ?? {
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
teamBWins: 0,
|
||||
};
|
||||
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSeriesRefForGameNumber(
|
||||
match: MatchDocument,
|
||||
gameNumber: number,
|
||||
): { teamAIndex: number; teamBIndex: number } {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
|
||||
if (gameMode === 'round-robin') {
|
||||
const persisted = match.gameSchedule?.find(
|
||||
(entry) => entry.gameNumber === gameNumber,
|
||||
);
|
||||
if (persisted) {
|
||||
return {
|
||||
teamAIndex: persisted.teamAIndex,
|
||||
teamBIndex: persisted.teamBIndex,
|
||||
};
|
||||
}
|
||||
|
||||
const perSeries = match.gameCount || 1;
|
||||
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
|
||||
return (
|
||||
roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? {
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const perSeries = match.gameCount || 1;
|
||||
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||
return {
|
||||
teamAIndex: (seriesIndex - 1) * 2 + 1,
|
||||
teamBIndex: (seriesIndex - 1) * 2 + 2,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveRequiredGameSlots(match: MatchDocument): number {
|
||||
const gameMode = match.gameMode ?? 'pair';
|
||||
if (gameMode === 'round-robin') {
|
||||
const teamCount = resolveRoundRobinTeamCount(match);
|
||||
return roundRobinPairCount(teamCount) * (match.gameCount || 1);
|
||||
}
|
||||
|
||||
const activeParticipantCount = match.participants.filter(
|
||||
(participant) => !participant.excluded,
|
||||
).length;
|
||||
const participantSeriesCount = Math.floor(activeParticipantCount / 10);
|
||||
const teamSeriesCount = Math.ceil(match.teams.length / 2);
|
||||
const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount);
|
||||
return seriesCount * (match.gameCount || 1);
|
||||
}
|
||||
|
||||
private resolveMatchWinnerTeamIndex(
|
||||
seriesResults: NonNullable<MatchDocument['result']>['seriesResults'],
|
||||
): number | undefined {
|
||||
const winsByTeam = new Map<number, number>();
|
||||
for (const series of seriesResults ?? []) {
|
||||
if (!series.winnerTeamIndex) continue;
|
||||
winsByTeam.set(
|
||||
series.winnerTeamIndex,
|
||||
(winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
const sorted = [...winsByTeam.entries()].sort(
|
||||
(left, right) => right[1] - left[1],
|
||||
);
|
||||
if (sorted.length === 0) return undefined;
|
||||
if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined;
|
||||
return sorted[0][0];
|
||||
}
|
||||
|
||||
private async updatePollState(
|
||||
match: MatchDocument,
|
||||
outcome: 'matched' | 'not-found' | 'failed',
|
||||
expandedToAllPuuids: boolean,
|
||||
): Promise<void> {
|
||||
match.resultPollState = {
|
||||
startedAt: match.resultPollState?.startedAt ?? new Date(),
|
||||
lastPolledAt: new Date(),
|
||||
lastPollOutcome: outcome,
|
||||
matchedCount: match.result?.games?.length ?? 0,
|
||||
expandedToAllPuuids,
|
||||
state: outcome === 'failed' ? 'failed' : 'polling',
|
||||
};
|
||||
await match.save();
|
||||
}
|
||||
|
||||
private nextPollDelayMs(elapsedMs: number): number | null {
|
||||
if (elapsedMs >= POLL_EXPIRY_MS) return null;
|
||||
if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS;
|
||||
return LATER_POLL_DELAY_MS;
|
||||
}
|
||||
|
||||
private resolveStartTime(match: MatchDocument): number {
|
||||
return Math.max(
|
||||
0,
|
||||
Math.floor(match.teamBuiltAt!.getTime() / 1000) -
|
||||
TOURNAMENT_LOOKUP_START_MARGIN_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
private isReadyToPoll(match: MatchDocument): boolean {
|
||||
return Boolean(
|
||||
match.teamBuiltAt &&
|
||||
match.tournamentCodeIds.length > 0 &&
|
||||
match.teams.length >= 2 &&
|
||||
match.teams.every((team) => team.members.length > 0),
|
||||
);
|
||||
}
|
||||
|
||||
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> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match =
|
||||
matchOrId instanceof mongoose.Types.ObjectId
|
||||
? await MatchModel.findById(matchOrId)
|
||||
: await MatchModel.findById(matchOrId._id);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
return match;
|
||||
}
|
||||
}
|
||||
|
||||
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'metadata' in value &&
|
||||
'info' in value,
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user