TypeScript
fix(shared): port checks no longer fail on hosts with IPv6 disabled (#15044)
mr-joom74904e36ee4e
diff --git a/packages/shared/src/Net.test.ts b/packages/shared/src/Net.test.tsindex 15c78f72ba3..0fdc0150489 100644--- a/packages/shared/src/Net.test.ts+++ b/packages/shared/src/Net.test.ts@@ -2,6 +2,7 @@ import * as NodeNet from "node:net";import { assert, describe, it } from "@effect/vitest";import * as Effect from "effect/Effect";+import { vi } from "vite-plus/test";import * as NetService from "./Net.ts";@@ -54,6 +55,33 @@ it.layer(NetService.layer)("NetService", (it) => {}),);+ it.effect.each(["EAFNOSUPPORT", "EADDRNOTAVAIL"])(+ "keeps ports available when IPv6 binds fail with %s",+ (code) =>+ Effect.gen(function* () {+ const net = yield* NetService.NetService;+ const port = yield* net.reserveLoopbackPort();+ const listen = NodeNet.Server.prototype.listen;+ const spy = vi.spyOn(NodeNet.Server.prototype, "listen").mockImplementation(function (+ this: NodeNet.Server,+ ...args+ ) {+ const [options] = args;+ if (options?.host === "::1" || options?.host === "::") {+ process.nextTick(() => this.emit("error", Object.assign(new Error(code), { code })));+ return this;+ }+ return listen.apply(this, args);+ });+ try {+ assert.equal(yield* net.isPortAvailableOnLoopback(port), true);+ assert.equal(yield* net.canListenOnHost(port, "::"), true);+ } finally {+ spy.mockRestore();+ }+ }),+ );+it.effect("isPortAvailableOnLoopback reports false for an occupied port", () =>Effect.acquireUseRelease(openServer("127.0.0.1"),diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.tsindex a4d5955a597..7acb024d859 100644--- a/packages/shared/src/Net.ts+++ b/packages/shared/src/Net.ts@@ -44,10 +44,6 @@ export class NetService extends Context.Service<NetService, NetServiceShape>()(/** @public Service construction is part of the canonical Effect module API. */export const make = () => {- /**- * `EADDRNOTAVAIL` is treated as available so IPv6-absent hosts don't fail- * loopback availability checks.- */const canListenOnHost = (port: number, host: string): Effect.Effect<boolean> =>Effect.callback<boolean>((resume) => {const server = NodeNet.createServer();@@ -62,7 +58,11 @@ export const make = () => {server.unref();server.once("error", (cause) => {- if (isErrnoExceptionWithCode(cause) && cause.code === "EADDRNOTAVAIL") {+ // Missing IPv6 addresses or kernel support do not mean the port is occupied.+ if (+ isErrnoExceptionWithCode(cause) &&+ (cause.code === "EADDRNOTAVAIL" || cause.code === "EAFNOSUPPORT")+ ) {settle(true);return;}