From 2984bd16048963116fc5e0dcfb790b2a0a897205 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Thu, 25 Jun 2026 04:58:10 -0700 Subject: [PATCH] fix: resume tournament result polling after delayed codes --- .../tournament-code/tournament-code.module.ts | 2 + .../tournament-code.scheduler.spec.ts | 62 +++++++++++++++++++ .../tournament-code.scheduler.ts | 14 ++++- .../tournament-code.service.ts | 20 ++++-- .../team-mapping.util.spec.ts | 44 +++++++++++-- .../tournament-result/team-mapping.util.ts | 45 ++++++++++++-- .../tournament-result.service.spec.ts | 29 ++++++++- .../tournament-result.service.ts | 12 +++- 8 files changed, 207 insertions(+), 21 deletions(-) create mode 100644 apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts diff --git a/apps/api/src/modules/tournament-code/tournament-code.module.ts b/apps/api/src/modules/tournament-code/tournament-code.module.ts index 8cdd1f0d..4fe9838f 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.module.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.module.ts @@ -1,4 +1,5 @@ import { Module } from '@nestjs/common'; +import { TournamentResultModule } from '../tournament-result/tournament-result.module'; import { TournamentCodeController } from './tournament-code.controller'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeReplacementController } from './tournament-code-replacement.controller'; @@ -7,6 +8,7 @@ import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeVendorService } from './tournament-code-vendor.service'; @Module({ + imports: [TournamentResultModule], controllers: [TournamentCodeController, TournamentCodeReplacementController], providers: [ TournamentCodeService, diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts new file mode 100644 index 00000000..56e87f8c --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.spec.ts @@ -0,0 +1,62 @@ +import { TournamentCodeScheduler } from './tournament-code.scheduler'; + +describe('TournamentCodeScheduler', () => { + function createScheduler(params?: { + attachedMatches?: unknown[]; + scheduleInitialPoll?: jest.Mock; + }) { + const tournamentCodeService = { + attachPendingMatchDocuments: jest + .fn() + .mockResolvedValue(params?.attachedMatches ?? []), + markExpired: jest.fn().mockResolvedValue(0), + }; + const autoProvisionService = { + ensurePool: jest.fn().mockResolvedValue(undefined), + }; + const tournamentResultService = { + scheduleInitialPoll: + params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null), + }; + const scheduler = new TournamentCodeScheduler( + tournamentCodeService as never, + autoProvisionService as never, + tournamentResultService as never, + ) as unknown as { attachPending(): Promise }; + + return { + scheduler, + tournamentCodeService, + tournamentResultService, + }; + } + + it('starts result polling after attaching delayed tournament codes', async () => { + const attachedMatches = [{ _id: 'match-1' }, { _id: 'match-2' }]; + const { scheduler, tournamentResultService } = createScheduler({ + attachedMatches, + }); + + await scheduler.attachPending(); + + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledTimes( + 2, + ); + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith( + 1, + attachedMatches[0], + ); + expect(tournamentResultService.scheduleInitialPoll).toHaveBeenNthCalledWith( + 2, + attachedMatches[1], + ); + }); + + it('does not schedule result polling when no match received new codes', async () => { + const { scheduler, tournamentResultService } = createScheduler(); + + await scheduler.attachPending(); + + expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts index 16f04e3c..47846abb 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts @@ -1,4 +1,5 @@ import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeService } from './tournament-code.service'; @@ -12,6 +13,7 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { constructor( private readonly tournamentCodeService: TournamentCodeService, private readonly autoProvisionService: TournamentCodeAutoProvisionService, + private readonly tournamentResultService: TournamentResultService, ) {} public onModuleInit() { @@ -45,9 +47,15 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { private async attachPending() { try { - const touched = await this.tournamentCodeService.attachPendingMatches(); - if (touched > 0) { - this.logger.debug(`Attached tournament codes for ${touched} matches.`); + const matches = + await this.tournamentCodeService.attachPendingMatchDocuments(); + if (matches.length > 0) { + this.logger.debug( + `Attached tournament codes for ${matches.length} matches.`, + ); + for (const match of matches) { + await this.tournamentResultService.scheduleInitialPoll(match); + } } } catch (error) { this.logger.warn( diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index dc47de8d..a90c595f 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -430,6 +430,13 @@ export class TournamentCodeService { public async attachPendingMatches( communityId?: mongoose.Types.ObjectId, ): Promise { + const matches = await this.attachPendingMatchDocuments(communityId); + return matches.length; + } + + public async attachPendingMatchDocuments( + communityId?: mongoose.Types.ObjectId, + ): Promise { const MatchModel = await this.connectionService.getModel('match'); const filter: { status: { $in: string[] }; @@ -440,15 +447,18 @@ export class TournamentCodeService { if (communityId) filter.communityId = communityId; const matches = await MatchModel.find(filter).exec(); - let touched = 0; + const touched: MatchDocument[] = []; for (const match of matches) { - if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) { + if ( + (match.tournamentCodeIds?.length ?? 0) >= + this.resolveRequiredSlots(match) + ) { continue; } const before = match.tournamentCodeIds?.length ?? 0; - await this.reserveForMatch(match); - const after = match.tournamentCodeIds?.length ?? 0; - if (after > before) touched += 1; + const updatedMatch = await this.reserveForMatch(match); + const after = updatedMatch.tournamentCodeIds?.length ?? 0; + if (after > before) touched.push(updatedMatch); } return touched; } diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts index 4a254382..de5e512f 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -1,7 +1,11 @@ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; -import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util'; +import { + collectCaptainAndLimitedTeamMemberUserIds, + computeGameResult, + type MatchPuuidLookup, +} from './team-mapping.util'; function makeMatch(): { match: MatchDocument; @@ -9,8 +13,14 @@ function makeMatch(): { blueUserIds: mongoose.Types.ObjectId[]; redUserIds: mongoose.Types.ObjectId[]; } { - const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); - const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); + const blueUserIds = Array.from( + { length: 5 }, + () => new mongoose.Types.ObjectId(), + ); + const redUserIds = Array.from( + { length: 5 }, + () => new mongoose.Types.ObjectId(), + ); const puuidByUserId = new Map(); const userIdByPuuid = new Map(); @@ -47,7 +57,12 @@ function makeMatch(): { })), } as unknown as MatchDocument; - return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds }; + return { + match, + lookup: { puuidByUserId, userIdByPuuid }, + blueUserIds, + redUserIds, + }; } function makeRiotMatch(params: { @@ -154,3 +169,24 @@ describe('computeGameResult', () => { expect(result).toBeNull(); }); }); + +describe('collectCaptainAndLimitedTeamMemberUserIds', () => { + it('keeps captains and caps extra members per team', () => { + const { blueUserIds, match, redUserIds } = makeMatch(); + match.teams[0].captainUserId = blueUserIds[0]; + match.teams[1].captainUserId = redUserIds[0]; + + const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map( + (userId) => userId.toString(), + ); + + expect(userIds).toEqual([ + blueUserIds[0].toString(), + blueUserIds[1].toString(), + blueUserIds[2].toString(), + redUserIds[0].toString(), + redUserIds[1].toString(), + redUserIds[2].toString(), + ]); + }); +}); diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts index 8f463365..d21d551d 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -1,5 +1,9 @@ import mongoose from 'mongoose'; -import type { MatchDocument, MatchGameResult, TeamSide } from '../global/database/schema'; +import type { + MatchDocument, + MatchGameResult, + TeamSide, +} from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; const RIOT_BLUE_TEAM_ID = 100; @@ -11,19 +15,46 @@ export interface MatchPuuidLookup { userIdByPuuid: Map; } -export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { +export function collectCaptainUserIds( + match: MatchDocument, +): mongoose.Types.ObjectId[] { return match.teams .map((team) => team.captainUserId) .filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId)); } -export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { +export function collectCaptainAndLimitedTeamMemberUserIds( + match: MatchDocument, + memberLimitPerTeam: number, +): mongoose.Types.ObjectId[] { + const ids = new Map(); + for (const team of match.teams) { + if (team.captainUserId) { + ids.set(team.captainUserId.toString(), team.captainUserId); + } + let memberCount = 0; + for (const member of team.members) { + if (team.captainUserId?.toString() === member.userId.toString()) { + continue; + } + if (memberCount >= memberLimitPerTeam) break; + ids.set(member.userId.toString(), member.userId); + memberCount += 1; + } + } + return [...ids.values()]; +} + +export function collectMatchUserIds( + match: MatchDocument, +): mongoose.Types.ObjectId[] { const ids = new Map(); for (const participant of match.participants) { ids.set(participant.userId.toString(), participant.userId); } for (const team of match.teams) { - if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId); + if (team.captainUserId) + ids.set(team.captainUserId.toString(), team.captainUserId); for (const member of team.members) { ids.set(member.userId.toString(), member.userId); } @@ -78,8 +109,10 @@ export function computeGameResult(params: { const reversedOverlap = countOverlap(team100Puuids, teamBPuuids) + countOverlap(team200Puuids, teamAPuuids); - const blueTeamIndex = normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex; - const redTeamIndex = normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex; + const blueTeamIndex = + normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex; + const redTeamIndex = + normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex; const teamIndexByRiotTeamId: Record = { [RIOT_BLUE_TEAM_ID]: blueTeamIndex, [RIOT_RED_TEAM_ID]: redTeamIndex, diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 5f88a0d4..8fd75209 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -4,6 +4,7 @@ import type { RiotMatchDto } from '../riot/riot.types'; import { TournamentResultService } from './tournament-result.service'; type TournamentResultServiceInternals = TournamentResultService & { + nextPollDelayMs(elapsedMs: number): number | null; resolveRequiredGameSlots(match: MatchDocument): number; resolveSeriesRefForGameNumber( match: MatchDocument, @@ -235,7 +236,7 @@ describe('TournamentResultService tournament code polling', () => { { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, ); - return { service, match, code }; + return { service, match, code, riotMatchService }; } it('matches Riot tournament codes using exact casing', async () => { @@ -256,6 +257,23 @@ describe('TournamentResultService tournament code polling', () => { expect(match.result?.games).toHaveLength(1); }); + it('limits expanded polling to two team members per team', async () => { + const { service, match, riotMatchService } = createPollFixture({ + storedCode: 'AbC-12345', + riotTournamentCode: 'AbC-12345', + }); + + await service.processPollJob({ + matchId: match._id.toString(), + attempt: 1, + expandedToAllPuuids: true, + }); + + expect( + riotMatchService.getMatchIdsByPuuid.mock.calls.map(([puuid]) => puuid), + ).toEqual(['poll-puuid-1', 'poll-puuid-2', 'poll-puuid-6', 'poll-puuid-7']); + }); + it('does not match tournament codes when casing differs', async () => { const { service, match, code } = createPollFixture({ storedCode: 'ABC-12345', @@ -275,6 +293,15 @@ describe('TournamentResultService tournament code polling', () => { }); }); +describe('TournamentResultService polling cadence', () => { + it('polls every two minutes during the first hour', () => { + const service = createService(); + + expect(service.nextPollDelayMs(0)).toBe(2 * 60_000); + expect(service.nextPollDelayMs(60 * 60_000)).toBe(2 * 60_000); + }); +}); + describe('TournamentResultService manual result collection', () => { function createManualFixture() { const communityId = new mongoose.Types.ObjectId(); diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index ed2c90ad..de0e52f6 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -23,6 +23,7 @@ import { resolveRoundRobinTeamCount, } from '../tournament-code/round-robin.util'; import { + collectCaptainAndLimitedTeamMemberUserIds, collectCaptainUserIds, collectMatchUserIds, computeGameResult, @@ -34,10 +35,11 @@ import type { PollTournamentResultJob, } from './tournament-result.types'; -const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000; +const FIRST_HOUR_POLL_DELAY_MS = 2 * 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 EXPANDED_MEMBER_LIMIT_PER_TEAM = 2; const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; interface ManualGameAssignment { @@ -216,7 +218,13 @@ export class TournamentResultService { const region = community?.riotRegion ?? 'asia'; const lookup = await this.buildPuuidLookup(match); const puuids = job.expandedToAllPuuids - ? this.collectPollingPuuids(collectMatchUserIds(match), lookup) + ? this.collectPollingPuuids( + collectCaptainAndLimitedTeamMemberUserIds( + match, + EXPANDED_MEMBER_LIMIT_PER_TEAM, + ), + lookup, + ) : this.collectPollingPuuids(collectCaptainUserIds(match), lookup); const matchedGameNumbers = new Set();