.
This commit is contained in:
1 parent
c5d296d403
commit
2250b6072e
22 files changed
+1719
-42
No files matched your search
@@ -1,12 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
|
||||
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
import { AuctionController } from './auction.controller';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, TournamentCodeModule],
|
||||
imports: [RiotModule, TournamentCodeModule, TournamentResultModule],
|
||||
controllers: [AuctionController],
|
||||
providers: [AuctionService, AuctionGateway],
|
||||
exports: [AuctionService],
|
||||
|
||||
@@ -10,13 +10,24 @@ describe('AuctionService', () => {
|
||||
const enrichmentService = {
|
||||
enrichRiotAccount: jest.fn(),
|
||||
};
|
||||
const tournamentCodeService = {
|
||||
reserveForMatch: jest.fn().mockResolvedValue(undefined),
|
||||
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const tournamentResultService = {
|
||||
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
|
||||
return {
|
||||
service: new AuctionService(
|
||||
connectionService as never,
|
||||
enrichmentService as never,
|
||||
tournamentCodeService as never,
|
||||
tournamentResultService as never,
|
||||
),
|
||||
connectionService,
|
||||
tournamentCodeService,
|
||||
tournamentResultService,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
|
||||
const AUCTION_MAX_TEAM_SIZE = 5;
|
||||
|
||||
@@ -45,6 +46,7 @@ export class AuctionService {
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
) {}
|
||||
|
||||
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
|
||||
@@ -178,6 +180,7 @@ export class AuctionService {
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
|
||||
return auction;
|
||||
}
|
||||
@@ -321,6 +324,8 @@ export class AuctionService {
|
||||
match.teams = [];
|
||||
match.tournamentCodeIds = [];
|
||||
match.teamBuiltAt = undefined;
|
||||
match.result = undefined;
|
||||
match.resultPollState = undefined;
|
||||
await match.save({ session });
|
||||
}
|
||||
await session.commitTransaction();
|
||||
@@ -403,6 +408,7 @@ export class AuctionService {
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
}
|
||||
|
||||
private resolveTeamName(side: TeamSide): string {
|
||||
|
||||
@@ -57,6 +57,15 @@ export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [
|
||||
'ALL',
|
||||
];
|
||||
|
||||
export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed';
|
||||
export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed';
|
||||
export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [
|
||||
'polling',
|
||||
'complete',
|
||||
'expired',
|
||||
'failed',
|
||||
];
|
||||
|
||||
export interface PositionPreference {
|
||||
position: Position;
|
||||
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
|
||||
@@ -315,12 +324,41 @@ export interface MatchTeam {
|
||||
members: MatchTeamMember[];
|
||||
}
|
||||
|
||||
export interface MatchResult {
|
||||
export interface MatchGameResultParticipant {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
win: boolean;
|
||||
}
|
||||
|
||||
export interface MatchGameResult {
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
winnerSide: TeamSide;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
participants: MatchGameResultParticipant[];
|
||||
}
|
||||
|
||||
export interface MatchResult {
|
||||
winnerSide?: TeamSide;
|
||||
blueScore: number;
|
||||
redScore: number;
|
||||
mvpUserId?: mongoose.Types.ObjectId;
|
||||
riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들
|
||||
games: MatchGameResult[];
|
||||
}
|
||||
|
||||
export interface MatchResultPollState {
|
||||
startedAt: Date;
|
||||
lastPolledAt?: Date;
|
||||
lastPollOutcome?: MatchResultPollOutcome;
|
||||
matchedCount: number;
|
||||
expandedToAllPuuids: boolean;
|
||||
state: MatchResultPollStateValue;
|
||||
}
|
||||
|
||||
export interface MatchScheduleItem {
|
||||
@@ -343,6 +381,7 @@ export interface Match extends MongooseTimestamps {
|
||||
participants: MatchParticipant[];
|
||||
teams: MatchTeam[];
|
||||
result?: MatchResult;
|
||||
resultPollState?: MatchResultPollState;
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
schedule: MatchScheduleItem[];
|
||||
@@ -714,6 +753,7 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
|
||||
|
||||
RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 });
|
||||
RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 });
|
||||
RiotMatchSchema.index({ 'raw.info.tournamentCode': 1 }, { sparse: true });
|
||||
|
||||
export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
{
|
||||
@@ -805,13 +845,65 @@ const MatchTeamSubSchema = new Schema<MatchTeam>(
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchGameResultParticipantSubSchema =
|
||||
new Schema<MatchGameResultParticipant>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
side: { type: String, enum: TEAM_SIDES, required: true },
|
||||
championId: { type: Number, required: true },
|
||||
kills: { type: Number, required: true, default: 0 },
|
||||
deaths: { type: Number, required: true, default: 0 },
|
||||
assists: { type: Number, required: true, default: 0 },
|
||||
win: { type: Boolean, required: true, default: false },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchGameResultSubSchema = new Schema<MatchGameResult>(
|
||||
{
|
||||
gameNumber: { type: Number, required: true },
|
||||
riotMatchId: { type: String, required: true },
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: true },
|
||||
gameCreation: { type: Number, required: true },
|
||||
gameDuration: { type: Number, required: true },
|
||||
participants: {
|
||||
type: [MatchGameResultParticipantSubSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultSubSchema = new Schema<MatchResult>(
|
||||
{
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: true },
|
||||
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
|
||||
blueScore: { type: Number, required: true, default: 0 },
|
||||
redScore: { type: Number, required: true, default: 0 },
|
||||
mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
riotMatchIds: { type: [String], required: true, default: [] },
|
||||
games: { type: [MatchGameResultSubSchema], required: true, default: [] },
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
|
||||
const MatchResultPollStateSubSchema = new Schema<MatchResultPollState>(
|
||||
{
|
||||
startedAt: { type: Date, required: true },
|
||||
lastPolledAt: { type: Date },
|
||||
lastPollOutcome: {
|
||||
type: String,
|
||||
enum: ['matched', 'not-found', 'failed'],
|
||||
required: false,
|
||||
},
|
||||
matchedCount: { type: Number, required: true, default: 0 },
|
||||
expandedToAllPuuids: { type: Boolean, required: true, default: false },
|
||||
state: {
|
||||
type: String,
|
||||
enum: MATCH_RESULT_POLL_STATES,
|
||||
required: true,
|
||||
default: 'polling',
|
||||
},
|
||||
},
|
||||
{ _id: false },
|
||||
);
|
||||
@@ -864,6 +956,10 @@ export const MatchSchema = new Schema<Match>(
|
||||
},
|
||||
teams: { type: [MatchTeamSubSchema], required: true, default: [] },
|
||||
result: { type: MatchResultSubSchema, required: false },
|
||||
resultPollState: {
|
||||
type: MatchResultPollStateSubSchema,
|
||||
required: false,
|
||||
},
|
||||
prizes: { type: [String], required: true, default: [] },
|
||||
notices: { type: [String], required: true, default: [] },
|
||||
schedule: {
|
||||
|
||||
@@ -92,6 +92,11 @@ export class MatchService {
|
||||
|
||||
public async serialize(match: MatchDocument) {
|
||||
const obj = match.toObject();
|
||||
if (obj.result?.games) {
|
||||
obj.result.games = [...obj.result.games].sort(
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
);
|
||||
}
|
||||
return {
|
||||
...obj,
|
||||
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
@@ -116,6 +121,8 @@ export class MatchService {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.tournamentCodeIds = [];
|
||||
match.teamBuiltAt = undefined;
|
||||
match.result = undefined;
|
||||
match.resultPollState = undefined;
|
||||
}
|
||||
await match.save();
|
||||
return match;
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
||||
import { RiotJobQueueController } from './riot-job-queue.controller';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotJobWorkerService } from './riot-job-worker.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule],
|
||||
imports: [RiotModule, forwardRef(() => TournamentResultModule)],
|
||||
controllers: [RiotJobQueueController],
|
||||
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
|
||||
exports: [RiotJobQueueService],
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
RIOT_JOB_HIGH_STREAM,
|
||||
RIOT_JOB_LOW_COOLDOWN_SECONDS,
|
||||
RIOT_JOB_LOW_STREAM,
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
RIOT_JOB_STATUS_TTL_SECONDS,
|
||||
RiotJobPriority,
|
||||
RiotJobState,
|
||||
@@ -35,6 +36,10 @@ import {
|
||||
RiotRefreshEvent,
|
||||
RiotRefreshSubJob,
|
||||
} from './riot-job-queue.types';
|
||||
import type {
|
||||
EnqueueTournamentResultPollResult,
|
||||
PollTournamentResultJob,
|
||||
} from '../tournament-result/tournament-result.types';
|
||||
|
||||
interface RefreshContext {
|
||||
community: CommunityDocument;
|
||||
@@ -171,6 +176,68 @@ export class RiotJobQueueService {
|
||||
};
|
||||
}
|
||||
|
||||
public async enqueueTournamentResultPoll(params: {
|
||||
matchId: string;
|
||||
attempt: number;
|
||||
expandedToAllPuuids: boolean;
|
||||
priority: RiotJobPriority;
|
||||
deferUntilMs?: number;
|
||||
}): Promise<EnqueueTournamentResultPollResult> {
|
||||
const job: PollTournamentResultJob = {
|
||||
kind: 'poll-tournament-result',
|
||||
jobId: randomUUID(),
|
||||
matchId: params.matchId,
|
||||
attempt: params.attempt,
|
||||
expandedToAllPuuids: params.expandedToAllPuuids,
|
||||
enqueuedAt: Date.now(),
|
||||
priority: params.priority,
|
||||
};
|
||||
|
||||
if (params.deferUntilMs && params.deferUntilMs > Date.now()) {
|
||||
await this.scheduleJob(job, params.deferUntilMs);
|
||||
} else {
|
||||
await this.appendJob(job);
|
||||
}
|
||||
|
||||
return {
|
||||
jobId: job.jobId,
|
||||
matchId: job.matchId,
|
||||
priority: job.priority,
|
||||
attempt: job.attempt,
|
||||
expandedToAllPuuids: job.expandedToAllPuuids,
|
||||
};
|
||||
}
|
||||
|
||||
public async promoteDueScheduledJobs(limit = 100): Promise<number> {
|
||||
const client = this.garnetService.raw();
|
||||
const raw = (await client.sendCommand([
|
||||
'ZRANGEBYSCORE',
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
'-inf',
|
||||
String(Date.now()),
|
||||
'LIMIT',
|
||||
'0',
|
||||
String(limit),
|
||||
])) as string[] | null;
|
||||
const entries = raw ?? [];
|
||||
let promoted = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const removed = (await client.sendCommand([
|
||||
'ZREM',
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
entry,
|
||||
])) as number;
|
||||
if (removed !== 1) continue;
|
||||
const job = this.parseScheduledJob(entry);
|
||||
if (!job) continue;
|
||||
await this.appendJob(job);
|
||||
promoted += 1;
|
||||
}
|
||||
|
||||
return promoted;
|
||||
}
|
||||
|
||||
public async getStatus(jobId: string): Promise<RiotJobStatus | null> {
|
||||
return this.garnetService.getJson<RiotJobStatus>(this.statusKey(jobId));
|
||||
}
|
||||
@@ -332,6 +399,35 @@ export class RiotJobQueueService {
|
||||
return priority === 'high' ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM;
|
||||
}
|
||||
|
||||
private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) {
|
||||
await this.garnetService.appendStream(
|
||||
this.resolveStream(job.priority),
|
||||
{ job: JSON.stringify(job) },
|
||||
{ maxLen: 10_000 },
|
||||
);
|
||||
}
|
||||
|
||||
private async scheduleJob(
|
||||
job: PollTournamentResultJob,
|
||||
deferUntilMs: number,
|
||||
): Promise<void> {
|
||||
await this.garnetService.raw().sendCommand([
|
||||
'ZADD',
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
String(deferUntilMs),
|
||||
JSON.stringify(job),
|
||||
]);
|
||||
}
|
||||
|
||||
private parseScheduledJob(value: string): PollTournamentResultJob | null {
|
||||
try {
|
||||
const parsed = JSON.parse(value) as PollTournamentResultJob;
|
||||
return parsed.kind === 'poll-tournament-result' ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveParentState(subJobs: RiotJobStatus[]): RiotJobState {
|
||||
if (subJobs.some((job) => job.state === 'processing')) return 'processing';
|
||||
if (subJobs.some((job) => job.state === 'queued')) return 'queued';
|
||||
|
||||
@@ -3,9 +3,11 @@ import type {
|
||||
RiotRegionalRoute,
|
||||
} from '../riot/riot.types';
|
||||
import type { RiotQueueGroup } from '../riot/riot-queue.constants';
|
||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||
|
||||
export const RIOT_JOB_HIGH_STREAM = 'riot:queue:high';
|
||||
export const RIOT_JOB_LOW_STREAM = 'riot:queue:low';
|
||||
export const RIOT_JOB_SCHEDULED_ZSET = 'riot:queue:scheduled';
|
||||
export const RIOT_JOB_GROUP = 'riot-refresh-worker';
|
||||
export const RIOT_JOB_STATUS_TTL_SECONDS = 24 * 60 * 60;
|
||||
export const RIOT_JOB_DEDUP_TTL_SECONDS = 5 * 60;
|
||||
@@ -17,6 +19,7 @@ export type RiotJobPriority = 'high' | 'low';
|
||||
export type RiotJobState = 'queued' | 'processing' | 'completed' | 'failed';
|
||||
|
||||
export interface RiotRefreshSubJob {
|
||||
kind?: 'refresh-account';
|
||||
jobId: string;
|
||||
parentJobId: string;
|
||||
userId: string;
|
||||
@@ -30,6 +33,8 @@ export interface RiotRefreshSubJob {
|
||||
priority: RiotJobPriority;
|
||||
}
|
||||
|
||||
export type RiotJobPayload = RiotRefreshSubJob | PollTournamentResultJob;
|
||||
|
||||
export interface RiotJobStatus {
|
||||
jobId: string;
|
||||
parentJobId: string;
|
||||
|
||||
@@ -12,10 +12,13 @@ import {
|
||||
RIOT_JOB_GROUP,
|
||||
RIOT_JOB_HIGH_STREAM,
|
||||
RIOT_JOB_LOW_STREAM,
|
||||
RiotJobPayload,
|
||||
RiotRefreshSubJob,
|
||||
} from './riot-job-queue.types';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||
|
||||
const LEADER_KEY = 'riot:worker:leader';
|
||||
const LEADER_TTL_SECONDS = 60;
|
||||
@@ -32,6 +35,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly recentMatchesService: RiotRecentMatchesService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly refreshGateway: RiotRefreshGateway,
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
) {}
|
||||
|
||||
public async onModuleInit() {
|
||||
@@ -52,6 +56,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.jobQueueService.promoteDueScheduledJobs();
|
||||
const entry =
|
||||
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
|
||||
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
|
||||
@@ -77,6 +82,11 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.isTournamentResultJob(job)) {
|
||||
await this.tournamentResultService.processPollJob(job);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.jobQueueService.markProcessing(job);
|
||||
for (const queueId of job.queueIds) {
|
||||
await this.recentMatchesService.ensureFreshForQueue({
|
||||
@@ -89,6 +99,15 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
const event = await this.jobQueueService.markCompleted(job);
|
||||
this.refreshGateway.broadcastRefreshEvent(event);
|
||||
} catch (error) {
|
||||
if (this.isTournamentResultJob(job)) {
|
||||
this.logger.warn(
|
||||
`Tournament result poll job failed ${job.jobId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const event = await this.jobQueueService.markFailed(job, error);
|
||||
this.refreshGateway.broadcastRefreshEvent(event);
|
||||
this.logger.warn(
|
||||
@@ -119,16 +138,22 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
).exec();
|
||||
}
|
||||
|
||||
private parseJob(entry: StreamEntry): RiotRefreshSubJob | null {
|
||||
private parseJob(entry: StreamEntry): RiotJobPayload | null {
|
||||
const raw = entry.message.job;
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw) as RiotRefreshSubJob;
|
||||
return JSON.parse(raw) as RiotJobPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private isTournamentResultJob(
|
||||
job: RiotJobPayload,
|
||||
): job is PollTournamentResultJob {
|
||||
return job.kind === 'poll-tournament-result';
|
||||
}
|
||||
|
||||
private async readOne(
|
||||
stream: string,
|
||||
blockMs: number,
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
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';
|
||||
|
||||
function makeMatch(): {
|
||||
match: MatchDocument;
|
||||
lookup: MatchPuuidLookup;
|
||||
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 puuidByUserId = new Map<string, string>();
|
||||
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
|
||||
|
||||
for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) {
|
||||
const puuid = `puuid-${index}`;
|
||||
puuidByUserId.set(userId.toString(), puuid);
|
||||
userIdByPuuid.set(puuid, userId);
|
||||
}
|
||||
|
||||
const match = {
|
||||
teams: [
|
||||
{
|
||||
side: 'blue',
|
||||
name: '블루팀',
|
||||
members: blueUserIds.map((userId) => ({
|
||||
userId,
|
||||
assignedPosition: 'MID',
|
||||
})),
|
||||
},
|
||||
{
|
||||
side: 'red',
|
||||
name: '레드팀',
|
||||
members: redUserIds.map((userId) => ({
|
||||
userId,
|
||||
assignedPosition: 'MID',
|
||||
})),
|
||||
},
|
||||
],
|
||||
participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({
|
||||
userId,
|
||||
puuid: `puuid-${index}`,
|
||||
preferredPositions: [],
|
||||
joinedAt: new Date(),
|
||||
})),
|
||||
} as unknown as MatchDocument;
|
||||
|
||||
return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds };
|
||||
}
|
||||
|
||||
function makeRiotMatch(params: {
|
||||
team100Puuids: string[];
|
||||
team200Puuids: string[];
|
||||
winningTeamId: 100 | 200;
|
||||
}): RiotMatchDto {
|
||||
const participants = [
|
||||
...params.team100Puuids.map((puuid, index) => ({
|
||||
puuid,
|
||||
participantId: index + 1,
|
||||
teamId: 100,
|
||||
championId: 10 + index,
|
||||
kills: index,
|
||||
deaths: 1,
|
||||
assists: 2,
|
||||
win: params.winningTeamId === 100,
|
||||
})),
|
||||
...params.team200Puuids.map((puuid, index) => ({
|
||||
puuid,
|
||||
participantId: index + 6,
|
||||
teamId: 200,
|
||||
championId: 20 + index,
|
||||
kills: index,
|
||||
deaths: 2,
|
||||
assists: 3,
|
||||
win: params.winningTeamId === 200,
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
metadata: {
|
||||
dataVersion: '2',
|
||||
matchId: 'KR_1',
|
||||
participants: participants.map((participant) => participant.puuid),
|
||||
},
|
||||
info: {
|
||||
gameCreation: 1,
|
||||
gameDuration: 1800,
|
||||
participants,
|
||||
teams: [
|
||||
{ teamId: 100, win: params.winningTeamId === 100 },
|
||||
{ teamId: 200, win: params.winningTeamId === 200 },
|
||||
],
|
||||
},
|
||||
} as unknown as RiotMatchDto;
|
||||
}
|
||||
|
||||
describe('computeGameResult', () => {
|
||||
it('maps Riot teams to local blue/red by overlap', () => {
|
||||
const { match, lookup } = makeMatch();
|
||||
const detail = makeRiotMatch({
|
||||
team100Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'],
|
||||
team200Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'],
|
||||
winningTeamId: 100,
|
||||
});
|
||||
|
||||
const result = computeGameResult({ match, lookup, detail, gameNumber: 1 });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
gameNumber: 1,
|
||||
riotMatchId: 'KR_1',
|
||||
winnerSide: 'blue',
|
||||
gameDuration: 1800,
|
||||
});
|
||||
expect(result?.participants).toHaveLength(10);
|
||||
});
|
||||
|
||||
it('handles reversed Riot side assignment', () => {
|
||||
const { match, lookup } = makeMatch();
|
||||
const detail = makeRiotMatch({
|
||||
team100Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'],
|
||||
team200Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'],
|
||||
winningTeamId: 100,
|
||||
});
|
||||
|
||||
const result = computeGameResult({ match, lookup, detail, gameNumber: 2 });
|
||||
|
||||
expect(result?.winnerSide).toBe('red');
|
||||
});
|
||||
|
||||
it('rejects matches with too little overlap', () => {
|
||||
const { match, lookup } = makeMatch();
|
||||
const detail = makeRiotMatch({
|
||||
team100Puuids: ['other-1', 'other-2', 'other-3', 'other-4', 'other-5'],
|
||||
team200Puuids: ['other-6', 'other-7', 'other-8', 'other-9', 'other-10'],
|
||||
winningTeamId: 100,
|
||||
});
|
||||
|
||||
const result = computeGameResult({ match, lookup, detail, gameNumber: 3 });
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResult,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
|
||||
const RIOT_BLUE_TEAM_ID = 100;
|
||||
const RIOT_RED_TEAM_ID = 200;
|
||||
const MINIMUM_TRUSTED_OVERLAP = 6;
|
||||
|
||||
export interface MatchPuuidLookup {
|
||||
puuidByUserId: Map<string, string>;
|
||||
userIdByPuuid: Map<string, 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[] {
|
||||
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);
|
||||
for (const member of team.members) {
|
||||
ids.set(member.userId.toString(), member.userId);
|
||||
}
|
||||
}
|
||||
return [...ids.values()];
|
||||
}
|
||||
|
||||
export function collectTeamPuuids(
|
||||
match: MatchDocument,
|
||||
side: TeamSide,
|
||||
lookup: MatchPuuidLookup,
|
||||
): string[] {
|
||||
const team = match.teams.find((item) => item.side === side);
|
||||
if (!team) return [];
|
||||
return team.members
|
||||
.map((member) => lookup.puuidByUserId.get(member.userId.toString()))
|
||||
.filter((puuid): puuid is string => Boolean(puuid));
|
||||
}
|
||||
|
||||
export function computeGameResult(params: {
|
||||
match: MatchDocument;
|
||||
detail: RiotMatchDto;
|
||||
gameNumber: number;
|
||||
lookup: MatchPuuidLookup;
|
||||
}): MatchGameResult | null {
|
||||
const { match, detail, gameNumber, lookup } = params;
|
||||
const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup);
|
||||
const ourRedPuuids = collectTeamPuuids(match, 'red', lookup);
|
||||
const team100Puuids = detail.info.participants
|
||||
.filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID)
|
||||
.map((participant) => participant.puuid);
|
||||
const team200Puuids = detail.info.participants
|
||||
.filter((participant) => participant.teamId === RIOT_RED_TEAM_ID)
|
||||
.map((participant) => participant.puuid);
|
||||
|
||||
const normalOverlap =
|
||||
countOverlap(team100Puuids, ourBluePuuids) +
|
||||
countOverlap(team200Puuids, ourRedPuuids);
|
||||
const reversedOverlap =
|
||||
countOverlap(team100Puuids, ourRedPuuids) +
|
||||
countOverlap(team200Puuids, ourBluePuuids);
|
||||
const teamMapping: Record<number, TeamSide> =
|
||||
normalOverlap >= reversedOverlap
|
||||
? { [RIOT_BLUE_TEAM_ID]: 'blue', [RIOT_RED_TEAM_ID]: 'red' }
|
||||
: { [RIOT_BLUE_TEAM_ID]: 'red', [RIOT_RED_TEAM_ID]: 'blue' };
|
||||
|
||||
if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const winningTeam = detail.info.teams.find((team) => team.win);
|
||||
if (!winningTeam) return null;
|
||||
const winnerSide = teamMapping[winningTeam.teamId];
|
||||
if (!winnerSide) return null;
|
||||
|
||||
const participants = detail.info.participants
|
||||
.map((participant) => {
|
||||
const userId = lookup.userIdByPuuid.get(participant.puuid);
|
||||
const side = teamMapping[participant.teamId];
|
||||
if (!userId || !side) return null;
|
||||
return {
|
||||
userId,
|
||||
side,
|
||||
championId: participant.championId,
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
win: participant.win,
|
||||
};
|
||||
})
|
||||
.filter((participant): participant is NonNullable<typeof participant> =>
|
||||
Boolean(participant),
|
||||
);
|
||||
|
||||
return {
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
winnerSide,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
participants,
|
||||
};
|
||||
}
|
||||
|
||||
export function countOverlap(left: string[], right: string[]): number {
|
||||
const rightSet = new Set(right);
|
||||
return left.filter((item) => rightSet.has(item)).length;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
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 { 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
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, forwardRef(() => RiotJobQueueModule)],
|
||||
controllers: [TournamentResultController],
|
||||
providers: [TournamentResultService],
|
||||
exports: [TournamentResultService],
|
||||
})
|
||||
export class TournamentResultModule {}
|
||||
@@ -0,0 +1,453 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
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 {
|
||||
collectCaptainUserIds,
|
||||
collectMatchUserIds,
|
||||
computeGameResult,
|
||||
type MatchPuuidLookup,
|
||||
} from './team-mapping.util';
|
||||
import type {
|
||||
EnqueueTournamentResultPollResult,
|
||||
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;
|
||||
|
||||
@Injectable()
|
||||
export class TournamentResultService {
|
||||
private readonly logger = new Logger(TournamentResultService.name);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly riotMatchService: RiotMatchService,
|
||||
private readonly riotJobQueueService: RiotJobQueueService,
|
||||
) {}
|
||||
|
||||
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 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,
|
||||
});
|
||||
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();
|
||||
return true;
|
||||
}
|
||||
|
||||
private async advanceMatchIfReady(
|
||||
match: MatchDocument,
|
||||
codes: TournamentCodeDocument[],
|
||||
): Promise<boolean> {
|
||||
if (codes.length < match.gameCount) return false;
|
||||
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
match.status = 'finished';
|
||||
if (match.result) {
|
||||
match.result.winnerSide =
|
||||
match.result.blueScore > match.result.redScore
|
||||
? 'blue'
|
||||
: match.result.redScore > match.result.blueScore
|
||||
? 'red'
|
||||
: undefined;
|
||||
}
|
||||
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();
|
||||
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 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);
|
||||
|
||||
match.result = {
|
||||
winnerSide: match.result?.winnerSide,
|
||||
blueScore: games.filter((game) => game.winnerSide === 'blue').length,
|
||||
redScore: games.filter((game) => game.winnerSide === 'red').length,
|
||||
mvpUserId: match.result?.mvpUserId,
|
||||
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
|
||||
games,
|
||||
};
|
||||
}
|
||||
|
||||
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 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,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { TeamSide } from '../global/database/schema';
|
||||
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
|
||||
|
||||
export interface PollTournamentResultJob {
|
||||
kind: 'poll-tournament-result';
|
||||
jobId: string;
|
||||
matchId: string;
|
||||
attempt: number;
|
||||
expandedToAllPuuids: boolean;
|
||||
enqueuedAt: number;
|
||||
priority: RiotJobPriority;
|
||||
}
|
||||
|
||||
export interface EnqueueTournamentResultPollResult {
|
||||
jobId: string;
|
||||
matchId: string;
|
||||
priority: RiotJobPriority;
|
||||
attempt: number;
|
||||
expandedToAllPuuids: boolean;
|
||||
}
|
||||
|
||||
export interface ComputedGameParticipant {
|
||||
userId: string;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
win: boolean;
|
||||
}
|
||||
Reference in new issue
Block a user