feat: SSE/ndjson streaming responses with backpressure and cleanup
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+141
-26
No files matched your search
@@ -1,6 +1,7 @@
|
|||||||
export type LifecycleEvent =
|
export type LifecycleEvent =
|
||||||
| 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
|
| 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail'
|
||||||
| 'request:step:enter' | 'request:step:leave' | 'request:step:error'
|
| 'request:step:enter' | 'request:step:leave' | 'request:step:error'
|
||||||
|
| 'stream:open' | 'stream:close' | 'stream:error'
|
||||||
| 'plugin:mounted';
|
| 'plugin:mounted';
|
||||||
|
|
||||||
export interface EventPayload {
|
export interface EventPayload {
|
||||||
|
|||||||
+79
-22
@@ -1,6 +1,10 @@
|
|||||||
import http from 'http';
|
import http from 'http';
|
||||||
|
import { once } from 'events';
|
||||||
import { errorToResponse } from './transformers';
|
import { errorToResponse } from './transformers';
|
||||||
import type { ResponseShape } from './pipeline';
|
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||||
|
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||||
|
import type { Transport } from './metadata';
|
||||||
|
import type { Bus } from './bus';
|
||||||
|
|
||||||
export type RouteHandler = (req: {
|
export type RouteHandler = (req: {
|
||||||
method: string; url: string;
|
method: string; url: string;
|
||||||
@@ -8,24 +12,38 @@ export type RouteHandler = (req: {
|
|||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
query: Record<string, string>;
|
query: Record<string, string>;
|
||||||
body: unknown;
|
body: unknown;
|
||||||
}) => Promise<ResponseShape>;
|
}) => Promise<PipelineResult>;
|
||||||
|
|
||||||
export interface RouteDef { method: string; pattern: string; handler: RouteHandler }
|
export interface RouteDef { method: string; pattern: string; transport: Transport; handler: RouteHandler }
|
||||||
export interface MatchedRoute { params: Record<string, string>; handler: RouteHandler }
|
export interface MatchedRoute { params: Record<string, string>; def: RouteDef }
|
||||||
|
|
||||||
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
export interface WsOpenCtx {
|
||||||
|
params: Record<string, string>;
|
||||||
|
inbound: AsyncIterable<unknown>;
|
||||||
|
abort: AbortSignal;
|
||||||
|
req: http.IncomingMessage;
|
||||||
|
}
|
||||||
|
export interface WsRouteDef { pattern: string; open: (ctx: WsOpenCtx) => Promise<AsyncIterable<unknown>> }
|
||||||
|
|
||||||
|
const PING_MS = 15_000;
|
||||||
|
|
||||||
|
export function matchPattern(pattern: string, path: string): Record<string, string> | undefined {
|
||||||
const segs = path.split('/').filter(Boolean);
|
const segs = path.split('/').filter(Boolean);
|
||||||
for (const r of routes) {
|
const pat = pattern.split('/').filter(Boolean);
|
||||||
if (r.method !== method) continue;
|
if (pat.length !== segs.length) return undefined;
|
||||||
const pat = r.pattern.split('/').filter(Boolean);
|
|
||||||
if (pat.length !== segs.length) continue;
|
|
||||||
const params: Record<string, string> = {};
|
const params: Record<string, string> = {};
|
||||||
let ok = true;
|
|
||||||
for (let i = 0; i < pat.length; i++) {
|
for (let i = 0; i < pat.length; i++) {
|
||||||
if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]);
|
if (pat[i].startsWith(':')) params[pat[i].slice(1)] = decodeURIComponent(segs[i]);
|
||||||
else if (pat[i] !== segs[i]) { ok = false; break; }
|
else if (pat[i] !== segs[i]) return undefined;
|
||||||
}
|
}
|
||||||
if (ok) return { params, handler: r.handler };
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined {
|
||||||
|
for (const r of routes) {
|
||||||
|
if (r.method !== method) continue;
|
||||||
|
const params = matchPattern(r.pattern, path);
|
||||||
|
if (params) return { params, def: r };
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -45,8 +63,42 @@ async function readBody(req: http.IncomingMessage): Promise<string | undefined>
|
|||||||
return raw === '' ? undefined : raw;
|
return raw === '' ? undefined : raw;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createHttpServer(routes: RouteDef[]): http.Server {
|
function pickEncoder(transport: Transport, accept: string): StreamEncoder {
|
||||||
return http.createServer(async (req, res) => {
|
if (transport === 'sse') return sseEncoder;
|
||||||
|
if (transport === 'ndjson') return ndjsonEncoder;
|
||||||
|
return accept.includes('text/event-stream') ? sseEncoder : ndjsonEncoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pipeStream(
|
||||||
|
res: http.ServerResponse, stream: AsyncIterable<unknown>, encoder: StreamEncoder,
|
||||||
|
bus?: Bus, name = '',
|
||||||
|
): Promise<void> {
|
||||||
|
res.writeHead(200, encoder.headers);
|
||||||
|
bus?.emit('stream:open', { name });
|
||||||
|
const it = stream[Symbol.asyncIterator]();
|
||||||
|
let ping: ReturnType<typeof setInterval> | undefined;
|
||||||
|
if (encoder.ping) { ping = setInterval(() => res.write(encoder.ping!()), PING_MS); ping.unref?.(); }
|
||||||
|
const stop = () => { if (ping) clearInterval(ping); void it.return?.(); };
|
||||||
|
res.on('close', stop);
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await it.next();
|
||||||
|
if (done) break;
|
||||||
|
if (!res.write(encoder.encode(value))) await once(res, 'drain');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
bus?.emit('stream:error', { name, error: err });
|
||||||
|
const frame = encoder.encodeError(err);
|
||||||
|
if (frame && !res.writableEnded) res.write(frame);
|
||||||
|
} finally {
|
||||||
|
if (ping) clearInterval(ping);
|
||||||
|
if (!res.writableEnded) res.end();
|
||||||
|
bus?.emit('stream:close', { name });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus): http.Server {
|
||||||
|
const server = http.createServer(async (req, res) => {
|
||||||
const url = req.url ?? '/';
|
const url = req.url ?? '/';
|
||||||
const path = url.split('?')[0];
|
const path = url.split('?')[0];
|
||||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
||||||
@@ -59,7 +111,6 @@ export function createHttpServer(routes: RouteDef[]): http.Server {
|
|||||||
try {
|
try {
|
||||||
raw = await readBody(req);
|
raw = await readBody(req);
|
||||||
} catch {
|
} catch {
|
||||||
// stream/network failure — not the client's JSON fault
|
|
||||||
res.writeHead(500, { 'content-type': 'application/json' });
|
res.writeHead(500, { 'content-type': 'application/json' });
|
||||||
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
||||||
return;
|
return;
|
||||||
@@ -67,24 +118,30 @@ export function createHttpServer(routes: RouteDef[]): http.Server {
|
|||||||
let body: unknown = raw;
|
let body: unknown = raw;
|
||||||
const ct = String(req.headers['content-type'] ?? '');
|
const ct = String(req.headers['content-type'] ?? '');
|
||||||
if (raw !== undefined && ct.includes('application/json')) {
|
if (raw !== undefined && ct.includes('application/json')) {
|
||||||
try {
|
try { body = JSON.parse(raw); }
|
||||||
body = JSON.parse(raw);
|
catch {
|
||||||
} catch {
|
|
||||||
res.writeHead(400, { 'content-type': 'application/json' });
|
res.writeHead(400, { 'content-type': 'application/json' });
|
||||||
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let result: ResponseShape;
|
let result: PipelineResult;
|
||||||
try {
|
try {
|
||||||
result = await matched.handler({
|
result = await matched.def.handler({
|
||||||
method: req.method ?? 'GET', url, headers: req.headers,
|
method: req.method ?? 'GET', url, headers: req.headers,
|
||||||
params: matched.params, query: parseQuery(url), body,
|
params: matched.params, query: parseQuery(url), body,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
result = errorToResponse(error);
|
result = errorToResponse(error);
|
||||||
}
|
}
|
||||||
res.writeHead(result.status, result.headers);
|
if (isStreamResult(result)) {
|
||||||
res.end(result.body);
|
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||||
|
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const r: ResponseShape = result;
|
||||||
|
res.writeHead(r.status, r.headers);
|
||||||
|
res.end(r.body);
|
||||||
});
|
});
|
||||||
|
return server; // Task 7 will insert `attachWs(server, wsRoutes);` before this line
|
||||||
}
|
}
|
||||||
+61
-4
@@ -1,16 +1,16 @@
|
|||||||
import { expect, test } from 'vitest';
|
import { describe, expect, it, test } from 'vitest';
|
||||||
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
|
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
|
||||||
|
|
||||||
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
|
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
|
||||||
|
|
||||||
test('matches a static + :param route and extracts params', () => {
|
test('matches a static + :param route and extracts params', () => {
|
||||||
const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }];
|
const routes = [{ method: 'GET', pattern: '/api/users/:id', transport: 'buffer' as const, handler }];
|
||||||
const m = matchRoute(routes, 'GET', '/api/users/42');
|
const m = matchRoute(routes, 'GET', '/api/users/42');
|
||||||
expect(m?.params).toEqual({ id: '42' });
|
expect(m?.params).toEqual({ id: '42' });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('returns undefined when nothing matches', () => {
|
test('returns undefined when nothing matches', () => {
|
||||||
const routes = [{ method: 'GET', pattern: '/api/users/:id', handler }];
|
const routes = [{ method: 'GET', pattern: '/api/users/:id', transport: 'buffer' as const, handler }];
|
||||||
expect(matchRoute(routes, 'GET', '/api/orders/1')).toBeUndefined();
|
expect(matchRoute(routes, 'GET', '/api/orders/1')).toBeUndefined();
|
||||||
expect(matchRoute(routes, 'POST', '/api/users/1')).toBeUndefined();
|
expect(matchRoute(routes, 'POST', '/api/users/1')).toBeUndefined();
|
||||||
});
|
});
|
||||||
@@ -22,7 +22,7 @@ test('parseQuery extracts query params from a url', () => {
|
|||||||
|
|
||||||
test('server parses json body and rejects malformed json with 400', async () => {
|
test('server parses json body and rejects malformed json with 400', async () => {
|
||||||
const server = createHttpServer([{
|
const server = createHttpServer([{
|
||||||
method: 'POST', pattern: '/echo',
|
method: 'POST', pattern: '/echo', transport: 'buffer',
|
||||||
handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body, q: req.query }) }),
|
handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body, q: req.query }) }),
|
||||||
}]);
|
}]);
|
||||||
await new Promise<void>((r) => server.listen(0, r));
|
await new Promise<void>((r) => server.listen(0, r));
|
||||||
@@ -40,3 +40,60 @@ test('server parses json body and rejects malformed json with 400', async () =>
|
|||||||
|
|
||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const getServerUrl = (server: import('http').Server) => {
|
||||||
|
const addr = server.address();
|
||||||
|
if (addr && typeof addr === 'object') return `http://127.0.0.1:${addr.port}`;
|
||||||
|
throw new Error('no address');
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('http streaming', () => {
|
||||||
|
it('streams SSE events from an async-iterable handler and runs finally on disconnect', async () => {
|
||||||
|
let cleanedUp = false;
|
||||||
|
async function* feed() {
|
||||||
|
try { yield { n: 1 }; yield { n: 2 }; await new Promise((r) => setTimeout(r, 50)); yield { n: 3 }; }
|
||||||
|
finally { cleanedUp = true; }
|
||||||
|
}
|
||||||
|
const server = createHttpServer([
|
||||||
|
{ method: 'GET', pattern: '/feed', transport: 'sse', handler: async () => ({ stream: feed() }) },
|
||||||
|
]);
|
||||||
|
await new Promise<void>((r) => server.listen(0, r));
|
||||||
|
const res = await fetch(`${getServerUrl(server)}/feed`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
expect(res.headers.get('content-type')).toBe('text/event-stream');
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
const dec = new TextDecoder();
|
||||||
|
let buf = '';
|
||||||
|
while (!buf.includes('data: {"n":2}')) buf += dec.decode((await reader.read()).value);
|
||||||
|
expect(buf).toContain('data: {"n":1}\n\n');
|
||||||
|
await reader.cancel(); // client disconnect
|
||||||
|
await new Promise((r) => setTimeout(r, 60));
|
||||||
|
expect(cleanedUp).toBe(true);
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('frames a mid-stream error and closes', async () => {
|
||||||
|
async function* boom() { yield { ok: true }; throw new Error('kaboom'); }
|
||||||
|
const server = createHttpServer([
|
||||||
|
{ method: 'GET', pattern: '/boom', transport: 'sse', handler: async () => ({ stream: boom() }) },
|
||||||
|
]);
|
||||||
|
await new Promise<void>((r) => server.listen(0, r));
|
||||||
|
const res = await fetch(`${getServerUrl(server)}/boom`, { headers: { accept: 'text/event-stream' } });
|
||||||
|
const text = await res.text();
|
||||||
|
expect(text).toContain('data: {"ok":true}\n\n');
|
||||||
|
expect(text).toContain('event: error');
|
||||||
|
expect(text).toContain('kaboom');
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('routes by method (non-GET no longer falls through)', async () => {
|
||||||
|
const server = createHttpServer([
|
||||||
|
{ method: 'POST', pattern: '/make', transport: 'buffer',
|
||||||
|
handler: async () => ({ status: 201, headers: { 'content-type': 'application/json' }, body: '{"made":true}' }) },
|
||||||
|
]);
|
||||||
|
await new Promise<void>((r) => server.listen(0, r));
|
||||||
|
const res = await fetch(`${getServerUrl(server)}/make`, { method: 'POST' });
|
||||||
|
expect(res.status).toBe(201);
|
||||||
|
expect(await res.json()).toEqual({ made: true });
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user