Skip to content

Commit 18f5af7

Browse files
committed
fix(common): servers#startOnPreferredPort no graceful fallback #683
The code of the method was not waiting for a promise to resolve which was masking the underlying exception that the code was supposed to catch and examine in order to determine if it should perform a fallback of binding to port zero or not. Fixed it by making sure the initial try of the preferred port allocation is awaited for so that the exception is thrown where it is expected by the algorithm. Fixes #683 Signed-off-by: Peter Somogyvari <[email protected]>
1 parent c966769 commit 18f5af7

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

packages/cactus-common/src/main/typescript/servers.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,8 @@ export class Servers {
8686
): Promise<Server> {
8787
if (preferredPort) {
8888
try {
89-
return Servers.startOnPort(preferredPort, host);
89+
const server = await Servers.startOnPort(preferredPort, host);
90+
return server;
9091
} catch (ex) {
9192
// if something else went wrong we still want to just give up
9293
if (!ex.message.includes("EADDRINUSE")) {

packages/cactus-common/src/test/typescript/unit/servers.test.ts

+30
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createServer } from "http";
2+
import { AddressInfo } from "net";
23

34
import test, { Test } from "tape-promise/tape";
45

@@ -37,5 +38,34 @@ test("Servers", async (tParent: Test) => {
3738
t.end();
3839
});
3940

41+
test("Servers#startOnPreferredPort()", async (t: Test) => {
42+
const prefPort = 4123;
43+
const host = "0.0.0.0";
44+
const portBlocker = createServer();
45+
test.onFinish(() => portBlocker.close());
46+
const listenOptionsBlocker = {
47+
server: portBlocker,
48+
hostname: host,
49+
port: prefPort,
50+
};
51+
await Servers.listen(listenOptionsBlocker);
52+
53+
await t.doesNotReject(async () => {
54+
const server = await Servers.startOnPreferredPort(prefPort, host);
55+
test.onFinish(() => server.close());
56+
t.ok(server, "Server returned truthy OK");
57+
const addressInfo = server.address() as AddressInfo;
58+
t.ok(addressInfo, "AddressInfo returned truthy OK");
59+
t.ok(addressInfo.port, "AddressInfo.port returned truthy OK");
60+
t.doesNotEqual(
61+
addressInfo.port,
62+
prefPort,
63+
"Peferred and actually allocated ports are different, therefore fallback is considered successful OK",
64+
);
65+
}, "Servers.startOnPreferredPort falls back without throwing OK");
66+
67+
t.end();
68+
});
69+
4070
tParent.end();
4171
});

0 commit comments

Comments
 (0)