Skip to content

Commit 4132dbf

Browse files
noseworthyhasezoey
andauthored
fix(getport): randomize first port using crypto.randomInt (#844)
* fix(getport): Randomize first port using crypto The current implementation of `getPort()` relies on using `Date.now()` to get the first port to try to launch mongo on, even when the `EXP_NET0LISTEN` flag is set. This causes a couple issues: - If the `Date` module is mocked, it can result in `getFreePort()` returning the same first port every time. - If multiple mongos are being started at once in parallel, it's possible for the same first port to be picked leading to port conflicts In order to better randomize the initial port selection so that port conflicts can be avoided, instead of using `Date.now()` for an initial seed, use `crypto.randomInt()` which should provide more randomness and hopefully avoid some of these race conditions. re #827 * fix(getport): change crypto.randomInt "max" to be inclusive --------- Co-authored-by: hasezoey <[email protected]>
1 parent 702df8f commit 4132dbf

File tree

1 file changed

+4
-3
lines changed
  • packages/mongodb-memory-server-core/src/util/getport

1 file changed

+4
-3
lines changed

packages/mongodb-memory-server-core/src/util/getport/index.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import resolveConfig, { ResolveConfigVariables, envToBool } from '../resolveConfig';
2+
import * as crypto from 'node:crypto';
23
import * as net from 'node:net';
34
import debug from 'debug';
45

@@ -48,10 +49,10 @@ export async function getFreePort(
4849
firstPort?: number,
4950
max_tries: number = MAX_DEFAULT_TRIES
5051
): Promise<number> {
51-
// use "Date" as a semi-random value to lessen conflicts between simultaneous tests
52-
firstPort = firstPort || validPort(Date.now());
52+
// Get a random value from crypto to use as first port if none is given
53+
firstPort = firstPort || validPort(crypto.randomInt(MIN_PORT, MAX_PORT + 1));
5354

54-
// clear ports cache after some time, but not on a interval
55+
// clear ports cache after some time, but not on an interval
5556
if (PORTS_CACHE.timeSet && Date.now() - PORTS_CACHE.timeSet > PORTS_CACHE_CLEAN_TIME) {
5657
PORTS_CACHE.ports.clear();
5758
PORTS_CACHE.timeSet = Date.now();

0 commit comments

Comments
 (0)