|
| 1 | +import { ServerResponse, type IncomingMessage, type Server } from "node:http" |
| 2 | +import type { Http2Bindings, HttpBindings } from "@hono/node-server" |
| 3 | + |
| 4 | +/** |
| 5 | + * Graceful shutdown for den-api. |
| 6 | + * |
| 7 | + * Render runs zero-downtime deploys: it moves traffic to the new instance, |
| 8 | + * waits 60s, sends SIGTERM to the old one, then SIGKILLs it after the |
| 9 | + * service's shutdown delay (`maxShutdownDelaySeconds`, 300s for den-api, |
| 10 | + * Render's maximum). Requests can still reach the old instance after the |
| 11 | + * switch because cloudflared keeps its pooled connections to it, so the old |
| 12 | + * instance must finish what it is already doing instead of cutting it off. |
| 13 | + * |
| 14 | + * On the first signal we: |
| 15 | + * - report draining (`/ready` answers 503), |
| 16 | + * - stop accepting connections and ask keep-alive callers to reconnect, |
| 17 | + * which lands their next request on the new instance, |
| 18 | + * - close long-lived GET event streams at once: they never finish on their |
| 19 | + * own, and their clients resume on the new instance with Last-Event-ID, |
| 20 | + * - stop background loops alongside the request drain, |
| 21 | + * - wait for both, bounded by one fixed drain deadline, then exit. |
| 22 | + * A second signal exits immediately. |
| 23 | + */ |
| 24 | + |
| 25 | +/** |
| 26 | + * Fixed request and background-work drain. With the after-stop work and the |
| 27 | + * final socket close it stays inside Render's 300s shutdown delay. |
| 28 | + */ |
| 29 | +export const DEN_SHUTDOWN_DRAIN_MS = 240_000 |
| 30 | + |
| 31 | +export type GracefulShutdownOptions = { |
| 32 | + /** Max time to wait for in-flight requests and background work after the first signal. */ |
| 33 | + drainTimeoutMs: number |
| 34 | + /** Called once when draining starts, before anything else. */ |
| 35 | + onDrainStart?: () => void |
| 36 | + /** Stops background loops. Runs alongside the request drain and shares its deadline. */ |
| 37 | + stopBackgroundWork?: () => Promise<void> |
| 38 | + /** Work to finish after requests and background work stop (telemetry flush). */ |
| 39 | + afterStop?: () => Promise<void> |
| 40 | + afterStopTimeoutMs?: number |
| 41 | + /** How often idle keep-alive sockets and event streams are closed while draining. */ |
| 42 | + sweepMs?: number |
| 43 | + exit?: (code: number) => void |
| 44 | + log?: (message: string, details?: Record<string, unknown>) => void |
| 45 | + signals?: NodeJS.Signals[] |
| 46 | + processTarget?: Pick<NodeJS.Process, "on" | "off"> |
| 47 | +} |
| 48 | + |
| 49 | +export type GracefulShutdown = { |
| 50 | + isDraining: () => boolean |
| 51 | + activeRequests: () => number |
| 52 | + shutdown: (reason: string) => Promise<void> |
| 53 | + dispose: () => void |
| 54 | +} |
| 55 | + |
| 56 | +type DenFetch = (request: Request, env: HttpBindings | Http2Bindings) => Response | Promise<Response> |
| 57 | + |
| 58 | +// Responses that are long-lived GET event streams. Filled by trackEventStreams |
| 59 | +// before @hono/node-server writes the response, read when draining. |
| 60 | +const eventStreams = new WeakSet<ServerResponse>() |
| 61 | + |
| 62 | +function isEventStream(request: Request, response: Response) { |
| 63 | + return request.method === "GET" |
| 64 | + && (response.headers.get("content-type") ?? "").toLowerCase().startsWith("text/event-stream") |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Wraps the app's fetch so shutdown can tell which responses are long-lived |
| 69 | + * GET event streams. Only GET streams are closed early: a POST that answers |
| 70 | + * with an event stream (an MCP tool call) is real work and drains normally. |
| 71 | + */ |
| 72 | +export function trackEventStreams(fetch: DenFetch): DenFetch { |
| 73 | + return async (request, env) => { |
| 74 | + const response = await fetch(request, env) |
| 75 | + if (env.outgoing instanceof ServerResponse && isEventStream(request, response)) eventStreams.add(env.outgoing) |
| 76 | + return response |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +async function withTimeout<T>(work: Promise<T>, ms: number): Promise<"done" | "timeout"> { |
| 81 | + let timer: ReturnType<typeof setTimeout> | undefined |
| 82 | + const timeout = new Promise<"timeout">((resolve) => { |
| 83 | + timer = setTimeout(() => resolve("timeout"), ms) |
| 84 | + timer.unref() |
| 85 | + }) |
| 86 | + try { |
| 87 | + return await Promise.race([work.then(() => "done" as const), timeout]) |
| 88 | + } finally { |
| 89 | + clearTimeout(timer) |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +function describeError(error: unknown) { |
| 94 | + return error instanceof Error ? error.message : String(error) |
| 95 | +} |
| 96 | + |
| 97 | +export function installGracefulShutdown(server: Server, options: GracefulShutdownOptions): GracefulShutdown { |
| 98 | + const exit = options.exit ?? ((code: number) => process.exit(code)) |
| 99 | + const log = options.log ?? ((message, details) => console.log(`[shutdown] ${message}`, details ?? "")) |
| 100 | + const target = options.processTarget ?? process |
| 101 | + const signals = options.signals ?? ["SIGTERM", "SIGINT"] |
| 102 | + const sweepMs = options.sweepMs ?? 1_000 |
| 103 | + const afterStopTimeoutMs = options.afterStopTimeoutMs ?? 5_000 |
| 104 | + |
| 105 | + let draining = false |
| 106 | + let shutdownPromise: Promise<void> | undefined |
| 107 | + const responses = new Set<ServerResponse>() |
| 108 | + const idleWaiters = new Set<() => void>() |
| 109 | + |
| 110 | + // Keep-alive callers (cloudflared) pool connections to this instance. Ask |
| 111 | + // them to open a fresh connection for their next request, which reaches a |
| 112 | + // live instance, instead of closing the socket under them. |
| 113 | + function askToReconnect(response: ServerResponse) { |
| 114 | + if (!response.headersSent) response.setHeader("Connection", "close") |
| 115 | + } |
| 116 | + |
| 117 | + function closeEventStreams() { |
| 118 | + for (const response of responses) { |
| 119 | + if (eventStreams.has(response)) response.destroy() |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + const onRequest = (_request: IncomingMessage, response: ServerResponse) => { |
| 124 | + responses.add(response) |
| 125 | + if (draining) askToReconnect(response) |
| 126 | + response.on("close", () => { |
| 127 | + responses.delete(response) |
| 128 | + if (responses.size === 0) for (const resolve of idleWaiters) resolve() |
| 129 | + }) |
| 130 | + } |
| 131 | + server.on("request", onRequest) |
| 132 | + |
| 133 | + function waitForRequests() { |
| 134 | + if (responses.size === 0) return Promise.resolve() |
| 135 | + return new Promise<void>((resolve) => { |
| 136 | + const done = () => { |
| 137 | + idleWaiters.delete(done) |
| 138 | + resolve() |
| 139 | + } |
| 140 | + idleWaiters.add(done) |
| 141 | + }) |
| 142 | + } |
| 143 | + |
| 144 | + function stopBackgroundWork() { |
| 145 | + if (!options.stopBackgroundWork) return Promise.resolve() |
| 146 | + return options.stopBackgroundWork().catch((error: unknown) => { |
| 147 | + log("background work shutdown failed", { error: describeError(error) }) |
| 148 | + }) |
| 149 | + } |
| 150 | + |
| 151 | + async function run(reason: string) { |
| 152 | + draining = true |
| 153 | + options.onDrainStart?.() |
| 154 | + for (const response of responses) askToReconnect(response) |
| 155 | + const startedAt = Date.now() |
| 156 | + log("draining", { reason, activeRequests: responses.size, drainTimeoutMs: options.drainTimeoutMs }) |
| 157 | + |
| 158 | + const closed = new Promise<void>((resolve) => server.close(() => resolve())) |
| 159 | + closeEventStreams() |
| 160 | + server.closeIdleConnections() |
| 161 | + const sweep = setInterval(() => { |
| 162 | + closeEventStreams() |
| 163 | + server.closeIdleConnections() |
| 164 | + }, sweepMs) |
| 165 | + sweep.unref() |
| 166 | + |
| 167 | + let requestsDone = false |
| 168 | + let backgroundDone = false |
| 169 | + const requests = waitForRequests().then(() => { requestsDone = true }) |
| 170 | + const background = stopBackgroundWork().then(() => { backgroundDone = true }) |
| 171 | + const drained = await withTimeout(Promise.all([requests, background]), options.drainTimeoutMs) |
| 172 | + clearInterval(sweep) |
| 173 | + |
| 174 | + if (!requestsDone) { |
| 175 | + log("request drain timed out, closing remaining connections", { activeRequests: responses.size }) |
| 176 | + server.closeAllConnections() |
| 177 | + } else { |
| 178 | + server.closeIdleConnections() |
| 179 | + } |
| 180 | + if (!backgroundDone) log("background work did not stop before the drain deadline") |
| 181 | + await withTimeout(closed, 1_000) |
| 182 | + |
| 183 | + if (options.afterStop) { |
| 184 | + const flushed = await withTimeout(options.afterStop().catch((error: unknown) => { |
| 185 | + log("after-stop work failed", { error: describeError(error) }) |
| 186 | + }), afterStopTimeoutMs) |
| 187 | + if (flushed === "timeout") log("after-stop work timed out", { afterStopTimeoutMs }) |
| 188 | + } |
| 189 | + |
| 190 | + log("stopped", { reason, drained: drained === "done", elapsedMs: Date.now() - startedAt }) |
| 191 | + } |
| 192 | + |
| 193 | + function shutdown(reason: string) { |
| 194 | + shutdownPromise ??= run(reason) |
| 195 | + return shutdownPromise |
| 196 | + } |
| 197 | + |
| 198 | + const handlers = new Map<NodeJS.Signals, () => void>() |
| 199 | + for (const signal of signals) { |
| 200 | + const handler = () => { |
| 201 | + if (shutdownPromise) { |
| 202 | + log("second signal, exiting now", { signal, activeRequests: responses.size }) |
| 203 | + exit(1) |
| 204 | + return |
| 205 | + } |
| 206 | + void shutdown(signal).then( |
| 207 | + () => exit(0), |
| 208 | + (error: unknown) => { |
| 209 | + log("shutdown failed", { error: describeError(error) }) |
| 210 | + exit(1) |
| 211 | + }, |
| 212 | + ) |
| 213 | + } |
| 214 | + handlers.set(signal, handler) |
| 215 | + target.on(signal, handler) |
| 216 | + } |
| 217 | + |
| 218 | + return { |
| 219 | + isDraining: () => draining, |
| 220 | + activeRequests: () => responses.size, |
| 221 | + shutdown, |
| 222 | + dispose() { |
| 223 | + server.off("request", onRequest) |
| 224 | + for (const [signal, handler] of handlers) target.off(signal, handler) |
| 225 | + }, |
| 226 | + } |
| 227 | +} |
0 commit comments