perf(gateway): skip force port scan when free

This commit is contained in:
Peter Steinberger
2026-05-03 15:52:53 +01:00
parent 72072d8b2e
commit 935f078a89
2 changed files with 14 additions and 8 deletions

View File

@@ -266,6 +266,10 @@ export async function forceFreePortAndWait(
let killed: PortProcess[] = [];
let useFuserFallback = false;
if (!(await isPortBusy(port))) {
return { killed, waitedMs: 0, escalatedToSigkill: false };
}
try {
killed = forceFreePort(port);
} catch (err) {

View File

@@ -32,6 +32,9 @@ describe("gateway --force helpers", () => {
originalKill = process.kill.bind(process);
originalPlatform = process.platform;
tryListenOnPortMock.mockReset();
tryListenOnPortMock.mockRejectedValue(
Object.assign(new Error("in use"), { code: "EADDRINUSE" }),
);
// Pin to linux so all lsof tests are platform-invariant.
Object.defineProperty(process, "platform", { value: "linux", configurable: true });
});
@@ -59,12 +62,8 @@ describe("gateway --force helpers", () => {
expect(listPortListeners(18789)).toEqual([]);
});
it("does not re-scan lsof when no listeners were killed", async () => {
(execFileSync as unknown as Mock).mockImplementation(() => {
const err = new Error("no matches") as NodeJS.ErrnoException & { status?: number };
err.status = 1; // lsof uses exit 1 for no matches
throw err;
});
it("skips lsof when the port is already bindable", async () => {
tryListenOnPortMock.mockResolvedValue(undefined);
const result = await forceFreePortAndWait(18789, { timeoutMs: 500, intervalMs: 100 });
@@ -73,7 +72,7 @@ describe("gateway --force helpers", () => {
waitedMs: 0,
escalatedToSigkill: false,
});
expect(execFileSync).toHaveBeenCalledOnce();
expect(execFileSync).not.toHaveBeenCalled();
});
it("throws when lsof missing", () => {
@@ -181,7 +180,9 @@ describe("gateway --force helpers", () => {
}
return "18789/tcp: 4242\n";
});
tryListenOnPortMock.mockResolvedValue(undefined);
tryListenOnPortMock
.mockRejectedValueOnce(Object.assign(new Error("in use"), { code: "EADDRINUSE" }))
.mockResolvedValue(undefined);
const result = await forceFreePortAndWait(18789, { timeoutMs: 500, intervalMs: 100 });
@@ -216,6 +217,7 @@ describe("gateway --force helpers", () => {
.mockRejectedValueOnce(busyErr)
.mockRejectedValueOnce(busyErr)
.mockRejectedValueOnce(busyErr)
.mockRejectedValueOnce(busyErr)
.mockResolvedValueOnce(undefined);
const promise = forceFreePortAndWait(18789, {