feat: add resumable competition migration runner

This commit is contained in:
dahyeon committed 2026-07-12 19:34:52 +00:00
1 parent 55e5b8df70
commit ee4c3eeb27
5 files changed
+1608

No files matched your search

@@ -0,0 +1,450 @@
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,
});
expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0);
expect(db.docs('competition')).toHaveLength(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('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);
});
});
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;
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 {
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.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 ?? {});
return {
matchedCount: inserted ? 0 : 1,
modifiedCount: 1,
upsertedCount: inserted ? 1 : 0,
};
},
async deleteOne(filter: Record<string, unknown>) {
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),
);
}
}
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(): 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: ['KR_MIGRATION_1'],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_MIGRATION_1',
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()): AnyDoc {
return {
_id: match.tournamentCodeIds[0],
matchId: match._id,
state: 'used',
gameNumber: 1,
riotMatchId: 'KR_MIGRATION_1',
reservedAt: new Date('2026-07-01T00:30:00.000Z'),
usedAt: new Date('2026-07-01T01:00:00.000Z'),
};
}
function riotArchive(): AnyDoc {
return {
_id: objectId(),
matchId: 'KR_MIGRATION_1',
raw: { metadata: { matchId: 'KR_MIGRATION_1' } },
};
}
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;
});
}