Retry Prism on occupied ports

This commit is contained in:
Gregory Schier
2026-08-19 23:36:43 -07:00
parent b405bd5161
commit 8a320cc81e
+27 -8
View File
@@ -55,22 +55,41 @@ function listIds(output) {
} }
async function startPrism(spec, port) { async function startPrism(spec, port) {
for (let attempt = 0; attempt < 20; attempt++, port++) {
const prism = spawn( const prism = spawn(
"npx", "npx",
["-y", "@stoplight/prism-cli", "mock", "--errors", "-p", String(port), "-h", "127.0.0.1", spec], [
"-y",
"@stoplight/prism-cli",
"mock",
"--errors",
"-p",
String(port),
"-h",
"127.0.0.1",
spec,
],
{ stdio: ["ignore", "pipe", "pipe"] }, { stdio: ["ignore", "pipe", "pipe"] },
); );
let log = ""; let log = "";
prism.stdout.on("data", (d) => (log += d)); prism.stdout.on("data", (d) => (log += d));
prism.stderr.on("data", (d) => (log += d)); prism.stderr.on("data", (d) => (log += d));
const deadline = Date.now() + 30_000; const deadline = Date.now() + 30_000;
let failed = false;
while (Date.now() < deadline) { while (Date.now() < deadline) {
if (log.includes("Prism is listening")) return { prism, getLog: () => log }; if (log.includes("Prism is listening")) return { prism, port, getLog: () => log };
if (prism.exitCode != null) throw new Error(`Prism exited:\n${log}`); if (log.includes("EADDRINUSE") || prism.exitCode != null) {
failed = true;
break;
}
await new Promise((r) => setTimeout(r, 200)); await new Promise((r) => setTimeout(r, 200));
} }
prism.kill(); prism.kill();
throw new Error(`Prism did not start in time:\n${log}`); if (failed && log.includes("EADDRINUSE")) continue;
if (!failed) throw new Error(`Prism did not start in time:\n${log}`);
throw new Error(`Prism exited:\n${log}`);
}
throw new Error("No free port found for Prism");
} }
function pointVariablesAtPrism(variables, prismUrl) { function pointVariablesAtPrism(variables, prismUrl) {
@@ -166,7 +185,10 @@ for (const spec of specs) {
JSON.stringify({ id: workspaceId, settingFollowRedirects: false }), JSON.stringify({ id: workspaceId, settingFollowRedirects: false }),
]); ]);
const prismUrl = `http://127.0.0.1:${port}`; const { prism, port: boundPort, getLog } = await startPrism(spec, port);
port = boundPort + 1;
try {
const prismUrl = `http://127.0.0.1:${boundPort}`;
const environmentIds = listIds(yaak(dataDir, ["environment", "list", workspaceId])); const environmentIds = listIds(yaak(dataDir, ["environment", "list", workspaceId]));
let activeEnvironment = null; let activeEnvironment = null;
for (const id of environmentIds) { for (const id of environmentIds) {
@@ -206,9 +228,6 @@ for (const spec of specs) {
} }
} }
const { prism, getLog } = await startPrism(spec, port);
port++;
try {
const sendArgs = ["send", workspaceId]; const sendArgs = ["send", workspaceId];
if (activeEnvironment != null) sendArgs.push("-e", activeEnvironment); if (activeEnvironment != null) sendArgs.push("-e", activeEnvironment);
try { try {