release/86 #2

Merged
dahyeon merged 108 commits from release/86 into main 2026-07-15 08:56:05 +00:00
8 changed files with 207 additions and 21 deletions
Showing only changes of commit 2984bd1604 - Show all commits

No files matched your search

@@ -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,
@@ -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<void> };
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();
});
});
@@ -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(
@@ -430,6 +430,13 @@ export class TournamentCodeService {
public async attachPendingMatches(
communityId?: mongoose.Types.ObjectId,
): Promise<number> {
const matches = await this.attachPendingMatchDocuments(communityId);
return matches.length;
}
public async attachPendingMatchDocuments(
communityId?: mongoose.Types.ObjectId,
): Promise<MatchDocument[]> {
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;
}
@@ -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<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
@@ -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(),
]);
});
});
@@ -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<string, mongoose.Types.ObjectId>;
}
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<string, mongoose.Types.ObjectId>();
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<string, mongoose.Types.ObjectId>();
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<number, number> = {
[RIOT_BLUE_TEAM_ID]: blueTeamIndex,
[RIOT_RED_TEAM_ID]: redTeamIndex,
@@ -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();
@@ -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<number>();