fix: close competition cutover integrity gaps

This commit is contained in:
dahyeon committed 2026-07-12 21:22:22 +00:00
1 parent 7ea2002975
commit 683d602d63
57 files changed
+4805 -1582

No files matched your search

@@ -2,6 +2,7 @@ import {
TournamentCodeSchema,
type MatchDocument,
} from '../global/database/schema';
import { Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service';
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
@@ -13,11 +14,6 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
ensureGameSchedule(match: MatchDocument): void;
replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<unknown>;
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
};
@@ -37,6 +33,21 @@ function createSession() {
};
}
function mongoQuery<T>(value: T) {
const query = {
exec: jest.fn().mockResolvedValue(value),
lean: jest.fn(),
limit: jest.fn(),
select: jest.fn(),
session: jest.fn(),
};
query.lean.mockReturnValue(query);
query.limit.mockReturnValue(query);
query.select.mockReturnValue(query);
query.session.mockReturnValue(query);
return query;
}
function createService() {
return new TournamentCodeService(
{} as never,
@@ -51,6 +62,7 @@ interface MatchOverrides {
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
doubleElimination?: MatchDocument['doubleElimination'];
tournamentCodeIds?: mongoose.Types.ObjectId[];
gameSchedule?: Array<{
gameNumber: number;
roundNumber?: number;
@@ -261,6 +273,43 @@ describe('TournamentCodeService round-robin scheduling', () => {
).toMatchObject({ gameCount: 3, requiredWins: 2 });
});
it('builds a missing bracket from already-persisted authoritative seeds', () => {
const service = createService();
const match = createMatch({
gameMode: 'double-elimination',
gameCount: 3,
teams: Array.from({ length: 4 }, (_, index) => ({
teamIndex: index + 1,
})),
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
resetFinalCreated: false,
seeds: [
{ seedNumber: 1, teamIndex: 3 },
{ seedNumber: 2, teamIndex: 1 },
{ seedNumber: 3, teamIndex: 4 },
{ seedNumber: 4, teamIndex: 2 },
],
bracketMatches: [],
placements: {},
events: [],
},
});
const random = jest.spyOn(Math, 'random').mockReturnValue(0);
service.ensureGameSchedule(match);
expect(match.doubleElimination?.seeds).toEqual([
{ seedNumber: 1, teamIndex: 3 },
{ seedNumber: 2, teamIndex: 1 },
{ seedNumber: 3, teamIndex: 4 },
{ seedNumber: 4, teamIndex: 2 },
]);
expect(random).not.toHaveBeenCalled();
random.mockRestore();
});
it('expands double-elimination winner bracket series into code slots', async () => {
const TournamentCodeModel = {
find: jest.fn().mockReturnValue({
@@ -437,6 +486,50 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(slots).toEqual([]);
});
it('shows the active replacement when a reversed terminal code shares its game number', async () => {
const oldCodeId = new mongoose.Types.ObjectId();
const replacementCodeId = new mongoose.Types.ObjectId();
const TournamentCodeModel = {
find: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([
{
_id: replacementCodeId,
code: 'NEW-CODE',
gameNumber: 1,
state: 'reserved',
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
{
_id: oldCodeId,
code: 'OLD-CODE',
gameNumber: 1,
state: 'released',
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
]),
}),
};
const service = new TournamentCodeService(
{ getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never,
createAuctionRedisService() as never,
) as unknown as TournamentCodeServiceInternals;
const match = createMatch({
gameCount: 1,
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [oldCodeId, replacementCodeId],
});
const slots = await service.buildSlots(match);
expect(slots[0]).toEqual(
expect.objectContaining({
gameNumber: 1,
code: 'NEW-CODE',
state: 'reserved',
}),
);
});
});
describe('TournamentCodeService bulk upload', () => {
@@ -639,228 +732,278 @@ describe('TournamentCodeService pending match attachment', () => {
});
});
describe('TournamentCodeService code replacement', () => {
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function createCode(overrides: Record<string, unknown>) {
return {
describe('TournamentCodeService Competition assignment safety', () => {
it('does not restore an actively reserved code outside Competition commands', async () => {
const code = {
_id: new mongoose.Types.ObjectId(),
code: 'CODE',
state: 'reserved',
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
matchId: new mongoose.Types.ObjectId(),
gameNumber: 1,
reservedAt: new Date(),
releasedAt: undefined,
riotMatchId: undefined,
save: jest.fn().mockResolvedValue(undefined),
...overrides,
save: jest.fn(),
};
}
function createReplacementFixture(params?: {
currentCode?: Record<string, unknown> | null;
replacementCode?: Record<string, unknown> | null;
match?: MatchDocument;
}) {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const oldCodeId = new mongoose.Types.ObjectId();
const newCodeId = new mongoose.Types.ObjectId();
const match =
params?.match ??
createMatch({
_id: matchId,
communityId,
status: 'in-progress',
gameCount: 1,
participants: Array.from({ length: 10 }, () => ({})),
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [oldCodeId],
} as unknown as MatchOverrides);
const currentCode =
params?.currentCode === null
? null
: createCode({
_id: oldCodeId,
code: 'OLD-CODE',
matchId,
gameNumber: 1,
...(params?.currentCode ?? {}),
});
const replacementCode =
params?.replacementCode === null
? null
: createCode({
_id: newCodeId,
code: 'NEW-CODE',
matchId,
gameNumber: 1,
...(params?.replacementCode ?? {}),
});
const MatchModel = {
findOne: jest.fn().mockReturnValue(queryResult(match)),
};
const TournamentCodeModel = {
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
updateOne: jest.fn().mockReturnValue(queryResult({ modifiedCount: 1 })),
};
const session = createSession();
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn().mockImplementation((modelName: string) => {
if (modelName === 'match') return Promise.resolve(MatchModel);
if (modelName === 'tournamentCode') {
return Promise.resolve(TournamentCodeModel);
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'tournamentCode') {
return Promise.resolve({
findById: jest.fn().mockResolvedValue(code),
});
}
throw new Error(`Unexpected model: ${modelName}`);
if (name === 'match') return Promise.resolve({});
throw new Error(`Unexpected model ${name}`);
}),
};
const auctionRedisService = createAuctionRedisService();
const service = new TournamentCodeService(
connectionService as never,
auctionRedisService as never,
) as unknown as TournamentCodeServiceInternals;
createAuctionRedisService() as never,
);
return {
match,
communityId,
matchId,
currentCode,
replacementCode,
MatchModel,
TournamentCodeModel,
auctionRedisService,
session,
service,
};
}
it('replaces a reserved code on the same game slot', async () => {
const {
match,
communityId,
matchId,
currentCode,
replacementCode,
MatchModel,
TournamentCodeModel,
auctionRedisService,
session,
service,
} = createReplacementFixture();
const slot = await service.replaceForMatchGame({
communityId,
matchId,
gameNumber: 1,
});
expect(slot).toEqual(
expect.objectContaining({
gameNumber: 1,
teamAIndex: 1,
teamBIndex: 2,
code: 'NEW-CODE',
state: 'reserved',
}),
await expect(service.restoreToAvailable(code._id)).rejects.toThrow(
'Active Competition assignments',
);
expect(MatchModel.findOne).toHaveBeenCalledWith({
_id: matchId,
communityId,
});
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
}),
expect.objectContaining({
$set: expect.objectContaining({
state: 'reserved',
matchId,
gameNumber: 1,
}),
}),
expect.objectContaining({ returnDocument: 'after' }),
);
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
`tournament-code:match:${matchId.toString()}:lock`,
expect.any(String),
expect.any(Number),
);
expect(session.startTransaction).toHaveBeenCalledTimes(1);
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith(
`tournament-code:match:${matchId.toString()}:lock`,
expect.any(String),
);
expect(TournamentCodeModel.updateOne).toHaveBeenCalledWith(
{ _id: currentCode?._id },
expect.objectContaining({
$set: expect.objectContaining({ state: 'released' }),
$unset: expect.objectContaining({
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
}),
}),
);
expect(currentCode?.save).not.toHaveBeenCalled();
expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([
replacementCode?._id.toString(),
]);
expect(match.save).toHaveBeenCalled();
expect(code.save).not.toHaveBeenCalled();
});
it('rejects replacement after the game result is collected', async () => {
it('expires a reserved code and releases its assignment and Match binding atomically', async () => {
const codeId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const fixture = createReplacementFixture({
match: createMatch({
_id: matchId,
communityId,
status: 'in-progress',
gameCount: 1,
participants: Array.from({ length: 10 }, () => ({})),
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [new mongoose.Types.ObjectId()],
result: {
riotMatchIds: ['KR_1'],
games: [{ gameNumber: 1 }],
seriesResults: [],
},
} as unknown as MatchOverrides),
const competitionId = new mongoose.Types.ObjectId();
const assignmentId = new mongoose.Types.ObjectId();
const session = createSession();
const code = { _id: codeId, state: 'reserved', matchId };
const codeUpdate = jest.fn().mockReturnValue(mongoQuery(code));
const assignmentUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const matchUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const models = {
tournamentCode: {
find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])),
findOne: jest.fn().mockReturnValue(mongoQuery(code)),
findOneAndUpdate: codeUpdate,
},
tournamentCodeAssignment: {
find: jest.fn().mockReturnValue(
mongoQuery([
{
_id: assignmentId,
competitionId,
state: 'reserved',
},
]),
),
updateOne: assignmentUpdate,
},
competition: {
findById: jest.fn().mockReturnValue(mongoQuery({ matchId })),
},
match: { updateOne: matchUpdate },
};
const service = new TournamentCodeService(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as never,
createAuctionRedisService() as never,
);
await expect(service.markExpired()).resolves.toEqual({
affectedMatchIds: [matchId],
expiredCount: 1,
failedCount: 0,
});
await expect(
fixture.service.replaceForMatchGame({
communityId,
matchId,
gameNumber: 1,
}),
).rejects.toThrow('already has a collected result');
expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled();
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(codeUpdate).toHaveBeenCalledWith(
{
_id: codeId,
expiresAt: { $lte: expect.any(Date) as Date },
state: 'reserved',
},
{
$set: { state: 'expired' },
$unset: {
bracketMatchId: 1,
gameNumber: 1,
matchId: 1,
reservedAt: 1,
},
},
{ returnDocument: 'before', session },
);
expect(assignmentUpdate).toHaveBeenCalledWith(
{ _id: assignmentId, state: 'reserved' },
{
$set: { releasedAt: expect.any(Date) as Date, state: 'released' },
},
{ session },
);
expect(matchUpdate).toHaveBeenCalledWith(
{ _id: matchId },
{ $pull: { tournamentCodeIds: codeId } },
{ session },
);
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('aborts the transaction when no replacement code is available', async () => {
const { match, communityId, matchId, currentCode, session, service } =
createReplacementFixture({
replacementCode: null,
});
it('isolates a used-assignment corruption and still expires the next valid candidate', async () => {
const corruptCodeId = new mongoose.Types.ObjectId();
const validCodeId = new mongoose.Types.ObjectId();
const corruptMatchId = new mongoose.Types.ObjectId();
const validMatchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const validAssignmentId = new mongoose.Types.ObjectId();
const sessions = [createSession(), createSession()];
const codeById = new Map([
[
corruptCodeId.toString(),
{ _id: corruptCodeId, state: 'reserved', matchId: corruptMatchId },
],
[
validCodeId.toString(),
{ _id: validCodeId, state: 'reserved', matchId: validMatchId },
],
]);
const codeUpdate = jest.fn((filter: { _id: mongoose.Types.ObjectId }) =>
mongoQuery(codeById.get(filter._id.toString())),
);
const assignmentUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const matchUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const models = {
tournamentCode: {
find: jest
.fn()
.mockReturnValue(
mongoQuery([{ _id: corruptCodeId }, { _id: validCodeId }]),
),
findOne: jest.fn((filter: { _id: mongoose.Types.ObjectId }) =>
mongoQuery(codeById.get(filter._id.toString())),
),
findOneAndUpdate: codeUpdate,
},
tournamentCodeAssignment: {
find: jest.fn((filter: { tournamentCodeId: mongoose.Types.ObjectId }) =>
mongoQuery(
filter.tournamentCodeId.equals(corruptCodeId)
? [
{
_id: new mongoose.Types.ObjectId(),
competitionId,
state: 'used',
},
]
: [
{
_id: validAssignmentId,
competitionId,
state: 'reserved',
},
],
),
),
updateOne: assignmentUpdate,
},
competition: {
findById: jest
.fn()
.mockReturnValue(mongoQuery({ matchId: validMatchId })),
},
match: { updateOne: matchUpdate },
};
const errorLog = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
const service = new TournamentCodeService(
{
createSession: jest
.fn()
.mockImplementation(() => Promise.resolve(sessions.shift())),
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as never,
createAuctionRedisService() as never,
);
await expect(
service.replaceForMatchGame({ communityId, matchId, gameNumber: 1 }),
).rejects.toThrow('No available tournament code');
expect(currentCode?.save).not.toHaveBeenCalled();
expect(match.save).not.toHaveBeenCalled();
await expect(service.markExpired()).resolves.toEqual({
affectedMatchIds: [validMatchId],
expiredCount: 1,
failedCount: 1,
});
expect(codeUpdate).toHaveBeenCalledTimes(1);
expect(codeUpdate.mock.calls[0][0]).toMatchObject({ _id: validCodeId });
expect(assignmentUpdate).toHaveBeenCalledWith(
{ _id: validAssignmentId, state: 'reserved' },
expect.any(Object),
expect.any(Object),
);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('used Competition assignment'),
);
errorLog.mockRestore();
});
it('leaves a foreign Competition assignment unchanged and reports the candidate failure', async () => {
const codeId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const foreignMatchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const code = { _id: codeId, state: 'reserved', matchId };
const codeUpdate = jest.fn();
const session = createSession();
const models = {
tournamentCode: {
find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])),
findOne: jest.fn().mockReturnValue(mongoQuery(code)),
findOneAndUpdate: codeUpdate,
},
tournamentCodeAssignment: {
find: jest.fn().mockReturnValue(
mongoQuery([
{
_id: new mongoose.Types.ObjectId(),
competitionId,
state: 'reserved',
},
]),
),
updateOne: jest.fn(),
},
competition: {
findById: jest
.fn()
.mockReturnValue(mongoQuery({ matchId: foreignMatchId })),
},
match: { updateOne: jest.fn() },
};
const errorLog = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
const service = new TournamentCodeService(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as never,
createAuctionRedisService() as never,
);
await expect(service.markExpired()).resolves.toEqual({
affectedMatchIds: [],
expiredCount: 0,
failedCount: 1,
});
expect(codeUpdate).not.toHaveBeenCalled();
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('ownership does not match'),
);
errorLog.mockRestore();
});
});