@evandu/super-pi 0.1.270 → 0.1.271
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/super-pi.js +40 -5
- package/bin/update-receipt.js +2 -2
- package/desktop/update-lifecycle.cjs +1 -1
- package/dist/client/.super-pi-client-sources.json +3 -3
- package/dist/client/assets/{CodeMirrorEditor-DTd2NBhi.js → CodeMirrorEditor-Q77Plbqw.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-BDy7xWCL.js → GitDiffEditor-C0XYcNpE.js} +1 -1
- package/dist/client/assets/{index-BaYymkGX.js → index-CoLvWsuI.js} +5 -5
- package/dist/client/index.html +1 -1
- package/dist/server/managed-http-direct.d.ts +1 -1
- package/dist/server/managed-http-direct.js +2 -2
- package/dist/server/managed-http-tunnel.js +1 -1
- package/dist/server/managed-servers.d.ts +10 -1
- package/dist/server/managed-servers.js +166 -56
- package/dist/shared/managed-servers.d.ts +3 -0
- package/package.json +1 -1
- package/scripts/restart-server.mjs +76 -23
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawn, execFile } from "node:child_process";
|
|
2
|
-
import { openSync, readFileSync, writeFileSync, renameSync } from "node:fs";
|
|
2
|
+
import { closeSync, openSync, readFileSync, writeFileSync, renameSync } from "node:fs";
|
|
3
|
+
import { createConnection, isIPv6 } from "node:net";
|
|
3
4
|
import { homedir, platform } from "node:os";
|
|
4
5
|
import { join, resolve } from "node:path";
|
|
5
6
|
import { promisify } from "node:util";
|
|
@@ -24,6 +25,9 @@ function savedPort() {
|
|
|
24
25
|
// as an argument and never sets this variable, so the script looked at 3080 and never found the
|
|
25
26
|
// running server it was supposed to replace.
|
|
26
27
|
const port = Number(process.env.SUPER_PI_PORT ?? savedPort() ?? 3080);
|
|
28
|
+
const bindHost = process.env.SUPER_PI_HOST;
|
|
29
|
+
const probeHost = !bindHost || bindHost === "0.0.0.0" ? "127.0.0.1" : bindHost === "::" ? "::1" : bindHost;
|
|
30
|
+
const origin = `http://${isIPv6(probeHost) ? `[${probeHost}]` : probeHost}:${port}`;
|
|
27
31
|
const entry = "dist/server/index.js";
|
|
28
32
|
const allowedEntries = [entry, "src/server/index.ts"];
|
|
29
33
|
/** Compare paths the way Windows reports them. A command line on Windows contains BACKSLASHES
|
|
@@ -32,38 +36,78 @@ const allowedEntries = [entry, "src/server/index.ts"];
|
|
|
32
36
|
const normalisePath = (value) => value.replace(/[\\/]+/g, "/").toLowerCase();
|
|
33
37
|
const waitMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
34
38
|
const dataDirectory = process.env.SUPER_PI_DATA_DIR || join(homedir(), '.super-pi');
|
|
39
|
+
const gracefulOnly = process.env.SUPER_PI_RESTART_GRACEFUL_ONLY === "1";
|
|
40
|
+
const expectedVersion = process.env.SUPER_PI_RESTART_EXPECTED_VERSION;
|
|
41
|
+
async function readHealth(timeout) {
|
|
42
|
+
try {
|
|
43
|
+
const response = await fetch(`${origin}/api/health`, { headers: { connection: "close" }, signal: AbortSignal.timeout(timeout) });
|
|
44
|
+
return response.ok ? await response.json() : undefined;
|
|
45
|
+
} catch { return undefined; }
|
|
46
|
+
}
|
|
35
47
|
const releaseRestart = await acquireRestartLock(dataDirectory);
|
|
36
48
|
process.once('exit', releaseRestart);
|
|
37
49
|
// A second helper for this same accepted operation must not restart its healthy successor.
|
|
38
50
|
if (process.env.SUPER_PI_UPDATE_OPERATION_ID) {
|
|
39
51
|
try {
|
|
40
52
|
const operation = JSON.parse(readFileSync(join(dataDirectory, 'update-status.json'), 'utf8'));
|
|
41
|
-
const
|
|
42
|
-
const health = await response.json();
|
|
53
|
+
const health = await readHealth(1500);
|
|
43
54
|
let finished;
|
|
44
55
|
try { finished = JSON.parse(readFileSync(join(dataDirectory, 'restart-service-completed.json'), 'utf8')); } catch {}
|
|
45
|
-
if (
|
|
56
|
+
if (health?.service === 'super-pi' && operation.id === process.env.SUPER_PI_UPDATE_OPERATION_ID && (operation.phase === 'completed' || finished?.id === operation.id && finished.version === operation.targetVersion) && health.runningVersion === operation.targetVersion) process.exit(0);
|
|
46
57
|
} catch { /* No healthy successor yet; this helper owns recovery. */ }
|
|
47
58
|
}
|
|
48
59
|
async function pidsOnPort() {
|
|
49
60
|
if (platform() === "win32") {
|
|
50
61
|
const { stdout } = await execFileAsync("netstat", ["-ano", "-p", "TCP"]);
|
|
51
|
-
return [...new Set(stdout.split(/\r?\n/).
|
|
62
|
+
return [...new Set(stdout.split(/\r?\n/).map(line => line.trim().split(/\s+/)).filter(([, local, , state]) => state === "LISTENING" && local.endsWith(`:${port}`)).map(fields => fields.at(-1)))];
|
|
52
63
|
}
|
|
53
64
|
try { const { stdout } = await execFileAsync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"]); return stdout.trim().split(/\s+/).filter(Boolean); }
|
|
54
|
-
catch
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === 1 && !error.stdout?.trim() && !error.stderr?.trim()) return [];
|
|
67
|
+
if (platform() !== "linux") throw error;
|
|
68
|
+
const { stdout } = await execFileAsync("ss", ["-lptn", "sport", "=", `:${port}`]);
|
|
69
|
+
return [...new Set([...stdout.matchAll(/pid=(\d+)/g)].map((match) => match[1]))];
|
|
70
|
+
}
|
|
55
71
|
}
|
|
56
72
|
async function commandLine(pid) {
|
|
57
73
|
return readProcessCommandLine(pid);
|
|
58
74
|
}
|
|
59
75
|
async function requestShutdown() {
|
|
60
|
-
const headers = {};
|
|
76
|
+
const headers = { connection: "close" };
|
|
61
77
|
if (process.env.SUPER_PI_ACCESS_TOKEN) headers.authorization = `Bearer ${process.env.SUPER_PI_ACCESS_TOKEN}`;
|
|
62
|
-
try { return (await fetch(
|
|
78
|
+
try { return (await fetch(`${origin}/api/shutdown`, { method: "POST", headers, signal: AbortSignal.timeout(2000) })).status; }
|
|
63
79
|
catch { return null; }
|
|
64
80
|
}
|
|
65
81
|
async function waitForPortRelease(timeoutMs) {
|
|
66
|
-
|
|
82
|
+
const deadline = Date.now() + timeoutMs;
|
|
83
|
+
do { if (!(await pidsOnPort()).length) return true; await waitMs(100); } while (Date.now() < deadline);
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function portReleased() {
|
|
88
|
+
return new Promise(resolve => {
|
|
89
|
+
const socket = createConnection({ host: probeHost, port });
|
|
90
|
+
socket.setTimeout(1000);
|
|
91
|
+
const done = released => { socket.destroy(); resolve(released); };
|
|
92
|
+
socket.once("error", error => done(error.code === "ECONNREFUSED"));
|
|
93
|
+
socket.once("connect", () => done(false));
|
|
94
|
+
socket.once("timeout", () => done(false));
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function stopGracefully() {
|
|
99
|
+
if (await portReleased()) return true;
|
|
100
|
+
const health = await readHealth(2000);
|
|
101
|
+
if (health?.service !== "super-pi") {
|
|
102
|
+
console.error(`Port ${port} is occupied by a service that did not identify itself as Super Pi.`);
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
const status = await requestShutdown();
|
|
106
|
+
if (status >= 200 && status < 300) {
|
|
107
|
+
const deadline = Date.now() + 20_000;
|
|
108
|
+
do { if (await portReleased()) return true; await waitMs(200); } while (Date.now() < deadline);
|
|
109
|
+
}
|
|
110
|
+
console.error(`Super Pi did not release port ${port} after a graceful shutdown request (HTTP ${status ?? "no response"}).`);
|
|
67
111
|
return false;
|
|
68
112
|
}
|
|
69
113
|
// On Windows a detached, console-less node.exe has no window to receive WM_CLOSE, so plain
|
|
@@ -75,12 +119,12 @@ async function forceKill(pid) {
|
|
|
75
119
|
}
|
|
76
120
|
async function stopConflicts() {
|
|
77
121
|
const pids = await pidsOnPort(); if (!pids.length) { console.log(`Port ${port} is free.`); return true; }
|
|
78
|
-
for (const pid of pids) { const cmd = await commandLine(pid);
|
|
122
|
+
for (const pid of pids) { const cmd = await commandLine(pid); if (!allowedEntries.some((candidate) => normalisePath(cmd).includes(normalisePath(candidate)))) { console.error(`Refusing to stop non-Super Pi process on port ${port} (PID ${pid}).`); return false; } }
|
|
79
123
|
const status = await requestShutdown();
|
|
80
124
|
if (status !== null && status >= 200 && status < 300) {
|
|
81
125
|
console.log(`Graceful shutdown accepted (HTTP ${status}); waiting for port ${port} to release...`);
|
|
82
126
|
if (await waitForPortRelease(3000)) { console.log(`Port ${port} released after graceful shutdown.`); return true; }
|
|
83
|
-
console.log(`Graceful shutdown did not release port ${port}
|
|
127
|
+
console.log(`Graceful shutdown did not release port ${port} in time.`);
|
|
84
128
|
} else {
|
|
85
129
|
console.log(`Graceful shutdown unavailable (HTTP ${status ?? "no response"}); the running server may predate the shutdown endpoint.`);
|
|
86
130
|
}
|
|
@@ -88,11 +132,19 @@ async function stopConflicts() {
|
|
|
88
132
|
if (await waitForPortRelease(2000)) { console.log(`Port ${port} released after force kill.`); return true; }
|
|
89
133
|
console.error(`Port ${port} is still occupied after force kill.`); process.exitCode = 1; return false;
|
|
90
134
|
}
|
|
91
|
-
if (await
|
|
135
|
+
if (!await (gracefulOnly ? stopGracefully() : stopConflicts())) process.exit(2);
|
|
92
136
|
console.log(`Starting ${entry} on port ${port}...`);
|
|
93
137
|
const logPath = process.env.SUPER_PI_LOG ?? "restart-server.log";
|
|
94
138
|
const logFd = openSync(logPath, "a");
|
|
95
|
-
const
|
|
139
|
+
const serverEnv = { ...process.env };
|
|
140
|
+
delete serverEnv.SUPER_PI_RESTART_EXPECTED_VERSION;
|
|
141
|
+
delete serverEnv.SUPER_PI_RESTART_GRACEFUL_ONLY;
|
|
142
|
+
delete serverEnv.SUPER_PI_UPDATE_OPERATION_ID;
|
|
143
|
+
let child;
|
|
144
|
+
try { child = spawn(process.execPath, [entry], { stdio: ["ignore", logFd, logFd], detached: true, env: serverEnv, windowsHide: true }); }
|
|
145
|
+
finally { closeSync(logFd); }
|
|
146
|
+
let startupError;
|
|
147
|
+
child.once("error", error => { startupError = error.message; });
|
|
96
148
|
child.unref();
|
|
97
149
|
// HOW LONG THE NEW SERVER MAY TAKE TO BECOME REACHABLE.
|
|
98
150
|
//
|
|
@@ -108,17 +160,18 @@ child.unref();
|
|
|
108
160
|
const READINESS_BUDGET_MS = 120000;
|
|
109
161
|
const deadline = Date.now() + READINESS_BUDGET_MS;
|
|
110
162
|
while (Date.now() < deadline) {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const file = join(dataDirectory, 'restart-service-completed.json'), temporary = `${file}.${process.pid}.tmp`;
|
|
117
|
-
writeFileSync(temporary, JSON.stringify({ id: process.env.SUPER_PI_UPDATE_OPERATION_ID, version: body.runningVersion })); renameSync(temporary, file);
|
|
118
|
-
}
|
|
119
|
-
console.log("Server ready: /api/health passed."); process.exit(0);
|
|
163
|
+
const body = await readHealth(2_000);
|
|
164
|
+
if (body?.status === "ok" && body.service === "super-pi" && (!expectedVersion || body.runningVersion === expectedVersion)) {
|
|
165
|
+
if (process.env.SUPER_PI_UPDATE_OPERATION_ID) {
|
|
166
|
+
const file = join(dataDirectory, 'restart-service-completed.json'), temporary = `${file}.${process.pid}.tmp`;
|
|
167
|
+
writeFileSync(temporary, JSON.stringify({ id: process.env.SUPER_PI_UPDATE_OPERATION_ID, version: body.runningVersion })); renameSync(temporary, file);
|
|
120
168
|
}
|
|
121
|
-
|
|
169
|
+
console.log("Server ready: /api/health passed."); process.exit(0);
|
|
170
|
+
}
|
|
171
|
+
if (startupError || child.exitCode !== null || child.signalCode !== null) {
|
|
172
|
+
console.error(`Server exited before becoming ready (${startupError ?? child.exitCode ?? child.signalCode}). See ${logPath}.`);
|
|
173
|
+
process.exit(1);
|
|
174
|
+
}
|
|
122
175
|
await waitMs(200);
|
|
123
176
|
}
|
|
124
177
|
console.error(`Server did not become reachable within ${READINESS_BUDGET_MS}ms. It is STILL RUNNING - do not kill it, a slow start still ends up serving. See ${logPath}:`); try { console.error(readFileSync(logPath, "utf8").slice(-8000)); } catch {}
|