1126 lines
35 KiB
TypeScript
1126 lines
35 KiB
TypeScript
import mongoose from 'mongoose';
|
|
import {
|
|
migrateCompetitionDomain,
|
|
type CompetitionDomainMigrationDb,
|
|
type CompetitionDomainMigrationSession,
|
|
} from './competition-domain-runner';
|
|
|
|
describe('migrateCompetitionDomain', () => {
|
|
it('defaults to a side-effect-free dry run and reports the deterministic plan', async () => {
|
|
const match = readyMatch();
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive()],
|
|
tournamentCode: [usedTournamentCode(match)],
|
|
});
|
|
const startSession = jest.fn(async () => new FakeSession());
|
|
|
|
const result = await migrateCompetitionDomain(db, { startSession });
|
|
|
|
expect(result.mode).toBe('dry-run');
|
|
expect(result.summary).toMatchObject({
|
|
scanned: 1,
|
|
ready: 1,
|
|
applied: 0,
|
|
quarantined: 0,
|
|
failed: 0,
|
|
unclassified: 0,
|
|
factsPlanned: 1,
|
|
assignmentsPlanned: 1,
|
|
});
|
|
expect(result.matches[0]).toMatchObject({
|
|
status: 'ready',
|
|
factCount: 1,
|
|
assignmentCount: 1,
|
|
});
|
|
if (result.matches[0].status !== 'ready') {
|
|
throw new Error('Expected a ready dry-run result.');
|
|
}
|
|
expect(result.matches[0].planHash).toMatch(/^sha256:[a-f0-9]{64}$/);
|
|
const repeated = await migrateCompetitionDomain(db);
|
|
expect(repeated.matches[0]).toMatchObject({ status: 'ready' });
|
|
if (repeated.matches[0].status !== 'ready') {
|
|
throw new Error('Expected a repeated ready dry-run result.');
|
|
}
|
|
expect(repeated.matches[0].planHash).toBe(result.matches[0].planHash);
|
|
expect(startSession).not.toHaveBeenCalled();
|
|
expect(db.writeCount).toBe(0);
|
|
expect(db.docs('competition')).toHaveLength(0);
|
|
expect(db.createdIndexes).toHaveLength(0);
|
|
});
|
|
|
|
it('reports apply-time global identity conflicts during dry-run without writes', async () => {
|
|
const riotMatchId = 'KR_DRY_RUN_GLOBAL_CONFLICT';
|
|
const match = readyMatch(riotMatchId);
|
|
const conflictingFactId = objectId();
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive(riotMatchId)],
|
|
tournamentCode: [usedTournamentCode(match, riotMatchId)],
|
|
competition_fact: [
|
|
{
|
|
_id: conflictingFactId,
|
|
competitionId: objectId(),
|
|
type: 'game-accepted',
|
|
evidence: { type: 'riot', riotMatchId },
|
|
},
|
|
],
|
|
});
|
|
|
|
const dryRun = await migrateCompetitionDomain(db);
|
|
|
|
expect(dryRun.summary).toMatchObject({
|
|
scanned: 1,
|
|
ready: 0,
|
|
applied: 0,
|
|
quarantined: 1,
|
|
failed: 0,
|
|
});
|
|
expect(dryRun.matches[0]).toMatchObject({ status: 'quarantined' });
|
|
if (dryRun.matches[0].status !== 'quarantined') {
|
|
throw new Error('Expected a quarantined dry-run result.');
|
|
}
|
|
const conflict = dryRun.matches[0].reasons.find(
|
|
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
|
);
|
|
expect(conflict?.details?.collection).toBe('competition_fact');
|
|
expect(conflict?.details?.indexName).toBe('evidence.riotMatchId_1');
|
|
expect(conflict?.details?.conflictingDocumentId).toBe(
|
|
conflictingFactId.toHexString(),
|
|
);
|
|
expect(db.writeCount).toBe(0);
|
|
expect(db.createdIndexes).toHaveLength(0);
|
|
|
|
const applied = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(applied.summary).toMatchObject({ applied: 0, quarantined: 1 });
|
|
expect(applied.matches[0]).toEqual(dryRun.matches[0]);
|
|
});
|
|
|
|
it.each([
|
|
['absent', (match: AnyDoc) => delete match.gameMode],
|
|
['null', (match: AnyDoc) => (match.gameMode = null)],
|
|
])(
|
|
'restores the historical pair default when raw Mongo Match gameMode is %s',
|
|
async (_label, omitGameMode) => {
|
|
const match = readyMatch();
|
|
omitGameMode(match);
|
|
const before = canonical(match);
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive()],
|
|
tournamentCode: [usedTournamentCode(match)],
|
|
});
|
|
|
|
const result = await migrateCompetitionDomain(db);
|
|
|
|
expect(result.summary).toMatchObject({
|
|
scanned: 1,
|
|
ready: 1,
|
|
quarantined: 0,
|
|
failed: 0,
|
|
});
|
|
expect(result.matches[0]).toMatchObject({
|
|
status: 'ready',
|
|
factCount: 1,
|
|
assignmentCount: 1,
|
|
});
|
|
expect(canonical(db.docs('match')[0])).toBe(before);
|
|
expect(db.writeCount).toBe(0);
|
|
},
|
|
);
|
|
|
|
it('keeps an explicitly unknown raw Mongo Match gameMode quarantined', async () => {
|
|
const match = readyMatch();
|
|
match.gameMode = 'future-mode';
|
|
const db = new MemoryMigrationDb({ match: [match] });
|
|
|
|
const result = await migrateCompetitionDomain(db);
|
|
|
|
expect(result.summary).toMatchObject({
|
|
scanned: 1,
|
|
ready: 0,
|
|
quarantined: 1,
|
|
failed: 0,
|
|
});
|
|
expect(result.matches[0]).toMatchObject({
|
|
status: 'quarantined',
|
|
reasons: [
|
|
expect.objectContaining({ code: 'UNSUPPORTED_LEGACY_GAME_MODE' }),
|
|
],
|
|
});
|
|
expect(db.writeCount).toBe(0);
|
|
});
|
|
|
|
it('applies one Match atomically and converges on an already-applied replay', async () => {
|
|
const match = readyMatch();
|
|
const originalResult = canonical(match.result);
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive()],
|
|
tournamentCode: [usedTournamentCode(match)],
|
|
});
|
|
const sessions: FakeSession[] = [];
|
|
const startSession = jest.fn(async () => {
|
|
const session = new FakeSession();
|
|
sessions.push(session);
|
|
return session;
|
|
});
|
|
|
|
const first = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession,
|
|
});
|
|
|
|
expect(first.summary).toMatchObject({
|
|
scanned: 1,
|
|
applied: 1,
|
|
alreadyApplied: 0,
|
|
failed: 0,
|
|
});
|
|
expect(db.docs('competition')).toHaveLength(1);
|
|
expect(db.docs('competition_fact')).toHaveLength(1);
|
|
expect(db.docs('competition_fact')[0].evidence).toMatchObject({
|
|
type: 'riot',
|
|
riotMatchId: 'KR_MIGRATION_1',
|
|
payloadHash: expect.stringMatching(/^sha256:[a-f0-9]{64}$/),
|
|
});
|
|
expect(db.docs('tournament_code_assignment')).toHaveLength(1);
|
|
expect(db.docs('competition_migration_quarantine')).toHaveLength(0);
|
|
expect(String(db.docs('match')[0].competitionId)).toBe(
|
|
first.matches[0].competitionId,
|
|
);
|
|
expect(canonical(db.docs('match')[0].result)).toBe(originalResult);
|
|
expect(sessions[0]).toMatchObject({
|
|
started: 1,
|
|
committed: 1,
|
|
aborted: 0,
|
|
ended: 1,
|
|
});
|
|
|
|
const second = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession,
|
|
});
|
|
|
|
expect(second.summary).toMatchObject({
|
|
scanned: 1,
|
|
applied: 0,
|
|
alreadyApplied: 1,
|
|
failed: 0,
|
|
});
|
|
expect(db.docs('competition')).toHaveLength(1);
|
|
expect(db.docs('competition_fact')).toHaveLength(1);
|
|
expect(db.docs('tournament_code_assignment')).toHaveLength(1);
|
|
expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
|
|
});
|
|
|
|
it('persists the source voidedAt timestamp without synthesizing it from usedAt', async () => {
|
|
const match = readyMatch('KR_VOIDED_TIMESTAMP');
|
|
const code = usedTournamentCode(match, 'KR_VOIDED_TIMESTAMP');
|
|
code.state = 'voided';
|
|
code.voidedAt = new Date('2026-07-03T00:00:00.000Z');
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive('KR_VOIDED_TIMESTAMP')],
|
|
tournamentCode: [code],
|
|
});
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(result.summary).toMatchObject({ applied: 1, failed: 0 });
|
|
expect(db.docs('tournament_code_assignment')).toContainEqual(
|
|
expect.objectContaining({
|
|
state: 'voided',
|
|
voidedAt: new Date('2026-07-03T00:00:00.000Z'),
|
|
updatedAt: new Date('2026-07-03T00:00:00.000Z'),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('hydrates Riot occurrence evidence and persists the normalized used transition idempotently', async () => {
|
|
const riotMatchId = 'KR_LEGACY_USED_TRANSITION';
|
|
const match = readyMatch(riotMatchId);
|
|
match.updatedAt = new Date('2026-07-03T00:06:00.000Z');
|
|
const legacyOccurrenceAt = new Date(1_782_864_000_000 + 1800 * 1000);
|
|
const code = usedTournamentCode(match, riotMatchId);
|
|
code.reservedAt = new Date('2026-07-03T00:00:00.000Z');
|
|
code.usedAt = legacyOccurrenceAt;
|
|
code.updatedAt = new Date('2026-07-03T00:05:00.000Z');
|
|
const originalCode = canonical(code);
|
|
const archive = riotArchive(riotMatchId);
|
|
archive.raw = {
|
|
info: {
|
|
gameCreation: 1_782_864_000_000,
|
|
gameEndTimestamp: legacyOccurrenceAt.getTime(),
|
|
},
|
|
};
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [archive],
|
|
tournamentCode: [code],
|
|
});
|
|
|
|
const dryRun = await migrateCompetitionDomain(db);
|
|
|
|
expect(dryRun.summary).toMatchObject({
|
|
ready: 1,
|
|
quarantined: 0,
|
|
warnings: 1,
|
|
});
|
|
const warning = dryRun.matches[0].warnings.find(
|
|
({ code: warningCode }) =>
|
|
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
|
|
);
|
|
expect(warning?.details).toMatchObject({
|
|
originalReservedAt: '2026-07-03T00:00:00.000Z',
|
|
originalUsedAt: legacyOccurrenceAt.toISOString(),
|
|
sourceUpdatedAt: '2026-07-03T00:05:00.000Z',
|
|
normalizedUsedAt: '2026-07-03T00:05:00.000Z',
|
|
legacyOccurrenceSource: 'riot-archive-gameEndTimestamp',
|
|
riotMatchId,
|
|
strategy: 'use-persisted-transition-time',
|
|
});
|
|
expect(db.writeCount).toBe(0);
|
|
|
|
const firstApply = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(firstApply.summary).toMatchObject({ applied: 1, failed: 0 });
|
|
expect(db.docs('tournament_code_assignment')).toContainEqual(
|
|
expect.objectContaining({
|
|
state: 'used',
|
|
reservedAt: new Date('2026-07-03T00:00:00.000Z'),
|
|
usedAt: new Date('2026-07-03T00:05:00.000Z'),
|
|
createdAt: new Date('2026-07-03T00:00:00.000Z'),
|
|
updatedAt: new Date('2026-07-03T00:05:00.000Z'),
|
|
}),
|
|
);
|
|
expect(canonical(db.docs('tournamentCode')[0])).toBe(originalCode);
|
|
|
|
const replay = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(replay.summary).toMatchObject({
|
|
applied: 0,
|
|
alreadyApplied: 1,
|
|
failed: 0,
|
|
});
|
|
});
|
|
|
|
it.each([
|
|
[
|
|
'raw.info.gameCreation',
|
|
{ raw: { info: { gameCreation: 1_782_864_000_000 } } },
|
|
],
|
|
[
|
|
'top-level gameCreation',
|
|
{
|
|
gameCreation: 1_782_864_000_000,
|
|
raw: { metadata: { matchId: 'KR_GAME_CREATION_FALLBACK' } },
|
|
},
|
|
],
|
|
])(
|
|
'hydrates the %s Riot occurrence fallback',
|
|
async (_label, archiveFields) => {
|
|
const riotMatchId = 'KR_GAME_CREATION_FALLBACK';
|
|
const match = readyMatch(riotMatchId);
|
|
const code = usedTournamentCode(match, riotMatchId);
|
|
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
|
|
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
|
|
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
|
|
const archive = Object.assign(riotArchive(riotMatchId), archiveFields);
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [archive],
|
|
tournamentCode: [code],
|
|
});
|
|
|
|
const result = await migrateCompetitionDomain(db);
|
|
|
|
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
|
|
const warning = result.matches[0].warnings.find(
|
|
({ code: warningCode }) =>
|
|
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
|
|
);
|
|
expect(warning?.details).toMatchObject({
|
|
originalUsedAt: '2026-07-01T00:00:00.000Z',
|
|
normalizedUsedAt: '2026-07-01T00:20:00.000Z',
|
|
legacyOccurrenceSource: 'riot-archive-gameCreation',
|
|
});
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
['null', null],
|
|
['blank', ''],
|
|
['invalid', 'not-a-date'],
|
|
])(
|
|
'falls back to archive gameCreation when gameEndTimestamp is %s',
|
|
async (_label, invalidGameEnd) => {
|
|
const riotMatchId = 'KR_INVALID_ARCHIVE_GAME_END';
|
|
const match = readyMatch(riotMatchId);
|
|
const code = usedTournamentCode(match, riotMatchId);
|
|
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
|
|
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
|
|
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
|
|
const archive = riotArchive(riotMatchId);
|
|
archive.raw = {
|
|
info: {
|
|
gameEndTimestamp: invalidGameEnd,
|
|
gameCreation: 1_782_864_000_000,
|
|
},
|
|
};
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [archive],
|
|
tournamentCode: [code],
|
|
});
|
|
|
|
const result = await migrateCompetitionDomain(db);
|
|
|
|
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
|
|
const warning = result.matches[0].warnings.find(
|
|
({ code: warningCode }) =>
|
|
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
|
|
);
|
|
expect(warning?.details).toMatchObject({
|
|
legacyOccurrenceSource: 'riot-archive-gameCreation',
|
|
});
|
|
},
|
|
);
|
|
|
|
it('quarantines an ambiguous Match without changing any legacy Match field', async () => {
|
|
const match = ambiguousMatch();
|
|
const before = canonical(match);
|
|
const db = new MemoryMigrationDb({ match: [match] });
|
|
const session = new FakeSession();
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: async () => session,
|
|
});
|
|
|
|
expect(result.summary).toMatchObject({
|
|
scanned: 1,
|
|
quarantined: 1,
|
|
applied: 0,
|
|
failed: 0,
|
|
});
|
|
expect(result.matches[0]).toMatchObject({
|
|
status: 'quarantined',
|
|
reasons: expect.arrayContaining([
|
|
expect.objectContaining({ code: 'AMBIGUOUS_GAME_ASSIGNMENT' }),
|
|
]),
|
|
});
|
|
expect(canonical(db.docs('match')[0])).toBe(before);
|
|
expect(db.docs('competition')).toHaveLength(0);
|
|
expect(db.docs('competition_fact')).toHaveLength(0);
|
|
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
|
|
expect(session).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
|
|
});
|
|
|
|
it('aborts and reports a failed Match when persisted projection replay diverges', async () => {
|
|
const match = readyMatch();
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive()],
|
|
tournamentCode: [usedTournamentCode(match)],
|
|
});
|
|
await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: async () => new FakeSession(),
|
|
});
|
|
db.docs('competition')[0].projection = {
|
|
phase: 'completed',
|
|
corrupt: true,
|
|
};
|
|
const session = new FakeSession();
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: async () => session,
|
|
});
|
|
|
|
expect(result.summary).toMatchObject({
|
|
scanned: 1,
|
|
applied: 0,
|
|
alreadyApplied: 0,
|
|
failed: 1,
|
|
});
|
|
expect(result.matches[0]).toMatchObject({
|
|
status: 'failed',
|
|
error: expect.stringContaining('replay'),
|
|
});
|
|
expect(session).toMatchObject({ committed: 0, aborted: 1, ended: 1 });
|
|
});
|
|
|
|
it('reports apply failures without attempting writes when no session can be created', async () => {
|
|
const db = new MemoryMigrationDb({ match: [readyMatch()] });
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: async () => undefined,
|
|
});
|
|
|
|
expect(result.summary.failed).toBe(1);
|
|
expect(result.matches[0]).toMatchObject({
|
|
status: 'failed',
|
|
error: expect.stringContaining('transaction session'),
|
|
});
|
|
expect(db.writeCount).toBe(0);
|
|
});
|
|
|
|
it('ensures every Competition unique or partial index before the first apply write', async () => {
|
|
const match = readyMatch();
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive()],
|
|
tournamentCode: [usedTournamentCode(match)],
|
|
});
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(result.indexPreflight).toMatchObject({
|
|
status: 'ensured',
|
|
requiredIndexes: 10,
|
|
conflicts: [],
|
|
});
|
|
expect(result.indexPreflight.ensuredIndexes).toHaveLength(10);
|
|
expect(db.createdIndexes).toHaveLength(10);
|
|
expect(db.createdIndexes).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
collection: 'match',
|
|
key: { competitionId: 1 },
|
|
options: expect.objectContaining({
|
|
unique: true,
|
|
partialFilterExpression: {
|
|
competitionId: { $type: 'objectId' },
|
|
},
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
collection: 'competition',
|
|
key: { matchId: 1 },
|
|
options: expect.objectContaining({ unique: true }),
|
|
}),
|
|
expect.objectContaining({
|
|
collection: 'competition_fact',
|
|
key: { 'evidence.riotMatchId': 1 },
|
|
options: expect.objectContaining({
|
|
unique: true,
|
|
partialFilterExpression: expect.any(Object),
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
collection: 'tournament_code_assignment',
|
|
key: { gameSlotId: 1 },
|
|
options: expect.objectContaining({
|
|
unique: true,
|
|
partialFilterExpression: expect.any(Object),
|
|
}),
|
|
}),
|
|
]),
|
|
);
|
|
expect(db.operations.indexOf('create-index')).toBeLessThan(
|
|
db.operations.indexOf('write'),
|
|
);
|
|
});
|
|
|
|
it('blocks apply with a machine-readable report when a required index cannot be created', async () => {
|
|
const match = readyMatch();
|
|
const db = new MemoryMigrationDb({ match: [match] });
|
|
db.indexCreationError = Object.assign(
|
|
new Error('E11000 duplicate key while building competitionId_1'),
|
|
{
|
|
code: 11000,
|
|
keyPattern: { competitionId: 1 },
|
|
keyValue: { competitionId: match._id },
|
|
},
|
|
);
|
|
const startSession = jest.fn(() => Promise.resolve(new FakeSession()));
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession,
|
|
});
|
|
|
|
expect(result.indexPreflight).toMatchObject({
|
|
status: 'blocked',
|
|
conflicts: [
|
|
expect.objectContaining({
|
|
collection: 'match',
|
|
code: 11000,
|
|
keyValue: {
|
|
competitionId: (match._id as mongoose.Types.ObjectId).toHexString(),
|
|
},
|
|
}),
|
|
],
|
|
});
|
|
expect(result.matches).toEqual([]);
|
|
expect(result.summary.scanned).toBe(0);
|
|
expect(startSession).not.toHaveBeenCalled();
|
|
expect(db.writeCount).toBe(0);
|
|
});
|
|
|
|
it('quarantines a later Match that reuses an already accepted global Riot identity', async () => {
|
|
const firstMatch = readyMatch('KR_SHARED_MIGRATION');
|
|
const secondMatch = readyMatch('KR_SHARED_MIGRATION');
|
|
const db = new MemoryMigrationDb({
|
|
match: [firstMatch, secondMatch],
|
|
riotMatch: [riotArchive('KR_SHARED_MIGRATION')],
|
|
tournamentCode: [
|
|
usedTournamentCode(firstMatch, 'KR_SHARED_MIGRATION'),
|
|
usedTournamentCode(secondMatch, 'KR_SHARED_MIGRATION'),
|
|
],
|
|
});
|
|
|
|
const result = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(result.summary).toMatchObject({ applied: 1, quarantined: 1 });
|
|
expect(result.matches).toContainEqual(
|
|
expect.objectContaining({
|
|
status: 'quarantined',
|
|
reasons: expect.arrayContaining([
|
|
expect.objectContaining({ code: 'GLOBAL_UNIQUE_INDEX_CONFLICT' }),
|
|
]),
|
|
}),
|
|
);
|
|
expect(db.docs('competition_fact')).toHaveLength(1);
|
|
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
|
|
});
|
|
|
|
it('detects the same global identity collision between dry-run plans as sequential apply', async () => {
|
|
const riotMatchId = 'KR_SHARED_DRY_RUN_MIGRATION';
|
|
const firstMatch = readyMatch(riotMatchId);
|
|
const secondMatch = readyMatch(riotMatchId);
|
|
const db = new MemoryMigrationDb({
|
|
match: [firstMatch, secondMatch],
|
|
riotMatch: [riotArchive(riotMatchId)],
|
|
tournamentCode: [
|
|
usedTournamentCode(firstMatch, riotMatchId),
|
|
usedTournamentCode(secondMatch, riotMatchId),
|
|
],
|
|
});
|
|
|
|
const dryRun = await migrateCompetitionDomain(db);
|
|
|
|
expect(dryRun.summary).toMatchObject({ ready: 1, quarantined: 1 });
|
|
expect(dryRun.matches.map(({ status }) => status)).toEqual([
|
|
'ready',
|
|
'quarantined',
|
|
]);
|
|
expect(dryRun.matches[1]).toMatchObject({ status: 'quarantined' });
|
|
if (dryRun.matches[1].status !== 'quarantined') {
|
|
throw new Error('Expected the second dry-run result to be quarantined.');
|
|
}
|
|
expect(
|
|
dryRun.matches[1].reasons.some(
|
|
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
|
),
|
|
).toBe(true);
|
|
expect(db.writeCount).toBe(0);
|
|
|
|
const applied = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(applied.summary).toMatchObject({ applied: 1, quarantined: 1 });
|
|
expect(applied.matches[1]).toEqual(dryRun.matches[1]);
|
|
});
|
|
|
|
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
|
|
const firstMatch = readyMatch('KR_BATCH_1');
|
|
const secondMatch = readyMatch('KR_BATCH_2');
|
|
const db = new MemoryMigrationDb({
|
|
match: [firstMatch, secondMatch],
|
|
riotMatch: [riotArchive('KR_BATCH_1'), riotArchive('KR_BATCH_2')],
|
|
tournamentCode: [
|
|
usedTournamentCode(firstMatch, 'KR_BATCH_1'),
|
|
usedTournamentCode(secondMatch, 'KR_BATCH_2'),
|
|
],
|
|
});
|
|
|
|
const first = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
const second = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(first.summary).toMatchObject({ scanned: 1, applied: 1 });
|
|
expect(first.resume).toMatchObject({
|
|
strategy: 'checkpoint',
|
|
hasMore: true,
|
|
completed: false,
|
|
});
|
|
expect(second.summary).toMatchObject({ scanned: 1, applied: 1 });
|
|
expect(second.matches[0].matchId).not.toBe(first.matches[0].matchId);
|
|
expect(second.resume).toMatchObject({
|
|
strategy: 'checkpoint',
|
|
startedAfterMatchId: first.matches[0].matchId,
|
|
hasMore: false,
|
|
completed: true,
|
|
});
|
|
expect(db.docs('competition')).toHaveLength(2);
|
|
expect(db.docs('competition_migration_checkpoint')).toHaveLength(1);
|
|
});
|
|
|
|
it('does not let an apply checkpoint silently narrow a later dry-run', async () => {
|
|
const firstMatch = readyMatch('KR_DRY_RUN_1');
|
|
const secondMatch = readyMatch('KR_DRY_RUN_2');
|
|
const db = new MemoryMigrationDb({
|
|
match: [firstMatch, secondMatch],
|
|
riotMatch: [riotArchive('KR_DRY_RUN_1'), riotArchive('KR_DRY_RUN_2')],
|
|
tournamentCode: [
|
|
usedTournamentCode(firstMatch, 'KR_DRY_RUN_1'),
|
|
usedTournamentCode(secondMatch, 'KR_DRY_RUN_2'),
|
|
],
|
|
});
|
|
const applied = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
const dryRun = await migrateCompetitionDomain(db, {
|
|
dryRun: true,
|
|
limit: 1,
|
|
});
|
|
|
|
expect(dryRun.resume.strategy).toBe('none');
|
|
expect(dryRun.matches[0].matchId).toBe(applied.matches[0].matchId);
|
|
});
|
|
|
|
it('does not advance a limited-run checkpoint past a failed Match', async () => {
|
|
const match = readyMatch('KR_RETRY_AFTER_FAILURE');
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive('KR_RETRY_AFTER_FAILURE')],
|
|
tournamentCode: [usedTournamentCode(match, 'KR_RETRY_AFTER_FAILURE')],
|
|
});
|
|
|
|
const failed = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
startSession: () => Promise.resolve(undefined),
|
|
});
|
|
|
|
expect(failed.summary).toMatchObject({ scanned: 1, failed: 1 });
|
|
expect(failed.resume).toMatchObject({
|
|
strategy: 'checkpoint',
|
|
hasMore: true,
|
|
completed: false,
|
|
});
|
|
expect(db.docs('competition_migration_checkpoint')).toHaveLength(0);
|
|
|
|
const retried = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(db.docs('competition_migration_checkpoint')).toHaveLength(1);
|
|
expect(retried.matches[0].matchId).toBe(failed.matches[0].matchId);
|
|
expect(retried.summary).toMatchObject({ scanned: 1, applied: 1 });
|
|
});
|
|
|
|
it('durably overrides a later checkpoint before an explicit earlier retry can fail', async () => {
|
|
const retryMatch = readyMatch('KR_EXPLICIT_RETRY');
|
|
const laterMatch = readyMatch('KR_LATER_CHECKPOINT');
|
|
const explicitAfter = '000000000000000000000000';
|
|
const migrationRunId = '20260712-competition-domain';
|
|
const db = new MemoryMigrationDb({
|
|
match: [retryMatch, laterMatch],
|
|
riotMatch: [
|
|
riotArchive('KR_EXPLICIT_RETRY'),
|
|
riotArchive('KR_LATER_CHECKPOINT'),
|
|
],
|
|
tournamentCode: [
|
|
usedTournamentCode(retryMatch, 'KR_EXPLICIT_RETRY'),
|
|
usedTournamentCode(laterMatch, 'KR_LATER_CHECKPOINT'),
|
|
],
|
|
competition_migration_checkpoint: [
|
|
{
|
|
_id: migrationRunId,
|
|
migrationRunId,
|
|
lastMatchId: laterMatch._id,
|
|
status: 'running',
|
|
},
|
|
],
|
|
});
|
|
|
|
const failed = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
afterMatchId: explicitAfter,
|
|
startSession: () => Promise.resolve(undefined),
|
|
});
|
|
|
|
expect(failed.summary).toMatchObject({ scanned: 1, failed: 1 });
|
|
expect(
|
|
String(db.docs('competition_migration_checkpoint')[0].lastMatchId),
|
|
).toBe(explicitAfter);
|
|
|
|
const retried = await migrateCompetitionDomain(db, {
|
|
dryRun: false,
|
|
limit: 1,
|
|
startSession: () => Promise.resolve(new FakeSession()),
|
|
});
|
|
|
|
expect(retried.matches[0].matchId).toBe(failed.matches[0].matchId);
|
|
expect(retried.summary).toMatchObject({ scanned: 1, applied: 1 });
|
|
});
|
|
|
|
it('does not persist an explicit checkpoint override during dry-run', async () => {
|
|
const match = readyMatch('KR_DRY_EXPLICIT_CURSOR');
|
|
const migrationRunId = '20260712-competition-domain';
|
|
const persistedCheckpoint = objectId();
|
|
const db = new MemoryMigrationDb({
|
|
match: [match],
|
|
riotMatch: [riotArchive('KR_DRY_EXPLICIT_CURSOR')],
|
|
tournamentCode: [usedTournamentCode(match, 'KR_DRY_EXPLICIT_CURSOR')],
|
|
competition_migration_checkpoint: [
|
|
{
|
|
_id: migrationRunId,
|
|
migrationRunId,
|
|
lastMatchId: persistedCheckpoint,
|
|
status: 'running',
|
|
},
|
|
],
|
|
});
|
|
|
|
await migrateCompetitionDomain(db, {
|
|
dryRun: true,
|
|
limit: 1,
|
|
afterMatchId: '000000000000000000000000',
|
|
});
|
|
|
|
expect(
|
|
String(db.docs('competition_migration_checkpoint')[0].lastMatchId),
|
|
).toBe(persistedCheckpoint.toHexString());
|
|
expect(db.writeCount).toBe(0);
|
|
});
|
|
});
|
|
|
|
class FakeSession implements CompetitionDomainMigrationSession {
|
|
public started = 0;
|
|
public committed = 0;
|
|
public aborted = 0;
|
|
public ended = 0;
|
|
|
|
startTransaction(): void {
|
|
this.started += 1;
|
|
}
|
|
|
|
async commitTransaction(): Promise<void> {
|
|
this.committed += 1;
|
|
}
|
|
|
|
async abortTransaction(): Promise<void> {
|
|
this.aborted += 1;
|
|
}
|
|
|
|
async endSession(): Promise<void> {
|
|
this.ended += 1;
|
|
}
|
|
}
|
|
|
|
type AnyDoc = Record<string, any> & { _id: unknown };
|
|
|
|
class MemoryMigrationDb implements CompetitionDomainMigrationDb {
|
|
private readonly collections = new Map<string, AnyDoc[]>();
|
|
public writeCount = 0;
|
|
public readonly createdIndexes: Array<{
|
|
collection: string;
|
|
key: Record<string, unknown>;
|
|
options: Record<string, unknown>;
|
|
}> = [];
|
|
public readonly operations: string[] = [];
|
|
public indexCreationError?: Error;
|
|
|
|
constructor(seed: Record<string, AnyDoc[]> = {}) {
|
|
for (const [name, docs] of Object.entries(seed)) {
|
|
this.collections.set(name, docs);
|
|
}
|
|
}
|
|
|
|
docs(name: string): AnyDoc[] {
|
|
const docs = this.collections.get(name) ?? [];
|
|
this.collections.set(name, docs);
|
|
return docs;
|
|
}
|
|
|
|
collection(name: string) {
|
|
const owner = this;
|
|
return {
|
|
createIndex(
|
|
key: Record<string, unknown>,
|
|
options: Record<string, unknown>,
|
|
) {
|
|
owner.operations.push('create-index');
|
|
if (owner.indexCreationError) {
|
|
const error = owner.indexCreationError;
|
|
owner.indexCreationError = undefined;
|
|
return Promise.reject(error);
|
|
}
|
|
owner.createdIndexes.push({ collection: name, key, options });
|
|
return Promise.resolve(
|
|
typeof options.name === 'string'
|
|
? options.name
|
|
: Object.keys(key).join('_'),
|
|
);
|
|
},
|
|
find(filter: Record<string, unknown>) {
|
|
return new MemoryCursor(() =>
|
|
owner.docs(name).filter((doc) => matches(doc, filter)),
|
|
);
|
|
},
|
|
async findOne(filter: Record<string, unknown>) {
|
|
return owner.docs(name).find((doc) => matches(doc, filter)) ?? null;
|
|
},
|
|
async updateOne(
|
|
filter: Record<string, unknown>,
|
|
update: Record<string, Record<string, unknown>>,
|
|
options: { upsert?: boolean } = {},
|
|
) {
|
|
owner.operations.push('write');
|
|
owner.writeCount += 1;
|
|
const docs = owner.docs(name);
|
|
let doc = docs.find((candidate) => matches(candidate, filter));
|
|
const inserted = !doc && options.upsert === true;
|
|
if (inserted) {
|
|
doc = materializeEqualityFilter(filter);
|
|
docs.push(doc);
|
|
}
|
|
if (!doc) return { matchedCount: 0, modifiedCount: 0 };
|
|
if (inserted) Object.assign(doc, update.$setOnInsert ?? {});
|
|
Object.assign(doc, update.$set ?? {});
|
|
for (const field of Object.keys(update.$unset ?? {})) delete doc[field];
|
|
return {
|
|
matchedCount: inserted ? 0 : 1,
|
|
modifiedCount: 1,
|
|
upsertedCount: inserted ? 1 : 0,
|
|
};
|
|
},
|
|
async deleteOne(filter: Record<string, unknown>) {
|
|
owner.operations.push('write');
|
|
owner.writeCount += 1;
|
|
const docs = owner.docs(name);
|
|
const index = docs.findIndex((doc) => matches(doc, filter));
|
|
if (index === -1) return { deletedCount: 0 };
|
|
docs.splice(index, 1);
|
|
return { deletedCount: 1 };
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
class MemoryCursor {
|
|
private sortSpec: Record<string, 1 | -1> = {};
|
|
private max = 0;
|
|
|
|
constructor(private readonly read: () => AnyDoc[]) {}
|
|
|
|
sort(spec: Record<string, 1 | -1>): this {
|
|
this.sortSpec = spec;
|
|
return this;
|
|
}
|
|
|
|
limit(limit: number): this {
|
|
this.max = limit;
|
|
return this;
|
|
}
|
|
|
|
async *[Symbol.asyncIterator](): AsyncIterator<AnyDoc> {
|
|
const entries = [...this.read()].sort((left, right) => {
|
|
for (const [key, direction] of Object.entries(this.sortSpec)) {
|
|
const compared = String(readPath(left, key)).localeCompare(
|
|
String(readPath(right, key)),
|
|
);
|
|
if (compared !== 0) return compared * direction;
|
|
}
|
|
return 0;
|
|
});
|
|
for (const doc of this.max > 0 ? entries.slice(0, this.max) : entries) {
|
|
yield doc;
|
|
}
|
|
}
|
|
}
|
|
|
|
function matches(doc: AnyDoc, filter: Record<string, unknown>): boolean {
|
|
return Object.entries(filter).every(([key, expected]) => {
|
|
if (key === '$or') {
|
|
return (expected as Record<string, unknown>[]).some((candidate) =>
|
|
matches(doc, candidate),
|
|
);
|
|
}
|
|
const actual = readPath(doc, key);
|
|
if (isRecord(expected)) {
|
|
if ('$exists' in expected) {
|
|
return (actual !== undefined) === Boolean(expected.$exists);
|
|
}
|
|
if ('$in' in expected) {
|
|
return (expected.$in as unknown[]).some((candidate) =>
|
|
sameValue(actual, candidate),
|
|
);
|
|
}
|
|
if ('$gt' in expected) {
|
|
return String(actual) > String(expected.$gt);
|
|
}
|
|
}
|
|
return sameValue(actual, expected);
|
|
});
|
|
}
|
|
|
|
function readPath(value: unknown, path: string): unknown {
|
|
return path.split('.').reduce<unknown>((current, segment) => {
|
|
if (Array.isArray(current) && /^\d+$/.test(segment)) {
|
|
return current[Number(segment)];
|
|
}
|
|
return isRecord(current) ? current[segment] : undefined;
|
|
}, value);
|
|
}
|
|
|
|
function materializeEqualityFilter(filter: Record<string, unknown>): AnyDoc {
|
|
return Object.fromEntries(
|
|
Object.entries(filter).filter(
|
|
([key, value]) => !key.startsWith('$') && !isRecord(value),
|
|
),
|
|
) as AnyDoc;
|
|
}
|
|
|
|
function sameValue(left: unknown, right: unknown): boolean {
|
|
return String(left) === String(right);
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, any> {
|
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
}
|
|
|
|
function readyMatch(riotMatchId = 'KR_MIGRATION_1'): AnyDoc {
|
|
const matchId = objectId();
|
|
const codeId = objectId();
|
|
return {
|
|
_id: matchId,
|
|
communityId: objectId(),
|
|
gameMode: 'pair',
|
|
gameCount: 1,
|
|
status: 'in-progress',
|
|
participants: [],
|
|
teams: [legacyTeam(1), legacyTeam(2)],
|
|
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
|
|
tournamentCodeIds: [codeId],
|
|
result: {
|
|
riotMatchIds: [riotMatchId],
|
|
games: [
|
|
{
|
|
gameNumber: 1,
|
|
riotMatchId,
|
|
blueTeamIndex: 1,
|
|
redTeamIndex: 2,
|
|
winnerTeamIndex: 1,
|
|
winnerSide: 'blue',
|
|
gameCreation: 1_782_864_000_000,
|
|
gameDuration: 1800,
|
|
participants: [],
|
|
},
|
|
],
|
|
seriesResults: [],
|
|
},
|
|
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
|
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
|
};
|
|
}
|
|
|
|
function usedTournamentCode(
|
|
match = readyMatch(),
|
|
riotMatchId = 'KR_MIGRATION_1',
|
|
): AnyDoc {
|
|
return {
|
|
_id: match.tournamentCodeIds[0],
|
|
matchId: match._id,
|
|
state: 'used',
|
|
gameNumber: 1,
|
|
riotMatchId,
|
|
reservedAt: new Date('2026-07-01T00:30:00.000Z'),
|
|
usedAt: new Date('2026-07-01T01:00:00.000Z'),
|
|
};
|
|
}
|
|
|
|
function riotArchive(matchId = 'KR_MIGRATION_1'): AnyDoc {
|
|
return {
|
|
_id: objectId(),
|
|
matchId,
|
|
raw: { metadata: { matchId } },
|
|
};
|
|
}
|
|
|
|
function ambiguousMatch(): AnyDoc {
|
|
const match = readyMatch();
|
|
match.teams = [legacyTeam(1), legacyTeam(2), legacyTeam(3), legacyTeam(4)];
|
|
match.gameSchedule = [
|
|
{ gameNumber: 7, teamAIndex: 1, teamBIndex: 2 },
|
|
{ gameNumber: 7, teamAIndex: 3, teamBIndex: 4 },
|
|
];
|
|
match.tournamentCodeIds = [];
|
|
match.result = {
|
|
games: [
|
|
{
|
|
gameNumber: 7,
|
|
riotMatchId: 'KR_AMBIGUOUS',
|
|
blueTeamIndex: 1,
|
|
redTeamIndex: 2,
|
|
winnerTeamIndex: 1,
|
|
winnerSide: 'blue',
|
|
participants: [],
|
|
},
|
|
],
|
|
seriesResults: [],
|
|
};
|
|
return match;
|
|
}
|
|
|
|
function legacyTeam(teamIndex: number) {
|
|
return {
|
|
teamIndex,
|
|
name: `${teamIndex}팀`,
|
|
captainUserId: objectId(),
|
|
members: [],
|
|
};
|
|
}
|
|
|
|
function objectId(): mongoose.Types.ObjectId {
|
|
return new mongoose.Types.ObjectId();
|
|
}
|
|
|
|
function canonical(value: unknown): string {
|
|
return JSON.stringify(value, (_key, child) => {
|
|
if (child instanceof mongoose.Types.ObjectId) return child.toHexString();
|
|
if (child instanceof Date) return child.toISOString();
|
|
return child;
|
|
});
|
|
}
|