-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsupervisor.ts
More file actions
205 lines (173 loc) · 6.3 KB
/
Copy pathsupervisor.ts
File metadata and controls
205 lines (173 loc) · 6.3 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { spawn, type ChildProcess } from "node:child_process";
import { createServer, request, type IncomingMessage, type ServerResponse } from "node:http";
import net from "node:net";
const publicHost = process.env.HOST || "127.0.0.1";
const publicPort = Number(process.env.PORT || 8787);
const childHost = process.env.PI_WEB_CHILD_HOST || "127.0.0.1";
const childPort = Number(process.env.PI_WEB_CHILD_PORT || publicPort + 1);
const token = process.env.PI_WEB_TOKEN || "";
const restartGraceMs = Number(process.env.PI_WEB_RESTART_GRACE_MS || 250);
let child: ChildProcess | undefined;
let childStarting = false;
let childGeneration = 0;
function requestToken(req: IncomingMessage): string {
const auth = req.headers.authorization || "";
if (auth.startsWith("Bearer ")) return auth.slice("Bearer ".length);
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
return url.searchParams.get("token") || "";
}
function isAuthorized(req: IncomingMessage): boolean {
return !token || requestToken(req) === token;
}
function sendJson(res: ServerResponse, status: number, value: unknown): void {
const body = JSON.stringify(value);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(body),
});
res.end(body);
}
function startChild(): void {
if (childStarting) return;
childStarting = true;
childGeneration += 1;
const generation = childGeneration;
const env = {
...process.env,
HOST: childHost,
PORT: String(childPort),
PI_WEB_DEV: process.env.PI_WEB_DEV || "1",
PI_WEB_SUPERVISED: "1",
};
console.log(`[supervisor] starting child #${generation} on ${childHost}:${childPort}`);
const nextChild = spawn(process.execPath, ["--import", "tsx", "server.ts"], {
cwd: process.cwd(),
env,
stdio: ["ignore", "pipe", "pipe"],
});
child = nextChild;
nextChild.stdout?.on("data", (chunk) => process.stdout.write(`[server] ${chunk}`));
nextChild.stderr?.on("data", (chunk) => process.stderr.write(`[server] ${chunk}`));
nextChild.on("spawn", () => {
childStarting = false;
});
nextChild.on("exit", (code, signal) => {
if (child?.pid === undefined || childGeneration !== generation) return;
console.log(`[supervisor] child #${generation} exited code=${code ?? ""} signal=${signal ?? ""}`);
child = undefined;
childStarting = false;
if (code !== 0 && signal !== "SIGTERM" && signal !== "SIGINT") {
setTimeout(startChild, 1000);
}
});
}
function stopChild(): Promise<void> {
return new Promise((resolve) => {
const current = child;
if (!current || current.killed) return resolve();
const timeout = setTimeout(() => {
current.kill("SIGKILL");
resolve();
}, 5000);
current.once("exit", () => {
clearTimeout(timeout);
resolve();
});
current.kill("SIGTERM");
});
}
async function restartChild(): Promise<void> {
console.log("[supervisor] restarting child");
await stopChild();
await new Promise((resolve) => setTimeout(resolve, restartGraceMs));
startChild();
}
function destroyQuietly(socket: NodeJS.WritableStream & { destroy?: (error?: Error) => void }, error?: Error): void {
socket.destroy?.(error);
}
function proxyHttp(req: IncomingMessage, res: ServerResponse): void {
const headers = { ...req.headers, host: `${childHost}:${childPort}` };
const upstream = request({
host: childHost,
port: childPort,
method: req.method,
path: req.url,
headers,
}, (upstreamRes) => {
res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers);
upstreamRes.pipe(res);
});
upstream.on("error", (error) => {
if (!res.headersSent && !res.destroyed) {
sendJson(res, 502, { ok: false, error: `pi-web child unavailable: ${error.message}` });
} else {
destroyQuietly(res, error);
}
});
req.on("error", (error) => destroyQuietly(upstream, error));
res.on("error", (error) => destroyQuietly(upstream, error));
req.pipe(upstream);
}
const supervisor = createServer(async (req, res) => {
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
if (url.pathname === "/api/restart" || url.pathname === "/__supervisor/restart") {
if (!isAuthorized(req)) return sendJson(res, 401, { ok: false, error: "Unauthorized" });
sendJson(res, 202, { ok: true, message: "Restarting pi-web child" });
void restartChild();
return;
}
if (url.pathname === "/__supervisor/status") {
if (!isAuthorized(req)) return sendJson(res, 401, { ok: false, error: "Unauthorized" });
return sendJson(res, 200, {
ok: true,
childPid: child?.pid,
childGeneration,
childHost,
childPort,
});
}
proxyHttp(req, res);
});
supervisor.on("upgrade", (req, socket, head) => {
const upstream = net.connect(childPort, childHost);
let closed = false;
const closeBoth = (error?: Error) => {
if (closed) return;
closed = true;
destroyQuietly(socket, error);
destroyQuietly(upstream, error);
};
socket.on("error", (error) => closeBoth(error));
upstream.on("error", (error) => closeBoth(error));
socket.on("close", () => closeBoth());
upstream.on("close", () => closeBoth());
upstream.on("connect", () => {
upstream.write(`${req.method} ${req.url} HTTP/${req.httpVersion}\r\n`);
for (const [name, value] of Object.entries(req.headers)) {
if (Array.isArray(value)) {
for (const item of value) upstream.write(`${name}: ${item}\r\n`);
} else if (value !== undefined) {
upstream.write(`${name}: ${value}\r\n`);
}
}
upstream.write("\r\n");
if (head.length) upstream.write(head);
socket.pipe(upstream).pipe(socket);
});
});
supervisor.on("clientError", (_error, socket) => {
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
});
function shutdown(): void {
console.log("[supervisor] shutting down");
supervisor.close();
void stopChild().finally(() => process.exit(0));
}
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
startChild();
supervisor.listen(publicPort, publicHost, () => {
console.log(`[supervisor] listening on http://${publicHost}:${publicPort}`);
console.log(`[supervisor] child target http://${childHost}:${childPort}`);
console.log(token ? "[supervisor] restart/status endpoints require token" : "[supervisor] auth disabled");
});