1343 lines
40 KiB
TypeScript
1343 lines
40 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import mongoose from 'mongoose';
|
|
import { projectCompetition } from '../../../competition/domain/competition-projector';
|
|
import {
|
|
COMPETITION_DOMAIN_INVARIANT_INDEXES,
|
|
type CompetitionDomainInvariantIndex,
|
|
} from '../../../competition/competition.schema';
|
|
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 {
|
|
createIndex(
|
|
key: mongoose.IndexDefinition,
|
|
options: mongoose.IndexOptions,
|
|
): Promise<string>;
|
|
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>;
|
|
$unset?: 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;
|
|
afterMatchId?: string;
|
|
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';
|
|
indexPreflight: CompetitionDomainIndexPreflight;
|
|
resume: CompetitionDomainMigrationResume;
|
|
summary: CompetitionDomainMigrationSummary;
|
|
matches: CompetitionDomainMigrationMatchResult[];
|
|
}
|
|
|
|
export interface CompetitionDomainMigrationResume {
|
|
strategy: 'none' | 'cursor' | 'checkpoint';
|
|
startedAfterMatchId?: string;
|
|
checkpointAfterMatchId?: string;
|
|
hasMore: boolean;
|
|
completed: boolean;
|
|
}
|
|
|
|
export interface CompetitionDomainIndexConflict {
|
|
collection: CompetitionDomainInvariantIndex['collection'];
|
|
indexName: string;
|
|
key: Record<string, unknown>;
|
|
code?: number;
|
|
keyPattern?: Record<string, unknown>;
|
|
keyValue?: unknown;
|
|
message: string;
|
|
}
|
|
|
|
export interface CompetitionDomainIndexPreflight {
|
|
status: 'dry-run' | 'ensured' | 'blocked';
|
|
requiredIndexes: number;
|
|
ensuredIndexes: string[];
|
|
conflicts: CompetitionDomainIndexConflict[];
|
|
}
|
|
|
|
/**
|
|
* 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 resumeStart = await resolveResumeStart(
|
|
db,
|
|
migrationRunId,
|
|
options,
|
|
dryRun,
|
|
);
|
|
|
|
const indexPreflight = await ensureCompetitionDomainIndexes(db, dryRun);
|
|
if (indexPreflight.status === 'blocked') {
|
|
return {
|
|
migrationRunId,
|
|
mode: 'apply',
|
|
indexPreflight,
|
|
resume: resumeReport(resumeStart, undefined, true, false),
|
|
summary: summarize([]),
|
|
matches: [],
|
|
};
|
|
}
|
|
if (!dryRun && options.limit !== undefined && options.afterMatchId) {
|
|
await persistMigrationCheckpoint(db, {
|
|
migrationRunId,
|
|
matchId: options.afterMatchId,
|
|
completed: false,
|
|
resetMatchStatus: true,
|
|
observedAt: options.now ?? new Date(),
|
|
});
|
|
}
|
|
|
|
const scan = await scanMatches(
|
|
db,
|
|
options.limit,
|
|
resumeStart.startedAfterMatchId,
|
|
);
|
|
const matches: CompetitionDomainMigrationMatchResult[] = [];
|
|
let checkpointAfterMatchId = resumeStart.startedAfterMatchId;
|
|
let haltedOnFailure = false;
|
|
for (const [index, scannedMatch] of scan.matches.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: scan.matches.length,
|
|
});
|
|
if (!dryRun && options.limit !== undefined) {
|
|
if (result.status === 'failed') {
|
|
haltedOnFailure = true;
|
|
break;
|
|
}
|
|
await persistMigrationCheckpoint(db, {
|
|
migrationRunId,
|
|
matchId: result.matchId,
|
|
matchStatus: result.status,
|
|
completed: false,
|
|
observedAt: options.now ?? new Date(),
|
|
});
|
|
checkpointAfterMatchId = result.matchId;
|
|
}
|
|
}
|
|
|
|
const hasMore =
|
|
scan.hasMore || haltedOnFailure || matches.length < scan.matches.length;
|
|
const completed =
|
|
!hasMore && !matches.some(({ status }) => status === 'failed');
|
|
if (!dryRun && options.limit !== undefined && completed) {
|
|
await persistMigrationCheckpoint(db, {
|
|
migrationRunId,
|
|
matchId: checkpointAfterMatchId,
|
|
completed: true,
|
|
observedAt: options.now ?? new Date(),
|
|
});
|
|
}
|
|
|
|
return {
|
|
migrationRunId,
|
|
mode: dryRun ? 'dry-run' : 'apply',
|
|
indexPreflight,
|
|
resume: resumeReport(
|
|
resumeStart,
|
|
checkpointAfterMatchId,
|
|
hasMore,
|
|
completed,
|
|
),
|
|
summary: summarize(matches),
|
|
matches,
|
|
};
|
|
}
|
|
|
|
interface ResumeStart {
|
|
strategy: CompetitionDomainMigrationResume['strategy'];
|
|
startedAfterMatchId?: string;
|
|
}
|
|
|
|
async function resolveResumeStart(
|
|
db: CompetitionDomainMigrationDb,
|
|
migrationRunId: string,
|
|
options: CompetitionDomainMigrationOptions,
|
|
dryRun: boolean,
|
|
): Promise<ResumeStart> {
|
|
if (dryRun || options.limit === undefined) {
|
|
return {
|
|
strategy: options.afterMatchId ? 'cursor' : 'none',
|
|
...(options.afterMatchId
|
|
? { startedAfterMatchId: options.afterMatchId }
|
|
: {}),
|
|
};
|
|
}
|
|
if (options.afterMatchId) {
|
|
return {
|
|
strategy: 'cursor',
|
|
startedAfterMatchId: options.afterMatchId,
|
|
};
|
|
}
|
|
const checkpoint = await db
|
|
.collection('competition_migration_checkpoint')
|
|
.findOne({ _id: migrationRunId });
|
|
const checkpointMatchId = optionalIdString(checkpoint?.lastMatchId);
|
|
if (checkpointMatchId) assertMatchCursor(checkpointMatchId);
|
|
return {
|
|
strategy: 'checkpoint',
|
|
...(checkpointMatchId ? { startedAfterMatchId: checkpointMatchId } : {}),
|
|
};
|
|
}
|
|
|
|
function resumeReport(
|
|
start: ResumeStart,
|
|
checkpointAfterMatchId: string | undefined,
|
|
hasMore: boolean,
|
|
completed: boolean,
|
|
): CompetitionDomainMigrationResume {
|
|
return {
|
|
strategy: start.strategy,
|
|
...(start.startedAfterMatchId
|
|
? { startedAfterMatchId: start.startedAfterMatchId }
|
|
: {}),
|
|
...(checkpointAfterMatchId ? { checkpointAfterMatchId } : {}),
|
|
hasMore,
|
|
completed,
|
|
};
|
|
}
|
|
|
|
async function persistMigrationCheckpoint(
|
|
db: CompetitionDomainMigrationDb,
|
|
params: {
|
|
migrationRunId: string;
|
|
matchId?: string;
|
|
matchStatus?: CompetitionDomainMigrationMatchResult['status'];
|
|
completed: boolean;
|
|
resetMatchStatus?: boolean;
|
|
observedAt: Date;
|
|
},
|
|
): Promise<void> {
|
|
await db.collection('competition_migration_checkpoint').updateOne(
|
|
{ _id: params.migrationRunId },
|
|
{
|
|
$set: {
|
|
migrationRunId: params.migrationRunId,
|
|
status: params.completed ? 'completed' : 'running',
|
|
...(params.matchId
|
|
? { lastMatchId: persistenceId(params.matchId) }
|
|
: {}),
|
|
...(params.matchStatus ? { lastMatchStatus: params.matchStatus } : {}),
|
|
updatedAt: params.observedAt,
|
|
},
|
|
$setOnInsert: {
|
|
_id: params.migrationRunId,
|
|
createdAt: params.observedAt,
|
|
},
|
|
...(params.resetMatchStatus ? { $unset: { lastMatchStatus: 1 } } : {}),
|
|
},
|
|
{ upsert: true },
|
|
);
|
|
}
|
|
|
|
async function ensureCompetitionDomainIndexes(
|
|
db: CompetitionDomainMigrationDb,
|
|
dryRun: boolean,
|
|
): Promise<CompetitionDomainIndexPreflight> {
|
|
if (dryRun) {
|
|
return {
|
|
status: 'dry-run',
|
|
requiredIndexes: COMPETITION_DOMAIN_INVARIANT_INDEXES.length,
|
|
ensuredIndexes: [],
|
|
conflicts: [],
|
|
};
|
|
}
|
|
|
|
const ensuredIndexes: string[] = [];
|
|
const conflicts: CompetitionDomainIndexConflict[] = [];
|
|
for (const index of COMPETITION_DOMAIN_INVARIANT_INDEXES) {
|
|
try {
|
|
const createdName = await db
|
|
.collection(index.collection)
|
|
.createIndex(index.key, index.options);
|
|
ensuredIndexes.push(createdName);
|
|
} catch (error) {
|
|
conflicts.push(indexConflict(index, error));
|
|
}
|
|
}
|
|
return {
|
|
status: conflicts.length > 0 ? 'blocked' : 'ensured',
|
|
requiredIndexes: COMPETITION_DOMAIN_INVARIANT_INDEXES.length,
|
|
ensuredIndexes,
|
|
conflicts,
|
|
};
|
|
}
|
|
|
|
function indexConflict(
|
|
index: CompetitionDomainInvariantIndex,
|
|
error: unknown,
|
|
): CompetitionDomainIndexConflict {
|
|
const record = isRecord(error) ? error : {};
|
|
const code =
|
|
typeof record.code === 'number' && Number.isInteger(record.code)
|
|
? record.code
|
|
: undefined;
|
|
const keyPattern = isRecord(record.keyPattern)
|
|
? (canonicalValue(record.keyPattern) as Record<string, unknown>)
|
|
: undefined;
|
|
const keyValue =
|
|
record.keyValue === undefined ? undefined : canonicalValue(record.keyValue);
|
|
return {
|
|
collection: index.collection,
|
|
indexName: index.options.name,
|
|
key: canonicalValue(index.key) as Record<string, unknown>,
|
|
...(code === undefined ? {} : { code }),
|
|
...(keyPattern ? { keyPattern } : {}),
|
|
...(keyValue === undefined ? {} : { keyValue }),
|
|
message: error instanceof Error ? error.message : String(error),
|
|
};
|
|
}
|
|
|
|
async function scanMatches(
|
|
db: CompetitionDomainMigrationDb,
|
|
limit: number | undefined,
|
|
afterMatchId: string | undefined,
|
|
): Promise<{ matches: AnyDocument[]; hasMore: boolean }> {
|
|
const scanned = await readCursor(
|
|
db
|
|
.collection('match')
|
|
.find({
|
|
...MATCH_SCAN_FILTER,
|
|
...(afterMatchId ? { _id: { $gt: persistenceId(afterMatchId) } } : {}),
|
|
})
|
|
.sort({ _id: 1 })
|
|
.limit(limit === undefined ? 0 : limit + 1),
|
|
);
|
|
if (limit === undefined) return { matches: scanned, hasMore: false };
|
|
return {
|
|
matches: scanned.slice(0, limit),
|
|
hasMore: scanned.length > limit,
|
|
};
|
|
}
|
|
|
|
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,
|
|
};
|
|
}
|
|
|
|
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
|
|
db,
|
|
plan,
|
|
session,
|
|
);
|
|
if (uniquenessConflicts.length > 0) {
|
|
await persistQuarantine(
|
|
db,
|
|
currentMatch,
|
|
uniquenessConflicts,
|
|
plan.warnings,
|
|
migrationRunId,
|
|
options.now ?? new Date(),
|
|
session,
|
|
);
|
|
await session.commitTransaction();
|
|
return {
|
|
status: 'quarantined',
|
|
matchId,
|
|
warnings: plan.warnings,
|
|
reasons: uniquenessConflicts,
|
|
};
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
interface UniqueIdentityCheck {
|
|
collection: 'competition' | 'competition_fact' | 'tournament_code_assignment';
|
|
indexName: string;
|
|
filter: Record<string, unknown>;
|
|
expectedDocumentId: string;
|
|
}
|
|
|
|
async function findReadyPlanUniquenessConflicts(
|
|
db: CompetitionDomainMigrationDb,
|
|
plan: ReadyCompetitionMigrationPlan,
|
|
session: CompetitionDomainMigrationSession,
|
|
): Promise<CompetitionMigrationIssue[]> {
|
|
const checks: UniqueIdentityCheck[] = [
|
|
{
|
|
collection: 'competition',
|
|
indexName: 'matchId_1',
|
|
filter: { matchId: persistenceId(plan.competition.matchId) },
|
|
expectedDocumentId: plan.competition.id,
|
|
},
|
|
];
|
|
|
|
for (const fact of plan.facts) {
|
|
checks.push(
|
|
{
|
|
collection: 'competition_fact',
|
|
indexName: 'competitionId_1_revision_1_ordinalWithinRevision_1',
|
|
filter: {
|
|
competitionId: persistenceId(fact.competitionId),
|
|
revision: fact.revision,
|
|
ordinalWithinRevision: fact.ordinalWithinRevision,
|
|
},
|
|
expectedDocumentId: fact.id,
|
|
},
|
|
{
|
|
collection: 'competition_fact',
|
|
indexName: 'competitionId_1_commandId_1_ordinalWithinRevision_1',
|
|
filter: {
|
|
competitionId: persistenceId(fact.competitionId),
|
|
commandId: fact.commandId,
|
|
ordinalWithinRevision: fact.ordinalWithinRevision,
|
|
},
|
|
expectedDocumentId: fact.id,
|
|
},
|
|
);
|
|
if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') {
|
|
checks.push({
|
|
collection: 'competition_fact',
|
|
indexName: 'evidence.riotMatchId_1',
|
|
filter: {
|
|
type: 'game-accepted',
|
|
'evidence.riotMatchId': fact.evidence.riotMatchId,
|
|
},
|
|
expectedDocumentId: fact.id,
|
|
});
|
|
}
|
|
}
|
|
|
|
for (const assignment of plan.assignments) {
|
|
if (assignment.state === 'reserved' || assignment.state === 'used') {
|
|
checks.push(
|
|
{
|
|
collection: 'tournament_code_assignment',
|
|
indexName: 'gameSlotId_1',
|
|
filter: {
|
|
gameSlotId: persistenceId(assignment.gameSlotId),
|
|
state: { $in: ['reserved', 'used'] },
|
|
},
|
|
expectedDocumentId: assignment.id,
|
|
},
|
|
{
|
|
collection: 'tournament_code_assignment',
|
|
indexName: 'tournamentCodeId_1',
|
|
filter: {
|
|
tournamentCodeId: persistenceId(assignment.tournamentCodeId),
|
|
state: { $in: ['reserved', 'used'] },
|
|
},
|
|
expectedDocumentId: assignment.id,
|
|
},
|
|
);
|
|
}
|
|
if (assignment.riotMatchId) {
|
|
checks.push({
|
|
collection: 'tournament_code_assignment',
|
|
indexName: 'riotMatchId_1',
|
|
filter: { riotMatchId: assignment.riotMatchId },
|
|
expectedDocumentId: assignment.id,
|
|
});
|
|
}
|
|
}
|
|
|
|
const conflicts: CompetitionMigrationIssue[] = [];
|
|
// Mongo sessions do not support parallel operations inside one transaction.
|
|
for (const check of checks) {
|
|
const existing = await db
|
|
.collection(check.collection)
|
|
.findOne(check.filter, { session });
|
|
if (!existing || idString(existing._id) === check.expectedDocumentId) {
|
|
continue;
|
|
}
|
|
conflicts.push({
|
|
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
|
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
|
|
details: {
|
|
collection: check.collection,
|
|
indexName: check.indexName,
|
|
key: canonicalValue(check.filter) as Record<string, unknown>,
|
|
expectedDocumentId: check.expectedDocumentId,
|
|
conflictingDocumentId: idString(existing._id),
|
|
...(existing.competitionId
|
|
? { conflictingCompetitionId: idString(existing.competitionId) }
|
|
: {}),
|
|
},
|
|
});
|
|
}
|
|
return conflicts;
|
|
}
|
|
|
|
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 = arrayOf(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,
|
|
// Native collection reads bypass the MatchSchema default. Historical
|
|
// documents without a persisted gameMode still executed as pair mode via
|
|
// the runtime fallback.
|
|
gameMode: match.gameMode ?? 'pair',
|
|
...(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.');
|
|
}
|
|
if (options.afterMatchId !== undefined) {
|
|
assertMatchCursor(options.afterMatchId);
|
|
}
|
|
}
|
|
|
|
function assertMatchCursor(value: string): void {
|
|
if (!/^[a-f\d]{24}$/i.test(value)) {
|
|
throw new Error(
|
|
'Competition migration afterMatchId must be a 24-character hexadecimal Match ObjectId.',
|
|
);
|
|
}
|
|
}
|
|
|
|
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 (hasHexString(value)) {
|
|
const rendered = value.toHexString();
|
|
if (typeof rendered === 'string') return rendered;
|
|
}
|
|
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 (hasHexString(value)) {
|
|
const rendered = value.toHexString();
|
|
if (typeof rendered === 'string') return rendered;
|
|
}
|
|
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;
|
|
}
|
|
|
|
function hasHexString(value: unknown): value is { toHexString(): unknown } {
|
|
return (
|
|
value !== null &&
|
|
typeof value === 'object' &&
|
|
'toHexString' in value &&
|
|
typeof value.toHexString === 'function'
|
|
);
|
|
}
|