diff --git a/src/app.ts b/src/app.ts index f6a415e..19e7079 100644 --- a/src/app.ts +++ b/src/app.ts @@ -20,6 +20,7 @@ import type { RequestEnvelope, RouteEntry } from './mesh/protocol'; export interface InspectLine { name: string; kind: 'provider' | 'step' | 'handler'; origin: string } export interface App { listen(port: number): Promise; + close(): Promise; inspect(routePath: string): InspectLine[]; bus: Bus; } @@ -46,6 +47,8 @@ export interface MeshConfig { export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App { const bus = new Bus(); const container = new Container(); + let server: http.Server | undefined; + const streams = new Set<() => void>(); const extraSteps: ScopeNode[] = []; 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 { /* */ } } }); - await new Promise((resolve) => server.listen(port, resolve)); + await new Promise((resolve) => server!.listen(port, resolve)); return server; }; - return { listen, inspect, bus }; + const close = (): Promise => new Promise((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> { diff --git a/src/http.ts b/src/http.ts index a0bc495..c4602c0 100644 --- a/src/http.ts +++ b/src/http.ts @@ -14,7 +14,7 @@ export interface RequestLimits { headersTimeoutMs?: number; // default 10_000 keepAliveTimeoutMs?: number; // default 5_000 } -export interface HttpOptions { limits?: RequestLimits } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void> } export type RouteHandler = (req: { method: string; url: string; @@ -88,7 +88,7 @@ function pickEncoder(transport: Transport, accept: string): StreamEncoder { async function pipeStream( res: http.ServerResponse, stream: AsyncIterable, encoder: StreamEncoder, - bus?: Bus, name = '', + bus?: Bus, name = '', streams?: Set<() => void>, ): Promise { res.writeHead(200, encoder.headers); 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?.(); } const stop = () => { if (ping) clearInterval(ping); void Promise.resolve(it.return?.()).catch(() => {}); }; res.on('close', stop); + const closer = () => { try { res.destroy(); } catch { /* */ } }; + streams?.add(closer); const onClose = once(res, 'close'); try { while (true) { @@ -113,6 +115,7 @@ async function pipeStream( if (frame && !res.writableEnded) res.write(frame); } finally { if (ping) clearInterval(ping); + streams?.delete(closer); if (!res.writableEnded && !res.destroyed) res.end(); bus?.emit('stream:close', { name }); } @@ -122,7 +125,9 @@ function loadWss(): any | 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; const WSS = loadWss(); 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 (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; } 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(); const ac = new AbortController(); ws.on('message', (d: Buffer) => inbound.push(d.toString())); @@ -211,7 +219,7 @@ export function createHttpServer( } if (isStreamResult(result)) { 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; } const r: ResponseShape = result; @@ -221,6 +229,6 @@ export function createHttpServer( server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl); + attachWs(server, wsRoutes, bus, meshControl, opts?.streams); return server; } diff --git a/test/app.test.ts b/test/app.test.ts index 250bd36..cb1c6d8 100644 --- a/test/app.test.ts +++ b/test/app.test.ts @@ -153,3 +153,22 @@ describe('app streaming wiring', () => { 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(() => {}); + }); +});