Files
lolympus-tournament-support/apps/api/src/modules/legacy-import/legacy-import.service.ts
T
dahyeon 0d7617e2d2 feat: connect tournament views to APIs and recover archived stats
Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
2026-11-11 02:00:35 +09:00

1499 lines
48 KiB
TypeScript

import {
BadRequestException,
ConflictException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { createHash, randomUUID } from 'node:crypto';
import mongoose from 'mongoose';
import {
CompetitionBootstrapService,
type CompetitionBootstrapMatch,
} from '../competition/competition-bootstrap.service';
import {
CompetitionCommandService,
type CompetitionCommandActor,
} from '../competition/competition-command.service';
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 DistributedLockOwnership,
DistributedLockService,
} from '../global/redis/distributed-lock.service';
import type {
LegacyImportJobDocument,
Match,
MatchDocument,
RiotMatch as StoredRiotMatch,
UserDocument,
} from '../global/database/schema';
import { RedisService } from '../global/redis/redis.service';
import { RIOT_JOB_LOW_STREAM } from '../riot-job-queue/riot-job-queue.types';
import { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
resolveReadyCompetitionSlot,
type CompetitionResultSnapshot,
} from '../tournament-result/competition-result.adapter';
import type { MatchPuuidLookup } from '../tournament-result/team-mapping.util';
import {
buildParticipantsSnapshot,
buildTeams,
buildUserByPuuidMap,
countKnownParticipants,
resolveExternalCount,
type UserByPuuidMap,
} from './match-builder.util';
import {
LEGACY_IMPORT_DEFAULT_START_ISO,
LEGACY_IMPORT_LOCK_TTL_SECONDS,
LEGACY_IMPORT_MEMBER_AVG_SECONDS,
type BulkDeleteLegacyMatchesRequest,
type LegacyImportMemberJob,
type LegacyImportMemberWindowView,
type LegacyMatchListResponse,
type RebuildLegacyMatchesResponse,
type StartLegacyImportRequest,
type StartLegacyImportResponse,
} from './legacy-import.types';
const MATCH_IMPORT_LOCK_TTL_SECONDS = 60;
const MATCH_ID_PAGE_SIZE = 100;
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
type ResultlessMatchPatch = Omit<
Partial<Match>,
'result' | 'doubleElimination'
>;
@Injectable()
export class LegacyImportService {
private readonly logger = new Logger(LegacyImportService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly redisService: RedisService,
private readonly riotMatchService: RiotMatchService,
private readonly communityStatsService: CommunityStatsService,
private readonly matchStatsService: MatchStatsService,
private readonly distributedLockService: DistributedLockService,
private readonly competitionBootstrapService: CompetitionBootstrapService,
private readonly competitionCommandService: CompetitionCommandService,
) {}
public async previewMembers(params: {
communityId: mongoose.Types.ObjectId;
windowStart?: string;
windowEnd?: string;
}): Promise<{ members: LegacyImportMemberWindowView[] }> {
const { windowStart, windowEnd } = this.resolveWindow(params);
const users = await this.findImportableUsers(params.communityId);
return {
members: users.map((user) =>
this.toMemberWindowView(user, windowStart, windowEnd),
),
};
}
public async start(params: {
communityId: mongoose.Types.ObjectId;
triggeredBy: mongoose.Types.ObjectId;
body: StartLegacyImportRequest;
}): Promise<StartLegacyImportResponse> {
const lockKey = this.communityLockKey(params.communityId);
const jobId = randomUUID();
const communityImportLockOwnership =
await this.distributedLockService.acquireLock({
lockKey,
lockOwnershipToken: jobId,
lockExpirationDurationMilliseconds:
LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
});
if (!communityImportLockOwnership) {
throw new ConflictException('Legacy import is already running.');
}
try {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(params.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
if (!community) throw new NotFoundException('Community not found.');
const { windowStart, windowEnd } = this.resolveWindow({
windowStart: params.body.windowStart,
windowEnd: params.body.windowEnd,
});
const users = await this.findImportableUsers(params.communityId);
const overrides = new Map(
(params.body.memberOverrides ?? []).map((override) => [
override.userId,
override,
]),
);
const windows = users
.map((user) =>
this.resolveMemberWindow(user, windowStart, windowEnd, overrides),
)
.filter(
(window) => window.startTime.getTime() <= window.endTime.getTime(),
);
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.create({
jobId,
communityId: params.communityId,
triggeredBy: params.triggeredBy,
startedAt: new Date(),
state: 'running',
windowStart,
windowEnd,
memberOverrides: windows,
totalMembers: windows.length,
processedMembers: 0,
totalDiscoveredMatchIds: 0,
totalImportedMatches: 0,
totalSkippedDuplicate: 0,
totalErrors: 0,
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
completedMemberJobIds: [],
});
for (const window of windows) {
const job: LegacyImportMemberJob = {
kind: 'legacy-import-member',
jobId: randomUUID(),
parentJobId: jobId,
communityId: params.communityId.toString(),
userId: window.userId.toString(),
puuid: window.puuid,
startTime: Math.floor(window.startTime.getTime() / 1000),
endTime: Math.floor(window.endTime.getTime() / 1000),
triggeredBy: params.triggeredBy.toString(),
region: community.riotRegion ?? 'asia',
};
await this.redisService.appendStream(
RIOT_JOB_LOW_STREAM,
{ job: JSON.stringify(job) },
{ maxLen: 10_000 },
);
}
if (windows.length === 0) {
await LegacyImportJobModel.updateOne(
{ jobId },
{ $set: { state: 'completed', completedAt: new Date() } },
).exec();
await this.releaseDistributedLockSafely(communityImportLockOwnership);
}
return {
jobId,
totalMembers: windows.length,
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
};
} catch (error) {
await this.releaseDistributedLockSafely(communityImportLockOwnership);
throw error;
}
}
public async listJobs(params: {
communityId: mongoose.Types.ObjectId;
limit?: number;
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const jobs = await LegacyImportJobModel.find({
communityId: params.communityId,
})
.sort({ startedAt: -1 })
.limit(Math.min(params.limit ?? 10, 50))
.exec();
return { jobs };
}
public async getJob(params: {
communityId: mongoose.Types.ObjectId;
jobId: string;
}): Promise<LegacyImportJobDocument> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOne({
communityId: params.communityId,
jobId: params.jobId,
}).exec();
if (!job) throw new NotFoundException('Legacy import job not found.');
return job;
}
public async cancel(params: {
communityId: mongoose.Types.ObjectId;
jobId: string;
}): Promise<LegacyImportJobDocument> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOneAndUpdate(
{
communityId: params.communityId,
jobId: params.jobId,
state: { $in: ['pending', 'running'] },
},
{ $set: { state: 'cancelled', completedAt: new Date() } },
{ returnDocument: 'after' },
).exec();
if (!job)
throw new NotFoundException('Running legacy import job not found.');
await this.distributedLockService.releaseLockIfOwned({
lockKey: this.communityLockKey(params.communityId),
lockOwnershipToken: job.jobId,
lockExpirationDurationMilliseconds: LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
});
return job;
}
public async processMemberJob(job: LegacyImportMemberJob): Promise<void> {
const started = Date.now();
const legacyJob = await this.getRunnableJob(job);
if (!legacyJob) return;
if (legacyJob.completedMemberJobIds?.includes(job.jobId)) return;
let discovered = 0;
let imported = 0;
let duplicates = 0;
let errors = 0;
try {
const userByPuuid = await this.buildUserByPuuidMap(
new mongoose.Types.ObjectId(job.communityId),
);
const matchIds = await this.collectMatchIds(job);
discovered = matchIds.size;
for (const matchId of matchIds) {
if (await this.isCancelled(job.parentJobId)) break;
const outcome = await this.importSingleMatch(matchId, job, userByPuuid);
if (outcome === 'imported') imported += 1;
if (outcome === 'duplicate') duplicates += 1;
if (outcome === 'error') errors += 1;
}
} catch (error) {
errors += 1;
await this.recordError(job.parentJobId, {
puuid: job.puuid,
reason: error instanceof Error ? error.message : String(error),
});
this.logger.warn(
`Legacy import member job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
} finally {
await this.finishMemberJob(job, {
discovered,
imported,
duplicates,
errors,
elapsedSeconds: Math.max(1, Math.round((Date.now() - started) / 1000)),
});
}
}
public async listLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
cursor?: number;
limit?: number;
}): Promise<LegacyMatchListResponse> {
const MatchModel = await this.connectionService.getModel('match');
const limit = Math.max(1, Math.min(params.limit ?? 30, 100));
const filter: Record<string, unknown> = {
communityId: params.communityId,
legacyImported: true,
};
if (params.cursor) {
filter.scheduledAt = { $lt: new Date(params.cursor) };
}
const matches = await MatchModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(limit + 1)
.exec();
const visible = matches.slice(0, limit);
const competitionByMatchId = await this.loadCompetitionByMatchId(
visible.map(({ _id }) => _id),
);
const summaryByMatchId = new Map(
visible.map((match) => [
match._id.toString(),
summarizeCompetitionResult(
competitionByMatchId.get(match._id.toString()),
) ?? summarizeLegacyMatchResult(match),
]),
);
const riotMatchIds = [...summaryByMatchId.values()]
.map(({ riotMatchId }) => riotMatchId)
.filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({
matchId: { $in: riotMatchIds },
})
.lean()
.exec();
const rawById = new Map(
rawDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
);
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
return {
matches: visible.map((match) => {
const summary = summaryByMatchId.get(match._id.toString())!;
const riotMatchId = summary.riotMatchId;
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
riotMatchId,
memberCount: summary.memberCount,
externalCount: raw
? resolveExternalCount(raw, userByPuuid)
: Math.max(0, 10 - summary.memberCount),
teamAIndex: summary.teamAIndex,
teamBIndex: summary.teamBIndex,
teamAWins: summary.teamAWins,
teamBWins: summary.teamBWins,
winnerTeamIndex: summary.winnerTeamIndex,
};
}),
nextCursor:
matches.length > limit
? (visible[visible.length - 1]?.scheduledAt.getTime() ?? null)
: null,
};
}
public async bulkDeleteLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
body: BulkDeleteLegacyMatchesRequest;
}): Promise<{ deleted: number }> {
const ids = (params.body.matchIds ?? [])
.filter((id) => mongoose.isValidObjectId(id))
.map((id) => new mongoose.Types.ObjectId(id));
if (ids.length === 0) return { deleted: 0 };
const [
MatchModel,
CompetitionModel,
CompetitionFactModel,
CompetitionOutboxModel,
AssignmentModel,
TournamentCodeModel,
MatchStatsModel,
connection,
] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'),
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('matchStats'),
this.connectionService.getConnection(),
]);
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException(
'A MongoDB transaction is required to delete legacy Matches.',
);
}
let deleted = 0;
try {
session.startTransaction();
const targets = await MatchModel.find({
_id: { $in: ids },
communityId: params.communityId,
legacyImported: true,
})
.select({ _id: 1 })
.session(session)
.exec();
const targetIds = targets.map((match) => match._id);
if (targetIds.length === 0) {
await session.commitTransaction();
} else {
const competitions = await CompetitionModel.find({
matchId: { $in: targetIds },
})
.select({ _id: 1 })
.session(session)
.lean()
.exec();
const competitionIds = competitions.map(({ _id }) => _id);
if (competitionIds.length > 0) {
const assignments = await AssignmentModel.find({
competitionId: { $in: competitionIds },
state: { $in: ['reserved', 'used'] },
})
.select({ tournamentCodeId: 1, state: 1 })
.session(session)
.lean()
.exec();
const assignmentCodeIds = assignments.map(
({ tournamentCodeId }) => tournamentCodeId,
);
const uniqueAssignmentCodeIds = new Set(
assignmentCodeIds.map((id) => id.toString()),
);
if (uniqueAssignmentCodeIds.size !== assignmentCodeIds.length) {
throw new ConflictException(
'Tournament Code assignments contain a duplicate active code identity.',
);
}
const tournamentCodes =
assignmentCodeIds.length === 0
? []
: await TournamentCodeModel.find({
_id: { $in: assignmentCodeIds },
})
.select({ _id: 1, state: 1, matchId: 1 })
.session(session)
.lean()
.exec();
const tournamentCodeById = new Map(
tournamentCodes.map((code) => [code._id.toString(), code]),
);
const targetIdSet = new Set(targetIds.map((id) => id.toString()));
for (const assignment of assignments) {
const code = tournamentCodeById.get(
assignment.tournamentCodeId.toString(),
);
if (
!code ||
code.state !== assignment.state ||
!code.matchId ||
!targetIdSet.has(code.matchId.toString())
) {
throw new ConflictException(
'Tournament Code assignment ownership or state does not match the target legacy Match.',
);
}
}
const releasedCodeIds = assignments
.filter(({ state }) => state === 'reserved')
.map(({ tournamentCodeId }) => tournamentCodeId);
const voidedCodeIds = assignments
.filter(({ state }) => state === 'used')
.map(({ tournamentCodeId }) => tournamentCodeId);
const terminalAt = new Date();
if (releasedCodeIds.length > 0) {
const released = await TournamentCodeModel.updateMany(
{
_id: { $in: releasedCodeIds },
matchId: { $in: targetIds },
state: 'reserved',
},
{
$set: { state: 'released', releasedAt: terminalAt },
$unset: legacyTournamentCodeBindingUnset(),
},
)
.session(session)
.exec();
assertExactTournamentCodeTransition(
released,
releasedCodeIds.length,
);
}
if (voidedCodeIds.length > 0) {
const voided = await TournamentCodeModel.updateMany(
{
_id: { $in: voidedCodeIds },
matchId: { $in: targetIds },
state: 'used',
},
{
$set: { state: 'voided', voidedAt: terminalAt },
$unset: legacyTournamentCodeBindingUnset(),
},
)
.session(session)
.exec();
assertExactTournamentCodeTransition(voided, voidedCodeIds.length);
}
await CompetitionFactModel.deleteMany({
competitionId: { $in: competitionIds },
})
.session(session)
.exec();
await CompetitionOutboxModel.deleteMany({
competitionId: { $in: competitionIds },
})
.session(session)
.exec();
await AssignmentModel.deleteMany({
competitionId: { $in: competitionIds },
})
.session(session)
.exec();
await CompetitionModel.deleteMany({
_id: { $in: competitionIds },
})
.session(session)
.exec();
}
await connection
.collection('competition_migration_quarantine')
.deleteMany({ _id: { $in: targetIds } }, { session });
const result = await MatchModel.deleteMany({
_id: { $in: targetIds },
communityId: params.communityId,
legacyImported: true,
})
.session(session)
.exec();
await MatchStatsModel.deleteMany({ matchId: { $in: targetIds } })
.session(session)
.exec();
deleted = result.deletedCount ?? 0;
await session.commitTransaction();
}
} catch (error) {
await session.abortTransaction().catch(() => undefined);
throw error;
} finally {
await session.endSession().catch(() => undefined);
}
await this.communityStatsService.invalidateCommunity(params.communityId);
return { deleted };
}
public async rebuildLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
}): Promise<RebuildLegacyMatchesResponse> {
const MatchModel = await this.connectionService.getModel('match');
const matches = await MatchModel.find({
communityId: params.communityId,
legacyImported: true,
}).exec();
const competitionByMatchId = await this.loadCompetitionByMatchId(
matches.map(({ _id }) => _id),
);
const summaryByMatchId = new Map(
matches.map((match) => [
match._id.toString(),
summarizeCompetitionResult(
competitionByMatchId.get(match._id.toString()),
) ?? summarizeLegacyMatchResult(match),
]),
);
const riotMatchIds = [...summaryByMatchId.values()]
.map(({ riotMatchId }) => riotMatchId)
.filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({
matchId: { $in: riotMatchIds },
})
.lean()
.exec();
const rawById = new Map<string, RiotMatchDto>();
for (const doc of rawDocs) {
if (isRiotMatchDto(doc.raw)) rawById.set(doc.matchId, doc.raw);
}
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
const result: RebuildLegacyMatchesResponse = {
scanned: matches.length,
rebuilt: 0,
normalizedTitles: 0,
skippedMissingRaw: 0,
skippedNoKnownParticipants: 0,
};
for (const match of matches) {
const existingCompetition = competitionByMatchId.get(
match._id.toString(),
);
const summary = summaryByMatchId.get(match._id.toString())!;
const riotMatchId = summary.riotMatchId;
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
const title = this.normalizeLegacyTitle(
match.title,
raw?.info.gameCreation ?? match.scheduledAt.getTime(),
);
const update: ResultlessMatchPatch = {};
if (title !== match.title) {
update.title = title;
result.normalizedTitles += 1;
}
if (!raw || !riotMatchId) {
result.skippedMissingRaw += 1;
if (Object.keys(update).length > 0) {
await MatchModel.updateOne(
{ _id: match._id },
{ $set: update },
).exec();
await this.rebuildMatchStats(
match._id,
competitionRevision(existingCompetition),
);
}
continue;
}
const participants = buildParticipantsSnapshot(raw, userByPuuid);
const teams = buildTeams(raw, userByPuuid);
const counts = countKnownParticipants(raw, userByPuuid);
if (
!hasDecisiveRiotWinner(raw) ||
!hasTrustedCompetitionRoster(counts, participants, teams)
) {
result.skippedNoKnownParticipants += 1;
if (Object.keys(update).length > 0) {
await MatchModel.updateOne(
{ _id: match._id },
{ $set: update },
).exec();
await this.rebuildMatchStats(
match._id,
competitionRevision(existingCompetition),
);
}
continue;
}
update.mapId = raw.info.mapId ?? match.mapId;
update.participants = participants;
update.teams = teams;
update.gameMode = 'pair';
update.gameCount = 1;
update.teamBuiltAt = match.teamBuiltAt ?? new Date(raw.info.gameCreation);
await MatchModel.updateOne(
{
_id: match._id,
communityId: params.communityId,
legacyImported: true,
},
{ $set: update },
).exec();
let sourceRevision = competitionRevision(existingCompetition);
if (!summarizeCompetitionResult(existingCompetition)) {
const updatedMatch = {
...toPlainRecord(match),
...update,
_id: match._id,
communityId: match.communityId,
} as unknown as MatchDocument;
sourceRevision =
(await this.acceptRiotCompetitionFact({
match: updatedMatch,
detail: raw,
actor: { type: 'system' },
})) ?? undefined;
}
if (sourceRevision === undefined) {
result.skippedNoKnownParticipants += 1;
continue;
}
await MatchModel.updateOne(
{ _id: match._id },
{ $set: { status: 'finished' } },
).exec();
await this.rebuildMatchStats(match._id, sourceRevision);
result.rebuilt += 1;
}
if (result.rebuilt > 0 || result.normalizedTitles > 0) {
await this.communityStatsService.invalidateCommunity(params.communityId);
}
return result;
}
private async loadCompetitionByMatchId(
matchIds: mongoose.Types.ObjectId[],
): Promise<Map<string, unknown>> {
if (matchIds.length === 0) return new Map();
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions = await CompetitionModel.find({
matchId: { $in: matchIds },
})
.lean()
.exec();
return new Map(
competitions.map((competition) => [
competition.matchId.toString(),
competition,
]),
);
}
private rebuildMatchStats(
matchId: mongoose.Types.ObjectId,
sourceRevision?: number,
): Promise<void> {
return this.matchStatsService
.buildAndUpsert(matchId, {
...(sourceRevision === undefined ? {} : { sourceRevision }),
})
.catch((error: unknown) => {
this.logger.warn(
`Failed to rebuild legacy Match stats ${matchId.toString()}${
sourceRevision === undefined
? ''
: ` at Competition revision ${sourceRevision}`
}: ${error instanceof Error ? error.message : String(error)}`,
);
});
}
private async collectMatchIds(
job: LegacyImportMemberJob,
): Promise<Set<string>> {
const matchIds = new Set<string>();
let start = 0;
while (true) {
const ids = await this.riotMatchService.getMatchIdsByPuuid(job.puuid, {
region: job.region,
type: 'tourney',
startTime: job.startTime,
endTime: job.endTime,
start,
count: MATCH_ID_PAGE_SIZE,
});
ids.forEach((matchId) => matchIds.add(matchId));
if (ids.length < MATCH_ID_PAGE_SIZE) break;
start += MATCH_ID_PAGE_SIZE;
}
return matchIds;
}
private async importSingleMatch(
riotMatchId: string,
job: LegacyImportMemberJob,
userByPuuid: UserByPuuidMap,
): Promise<ImportOutcome> {
const lockKey = `legacy-import:match:${riotMatchId}`;
try {
const importOutcome = await this.distributedLockService.runWithLock(
{
lockKey,
lockExpirationDurationMilliseconds:
MATCH_IMPORT_LOCK_TTL_SECONDS * 1000,
},
async () => {
const CompetitionFactModel =
await this.connectionService.getModel('competitionFact');
const existing = await CompetitionFactModel.exists({
type: 'game-accepted',
'evidence.type': 'riot',
'evidence.riotMatchId': riotMatchId,
});
if (existing) {
return 'duplicate';
}
const detail = await this.ensureRiotMatchPersisted(
riotMatchId,
job.region,
);
if (!detail.info.tournamentCode) return 'skipped';
const counts = countKnownParticipants(detail, userByPuuid);
const participants = buildParticipantsSnapshot(detail, userByPuuid);
const teams = buildTeams(detail, userByPuuid);
if (
!hasDecisiveRiotWinner(detail) ||
!hasTrustedCompetitionRoster(counts, participants, teams)
) {
return 'skipped';
}
const matchPayload: ResultlessMatchPatch = {
communityId: new mongoose.Types.ObjectId(job.communityId),
title: this.formatLegacyDate(detail.info.gameCreation),
description: 'Legacy import (자동 생성)',
mapId: detail.info.mapId ?? 11,
status: 'team-built',
scheduledAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
gameMode: 'pair',
tournamentCodeIds: [],
gameSchedule: [],
teamBuiltAt: new Date(detail.info.gameCreation),
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
participants,
teams,
legacyImported: true,
legacyImportSource: {
importedAt: new Date(),
importedBy: new mongoose.Types.ObjectId(job.triggeredBy),
triggeringPuuid: job.puuid,
jobId: job.parentJobId,
},
prizes: [],
notices: [],
schedule: [],
};
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOneAndUpdate(
{
_id: deterministicObjectId(`legacy-import:match:${riotMatchId}`),
},
{ $setOnInsert: matchPayload },
{
upsert: true,
returnDocument: 'after',
setDefaultsOnInsert: true,
runValidators: true,
},
).exec();
if (!match)
throw new Error('Legacy Match upsert returned no document.');
const sourceRevision = await this.acceptRiotCompetitionFact({
match,
detail,
actor: {
type: 'migration',
migrationRunId: job.parentJobId,
},
});
if (sourceRevision === null) return 'skipped';
await MatchModel.updateOne(
{ _id: match._id },
{ $set: { status: 'finished' } },
).exec();
await this.rebuildMatchStats(match._id, sourceRevision);
return 'imported';
},
);
if (importOutcome === null) return 'duplicate';
return importOutcome;
} catch (error) {
await this.recordError(job.parentJobId, {
puuid: job.puuid,
matchId: riotMatchId,
reason: error instanceof Error ? error.message : String(error),
});
return 'error';
}
}
private async acceptRiotCompetitionFact(params: {
match: MatchDocument;
detail: RiotMatchDto;
actor: CompetitionCommandActor;
}): Promise<number | null> {
const competitionDocument =
await this.competitionBootstrapService.bootstrap(
params.match as unknown as CompetitionBootstrapMatch,
);
const competition = toCompetitionResultSnapshot(competitionDocument);
const mapped = resolveReadyCompetitionSlot({
competition,
detail: params.detail,
lookup: buildMatchPuuidLookup(params.match),
});
if (!mapped) return null;
const accepted = await this.competitionCommandService.acceptGame({
competitionId: competition.competitionId,
expectedRevision: competition.revision,
idempotencyKey: `legacy-import:riot:${params.detail.metadata.matchId}`,
actor: params.actor,
occurredAt: mapped.occurredAt,
gameId: mapped.gameId,
seriesId: mapped.seriesId,
gameSlotId: mapped.gameSlotId,
ordinal: mapped.ordinal,
evidence: mapped.evidence,
mapping: mapped.mapping,
startedAt: mapped.startedAt,
durationSeconds: mapped.durationSeconds,
participants: mapped.normalizedParticipants,
});
return accepted.revision;
}
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 },
{ $set: payload },
{ upsert: true },
).exec();
await this.communityStatsService
.refreshForRiotMatches([dto.metadata.matchId])
.catch((error: unknown) => {
this.logger.warn(
`Stats recovery failed after saving ${dto.metadata.matchId}: ${String(error)}`,
);
});
return dto;
}
private async finishMemberJob(
job: LegacyImportMemberJob,
stats: {
discovered: number;
imported: number;
duplicates: number;
errors: number;
elapsedSeconds: number;
},
): Promise<void> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const current = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
}).exec();
if (!current || current.state === 'cancelled') return;
if (current.completedMemberJobIds?.includes(job.jobId)) return;
const average =
current.averageMemberSeconds === undefined
? stats.elapsedSeconds
: Math.round(
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
);
const updateResult = await LegacyImportJobModel.updateOne(
{
jobId: job.parentJobId,
completedMemberJobIds: { $ne: job.jobId },
state: { $ne: 'cancelled' },
},
{
$set: {
averageMemberSeconds: average,
},
$inc: {
processedMembers: 1,
totalDiscoveredMatchIds: stats.discovered,
totalImportedMatches: stats.imported,
totalSkippedDuplicate: stats.duplicates,
totalErrors: stats.errors,
},
$addToSet: {
completedMemberJobIds: job.jobId,
},
},
).exec();
if (updateResult.modifiedCount === 0) return;
const updated = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
})
.select({
processedMembers: 1,
totalMembers: 1,
state: 1,
completedAt: 1,
})
.lean()
.exec();
const completed = Boolean(
updated &&
updated.state !== 'cancelled' &&
updated.processedMembers >= updated.totalMembers,
);
if (completed) {
await LegacyImportJobModel.updateOne(
{
jobId: job.parentJobId,
state: { $ne: 'cancelled' },
},
{
$set: {
state: 'completed',
completedAt: updated?.completedAt ?? new Date(),
},
},
).exec();
}
if (completed) {
await Promise.all([
this.distributedLockService.releaseLockIfOwned({
lockKey: this.communityLockKey(
new mongoose.Types.ObjectId(job.communityId),
),
lockOwnershipToken: job.parentJobId,
lockExpirationDurationMilliseconds:
LEGACY_IMPORT_LOCK_TTL_SECONDS * 1000,
}),
this.communityStatsService.invalidateCommunity(
new mongoose.Types.ObjectId(job.communityId),
),
]);
}
}
private async getRunnableJob(
job: LegacyImportMemberJob,
): Promise<LegacyImportJobDocument | null> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const legacyJob = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
}).exec();
if (!legacyJob || legacyJob.state === 'cancelled') return null;
if (legacyJob.state === 'completed' || legacyJob.state === 'failed')
return null;
return legacyJob;
}
private async releaseDistributedLockSafely(
lockOwnership: DistributedLockOwnership,
): Promise<void> {
await this.distributedLockService
.releaseLockIfOwned(lockOwnership)
.catch((error: unknown) => {
this.logger.warn(
`Failed to release legacy import lock ${lockOwnership.lockKey}: ${
error instanceof Error ? error.message : String(error)
}`,
);
});
}
private async isCancelled(parentJobId: string): Promise<boolean> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOne({ jobId: parentJobId })
.select({ state: 1 })
.lean()
.exec();
return job?.state === 'cancelled';
}
private async recordError(
jobId: string,
error: { puuid?: string; matchId?: string; reason: string },
): Promise<void> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.updateOne(
{ jobId },
{
$push: {
errors: {
...error,
at: new Date(),
},
},
},
).exec();
}
private async buildUserByPuuidMap(
communityId: mongoose.Types.ObjectId,
): Promise<UserByPuuidMap> {
const users = await this.findImportableUsers(communityId);
return buildUserByPuuidMap(users);
}
private async findImportableUsers(
communityId: mongoose.Types.ObjectId,
): Promise<UserDocument[]> {
const UserModel = await this.connectionService.getModel('user');
return UserModel.find({
communityId,
'riotAccounts.0': { $exists: true },
}).exec();
}
private toMemberWindowView(
user: UserDocument,
windowStart: Date,
windowEnd: Date,
): LegacyImportMemberWindowView {
const resolved = this.resolveMemberWindow(
user,
windowStart,
windowEnd,
new Map(),
);
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
return {
userId: user._id.toString(),
puuid: account.puuid,
displayName:
user.kakaoTalkNickname ??
user.discordNickname ??
account.gameName ??
user._id.toString(),
gameName: account.gameName,
tagLine: account.tagLine,
profileIconId: account.profileIconId,
isActivated: user.isActivated,
startTime: resolved.startTime.toISOString(),
endTime: resolved.endTime.toISOString(),
};
}
private resolveMemberWindow(
user: UserDocument,
windowStart: Date,
windowEnd: Date,
overrides: Map<string, { startTime?: string; endTime?: string }>,
) {
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) throw new BadRequestException('Riot account not found.');
const override = overrides.get(user._id.toString());
const overrideStart = this.parseOptionalDate(override?.startTime);
const overrideEnd = this.parseOptionalDate(override?.endTime);
const activeEnd = user.isActivated ? windowEnd : user.updatedAt;
const startTime = overrideStart ?? windowStart;
const endTime = this.minDate(windowEnd, activeEnd, overrideEnd);
return {
userId: user._id,
puuid: account.puuid,
startTime,
endTime,
};
}
private resolveWindow(params: { windowStart?: string; windowEnd?: string }) {
const windowStart =
this.parseOptionalDate(params.windowStart) ??
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
const windowEnd = this.parseOptionalDate(params.windowEnd) ?? new Date();
if (windowStart.getTime() > windowEnd.getTime()) {
throw new BadRequestException('windowStart must be before windowEnd.');
}
return { windowStart, windowEnd };
}
private parseOptionalDate(value: string | undefined): Date | undefined {
if (!value) return undefined;
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
throw new BadRequestException('Invalid date.');
}
return parsed;
}
private minDate(...values: Array<Date | undefined>): Date {
return new Date(
Math.min(...values.filter(Boolean).map((date) => date!.getTime())),
);
}
private normalizeLegacyTitle(title: string, gameCreation: number): string {
const stripped = title.replace(/^\[(?:legacy|lagacy)\]\s*/i, '').trim();
return stripped || this.formatLegacyDate(gameCreation);
}
private formatLegacyDate(gameCreation: number): string {
return new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(gameCreation));
}
private communityLockKey(communityId: mongoose.Types.ObjectId): string {
return `legacy-import:lock:${communityId.toString()}`;
}
}
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
return Boolean(
value &&
typeof value === 'object' &&
'metadata' in value &&
'info' in value,
);
}
interface LegacyResultSummary {
riotMatchId: string | null;
memberCount: number;
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
winnerTeamIndex?: number;
}
function summarizeCompetitionResult(
value: unknown,
): LegacyResultSummary | null {
if (!value) return null;
const competition = toPlainRecord(value);
const projection = toRecord(competition.projection);
const games = toArray(projection.games).map(toRecord);
const game = games.find((candidate) => {
const evidence = toRecord(candidate.evidence);
return evidence.type === 'riot' && typeof evidence.riotMatchId === 'string';
});
if (!game) return null;
const evidence = toRecord(game.evidence);
const series = toArray(projection.series)
.map(toRecord)
.find(
(candidate) => idString(candidate.seriesId) === idString(game.seriesId),
);
const entries = toArray(series?.entries).map(toRecord);
const teamIndexById = new Map(
toArray(competition.teams).map((teamValue) => {
const team = toRecord(teamValue);
return [
idString(team.teamId),
optionalNumber(team.legacyTeamIndex) ?? numberValue(team.displayOrder),
];
}),
);
const teamA = entries.find((entry) => entry.slot === 'A');
const teamB = entries.find((entry) => entry.slot === 'B');
const teamAId = idString(teamA?.teamId);
const teamBId = idString(teamB?.teamId);
const winnerTeamId =
idString(toRecord(series?.outcome).winnerTeamId) ||
idString(game.winnerTeamId);
return {
riotMatchId: String(evidence.riotMatchId),
memberCount: toArray(game.participants).filter(
(participant) => idString(toRecord(participant).userId).length > 0,
).length,
teamAIndex: teamIndexById.get(teamAId) ?? 1,
teamBIndex: teamIndexById.get(teamBId) ?? 2,
teamAWins: numberValue(teamA?.gameWins),
teamBWins: numberValue(teamB?.gameWins),
...(teamIndexById.has(winnerTeamId)
? { winnerTeamIndex: teamIndexById.get(winnerTeamId) }
: {}),
};
}
function summarizeLegacyMatchResult(match: MatchDocument): LegacyResultSummary {
const series = match.result?.seriesResults?.[0];
const game = match.result?.games?.[0];
return {
riotMatchId: game?.riotMatchId ?? match.result?.riotMatchIds?.[0] ?? null,
memberCount: game?.participants.length ?? 0,
teamAIndex: series?.teamAIndex ?? 1,
teamBIndex: series?.teamBIndex ?? 2,
teamAWins: series?.teamAWins ?? 0,
teamBWins: series?.teamBWins ?? 0,
...(match.result?.winnerTeamIndex === undefined
? {}
: { winnerTeamIndex: match.result.winnerTeamIndex }),
};
}
function competitionRevision(value: unknown): number | undefined {
return value ? optionalNumber(toPlainRecord(value).revision) : undefined;
}
function hasDecisiveRiotWinner(detail: RiotMatchDto): boolean {
return (
detail.info.teams.filter(
({ teamId, win }) => win && (teamId === 100 || teamId === 200),
).length === 1
);
}
function hasTrustedCompetitionRoster(
counts: { team100: number; team200: number; total: number },
participants: Match['participants'],
teams: Match['teams'],
): boolean {
if (
counts.total < 6 ||
counts.team100 !== counts.team200 ||
counts.team100 === 0 ||
teams.length !== 2 ||
teams.some((team) => team.members.length !== counts.team100)
) {
return false;
}
const userIds = participants.map(({ userId }) => userId.toString());
return (
userIds.length === counts.total && new Set(userIds).size === userIds.length
);
}
function buildMatchPuuidLookup(match: MatchDocument): 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;
puuidByUserId.set(participant.userId.toString(), participant.puuid);
userIdByPuuid.set(participant.puuid, participant.userId);
}
return { puuidByUserId, userIdByPuuid };
}
function toCompetitionResultSnapshot(
value: unknown,
): CompetitionResultSnapshot {
const raw = toPlainRecord(value);
const projection = toRecord(raw.projection);
return {
competitionId: idString(raw._id),
revision: numberValue(raw.revision),
phase: String(raw.phase) as CompetitionResultSnapshot['phase'],
teams: toArray(raw.teams).map((teamValue) => {
const team = toRecord(teamValue);
return {
teamId: idString(team.teamId),
members: toArray(team.members).map((memberValue) => ({
userId: idString(toRecord(memberValue).userId),
})),
};
}),
projection: {
phase: String(
projection.phase,
) as CompetitionResultSnapshot['projection']['phase'],
series: toArray(projection.series).map((seriesValue) => {
const series = toRecord(seriesValue);
return {
seriesId: idString(series.seriesId),
status: String(
series.status,
) as CompetitionResultSnapshot['projection']['series'][number]['status'],
entries: toArray(series.entries).map((entryValue) => {
const entry = toRecord(entryValue);
return {
slot: String(entry.slot) as 'A' | 'B',
teamId: entry.teamId == null ? null : idString(entry.teamId),
gameWins: numberValue(entry.gameWins),
};
}),
};
}),
gameSlots: toArray(projection.gameSlots).map((slotValue) => {
const slot = toRecord(slotValue);
return {
id: idString(slot.id),
seriesId: idString(slot.seriesId),
ordinal: numberValue(slot.ordinal),
displayNumber: numberValue(slot.displayNumber),
status: String(
slot.status,
) as CompetitionResultSnapshot['projection']['gameSlots'][number]['status'],
};
}),
games: toArray(projection.games).map((gameValue) => {
const evidence = toRecord(toRecord(gameValue).evidence);
return {
evidence: {
type: typeof evidence.type === 'string' ? evidence.type : undefined,
riotMatchId:
typeof evidence.riotMatchId === 'string'
? evidence.riotMatchId
: undefined,
},
};
}),
},
};
}
function toPlainRecord(value: unknown): Record<string, unknown> {
if (
value &&
typeof value === 'object' &&
'toObject' in value &&
typeof value.toObject === 'function'
) {
const document = value as { toObject: () => unknown };
return toRecord(document.toObject());
}
return toRecord(value);
}
function toRecord(value: unknown): Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function toArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function idString(value: unknown): string {
if (value instanceof mongoose.Types.ObjectId) return value.toString();
return typeof value === 'string' ? value : '';
}
function numberValue(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function optionalNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function legacyTournamentCodeBindingUnset(): Record<string, 1> {
return {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
};
}
function assertExactTournamentCodeTransition(
result: { matchedCount?: number; modifiedCount?: number },
expectedCount: number,
): void {
if (
result.matchedCount !== expectedCount ||
result.modifiedCount !== expectedCount
) {
throw new ConflictException(
'Tournament Code transition did not update every validated assignment.',
);
}
}
function deterministicObjectId(key: string): mongoose.Types.ObjectId {
return new mongoose.Types.ObjectId(
createHash('sha256').update(key).digest('hex').slice(0, 24),
);
}