fix: stabilize competition results flow

This commit is contained in:
dahyeon committed 2026-07-13 13:55:08 +00:00
1 parent 3bd3120eb1
commit a88562b208
20 files changed
+411 -65

No files matched your search

@@ -66,7 +66,10 @@ describe('CompetitionCommandService', () => {
$inc: { revision: 1 },
$set: { projection: PROJECTION },
});
expect(casOptions).toMatchObject({ new: true, session: harness.session });
expect(casOptions).toMatchObject({
returnDocument: 'after',
session: harness.session,
});
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
});
@@ -321,7 +321,7 @@ export class CompetitionCommandService {
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
{ returnDocument: 'after', runValidators: true, session },
)
.lean()
.exec();
@@ -475,7 +475,7 @@ export class CompetitionCommandService {
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
{ returnDocument: 'after', runValidators: true, session },
)
.lean()
.exec();
@@ -1,4 +1,8 @@
import { ConflictException, ForbiddenException } from '@nestjs/common';
import {
ConflictException,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionQueryService } from './competition-query.service';
@@ -55,6 +59,38 @@ describe('CompetitionQueryService', () => {
});
});
it('resolves a team view from an explicit team id without a caller identity', async () => {
const harness = createHarness();
const service = createService(harness);
const result = await service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: TEAM_A_ID,
});
expect(result).toMatchObject({
teamId: TEAM_A_ID.toHexString(),
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
tournamentCodes: [
expect.objectContaining({ code: 'TEAM-A-SECRET-CODE' }),
],
});
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
});
it('does not resolve a team view for an unknown team id', async () => {
const service = createService(createHarness());
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: new Types.ObjectId('64c000000000000000000098'),
}),
).rejects.toBeInstanceOf(NotFoundException);
});
it('does not reveal a team view to an authenticated non-participant', async () => {
const service = createService(createHarness());
@@ -22,6 +22,17 @@ export interface CompetitionScope {
matchId: mongoose.Types.ObjectId;
}
/**
* A team view is addressed either by the caller's membership (signed-in) or by
* an explicit team id. The explicit form exists so that the team progress page
* stays usable while community members have not all signed in yet.
*/
export type TeamViewScope = CompetitionScope &
(
| { userId: mongoose.Types.ObjectId; teamId?: undefined }
| { teamId: mongoose.Types.ObjectId; userId?: undefined }
);
interface CompetitionProjectionSource {
series?: Array<Record<string, unknown>>;
gameSlots?: Array<Record<string, unknown>>;
@@ -68,15 +79,21 @@ export class CompetitionQueryService {
}
public async getTeamView(
scope: CompetitionScope & { userId: mongoose.Types.ObjectId },
scope: TeamViewScope,
): Promise<TeamCompetitionViewResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const team = competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
const requestedTeamId = scope.teamId;
const team = requestedTeamId
? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId))
: competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
if (!team) {
if (requestedTeamId) {
throw new NotFoundException('Competition team not found.');
}
throw new ForbiddenException(
'Only a Competition team member may access the team view.',
);
@@ -7,7 +7,7 @@ import { CompetitionController } from './competition.controller';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionController', () => {
it('marks only the detail endpoint public and writes a revision ETag', async () => {
it('marks the read endpoints public and writes a revision ETag', async () => {
const { controller, queryService } = createHarness();
const response = { setHeader: jest.fn() };
@@ -17,18 +17,14 @@ describe('CompetitionController', () => {
response as never,
);
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getDetail,
),
).toBe(true);
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getTeamView,
),
).not.toBe(true);
for (const method of ['getDetail', 'getTeamView'] as const) {
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype[method],
),
).toBe(true);
}
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
expect(queryService.getCompetition).toHaveBeenCalledWith({
@@ -37,6 +33,65 @@ describe('CompetitionController', () => {
});
});
it('reads a team view by explicit team id without an authenticated caller', async () => {
const { controller, queryService } = createHarness();
queryService.getTeamView.mockResolvedValue({ revision: 7 });
const response = { setHeader: jest.fn() };
const result = await controller.getTeamView(
undefined,
COMMUNITY_ID,
MATCH_ID,
TEAM_A_ID.toHexString(),
response as never,
);
expect(queryService.getTeamView).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
teamId: TEAM_A_ID,
});
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
});
it('falls back to the membership-scoped team view for a signed-in caller', async () => {
const { controller, queryService } = createHarness();
queryService.getTeamView.mockResolvedValue({ revision: 7 });
await controller.getTeamView(adminUser(), COMMUNITY_ID, MATCH_ID);
expect(queryService.getTeamView).toHaveBeenCalledWith({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: ADMIN_ID,
});
});
it('rejects an anonymous team view request that names no team', async () => {
const { controller, queryService } = createHarness();
await expect(
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID),
).rejects.toMatchObject({
status: 401,
response: { error: { code: 'COMPETITION_TEAM_UNIDENTIFIED' } },
});
expect(queryService.getTeamView).not.toHaveBeenCalled();
});
it('rejects a malformed team id', async () => {
const { controller, queryService } = createHarness();
await expect(
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID, 'not-an-id'),
).rejects.toMatchObject({
status: 422,
response: { error: { code: 'INVALID_COMPETITION_REQUEST' } },
});
expect(queryService.getTeamView).not.toHaveBeenCalled();
});
it('protects audit and mutation endpoints with admin roles', () => {
for (const method of [
'listFacts',
@@ -63,20 +63,36 @@ export class CompetitionController {
});
}
// Temporarily public: community members are not all signed in yet, so the
// team progress page addresses a team through an explicit `teamId` instead of
// the caller's identity. A signed-in caller with no `teamId` keeps the
// membership-scoped behaviour.
@Get('team')
@AllowPublicAccess()
public async getTeamView(
@CurrentUser() currentUser: UserDocument,
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query('teamId') requestedTeamId?: string,
@Res({ passthrough: true }) response?: Response,
): Promise<TeamCompetitionViewResponse> {
return this.translate(async () => {
assertSameCommunity(currentUser, communityId);
const teamId = parseOptionalObjectId(requestedTeamId, 'teamId');
if (!teamId) {
if (!currentUser) {
throw apiHttpError(
401,
'COMPETITION_TEAM_UNIDENTIFIED',
'Sign in or provide a teamId query parameter to read a team view.',
);
}
assertSameCommunity(currentUser, communityId);
}
const result = await this.queryService.getTeamView({
communityId,
matchId,
userId: currentUser._id,
...(teamId ? { teamId } : { userId: currentUser!._id }),
});
response?.setHeader('ETag', revisionEtag(result.revision));
return result;
@@ -298,6 +314,21 @@ function requireCommandHeaders(
return revision;
}
function parseOptionalObjectId(
value: string | undefined,
field: string,
): mongoose.Types.ObjectId | undefined {
if (value === undefined || value.trim().length === 0) return undefined;
if (!mongoose.isValidObjectId(value)) {
throw apiHttpError(
422,
'INVALID_COMPETITION_REQUEST',
`The ${field} query parameter must be a valid ObjectId.`,
);
}
return new mongoose.Types.ObjectId(value);
}
function requireRevisionHeader(ifMatch: string | undefined): number {
const revision = parseRevision(ifMatch);
if (revision === undefined) {
@@ -1,9 +1,75 @@
import mongoose from 'mongoose';
import {
ConnectionService,
resolveMongoAppName,
resolveMongoConnectionOptions,
resolveMongoDbName,
} from './connection.service';
function createFakeConnection(connectionId: string) {
const models: Record<string, unknown> = {};
return {
readyState: mongoose.ConnectionStates.connected,
models,
model: jest.fn((name: string) => {
const model = { connectionId, modelName: name };
models[name] = model;
return model;
}),
};
}
describe('ConnectionService', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('shares one MongoDB connection across concurrent initialization calls', async () => {
const connection = createFakeConnection('shared');
const createConnection = jest
.spyOn(mongoose, 'createConnection')
.mockReturnValue({
asPromise: jest.fn().mockResolvedValue(connection),
} as never);
const service = new ConnectionService({
get: jest.fn().mockResolvedValue('mongodb://localhost/test'),
} as never);
const [first, second] = await Promise.all([
service.getConnection(),
service.getConnection(),
]);
expect(first).toBe(connection);
expect(second).toBe(connection);
expect(createConnection).toHaveBeenCalledTimes(1);
});
it('rebuilds models from the replacement connection after disconnect', async () => {
const firstConnection = createFakeConnection('first');
const secondConnection = createFakeConnection('second');
jest
.spyOn(mongoose, 'createConnection')
.mockReturnValueOnce({
asPromise: jest.fn().mockResolvedValue(firstConnection),
} as never)
.mockReturnValueOnce({
asPromise: jest.fn().mockResolvedValue(secondConnection),
} as never);
const service = new ConnectionService({
get: jest.fn().mockResolvedValue('mongodb://localhost/test'),
} as never);
const firstModel = await service.getModel('match');
firstConnection.readyState = mongoose.ConnectionStates.disconnected;
const secondModel = await service.getModel('match');
expect(firstModel).toMatchObject({ connectionId: 'first' });
expect(secondModel).toMatchObject({ connectionId: 'second' });
expect(secondModel).not.toBe(firstModel);
});
});
describe('resolveMongoDbName', () => {
it('uses production database only for prod', () => {
expect(resolveMongoDbName('prod')).toBe('lolympus');
@@ -39,6 +39,7 @@ export function resolveMongoConnectionOptions(
export class ConnectionService implements OnModuleInit {
private readonly logger = new Logger(ConnectionService.name);
private connection: mongoose.Connection | null = null;
private connectionPromise: Promise<mongoose.Connection> | null = null;
constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
@@ -51,35 +52,49 @@ export class ConnectionService implements OnModuleInit {
return this.connection;
}
const pendingConnection = this.connectionPromise ?? this.openConnection();
this.connectionPromise = pendingConnection;
try {
return await pendingConnection;
} finally {
if (this.connectionPromise === pendingConnection) {
this.connectionPromise = null;
}
}
}
private async openConnection(): Promise<mongoose.Connection> {
const connectionString = await this.secretService.get(
'MONGODB_CONNECTION_STRING',
);
const dbName = resolveMongoDbName();
const appName = resolveMongoAppName();
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
const defaultConnection = await mongoose
const connection = await mongoose
.createConnection(connectionString, connectionOptions)
.asPromise();
this.connection = defaultConnection;
this.connection = connection;
this.tournamentModels = null;
this.logger.log(
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
connectionOptions.autoIndex === true
}`,
);
return this.connection;
return connection;
}
public async getModel<K extends keyof TournamentModelTypes>(
modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
const connection = await this.getConnection();
if (this.tournamentModels)
return this.tournamentModels.get(modelKey) as mongoose.Model<
TournamentModelTypes[K]
>;
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
const connection = await this.getConnection();
tournamentModelDefinitions.forEach((modelDefinition) => {
applyMongoosePerformancePlugin(modelDefinition.schema);
@@ -36,7 +36,7 @@ describe('CompetitionAssignmentProvisioner', () => {
}),
},
expect.objectContaining({
new: true,
returnDocument: 'after',
session: harness.session,
sort: { expiresAt: 1 },
}),
@@ -122,14 +122,14 @@ describe('CompetitionAssignmentProvisioner', () => {
expect(harness.assignmentModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: assignmentId, state: 'reserved' },
{ $set: expect.objectContaining({ state: 'released' }) },
{ new: true, session: harness.session },
{ returnDocument: 'after', session: harness.session },
);
expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: harness.codeId, state: 'reserved' },
expect.objectContaining({
$set: expect.objectContaining({ state: 'released' }),
}),
{ new: true, session: harness.session },
{ returnDocument: 'after', session: harness.session },
);
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: harness.matchId },
@@ -156,7 +156,7 @@ export class CompetitionAssignmentProvisioner {
const assignment = (await params.AssignmentModel.findOneAndUpdate(
{ _id: params.assignment._id, state: 'reserved' },
{ $set: { state: 'released', releasedAt } },
{ new: true, session },
{ returnDocument: 'after', session },
).exec()) as AssignmentRecord | null;
if (!assignment) {
await session.commitTransaction();
@@ -173,7 +173,7 @@ export class CompetitionAssignmentProvisioner {
reservedAt: 1,
},
},
{ new: true, session },
{ returnDocument: 'after', session },
).exec()) as CodeRecord | null;
if (!code) {
throw new Error(
@@ -354,7 +354,7 @@ export class CompetitionAssignmentProvisioner {
gameNumber: params.displayNumber,
},
{ $set: { gameNumber: params.displayNumber } },
{ new: true, session: params.session },
{ returnDocument: 'after', session: params.session },
).exec()) as CodeRecord | null;
if (promoted) return promoted;
}
@@ -377,7 +377,11 @@ export class CompetitionAssignmentProvisioner {
reservedAt: new Date(),
},
},
{ new: true, session: params.session, sort: { expiresAt: 1 } },
{
returnDocument: 'after',
session: params.session,
sort: { expiresAt: 1 },
},
).exec()) as CodeRecord | null;
}
@@ -110,7 +110,7 @@ export class CompetitionOutboxProcessor
$unset: { lastError: 1 },
},
{
new: true,
returnDocument: 'after',
sort: { availableAt: 1, revision: 1, _id: 1 },
},
)