feat: graceful shutdown via app.close() force-closing streams and connections
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+45
-8
No files matched your search
+13
-3
@@ -20,6 +20,7 @@ import type { RequestEnvelope, RouteEntry } from './mesh/protocol';
|
|||||||
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string }
|
||||||
export interface App {
|
export interface App {
|
||||||
listen(port: number): Promise<http.Server>;
|
listen(port: number): Promise<http.Server>;
|
||||||
|
close(): Promise<void>;
|
||||||
inspect(routePath: string): InspectLine[];
|
inspect(routePath: string): InspectLine[];
|
||||||
bus: Bus;
|
bus: Bus;
|
||||||
}
|
}
|
||||||
@@ -46,6 +47,8 @@ export interface MeshConfig {
|
|||||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App {
|
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App {
|
||||||
const bus = new Bus();
|
const bus = new Bus();
|
||||||
const container = new Container();
|
const container = new Container();
|
||||||
|
let server: http.Server | undefined;
|
||||||
|
const streams = new Set<() => void>();
|
||||||
const extraSteps: ScopeNode[] = [];
|
const extraSteps: ScopeNode[] = [];
|
||||||
const scope: ScopeApi = { add: (n) => extraSteps.push(n) };
|
const scope: ScopeApi = { add: (n) => extraSteps.push(n) };
|
||||||
|
|
||||||
@@ -279,13 +282,20 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits });
|
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams });
|
||||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||||
await new Promise<void>((resolve) => server.listen(port, resolve));
|
await new Promise<void>((resolve) => server!.listen(port, resolve));
|
||||||
return server;
|
return server;
|
||||||
};
|
};
|
||||||
|
|
||||||
return { listen, inspect, bus };
|
const close = (): Promise<void> => new Promise<void>((resolve) => {
|
||||||
|
if (!server) return resolve();
|
||||||
|
server.close(() => resolve()); // waits for in-flight buffered to drain
|
||||||
|
for (const closeStream of streams) closeStream(); // force-close long-lived SSE/WS so close() resolves
|
||||||
|
server.closeIdleConnections(); // Node >=18.2: drop idle keep-alive
|
||||||
|
});
|
||||||
|
|
||||||
|
return { listen, close, inspect, bus };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function snapshot(c: Container, needs: string[]): Promise<Record<string, unknown>> {
|
async function snapshot(c: Container, needs: string[]): Promise<Record<string, unknown>> {
|
||||||
|
|||||||
+13
-5
@@ -14,7 +14,7 @@ export interface RequestLimits {
|
|||||||
headersTimeoutMs?: number; // default 10_000
|
headersTimeoutMs?: number; // default 10_000
|
||||||
keepAliveTimeoutMs?: number; // default 5_000
|
keepAliveTimeoutMs?: number; // default 5_000
|
||||||
}
|
}
|
||||||
export interface HttpOptions { limits?: RequestLimits }
|
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> }
|
||||||
|
|
||||||
export type RouteHandler = (req: {
|
export type RouteHandler = (req: {
|
||||||
method: string; url: string;
|
method: string; url: string;
|
||||||
@@ -88,7 +88,7 @@ function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
|||||||
|
|
||||||
async function pipeStream(
|
async function pipeStream(
|
||||||
res: http.ServerResponse, stream: AsyncIterable<unknown>, encoder: StreamEncoder,
|
res: http.ServerResponse, stream: AsyncIterable<unknown>, encoder: StreamEncoder,
|
||||||
bus?: Bus, name = '',
|
bus?: Bus, name = '', streams?: Set<() => void>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
res.writeHead(200, encoder.headers);
|
res.writeHead(200, encoder.headers);
|
||||||
bus?.emit('stream:open', { name });
|
bus?.emit('stream:open', { name });
|
||||||
@@ -97,6 +97,8 @@ async function pipeStream(
|
|||||||
if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); }
|
if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); }
|
||||||
const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); };
|
const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); };
|
||||||
res.on('close', stop);
|
res.on('close', stop);
|
||||||
|
const closer = () => { try { res.destroy(); } catch { /* */ } };
|
||||||
|
streams?.add(closer);
|
||||||
const onClose = once(res, 'close');
|
const onClose = once(res, 'close');
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
@@ -113,6 +115,7 @@ async function pipeStream(
|
|||||||
if (frame && !res.writableEnded) res.write(frame);
|
if (frame && !res.writableEnded) res.write(frame);
|
||||||
} finally {
|
} finally {
|
||||||
if (ping) clearInterval(ping);
|
if (ping) clearInterval(ping);
|
||||||
|
streams?.delete(closer);
|
||||||
if (!res.writableEnded && !res.destroyed) res.end();
|
if (!res.writableEnded && !res.destroyed) res.end();
|
||||||
bus?.emit('stream:close', { name });
|
bus?.emit('stream:close', { name });
|
||||||
}
|
}
|
||||||
@@ -122,7 +125,9 @@ function loadWss(): any | null {
|
|||||||
try { return require('ws').WebSocketServer; } catch { return null; }
|
try { return require('ws').WebSocketServer; } catch { return null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl): void {
|
function attachWs(
|
||||||
|
server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshControl?: MeshControl, streams?: Set<() => void>,
|
||||||
|
): void {
|
||||||
if (wsRoutes.length === 0 && !meshControl) return;
|
if (wsRoutes.length === 0 && !meshControl) return;
|
||||||
const WSS = loadWss();
|
const WSS = loadWss();
|
||||||
const wss = WSS ? new WSS({ noServer: true }) : null;
|
const wss = WSS ? new WSS({ noServer: true }) : null;
|
||||||
@@ -137,6 +142,9 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo
|
|||||||
if (!route) { socket.destroy(); return; }
|
if (!route) { socket.destroy(); return; }
|
||||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||||
wss.handleUpgrade(req, socket, head, async (ws: any) => {
|
wss.handleUpgrade(req, socket, head, async (ws: any) => {
|
||||||
|
const closer = () => { try { (ws.terminate ?? ws.close).call(ws); } catch { /* */ } };
|
||||||
|
streams?.add(closer);
|
||||||
|
ws.on('close', () => streams?.delete(closer));
|
||||||
const inbound = channel<unknown>();
|
const inbound = channel<unknown>();
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
ws.on('message', (d: Buffer) => inbound.push(d.toString()));
|
ws.on('message', (d: Buffer) => inbound.push(d.toString()));
|
||||||
@@ -211,7 +219,7 @@ export function createHttpServer(
|
|||||||
}
|
}
|
||||||
if (isStreamResult(result)) {
|
if (isStreamResult(result)) {
|
||||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||||
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern);
|
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const r: ResponseShape = result;
|
const r: ResponseShape = result;
|
||||||
@@ -221,6 +229,6 @@ export function createHttpServer(
|
|||||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||||
attachWs(server, wsRoutes, bus, meshControl);
|
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
@@ -153,3 +153,22 @@ describe('app streaming wiring', () => {
|
|||||||
client.close(); server.close();
|
client.close(); server.close();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('graceful shutdown', () => {
|
||||||
|
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
|
||||||
|
@Route('/')
|
||||||
|
class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as any).port;
|
||||||
|
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
await reader.read(); // first event; stream still open
|
||||||
|
|
||||||
|
await app.close(); // must NOT hang despite the open stream
|
||||||
|
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
|
||||||
|
reader.cancel().catch(() => {});
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user