Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix in-process race condition #36

Merged
merged 8 commits into from Dec 18, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 22 additions & 3 deletions index.js
@@ -1,6 +1,10 @@
'use strict';
const net = require('net');

const used = {
davidmarkclements marked this conversation as resolved.
Show resolved Hide resolved
old: new Set(),
young: new Set()
};
const getAvailablePort = options => new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
Expand All @@ -23,16 +27,31 @@ const portCheckSequence = function * (ports) {

module.exports = async options => {
let ports = null;

const sweep = 1000 * 15;
davidmarkclements marked this conversation as resolved.
Show resolved Hide resolved
if (options) {
ports = typeof options.port === 'number' ? [options.port] : options.port;
}

const interval = setInterval(() => {
used.old = used.young;
used.young = new Set();
}, sweep);
davidmarkclements marked this conversation as resolved.
Show resolved Hide resolved
interval.unref();
for (const port of portCheckSequence(ports)) {
try {
return await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
let p = await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
davidmarkclements marked this conversation as resolved.
Show resolved Hide resolved
while (used.old.has(p) || used.young.has(p)) {
if (port !== 0) {
throw new Error('locked');
davidmarkclements marked this conversation as resolved.
Show resolved Hide resolved
}

p = await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
}

used.young.add(p);
return p;
} catch (error) {
if (error.code !== 'EADDRINUSE') {
if (error.code !== 'EADDRINUSE' && error.message !== 'locked') {
throw error;
}
}
Expand Down
2 changes: 1 addition & 1 deletion test.js
Expand Up @@ -44,7 +44,7 @@ test('port can be bound to IPv4 host when promise resolves', async t => {
});

test('preferred port given IPv4 host', async t => {
const desiredPort = 8080;
const desiredPort = 8081;
const port = await getPort({
port: desiredPort,
host: '0.0.0.0'
Expand Down