-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
114 lines (101 loc) · 4.82 KB
/
Copy pathserver.ts
File metadata and controls
114 lines (101 loc) · 4.82 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
// Copyright (c) 2026 Interactor, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
/**
* Custom Next.js server.
*
* Wraps the standard Next.js request handler and intercepts HTTP upgrade
* events for WebSocket terminal relay paths. All other traffic is forwarded
* to Next.js unchanged.
*
* Usage (replaces `next start` / `next dev`):
* tsx server.ts # dev (hot-reload via next dev internals)
* node dist/server.js # prod (after `next build`)
*/
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { handleTerminalUpgrade, drainTunnels } from "./src/lib/terminal/relay";
import { routeUpgrade } from "./src/lib/terminal/upgrade-route";
import { startMemorySampler } from "./src/lib/observability/memory-sampler";
const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.HOSTNAME ?? "0.0.0.0";
const port = parseInt(process.env.PORT ?? "4025", 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
// Next.js's own upgrade handler — owns the dev HMR socket (/_next/webpack-hmr)
// and rejects unknown upgrades. We forward to it instead of destroying sockets.
// Must be obtained after prepare() (getUpgradeHandler throws otherwise).
const handleUpgrade = app.getUpgradeHandler();
const server = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url ?? "/", true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error handling request:", err);
res.statusCode = 500;
res.end("Internal Server Error");
}
});
server.on("upgrade", (req, socket, head) => {
const url = req.url ?? "";
if (routeUpgrade(url) === "tunnel") {
void handleTerminalUpgrade(req, socket, head);
} else {
// Forward to Next.js (HMR in dev; it rejects unknown upgrades itself)
// rather than hard-destroying the socket, which broke dev hydration.
void handleUpgrade(req, socket, head);
}
});
// Periodic memory sampler (opt-in via MEMORY_SAMPLE_INTERVAL_MS) — logs the
// web process's rss/heap/external growth curve so a leak can be diagnosed from
// logs without SSH. No-op unless the interval env var is set. Stopped on
// shutdown; the timer is also unref()'d so it never blocks a graceful exit.
let stopMemorySampler: () => void = () => {};
server.listen(port, hostname, () => {
console.log(`> Ready on http://${hostname}:${port} [${dev ? "dev" : "production"}]`);
// Tell PM2 (ecosystem `wait_ready: true`) that the new fork is actually
// listening, so PM2 only SIGINTs the OLD fork once we can serve traffic —
// closing the undrained reload-swap gap. No-op when not spawned by PM2
// (process.send is undefined under `tsx server.ts` / plain `node`).
process.send?.("ready");
stopMemorySampler = startMemorySampler();
});
// ── Graceful shutdown (PM2 reload) ─────────────────────────────────────────
// PM2 sends SIGINT to the OLD fork once the new one reports 'ready'. We:
// (a) stop accepting new connections (server.close + drop idle keep-alives),
// (b) drain in-flight terminal/shell WS tunnels via the relay — clients are
// told to reconnect to the new fork rather than having sockets reset,
// (c) exit 0 once the HTTP server has drained, or after a bounded timeout.
// The timeout sits just under the ecosystem `kill_timeout` (8000ms) so we exit
// cleanly before PM2 escalates to SIGKILL.
const SHUTDOWN_TIMEOUT_MS = 7_000;
let shuttingDown = false;
function shutdown(signal: string): void {
if (shuttingDown) return;
shuttingDown = true;
stopMemorySampler();
console.log(`> ${signal} received — draining connections…`);
// Hard ceiling: a stuck socket must never hold the process past PM2's
// SIGKILL window. unref() so this timer can't itself keep us alive.
const forceExit = setTimeout(() => {
console.warn(`> drain timed out after ${SHUTDOWN_TIMEOUT_MS}ms — forcing exit`);
process.exit(0);
}, SHUTDOWN_TIMEOUT_MS);
forceExit.unref();
const drained = drainTunnels();
console.log(`> closed ${drained} terminal/shell tunnel(s)`);
server.close((err) => {
if (err) console.error("> error closing HTTP server:", err);
else console.log("> HTTP server drained — exiting");
clearTimeout(forceExit);
process.exit(0);
});
// server.close() waits for existing connections to finish but leaves idle
// keep-alive sockets open; drop those so the close callback fires promptly
// once genuine in-flight requests complete.
server.closeIdleConnections?.();
}
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
});