Skip to content

Commit fe2cb3c

Browse files
committed
test: retain owned sockets in portal collision fixtures
1 parent 185c88c commit fe2cb3c

1 file changed

Lines changed: 76 additions & 63 deletions

File tree

‎src/gateway/portals/portal-service.test.ts‎

Lines changed: 76 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { request, type Server } from "node:http";
22
import type { Duplex } from "node:stream";
33
import { afterEach, describe, expect, it, vi } from "vitest";
4-
import { getFreePort } from "../../test-utils/ports.js";
4+
import { readResponseWithLimit } from "../../infra/http-body.js";
5+
import { withServer } from "../../plugin-sdk/test-helpers/http-test-server.js";
56
import * as httpListen from "../server/http-listen.js";
67
import { createGatewayPortalService, type GatewayPortalService } from "./portal-service.js";
78

@@ -35,14 +36,13 @@ async function getStatus(host: string, port: number, path: string): Promise<numb
3536
});
3637
}
3738

38-
async function getDistinctFreePort(excluded: number): Promise<number> {
39-
for (let attempt = 0; attempt < 10; attempt += 1) {
40-
const port = await getFreePort();
41-
if (port !== excluded) {
42-
return port;
43-
}
39+
function reportTargetPortCollision(server: Server, targetPort: number): void {
40+
const address = server.address();
41+
if (!address || typeof address === "string") {
42+
throw new Error("Missing portal listener address");
4443
}
45-
throw new Error("Failed to reserve a distinct test port");
44+
// Keep the OS allocation owned; only the next collision check sees the target port.
45+
vi.spyOn(server, "address").mockReturnValueOnce({ ...address, port: targetPort });
4646
}
4747

4848
describe("portal open authority fence", () => {
@@ -109,67 +109,80 @@ describe("gateway portal service", () => {
109109
});
110110

111111
it("retries a target-port collision before binding sibling hosts", async () => {
112-
const targetPort = await getFreePort();
113-
const acceptedPort = await getDistinctFreePort(targetPort);
114-
const actualListen = httpListen.listenGatewayHttpServer;
115-
const calls: Array<{ host: string; port: number }> = [];
116-
let primaryAttempt = 0;
117-
vi.spyOn(httpListen, "listenGatewayHttpServer").mockImplementation(async (params) => {
118-
calls.push({ host: params.bindHost, port: params.port });
119-
if (params.bindHost === "127.0.0.1" && params.port === 0) {
120-
primaryAttempt += 1;
121-
await actualListen({
122-
...params,
123-
port: primaryAttempt === 1 ? targetPort : acceptedPort,
112+
await withServer(
113+
(_req, res) => res.end("target"),
114+
async (targetUrl) => {
115+
const targetPort = Number(new URL(targetUrl).port);
116+
const actualListen = httpListen.listenGatewayHttpServer;
117+
const calls: Array<{ host: string; port: number }> = [];
118+
let primaryAttempt = 0;
119+
vi.spyOn(httpListen, "listenGatewayHttpServer").mockImplementation(async (params) => {
120+
calls.push({ host: params.bindHost, port: params.port });
121+
await actualListen(params);
122+
if (params.bindHost === "127.0.0.1" && params.port === 0) {
123+
primaryAttempt += 1;
124+
if (primaryAttempt === 1) {
125+
reportTargetPortCollision(params.httpServer, targetPort);
126+
}
127+
}
124128
});
125-
return;
126-
}
127-
await actualListen(params);
128-
});
129-
const { service, httpServers } = makeService(["127.0.0.1", "::1"]);
130-
131-
const portal = await service.open({ targetPort });
132-
133-
expect(portal.listenPort).toBe(acceptedPort);
134-
expect(calls).toEqual([
135-
{ host: "127.0.0.1", port: 0 },
136-
{ host: "127.0.0.1", port: 0 },
137-
{ host: "::1", port: acceptedPort },
138-
]);
139-
expect(httpServers).toHaveLength(2);
140-
expect(httpServers.every((server) => server.listening)).toBe(true);
141-
expect(await getStatus("127.0.0.1", portal.listenPort, `/?${portal.tokenQuery}`)).toBe(502);
142-
143-
const ownedServers = [...httpServers];
144-
await service.closeAll();
145-
expect(httpServers).toEqual([]);
146-
expect(ownedServers.every((server) => !server.listening && server.address() === null)).toBe(
147-
true,
129+
const { service, httpServers } = makeService(["127.0.0.1", "::1"]);
130+
131+
const portal = await service.open({ targetPort });
132+
133+
expect(portal.listenPort).not.toBe(targetPort);
134+
expect(calls).toEqual([
135+
{ host: "127.0.0.1", port: 0 },
136+
{ host: "127.0.0.1", port: 0 },
137+
{ host: "::1", port: portal.listenPort },
138+
]);
139+
expect(httpServers).toHaveLength(2);
140+
expect(httpServers.every((server) => server.listening)).toBe(true);
141+
for (const server of httpServers) {
142+
expect(server.address()).toMatchObject({ port: portal.listenPort });
143+
}
144+
const response = await fetch(portal.url);
145+
expect(response.status).toBe(200);
146+
expect((await readResponseWithLimit(response, 32)).toString("utf8")).toBe("target");
147+
148+
const ownedServers = [...httpServers];
149+
await service.closeAll();
150+
expect(httpServers).toEqual([]);
151+
expect(ownedServers.every((server) => !server.listening && server.address() === null)).toBe(
152+
true,
153+
);
154+
},
148155
);
149156
});
150157

151158
it("cleans up when every allocation collides with the target port", async () => {
152-
const targetPort = await getFreePort();
153-
const actualListen = httpListen.listenGatewayHttpServer;
154-
const attemptedServers = new Set<Server>();
155-
const listen = vi
156-
.spyOn(httpListen, "listenGatewayHttpServer")
157-
.mockImplementation(async (params) => {
158-
attemptedServers.add(params.httpServer);
159-
await actualListen({ ...params, port: targetPort });
160-
});
161-
const { service, httpServers } = makeService(["127.0.0.1"]);
162-
163-
await expect(service.open({ targetPort })).rejects.toThrow(
164-
`Portal listener repeatedly allocated target port ${targetPort}`,
159+
await withServer(
160+
(_req, res) => res.end("target"),
161+
async (targetUrl) => {
162+
const targetPort = Number(new URL(targetUrl).port);
163+
const actualListen = httpListen.listenGatewayHttpServer;
164+
const attemptedServers = new Set<Server>();
165+
const listen = vi
166+
.spyOn(httpListen, "listenGatewayHttpServer")
167+
.mockImplementation(async (params) => {
168+
attemptedServers.add(params.httpServer);
169+
await actualListen(params);
170+
reportTargetPortCollision(params.httpServer, targetPort);
171+
});
172+
const { service, httpServers } = makeService(["127.0.0.1"]);
173+
174+
await expect(service.open({ targetPort })).rejects.toThrow(
175+
`Portal listener repeatedly allocated target port ${targetPort}`,
176+
);
177+
178+
expect(listen).toHaveBeenCalledTimes(10);
179+
expect(attemptedServers.size).toBe(1);
180+
expect(httpServers).toEqual([]);
181+
const [primaryServer] = attemptedServers;
182+
expect(primaryServer?.listening).toBe(false);
183+
expect(primaryServer?.address()).toBeNull();
184+
},
165185
);
166-
167-
expect(listen).toHaveBeenCalledTimes(10);
168-
expect(attemptedServers.size).toBe(1);
169-
expect(httpServers).toEqual([]);
170-
const [primaryServer] = attemptedServers;
171-
expect(primaryServer?.listening).toBe(false);
172-
expect(primaryServer?.address()).toBeNull();
173186
});
174187

175188
it("updates an existing target without replacing its listener or token", async () => {

0 commit comments

Comments
 (0)