fix: stabilize competition results flow
This commit is contained in:
1 parent
3bd3120eb1
commit
a88562b208
20 files changed
+411
-65
No files matched your search
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user