From b70d868cf5b6766e751ef6fec53e8e4ccccd1de6 Mon Sep 17 00:00:00 2001 From: hasezoey Date: Sat, 3 Aug 2024 13:29:14 +0200 Subject: [PATCH] fix(getport): check new port against cache this is to workaround the VM potentially executing another instance's getport before the other one could start the binary. re #883 --- .../src/util/getport/index.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/packages/mongodb-memory-server-core/src/util/getport/index.ts b/packages/mongodb-memory-server-core/src/util/getport/index.ts index 63f3a531..97b6b3e4 100644 --- a/packages/mongodb-memory-server-core/src/util/getport/index.ts +++ b/packages/mongodb-memory-server-core/src/util/getport/index.ts @@ -73,11 +73,21 @@ export async function getFreePort( const triedPort = await tryPort(nextPort); if (triedPort > 0) { - log('getFreePort: found free port', triedPort); + // check if triedPort is already in the cache (ie the vm executed another instance's getport before binary startup) + // and that the triedPort is not a custom port + const inCacheAndNotSame = PORTS_CACHE.ports.has(triedPort) && nextPort !== triedPort; + log( + `getFreePort: found free port ${triedPort}, in cache and not custom: ${inCacheAndNotSame}` + ); // returned port can be different than the "nextPort" (if net0listen) PORTS_CACHE.ports.add(nextPort); + // ensure that no other instance can get the same port if the vm decides to run the other instance's getport before starting the last one + if (inCacheAndNotSame) { + continue; + } + return triedPort; } }