Harden match and tournament code concurrency

This commit is contained in:
dahyeon committed 2026-06-27 12:28:05 -07:00
1 parent 292e37aaac
commit df7dcd3a9c
9 files changed
+2339 -128

No files matched your search

@@ -20,9 +20,26 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
};
function createAuctionRedisService() {
return {
acquireTokenLock: jest.fn().mockResolvedValue(true),
releaseTokenLock: jest.fn().mockResolvedValue(true),
};
}
function createSession() {
return {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
}
function createService() {
return new TournamentCodeService(
{} as never,
createAuctionRedisService() as never,
) as unknown as TournamentCodeServiceInternals;
}
@@ -297,6 +314,7 @@ describe('TournamentCodeService round-robin scheduling', () => {
};
const service = new TournamentCodeService(
connectionService as never,
createAuctionRedisService() as never,
) as unknown as TournamentCodeServiceInternals;
const slots = await service.buildSlots(
@@ -356,6 +374,40 @@ describe('TournamentCodeService round-robin scheduling', () => {
});
describe('TournamentCodeService bulk upload', () => {
it('defines unique slot and riot match indexes for multi-instance safety', () => {
const indexes = TournamentCodeSchema.indexes();
expect(indexes).toContainEqual([
{ matchId: 1, gameNumber: 1 },
expect.objectContaining({
unique: true,
partialFilterExpression: {
matchId: { $exists: true },
gameNumber: { $exists: true },
state: { $in: ['reserved', 'used'] },
},
}),
]);
expect(indexes).toContainEqual([
{ matchId: 1, bracketMatchId: 1 },
expect.objectContaining({
unique: true,
partialFilterExpression: {
matchId: { $exists: true },
bracketMatchId: { $exists: true },
state: { $in: ['reserved', 'used'] },
},
}),
]);
expect(indexes).toContainEqual([
{ riotMatchId: 1 },
expect.objectContaining({
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
}),
]);
});
it('preserves tournament code casing at the schema layer', async () => {
const connection = mongoose.createConnection();
try {
@@ -393,6 +445,7 @@ describe('TournamentCodeService bulk upload', () => {
};
const service = new TournamentCodeService(
connectionService as never,
createAuctionRedisService() as never,
) as unknown as TournamentCodeServiceInternals;
service.attachPendingMatches = jest.fn().mockResolvedValue(0);
@@ -426,7 +479,10 @@ describe('TournamentCodeService pool stats', () => {
const connectionService = {
getModel: jest.fn().mockResolvedValue({ countDocuments }),
};
const service = new TournamentCodeService(connectionService as never);
const service = new TournamentCodeService(
connectionService as never,
createAuctionRedisService() as never,
);
await expect(service.countUsableAvailable()).resolves.toBe(12);
expect(countDocuments).toHaveBeenCalledWith({
@@ -477,7 +533,9 @@ describe('TournamentCodeService pending match attachment', () => {
exec: jest.fn().mockResolvedValue({ _id: codeId }),
}),
};
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') {
@@ -486,7 +544,11 @@ describe('TournamentCodeService pending match attachment', () => {
throw new Error(`Unexpected model: ${modelName}`);
}),
};
const service = new TournamentCodeService(connectionService as never);
const auctionRedisService = createAuctionRedisService();
const service = new TournamentCodeService(
connectionService as never,
auctionRedisService as never,
);
const matches = await service.attachPendingMatchDocuments();
@@ -494,6 +556,17 @@ describe('TournamentCodeService pending match attachment', () => {
expect(MatchModel.findById).toHaveBeenCalledTimes(1);
expect(MatchModel.findById).toHaveBeenCalledWith(validMatch._id);
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
`tournament-code:match:${validMatch._id.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:${validMatch._id.toString()}:lock`,
expect.any(String),
);
expect(validMatch.tournamentCodeIds.map((id) => id.toString())).toEqual([
codeId.toString(),
]);
@@ -569,8 +642,11 @@ describe('TournamentCodeService code replacement', () => {
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') {
@@ -579,8 +655,10 @@ describe('TournamentCodeService code replacement', () => {
throw new Error(`Unexpected model: ${modelName}`);
}),
};
const auctionRedisService = createAuctionRedisService();
const service = new TournamentCodeService(
connectionService as never,
auctionRedisService as never,
) as unknown as TournamentCodeServiceInternals;
return {
@@ -591,6 +669,8 @@ describe('TournamentCodeService code replacement', () => {
replacementCode,
MatchModel,
TournamentCodeModel,
auctionRedisService,
session,
service,
};
}
@@ -604,6 +684,8 @@ describe('TournamentCodeService code replacement', () => {
replacementCode,
MatchModel,
TournamentCodeModel,
auctionRedisService,
session,
service,
} = createReplacementFixture();
@@ -642,10 +724,30 @@ describe('TournamentCodeService code replacement', () => {
}),
expect.objectContaining({ returnDocument: 'after' }),
);
expect(currentCode?.state).toBe('released');
expect(currentCode?.matchId).toBeUndefined();
expect(currentCode?.gameNumber).toBeUndefined();
expect(currentCode?.save).toHaveBeenCalled();
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(),
]);
@@ -683,8 +785,8 @@ describe('TournamentCodeService code replacement', () => {
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('leaves the current code untouched when no replacement code is available', async () => {
const { match, communityId, matchId, currentCode, service } =
it('aborts the transaction when no replacement code is available', async () => {
const { match, communityId, matchId, currentCode, session, service } =
createReplacementFixture({
replacementCode: null,
});
@@ -694,5 +796,6 @@ describe('TournamentCodeService code replacement', () => {
).rejects.toThrow('No available tournament code');
expect(currentCode?.save).not.toHaveBeenCalled();
expect(match.save).not.toHaveBeenCalled();
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
});
});