feat: add resumable competition migration runner
This commit is contained in:
1 parent
55e5b8df70
commit
ee4c3eeb27
5 files changed
+1608
No files matched your search
@@ -0,0 +1,927 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { projectCompetition } from '../../../competition/domain/competition-projector';
|
||||
import {
|
||||
planCompetitionMigration,
|
||||
type CompetitionMigrationAssignment,
|
||||
type CompetitionMigrationFact,
|
||||
type CompetitionMigrationIssue,
|
||||
type LegacyMatchInput,
|
||||
type ReadyCompetitionMigrationPlan,
|
||||
} from './20260712-competition-domain';
|
||||
|
||||
const DEFAULT_MIGRATION_RUN_ID = '20260712-competition-domain';
|
||||
const MATCH_SCAN_FILTER = { 'teams.1': { $exists: true } };
|
||||
|
||||
type AnyDocument = Record<string, unknown> & { _id: unknown };
|
||||
|
||||
export interface CompetitionDomainMigrationCursor extends AsyncIterable<AnyDocument> {
|
||||
sort(specification: Record<string, 1 | -1>): CompetitionDomainMigrationCursor;
|
||||
limit(limit: number): CompetitionDomainMigrationCursor;
|
||||
}
|
||||
|
||||
export interface CompetitionDomainMigrationCollection {
|
||||
find(
|
||||
filter: Record<string, unknown>,
|
||||
options?: { session?: CompetitionDomainMigrationSession },
|
||||
): CompetitionDomainMigrationCursor;
|
||||
findOne(
|
||||
filter: Record<string, unknown>,
|
||||
options?: { session?: CompetitionDomainMigrationSession },
|
||||
): Promise<AnyDocument | null>;
|
||||
updateOne(
|
||||
filter: Record<string, unknown>,
|
||||
update: {
|
||||
$set?: Record<string, unknown>;
|
||||
$setOnInsert?: Record<string, unknown>;
|
||||
},
|
||||
options?: {
|
||||
session?: CompetitionDomainMigrationSession;
|
||||
upsert?: boolean;
|
||||
},
|
||||
): Promise<{
|
||||
matchedCount?: number;
|
||||
modifiedCount?: number;
|
||||
upsertedCount?: number;
|
||||
}>;
|
||||
deleteOne(
|
||||
filter: Record<string, unknown>,
|
||||
options?: { session?: CompetitionDomainMigrationSession },
|
||||
): Promise<{ deletedCount?: number }>;
|
||||
}
|
||||
|
||||
export interface CompetitionDomainMigrationDb {
|
||||
collection(name: string): CompetitionDomainMigrationCollection;
|
||||
}
|
||||
|
||||
export interface CompetitionDomainMigrationSession {
|
||||
startTransaction(): void;
|
||||
commitTransaction(): Promise<void>;
|
||||
abortTransaction(): Promise<void>;
|
||||
endSession(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface CompetitionDomainMigrationOptions {
|
||||
dryRun?: boolean;
|
||||
limit?: number;
|
||||
migrationRunId?: string;
|
||||
now?: Date;
|
||||
startSession?: () => Promise<CompetitionDomainMigrationSession | undefined>;
|
||||
onProgress?: (progress: CompetitionDomainMigrationProgress) => void;
|
||||
}
|
||||
|
||||
export interface CompetitionDomainMigrationProgress {
|
||||
index: number;
|
||||
matchId: string;
|
||||
status: CompetitionDomainMigrationMatchResult['status'];
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface CompetitionDomainMigrationMatchBase {
|
||||
matchId: string;
|
||||
competitionId?: string;
|
||||
warnings: CompetitionMigrationIssue[];
|
||||
}
|
||||
|
||||
export type CompetitionDomainMigrationMatchResult =
|
||||
| (CompetitionDomainMigrationMatchBase & {
|
||||
status: 'ready' | 'applied';
|
||||
factCount: number;
|
||||
assignmentCount: number;
|
||||
})
|
||||
| (CompetitionDomainMigrationMatchBase & {
|
||||
status: 'already-applied';
|
||||
})
|
||||
| (CompetitionDomainMigrationMatchBase & {
|
||||
status: 'quarantined';
|
||||
reasons: CompetitionMigrationIssue[];
|
||||
})
|
||||
| (CompetitionDomainMigrationMatchBase & {
|
||||
status: 'failed';
|
||||
error: string;
|
||||
});
|
||||
|
||||
export interface CompetitionDomainMigrationSummary {
|
||||
scanned: number;
|
||||
ready: number;
|
||||
applied: number;
|
||||
alreadyApplied: number;
|
||||
quarantined: number;
|
||||
failed: number;
|
||||
/** Planner/runtime failures that were neither ready nor explicitly quarantined. */
|
||||
unclassified: number;
|
||||
factsPlanned: number;
|
||||
assignmentsPlanned: number;
|
||||
warnings: number;
|
||||
}
|
||||
|
||||
export interface CompetitionDomainMigrationResult {
|
||||
migrationRunId: string;
|
||||
mode: 'dry-run' | 'apply';
|
||||
summary: CompetitionDomainMigrationSummary;
|
||||
matches: CompetitionDomainMigrationMatchResult[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans or applies the clean-break Competition migration. Apply mode owns one
|
||||
* Mongo transaction per Match so a process can be stopped and safely resumed.
|
||||
*/
|
||||
export async function migrateCompetitionDomain(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
options: CompetitionDomainMigrationOptions = {},
|
||||
): Promise<CompetitionDomainMigrationResult> {
|
||||
const dryRun = options.dryRun ?? true;
|
||||
const migrationRunId =
|
||||
options.migrationRunId?.trim() || DEFAULT_MIGRATION_RUN_ID;
|
||||
assertOptions(options);
|
||||
|
||||
const matchSnapshots = await scanMatches(db, options.limit);
|
||||
const matches: CompetitionDomainMigrationMatchResult[] = [];
|
||||
for (const [index, scannedMatch] of matchSnapshots.entries()) {
|
||||
const result = dryRun
|
||||
? await inspectMatch(db, scannedMatch, migrationRunId)
|
||||
: await applyMatch(db, scannedMatch, migrationRunId, options);
|
||||
matches.push(result);
|
||||
options.onProgress?.({
|
||||
index: index + 1,
|
||||
matchId: result.matchId,
|
||||
status: result.status,
|
||||
total: matchSnapshots.length,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
migrationRunId,
|
||||
mode: dryRun ? 'dry-run' : 'apply',
|
||||
summary: summarize(matches),
|
||||
matches,
|
||||
};
|
||||
}
|
||||
|
||||
async function scanMatches(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
limit: number | undefined,
|
||||
): Promise<AnyDocument[]> {
|
||||
return readCursor(
|
||||
db
|
||||
.collection('match')
|
||||
.find(MATCH_SCAN_FILTER)
|
||||
.sort({ _id: 1 })
|
||||
.limit(limit ?? 0),
|
||||
);
|
||||
}
|
||||
|
||||
async function inspectMatch(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
scannedMatch: AnyDocument,
|
||||
migrationRunId: string,
|
||||
): Promise<CompetitionDomainMigrationMatchResult> {
|
||||
const matchId = idString(scannedMatch._id);
|
||||
try {
|
||||
const linkedCompetitionId = optionalIdString(scannedMatch.competitionId);
|
||||
if (linkedCompetitionId) {
|
||||
assertExpectedCompetitionId(matchId, linkedCompetitionId);
|
||||
await verifyProjectionReplay(db, linkedCompetitionId);
|
||||
return {
|
||||
status: 'already-applied',
|
||||
matchId,
|
||||
competitionId: linkedCompetitionId,
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
const legacy = await hydrateLegacyMatch(db, scannedMatch);
|
||||
const plan = planCompetitionMigration(legacy, { migrationRunId });
|
||||
return planResult(matchId, plan);
|
||||
} catch (error) {
|
||||
return failedResult(matchId, error);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyMatch(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
scannedMatch: AnyDocument,
|
||||
migrationRunId: string,
|
||||
options: CompetitionDomainMigrationOptions,
|
||||
): Promise<CompetitionDomainMigrationMatchResult> {
|
||||
const matchId = idString(scannedMatch._id);
|
||||
let session: CompetitionDomainMigrationSession | undefined;
|
||||
try {
|
||||
session = await options.startSession?.();
|
||||
if (!session) {
|
||||
throw new Error(
|
||||
'Apply mode requires a MongoDB transaction session for every Match.',
|
||||
);
|
||||
}
|
||||
session.startTransaction();
|
||||
|
||||
const currentMatch = await db
|
||||
.collection('match')
|
||||
.findOne({ _id: scannedMatch._id }, { session });
|
||||
if (!currentMatch) throw new Error(`Match ${matchId} no longer exists.`);
|
||||
|
||||
const linkedCompetitionId = optionalIdString(currentMatch.competitionId);
|
||||
if (linkedCompetitionId) {
|
||||
assertExpectedCompetitionId(matchId, linkedCompetitionId);
|
||||
await verifyProjectionReplay(db, linkedCompetitionId, session);
|
||||
await db
|
||||
.collection('competition_migration_quarantine')
|
||||
.deleteOne({ _id: currentMatch._id }, { session });
|
||||
await verifyProjectionReplay(db, linkedCompetitionId, session);
|
||||
await session.commitTransaction();
|
||||
return {
|
||||
status: 'already-applied',
|
||||
matchId,
|
||||
competitionId: linkedCompetitionId,
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Re-read all evidence inside the transaction. The scan is only a work
|
||||
// list; it is never treated as the source snapshot for an apply.
|
||||
const legacy = await hydrateLegacyMatch(db, currentMatch, session);
|
||||
const plan = planCompetitionMigration(legacy, { migrationRunId });
|
||||
if (plan.status === 'quarantined') {
|
||||
await persistQuarantine(
|
||||
db,
|
||||
currentMatch,
|
||||
plan.reasons,
|
||||
plan.warnings,
|
||||
migrationRunId,
|
||||
options.now ?? new Date(),
|
||||
session,
|
||||
);
|
||||
await session.commitTransaction();
|
||||
return {
|
||||
status: 'quarantined',
|
||||
matchId,
|
||||
warnings: plan.warnings,
|
||||
reasons: plan.reasons,
|
||||
};
|
||||
}
|
||||
|
||||
await upsertReadyPlan(db, plan, session);
|
||||
await verifyReadyPlan(db, plan, session);
|
||||
|
||||
const competitionId = plan.competition.id;
|
||||
const linkResult = await db.collection('match').updateOne(
|
||||
{
|
||||
_id: currentMatch._id,
|
||||
$or: [
|
||||
{ competitionId: { $exists: false } },
|
||||
{ competitionId: null },
|
||||
{ competitionId: persistenceId(competitionId) },
|
||||
],
|
||||
},
|
||||
{ $set: { competitionId: persistenceId(competitionId) } },
|
||||
{ session },
|
||||
);
|
||||
if (linkResult.matchedCount !== 1) {
|
||||
throw new Error(
|
||||
`Match ${matchId} was concurrently linked to another Competition.`,
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.collection('competition_migration_quarantine')
|
||||
.deleteOne({ _id: currentMatch._id }, { session });
|
||||
// Verify again after the final Match/quarantine writes, immediately before
|
||||
// committing, so every applied Match ends with a replay-equal aggregate.
|
||||
await verifyProjectionReplay(db, competitionId, session);
|
||||
await session.commitTransaction();
|
||||
return {
|
||||
status: 'applied',
|
||||
matchId,
|
||||
competitionId,
|
||||
factCount: plan.facts.length,
|
||||
assignmentCount: plan.assignments.length,
|
||||
warnings: plan.warnings,
|
||||
};
|
||||
} catch (error) {
|
||||
if (session) await session.abortTransaction().catch(() => undefined);
|
||||
return failedResult(matchId, error);
|
||||
} finally {
|
||||
if (session) await session.endSession().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function hydrateLegacyMatch(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
match: AnyDocument,
|
||||
session?: CompetitionDomainMigrationSession,
|
||||
): Promise<LegacyMatchInput> {
|
||||
const tournamentCodeIds = arrayOf(match.tournamentCodeIds);
|
||||
const tournamentCodes = await readCursor(
|
||||
db
|
||||
.collection('tournamentCode')
|
||||
.find(
|
||||
{
|
||||
$or: [
|
||||
...(tournamentCodeIds.length > 0
|
||||
? [{ _id: { $in: tournamentCodeIds } }]
|
||||
: []),
|
||||
{ matchId: match._id },
|
||||
],
|
||||
},
|
||||
{ session },
|
||||
)
|
||||
.sort({ _id: 1 })
|
||||
.limit(0),
|
||||
);
|
||||
const result = isRecord(match.result) ? match.result : undefined;
|
||||
const games = Array.isArray(result?.games) ? result.games : [];
|
||||
const riotMatchIds = uniqueStrings(
|
||||
games.map((game) => (isRecord(game) ? game.riotMatchId : undefined)),
|
||||
);
|
||||
const archives =
|
||||
riotMatchIds.length === 0
|
||||
? []
|
||||
: await readCursor(
|
||||
db
|
||||
.collection('riotMatch')
|
||||
.find({ matchId: { $in: riotMatchIds } }, { session })
|
||||
.sort({ matchId: 1 })
|
||||
.limit(0),
|
||||
);
|
||||
const archiveByMatchId = new Map(
|
||||
archives.map((archive) => [String(archive.matchId), archive]),
|
||||
);
|
||||
const archivedIds = new Set(archiveByMatchId.keys());
|
||||
const hydratedResult = result
|
||||
? {
|
||||
...result,
|
||||
games: games.map((game) =>
|
||||
isRecord(game)
|
||||
? hydrateLegacyGameEvidence(game, archiveByMatchId)
|
||||
: game,
|
||||
),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
...match,
|
||||
...(hydratedResult ? { result: hydratedResult } : {}),
|
||||
tournamentCodes,
|
||||
riotMatchArchiveIds: [...archivedIds].sort(),
|
||||
} as unknown as LegacyMatchInput;
|
||||
}
|
||||
|
||||
function hydrateLegacyGameEvidence(
|
||||
game: Record<string, unknown>,
|
||||
archiveByMatchId: ReadonlyMap<string, AnyDocument>,
|
||||
): Record<string, unknown> {
|
||||
const riotMatchId =
|
||||
typeof game.riotMatchId === 'string' ? game.riotMatchId : undefined;
|
||||
const archive = riotMatchId ? archiveByMatchId.get(riotMatchId) : undefined;
|
||||
if (!archive) return { ...game, riotArchivePresent: false };
|
||||
const existingPayloadHash =
|
||||
typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0
|
||||
? game.payloadHash
|
||||
: undefined;
|
||||
return {
|
||||
...game,
|
||||
riotArchivePresent: true,
|
||||
payloadHash:
|
||||
existingPayloadHash ??
|
||||
`sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function upsertReadyPlan(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
plan: ReadyCompetitionMigrationPlan,
|
||||
session: CompetitionDomainMigrationSession,
|
||||
): Promise<void> {
|
||||
const competition = competitionForPersistence(plan);
|
||||
await db
|
||||
.collection('competition')
|
||||
.updateOne(
|
||||
{ _id: competition._id },
|
||||
{ $setOnInsert: competition },
|
||||
{ upsert: true, session },
|
||||
);
|
||||
for (const fact of plan.facts) {
|
||||
const persisted = factForPersistence(fact);
|
||||
await db
|
||||
.collection('competition_fact')
|
||||
.updateOne(
|
||||
{ _id: persisted._id },
|
||||
{ $setOnInsert: persisted },
|
||||
{ upsert: true, session },
|
||||
);
|
||||
}
|
||||
for (const assignment of plan.assignments) {
|
||||
const persisted = assignmentForPersistence(assignment);
|
||||
await db
|
||||
.collection('tournament_code_assignment')
|
||||
.updateOne(
|
||||
{ _id: persisted._id },
|
||||
{ $setOnInsert: persisted },
|
||||
{ upsert: true, session },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyReadyPlan(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
plan: ReadyCompetitionMigrationPlan,
|
||||
session: CompetitionDomainMigrationSession,
|
||||
): Promise<void> {
|
||||
const competition = await db
|
||||
.collection('competition')
|
||||
.findOne({ _id: persistenceId(plan.competition.id) }, { session });
|
||||
if (!competition) {
|
||||
throw new Error(
|
||||
`Competition ${plan.competition.id} is missing after deterministic upsert.`,
|
||||
);
|
||||
}
|
||||
assertFieldsEqual(
|
||||
competition,
|
||||
competitionForPersistence(plan),
|
||||
[
|
||||
'_id',
|
||||
'matchId',
|
||||
'communityId',
|
||||
'schemaVersion',
|
||||
'projectorVersion',
|
||||
'teams',
|
||||
'format',
|
||||
'seriesGraph',
|
||||
],
|
||||
`Competition ${plan.competition.id}`,
|
||||
);
|
||||
|
||||
for (const fact of plan.facts) {
|
||||
const expected = factForPersistence(fact);
|
||||
const actual = await db
|
||||
.collection('competition_fact')
|
||||
.findOne({ _id: expected._id }, { session });
|
||||
if (!actual) throw new Error(`Migration fact ${fact.id} is missing.`);
|
||||
assertFieldsEqual(
|
||||
actual,
|
||||
expected,
|
||||
Object.keys(expected).filter(
|
||||
(key) => key !== 'createdAt' && key !== 'updatedAt',
|
||||
),
|
||||
`Migration fact ${fact.id}`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const assignment of plan.assignments) {
|
||||
const expected = assignmentForPersistence(assignment);
|
||||
const actual = await db
|
||||
.collection('tournament_code_assignment')
|
||||
.findOne({ _id: expected._id }, { session });
|
||||
if (!actual) {
|
||||
throw new Error(`TournamentCode assignment ${assignment.id} is missing.`);
|
||||
}
|
||||
assertFieldsEqual(
|
||||
actual,
|
||||
expected,
|
||||
Object.keys(expected).filter(
|
||||
(key) => key !== 'createdAt' && key !== 'updatedAt',
|
||||
),
|
||||
`TournamentCode assignment ${assignment.id}`,
|
||||
);
|
||||
}
|
||||
|
||||
await verifyProjectionReplay(db, plan.competition.id, session);
|
||||
}
|
||||
|
||||
async function verifyProjectionReplay(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
competitionId: string,
|
||||
session?: CompetitionDomainMigrationSession,
|
||||
): Promise<void> {
|
||||
const competition = await db
|
||||
.collection('competition')
|
||||
.findOne({ _id: persistenceId(competitionId) }, { session });
|
||||
if (!competition) {
|
||||
throw new Error(`Linked Competition ${competitionId} does not exist.`);
|
||||
}
|
||||
const facts = await readCursor(
|
||||
db
|
||||
.collection('competition_fact')
|
||||
.find({ competitionId: persistenceId(competitionId) }, { session })
|
||||
.sort({ revision: 1, ordinalWithinRevision: 1 })
|
||||
.limit(0),
|
||||
);
|
||||
const revision = numberField(competition, 'revision');
|
||||
const projectorVersion = numberField(competition, 'projectorVersion');
|
||||
assertLedgerRevision(facts, revision, competitionId);
|
||||
const replay = projectCompetition({
|
||||
competitionId,
|
||||
revision,
|
||||
projectorVersion,
|
||||
teams: canonicalValue(competition.teams) as never,
|
||||
format: canonicalValue(competition.format) as never,
|
||||
seriesGraph: canonicalValue(competition.seriesGraph) as never,
|
||||
facts: facts.map(factForProjection),
|
||||
});
|
||||
if (canonicalJson(replay) !== canonicalJson(competition.projection)) {
|
||||
throw new Error(
|
||||
`Competition ${competitionId} projection replay does not equal the persisted projection.`,
|
||||
);
|
||||
}
|
||||
if (replay.phase !== competition.phase) {
|
||||
throw new Error(
|
||||
`Competition ${competitionId} replay phase does not equal the persisted phase.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function assertLedgerRevision(
|
||||
facts: ReadonlyArray<Record<string, unknown>>,
|
||||
competitionRevision: number,
|
||||
competitionId: string,
|
||||
): void {
|
||||
const positions = new Set<string>();
|
||||
const revisions = new Set<number>();
|
||||
let maximumRevision = 0;
|
||||
for (const fact of facts) {
|
||||
const revision = numberField(fact, 'revision');
|
||||
const ordinal = numberField(fact, 'ordinalWithinRevision');
|
||||
if (revision < 1 || ordinal < 1) {
|
||||
throw new Error(
|
||||
`Competition ${competitionId} has an invalid fact ledger position.`,
|
||||
);
|
||||
}
|
||||
const position = `${revision}:${ordinal}`;
|
||||
if (positions.has(position)) {
|
||||
throw new Error(
|
||||
`Competition ${competitionId} has duplicate fact ledger position ${position}.`,
|
||||
);
|
||||
}
|
||||
positions.add(position);
|
||||
revisions.add(revision);
|
||||
maximumRevision = Math.max(maximumRevision, revision);
|
||||
}
|
||||
if (maximumRevision !== competitionRevision) {
|
||||
throw new Error(
|
||||
`Competition ${competitionId} revision ${competitionRevision} does not match fact ledger revision ${maximumRevision}.`,
|
||||
);
|
||||
}
|
||||
if (revisions.size !== maximumRevision) {
|
||||
throw new Error(
|
||||
`Competition ${competitionId} fact ledger has a revision gap.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function persistQuarantine(
|
||||
db: CompetitionDomainMigrationDb,
|
||||
match: AnyDocument,
|
||||
reasons: CompetitionMigrationIssue[],
|
||||
warnings: CompetitionMigrationIssue[],
|
||||
migrationRunId: string,
|
||||
observedAt: Date,
|
||||
session: CompetitionDomainMigrationSession,
|
||||
): Promise<void> {
|
||||
const sourceUpdatedAt = dateOrUndefined(match.updatedAt);
|
||||
const payload = {
|
||||
matchId: match._id,
|
||||
migrationRunId,
|
||||
status: 'quarantined',
|
||||
reasons,
|
||||
warnings,
|
||||
sourceUpdatedAt,
|
||||
planHash: canonicalHash({
|
||||
matchId: idString(match._id),
|
||||
sourceUpdatedAt,
|
||||
reasons,
|
||||
warnings,
|
||||
}),
|
||||
observedAt,
|
||||
updatedAt: observedAt,
|
||||
};
|
||||
await db.collection('competition_migration_quarantine').updateOne(
|
||||
{ _id: match._id },
|
||||
{
|
||||
$set: payload,
|
||||
$setOnInsert: { _id: match._id, createdAt: observedAt },
|
||||
},
|
||||
{ upsert: true, session },
|
||||
);
|
||||
}
|
||||
|
||||
function competitionForPersistence(
|
||||
plan: ReadyCompetitionMigrationPlan,
|
||||
): AnyDocument {
|
||||
const source = plan.competition;
|
||||
return {
|
||||
_id: persistenceId(source.id),
|
||||
matchId: persistenceId(source.matchId),
|
||||
communityId: persistenceId(source.communityId),
|
||||
schemaVersion: source.schemaVersion,
|
||||
projectorVersion: source.projectorVersion,
|
||||
revision: source.revision,
|
||||
phase: source.phase,
|
||||
teams: source.teams.map((team) => ({
|
||||
...team,
|
||||
teamId: persistenceId(team.teamId),
|
||||
...(team.captainUserId
|
||||
? { captainUserId: persistenceId(team.captainUserId) }
|
||||
: {}),
|
||||
members: team.members.map((member) => ({
|
||||
...member,
|
||||
userId: persistenceId(member.userId),
|
||||
})),
|
||||
})),
|
||||
format: source.format,
|
||||
seriesGraph: source.seriesGraph,
|
||||
projection: source.projection,
|
||||
createdAt: new Date(source.createdAt),
|
||||
updatedAt: new Date(source.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function factForPersistence(fact: CompetitionMigrationFact): AnyDocument {
|
||||
const recordedAt = new Date(fact.recordedAt);
|
||||
const common: AnyDocument = {
|
||||
...fact,
|
||||
_id: persistenceId(fact.id),
|
||||
competitionId: persistenceId(fact.competitionId),
|
||||
occurredAt: new Date(fact.occurredAt),
|
||||
recordedAt,
|
||||
createdAt: recordedAt,
|
||||
updatedAt: recordedAt,
|
||||
};
|
||||
delete common.id;
|
||||
if (fact.type === 'game-accepted') {
|
||||
common.gameId = persistenceId(fact.gameId);
|
||||
common.seriesId = persistenceId(fact.seriesId);
|
||||
common.gameSlotId = persistenceId(fact.gameSlotId);
|
||||
common.mapping = {
|
||||
...fact.mapping,
|
||||
blueTeamId: persistenceId(fact.mapping.blueTeamId),
|
||||
redTeamId: persistenceId(fact.mapping.redTeamId),
|
||||
winnerTeamId: persistenceId(fact.mapping.winnerTeamId),
|
||||
participantAssignments: fact.mapping.participantAssignments.map(
|
||||
(assignment) => ({
|
||||
...assignment,
|
||||
userId: persistenceId(assignment.userId),
|
||||
teamId: persistenceId(assignment.teamId),
|
||||
}),
|
||||
),
|
||||
};
|
||||
} else {
|
||||
common.seriesId = persistenceId(fact.seriesId);
|
||||
common.decision =
|
||||
'winnerTeamId' in fact.decision
|
||||
? {
|
||||
...fact.decision,
|
||||
winnerTeamId: persistenceId(fact.decision.winnerTeamId),
|
||||
}
|
||||
: fact.decision;
|
||||
}
|
||||
return common;
|
||||
}
|
||||
|
||||
function assignmentForPersistence(
|
||||
assignment: CompetitionMigrationAssignment,
|
||||
): AnyDocument {
|
||||
const reservedAt = new Date(assignment.reservedAt);
|
||||
const updatedAt = new Date(
|
||||
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt,
|
||||
);
|
||||
const voidedAt =
|
||||
assignment.state === 'voided'
|
||||
? new Date(
|
||||
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt,
|
||||
)
|
||||
: undefined;
|
||||
return {
|
||||
_id: persistenceId(assignment.id),
|
||||
competitionId: persistenceId(assignment.competitionId),
|
||||
seriesId: persistenceId(assignment.seriesId),
|
||||
gameSlotId: persistenceId(assignment.gameSlotId),
|
||||
tournamentCodeId: persistenceId(assignment.tournamentCodeId),
|
||||
state: assignment.state,
|
||||
reservedAt,
|
||||
...(assignment.usedAt ? { usedAt: new Date(assignment.usedAt) } : {}),
|
||||
...(assignment.releasedAt
|
||||
? { releasedAt: new Date(assignment.releasedAt) }
|
||||
: {}),
|
||||
...(voidedAt ? { voidedAt } : {}),
|
||||
...(assignment.riotMatchId ? { riotMatchId: assignment.riotMatchId } : {}),
|
||||
commandId: assignment.commandId,
|
||||
createdAt: reservedAt,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function factForProjection(
|
||||
fact: Readonly<Record<string, unknown>>,
|
||||
): Readonly<Record<string, unknown>> {
|
||||
const canonical = canonicalValue(fact) as Readonly<Record<string, unknown>>;
|
||||
return { ...canonical, id: idString(fact.id ?? fact._id) };
|
||||
}
|
||||
|
||||
function planResult(
|
||||
matchId: string,
|
||||
plan: ReturnType<typeof planCompetitionMigration>,
|
||||
): CompetitionDomainMigrationMatchResult {
|
||||
if (plan.status === 'quarantined') {
|
||||
return {
|
||||
status: 'quarantined',
|
||||
matchId,
|
||||
warnings: plan.warnings,
|
||||
reasons: plan.reasons,
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 'ready',
|
||||
matchId,
|
||||
competitionId: plan.competition.id,
|
||||
factCount: plan.facts.length,
|
||||
assignmentCount: plan.assignments.length,
|
||||
warnings: plan.warnings,
|
||||
};
|
||||
}
|
||||
|
||||
function failedResult(
|
||||
matchId: string,
|
||||
error: unknown,
|
||||
): CompetitionDomainMigrationMatchResult {
|
||||
return {
|
||||
status: 'failed',
|
||||
matchId,
|
||||
warnings: [],
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
|
||||
function summarize(
|
||||
matches: CompetitionDomainMigrationMatchResult[],
|
||||
): CompetitionDomainMigrationSummary {
|
||||
const count = (status: CompetitionDomainMigrationMatchResult['status']) =>
|
||||
matches.filter((match) => match.status === status).length;
|
||||
return {
|
||||
scanned: matches.length,
|
||||
ready: count('ready'),
|
||||
applied: count('applied'),
|
||||
alreadyApplied: count('already-applied'),
|
||||
quarantined: count('quarantined'),
|
||||
failed: count('failed'),
|
||||
unclassified: count('failed'),
|
||||
factsPlanned: matches.reduce(
|
||||
(sum, match) => sum + ('factCount' in match ? match.factCount : 0),
|
||||
0,
|
||||
),
|
||||
assignmentsPlanned: matches.reduce(
|
||||
(sum, match) =>
|
||||
sum + ('assignmentCount' in match ? match.assignmentCount : 0),
|
||||
0,
|
||||
),
|
||||
warnings: matches.reduce((sum, match) => sum + match.warnings.length, 0),
|
||||
};
|
||||
}
|
||||
|
||||
function assertExpectedCompetitionId(
|
||||
matchId: string,
|
||||
linkedCompetitionId: string,
|
||||
): void {
|
||||
const expected = deterministicCompetitionId(matchId);
|
||||
if (linkedCompetitionId !== expected) {
|
||||
throw new Error(
|
||||
`Match ${matchId} links Competition ${linkedCompetitionId}; expected deterministic Competition ${expected}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function deterministicCompetitionId(matchId: string): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify([matchId, 'competition']))
|
||||
.digest('hex')
|
||||
.slice(0, 24);
|
||||
}
|
||||
|
||||
function assertFieldsEqual(
|
||||
actual: Record<string, unknown>,
|
||||
expected: Record<string, unknown>,
|
||||
fields: string[],
|
||||
label: string,
|
||||
): void {
|
||||
for (const field of fields) {
|
||||
if (canonicalJson(actual[field]) !== canonicalJson(expected[field])) {
|
||||
throw new Error(`${label} has conflicting persisted field ${field}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertOptions(options: CompetitionDomainMigrationOptions): void {
|
||||
if (
|
||||
options.limit !== undefined &&
|
||||
(!Number.isInteger(options.limit) || options.limit < 1)
|
||||
) {
|
||||
throw new Error('Competition migration limit must be a positive integer.');
|
||||
}
|
||||
if (options.dryRun === false && !options.startSession) {
|
||||
throw new Error('Apply mode requires a transaction session factory.');
|
||||
}
|
||||
}
|
||||
|
||||
async function readCursor(
|
||||
cursor: CompetitionDomainMigrationCursor,
|
||||
): Promise<AnyDocument[]> {
|
||||
const result: AnyDocument[] = [];
|
||||
for await (const document of cursor) result.push(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
function numberField(document: Record<string, unknown>, field: string): number {
|
||||
const value = document[field];
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {
|
||||
throw new Error(`Competition has invalid ${field}.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function persistenceId(value: unknown): unknown {
|
||||
if (value instanceof mongoose.Types.ObjectId) return value;
|
||||
const stringValue = idString(value);
|
||||
return mongoose.Types.ObjectId.isValid(stringValue) &&
|
||||
/^[a-f\d]{24}$/i.test(stringValue)
|
||||
? new mongoose.Types.ObjectId(stringValue)
|
||||
: value;
|
||||
}
|
||||
|
||||
function optionalIdString(value: unknown): string | undefined {
|
||||
return value === undefined || value === null || value === ''
|
||||
? undefined
|
||||
: idString(value);
|
||||
}
|
||||
|
||||
function idString(value: unknown): string {
|
||||
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
|
||||
if (
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'toHexString' in value &&
|
||||
typeof value.toHexString === 'function'
|
||||
) {
|
||||
return String(value.toHexString());
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function arrayOf(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function uniqueStrings(values: unknown[]): string[] {
|
||||
return [
|
||||
...new Set(
|
||||
values.filter(
|
||||
(value): value is string =>
|
||||
typeof value === 'string' && value.trim().length > 0,
|
||||
),
|
||||
),
|
||||
].sort();
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function dateOrUndefined(value: unknown): Date | undefined {
|
||||
if (value === undefined || value === null || value === '') return undefined;
|
||||
const date = value instanceof Date ? value : new Date(value as string);
|
||||
return Number.isNaN(date.getTime()) ? undefined : date;
|
||||
}
|
||||
|
||||
function canonicalHash(value: unknown): string {
|
||||
return `sha256:${createNodeHash(canonicalJson(value))}`;
|
||||
}
|
||||
|
||||
function createNodeHash(value: string): string {
|
||||
// Kept in one helper so canonical hashes use exactly one encoding.
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
return JSON.stringify(canonicalValue(value));
|
||||
}
|
||||
|
||||
function canonicalValue(value: unknown): unknown {
|
||||
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'toHexString' in value &&
|
||||
typeof value.toHexString === 'function'
|
||||
) {
|
||||
return String(value.toHexString());
|
||||
}
|
||||
if (Array.isArray(value)) return value.map(canonicalValue);
|
||||
if (isRecord(value)) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value)
|
||||
.filter(([, child]) => child !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, child]) => [key, canonicalValue(child)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
Reference in new issue
Block a user