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

+182 -13
View File
@@ -51,9 +51,13 @@ describe('MatchService', () => {
};
}
function createService(match: Record<string, unknown>) {
function createService(
match: Record<string, unknown>,
updatedMatch: Record<string, unknown> | null = match,
) {
const MatchModel = {
findById: jest.fn().mockResolvedValue(match),
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
@@ -80,6 +84,7 @@ describe('MatchService', () => {
communityStatsService as never,
matchStatsService as never,
),
MatchModel,
tournamentCodeService,
matchStatsService,
};
@@ -132,12 +137,16 @@ describe('MatchService', () => {
function createServiceWithJoinModels(params: {
user: Record<string, unknown> | null;
match: Record<string, unknown> | null;
updatedMatch?: Record<string, unknown> | null;
}) {
const UserModel = {
findById: jest.fn().mockResolvedValue(params.user),
};
const MatchModel = {
findById: jest.fn().mockResolvedValue(params.match),
findOneAndUpdate: jest
.fn()
.mockResolvedValue(params.updatedMatch ?? params.match),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
@@ -282,25 +291,185 @@ describe('MatchService', () => {
participants: [],
save: jest.fn().mockResolvedValue(undefined),
};
const { service } = createServiceWithJoinModels({ user, match });
const updatedMatch = {
...match,
participants: [
{
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
},
],
};
const { service, MatchModel } = createServiceWithJoinModels({
user,
match,
updatedMatch,
});
await service.join({
const joined = await service.join({
matchId,
userId,
});
expect(match.participants).toEqual([
expect(joined).toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': { $ne: userId },
$expr: expect.any(Object),
}),
]);
expect(match.save).toHaveBeenCalledTimes(1);
{
$push: {
participants: expect.objectContaining({
userId,
puuid: 'puuid-1',
gameName: 'Dahyeon',
tagLine: 'KR1',
profileIconId: 7,
preferredPositions: [{ position: 'MID', priority: 1 }],
excluded: false,
}),
},
},
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
);
expect(match.participants).toEqual([]);
expect(match.save).not.toHaveBeenCalled();
});
it('cancels a join with an atomic participant pull', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const user = {
_id: userId,
communityId,
riotAccounts: [],
preferredPositions: [],
};
const match = {
_id: matchId,
communityId,
status: 'recruiting',
participants: [{ userId }],
save: jest.fn(),
};
const updatedMatch = { ...match, participants: [] };
const { service, MatchModel } = createServiceWithJoinModels({
user,
match,
updatedMatch,
});
await expect(service.cancelJoin({ matchId, userId })).resolves.toBe(
updatedMatch,
);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
{
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': userId,
},
{ $pull: { participants: { userId } } },
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
);
expect(match.save).not.toHaveBeenCalled();
});
it('removes a participant with an atomic participant pull', async () => {
const communityId = new mongoose.Types.ObjectId();
const targetUserId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
status: 'recruiting',
participants: [{ userId: targetUserId }],
save: jest.fn(),
};
const updatedMatch = { ...match, participants: [] };
const { service, MatchModel } = createService(match, updatedMatch);
await expect(
service.removeParticipant({ matchId, communityId, targetUserId }),
).resolves.toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
{
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': targetUserId,
},
{ $pull: { participants: { userId: targetUserId } } },
expect.objectContaining({ returnDocument: 'after', runValidators: true }),
);
expect(match.save).not.toHaveBeenCalled();
});
it('updates participant positions with an array-filtered atomic update', async () => {
const communityId = new mongoose.Types.ObjectId();
const targetUserId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
status: 'recruiting',
participants: [
{
userId: targetUserId,
preferredPositions: [
{ position: 'TOP', priority: 1 },
{ position: 'JUNGLE', priority: 2 },
{ position: 'MID', priority: 3 },
],
},
],
save: jest.fn(),
};
const updatedMatch = { ...match };
const { service, MatchModel } = createService(match, updatedMatch);
await expect(
service.updateParticipantPositions({
matchId,
communityId,
targetUserId,
mainPosition: 'MID',
subPosition: 'SUPPORT',
}),
).resolves.toBe(updatedMatch);
expect(MatchModel.findOneAndUpdate).toHaveBeenCalledWith(
{
_id: matchId,
communityId,
status: 'recruiting',
'participants.userId': targetUserId,
},
{
$set: {
'participants.$[participant].preferredPositions': [
{ position: 'MID', priority: 1 },
{ position: 'SUPPORT', priority: 2 },
{ position: 'TOP', priority: 3 },
{ position: 'JUNGLE', priority: 4 },
],
},
},
expect.objectContaining({
arrayFilters: [{ 'participant.userId': targetUserId }],
returnDocument: 'after',
runValidators: true,
}),
);
expect(match.save).not.toHaveBeenCalled();
});
it('normalizes double-elimination match creation', async () => {
+137 -52
View File
@@ -494,29 +494,11 @@ export class MatchService {
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.');
}
const alreadyIn = match.participants.some((p) => p.userId.equals(user._id));
if (alreadyIn) {
throw new BadRequestException('User already joined this match.');
}
const selectedRiot = params.riotPuuid
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
: user.riotAccounts.find((a) => a.isPrimary);
const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []);
match.participants.push({
const participant = {
userId: user._id,
puuid: selectedRiot?.puuid,
gameName: selectedRiot?.gameName,
@@ -529,9 +511,22 @@ export class MatchService {
),
joinedAt: new Date(),
excluded: false,
});
await match.save();
return match;
};
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: user.communityId,
status: 'recruiting',
'participants.userId': { $ne: user._id },
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
},
{ $push: { participants: participant } },
{ returnDocument: 'after', runValidators: true },
);
if (updatedMatch) return updatedMatch;
return await this.throwJoinFailure(MatchModel, params.matchId, user);
}
private normalizeMatchConfig<T extends Partial<Match> & DoubleEliminationConfigInput>(
@@ -729,52 +724,57 @@ export class MatchService {
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
const match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
const participantIndex = match.participants.findIndex((participant) =>
participant.userId.equals(user._id),
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: user.communityId,
status: 'recruiting',
'participants.userId': user._id,
},
{ $pull: { participants: { userId: user._id } } },
{ returnDocument: 'after', runValidators: true },
);
if (participantIndex === -1) {
throw new BadRequestException('User has not joined this match.');
}
if (updatedMatch) return updatedMatch;
match.participants.splice(participantIndex, 1);
await match.save();
return match;
return await this.throwCancelJoinFailure(MatchModel, params.matchId, user);
}
// 관리자 전용 — 특정 참가자를 강제로 제외한다.
public async removeParticipant(
params: RemoveParticipantParams,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: params.communityId,
status: 'recruiting',
'participants.userId': params.targetUserId,
},
{ $pull: { participants: { userId: params.targetUserId } } },
{ returnDocument: 'after', runValidators: true },
);
if (updatedMatch) return updatedMatch;
const match = await this.loadRecruitingMatch(
params.matchId,
params.communityId,
);
const participantIndex = match.participants.findIndex((participant) =>
participant.userId.equals(params.targetUserId),
);
if (participantIndex === -1) {
if (
!match.participants.some((participant) =>
this.sameObjectId(participant.userId, params.targetUserId),
)
) {
throw new NotFoundException('Participant not found.');
}
match.participants.splice(participantIndex, 1);
await match.save();
return match;
throw new BadRequestException('Participant could not be removed.');
}
// 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다.
public async updateParticipantPositions(
params: UpdateParticipantPositionsParams,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await this.loadRecruitingMatch(
params.matchId,
params.communityId,
@@ -785,14 +785,36 @@ export class MatchService {
if (!participant) {
throw new NotFoundException('Participant not found.');
}
participant.preferredPositions = this.reorderPreferredPositions(
const preferredPositions = this.reorderPreferredPositions(
params.mainPosition,
params.subPosition,
participant.preferredPositions,
);
match.markModified('participants');
await match.save();
return match;
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: params.communityId,
status: 'recruiting',
'participants.userId': params.targetUserId,
},
{
$set: {
'participants.$[participant].preferredPositions': preferredPositions,
},
},
{
arrayFilters: [{ 'participant.userId': params.targetUserId }],
returnDocument: 'after',
runValidators: true,
},
);
if (!updatedMatch) {
throw new BadRequestException(
'Participant positions could not be updated.',
);
}
return updatedMatch;
}
private async loadRecruitingMatch(
@@ -811,6 +833,69 @@ export class MatchService {
return match;
}
private async throwJoinFailure(
MatchModel: mongoose.Model<Match>,
matchId: mongoose.Types.ObjectId,
user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId },
): Promise<never> {
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!this.sameObjectId(match.communityId, user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (
match.participants.some((participant) =>
this.sameObjectId(participant.userId, user._id),
)
) {
throw new BadRequestException('User already joined this match.');
}
if (match.participants.length >= match.maxParticipants) {
throw new BadRequestException('Match is full.');
}
throw new BadRequestException('Unable to join this match.');
}
private async throwCancelJoinFailure(
MatchModel: mongoose.Model<Match>,
matchId: mongoose.Types.ObjectId,
user: { _id: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId },
): Promise<never> {
const match = await MatchModel.findById(matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!this.sameObjectId(match.communityId, user.communityId)) {
throw new BadRequestException(
'User and match belong to different communities.',
);
}
if (match.status !== 'recruiting') {
throw new BadRequestException('Match is not recruiting.');
}
if (
!match.participants.some((participant) =>
this.sameObjectId(participant.userId, user._id),
)
) {
throw new BadRequestException('User has not joined this match.');
}
throw new BadRequestException('Unable to cancel match join.');
}
private sameObjectId(
left: mongoose.Types.ObjectId | { toString(): string },
right: mongoose.Types.ObjectId | { toString(): string },
): boolean {
if (left instanceof mongoose.Types.ObjectId) {
return left.equals(right.toString());
}
return left.toString() === right.toString();
}
// 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다.
private reorderPreferredPositions(
mainPosition: Position,