Skip to content

Commit b19c4bf

Browse files
committed
fix: avoid infinite loop when waiting Primary
1 parent 2ba4ae5 commit b19c4bf

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

packages/mongodb-memory-server-core/src/MongoMemoryReplSet.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ export default class MongoMemoryReplSet extends EventEmitter {
261261
return server;
262262
}
263263

264-
async _waitForPrimary(): Promise<boolean> {
264+
async _waitForPrimary(timeout: number = 30000): Promise<boolean> {
265265
if (!this.admin) {
266266
return false;
267267
}
@@ -273,8 +273,14 @@ export default class MongoMemoryReplSet extends EventEmitter {
273273
this.debug(' replStatus:', replStatus);
274274
const hasPrimary = replStatus.repl.ismaster;
275275
if (!hasPrimary) {
276-
this.debug('No PRIMARY yet. Waiting...');
277-
return new Promise((resolve) => setTimeout(() => resolve(this._waitForPrimary()), 500));
276+
const restTimeout = timeout - 500;
277+
if (restTimeout <= 0) {
278+
throw new Error(`No PRIMARY elected yet. Timeout expired. Exiting...`);
279+
}
280+
this.debug(`No PRIMARY yet. Waiting... ${restTimeout}ms`);
281+
return new Promise((resolve) =>
282+
setTimeout(() => resolve(this._waitForPrimary(restTimeout)), 500)
283+
);
278284
}
279285

280286
return true;

0 commit comments

Comments
 (0)