-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage-runtime-smoke.mjs
More file actions
157 lines (142 loc) · 5.42 KB
/
Copy pathpackage-runtime-smoke.mjs
File metadata and controls
157 lines (142 loc) · 5.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { access, mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createServer } from "node:http";
import { runProcess } from "../operations/child-process.mjs";
const repoRoot = process.cwd();
const timeoutMs = Number.parseInt(process.env.PROMPT_REFINER_PACKAGE_SMOKE_TIMEOUT_MS || "120000", 10);
const tempRoot = await mkdtemp(join(tmpdir(), "prompt-refiner-package-smoke-"));
const packageDir = join(tempRoot, "package");
const prefixDir = join(tempRoot, "prefix");
const runtimeDir = join(tempRoot, "runtime");
const stateDir = join(tempRoot, "state");
const homeDir = join(tempRoot, "home");
const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
const npmExecPath = process.env.npm_execpath;
let runtime;
try {
await mkdir(packageDir, { recursive: true });
await mkdir(runtimeDir, { recursive: true });
await mkdir(stateDir, { recursive: true });
await mkdir(homeDir, { recursive: true });
const packOutput = await runNpm(["pack", "--json", "--pack-destination", packageDir]);
const packed = JSON.parse(packOutput.stdout);
const tarball = join(packageDir, packed[0].filename);
await runNpm(["install", "--global", "--prefix", prefixDir, "--no-fund", tarball]);
const bin = process.platform === "win32"
? join(prefixDir, "universal-refiner.cmd")
: join(prefixDir, "bin", "universal-refiner");
const packageRoot = await findInstalledPackageRoot(prefixDir);
const installedEntry = join(packageRoot, "dist", "src", "index.js");
await access(bin);
await access(installedEntry);
const port = await reservePort();
runtime = spawn(bin, [], {
cwd: runtimeDir,
env: {
...process.env,
HOME: homeDir,
PORT: String(port),
PROMPT_REFINER_BACKGROUND: "true",
PROMPT_REFINER_GLOBAL_DIR: stateDir,
USERPROFILE: homeDir,
},
stdio: ["ignore", "pipe", "pipe"],
shell: process.platform === "win32",
windowsHide: true,
});
let stdout = "";
let stderr = "";
runtime.stdout.setEncoding("utf8");
runtime.stderr.setEncoding("utf8");
runtime.stdout.on("data", chunk => stdout += chunk);
runtime.stderr.on("data", chunk => stderr += chunk);
await waitForHealth(port, () => `${stdout}\n${stderr}`, timeoutMs);
console.log(`Package runtime smoke passed: installed ${packed[0].name}-${packed[0].version} and served /api/health on ${port}.`);
} finally {
if (runtime) await terminateRuntime(runtime, 5_000);
await rm(tempRoot, { recursive: true, force: true });
}
async function terminateRuntime(child, timeoutMs) {
if (child.exitCode !== null || child.signalCode !== null) return;
if (process.platform === "win32" && child.pid) {
const killer = spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
stdio: "ignore",
windowsHide: true,
});
await waitForClose(killer, timeoutMs);
} else {
child.kill("SIGTERM");
}
await waitForClose(child, timeoutMs);
}
async function waitForClose(child, timeoutMs) {
if (child.exitCode !== null || child.signalCode !== null) return;
await Promise.race([
new Promise(resolve => child.once("close", resolve)),
new Promise((resolve) => {
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
resolve();
}, timeoutMs);
}),
]);
}
async function reservePort() {
const server = createServer();
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
assert.ok(address && typeof address !== "string", "Port reservation failed.");
const port = address.port;
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
return port;
}
function runNpm(args) {
return npmExecPath
? runProcess(process.execPath, [npmExecPath, ...args], { cwd: repoRoot, timeoutMs })
: runProcess(npmCommand, args, { cwd: repoRoot, timeoutMs });
}
async function findInstalledPackageRoot(prefixDir) {
const candidates = process.platform === "win32"
? [
join(prefixDir, "node_modules", "universal-refiner"),
join(prefixDir, "lib", "node_modules", "universal-refiner"),
]
: [
join(prefixDir, "lib", "node_modules", "universal-refiner"),
join(prefixDir, "node_modules", "universal-refiner"),
];
for (const candidate of candidates) {
try {
await access(candidate);
return candidate;
} catch {
// Try the next npm global install layout.
}
}
throw new Error(`Installed package root not found under npm prefix ${prefixDir}. Tried: ${candidates.join(", ")}`);
}
async function waitForHealth(port, readLogs, deadlineMs) {
const deadline = Date.now() + deadlineMs;
let lastError = "";
while (Date.now() < deadline) {
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health`);
if (response.ok) {
const body = await response.json();
assert.equal(body.runtime.status, "online");
return;
}
lastError = `HTTP ${response.status}`;
} catch (error) {
lastError = error instanceof Error ? error.message : String(error);
}
await new Promise(resolve => setTimeout(resolve, 250));
}
throw new Error(`Package runtime did not become healthy within ${deadlineMs}ms. Last error: ${lastError}\n${readLogs()}`);
}