Tier 3 for the beta: what the graph earns you, and an event stream you can build on #82
No files matched your search
+100
-2
@@ -11,10 +11,106 @@ export interface StreamEncoder {
|
||||
|
||||
const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
||||
|
||||
// Registered globally rather than module-local: this package ships twice — a bundle on npm and raw
|
||||
// source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped
|
||||
// being recognised across them would silently degrade back to an id-less `data:` frame.
|
||||
const SSE_EVENT = Symbol.for('green-tea.sse-event');
|
||||
|
||||
/** Optional SSE fields carried alongside a payload. See {@link sse}. */
|
||||
export interface SseFields {
|
||||
/**
|
||||
* The event's id, written as `id:`. The browser echoes the last one it saw back as the
|
||||
* `Last-Event-ID` request header when `EventSource` reconnects — read it with
|
||||
* `@header('last-event-id')` and resume from there.
|
||||
*/
|
||||
id?: string;
|
||||
/** Event name, written as `event:`. Dispatched to `addEventListener(name)` instead of `onmessage`. */
|
||||
event?: string;
|
||||
/** Reconnection delay in whole milliseconds, written as `retry:`. Applies to the connection, not the event. */
|
||||
retry?: number;
|
||||
}
|
||||
|
||||
/** A stream item carrying SSE fields as well as a payload. Build one with {@link sse}. */
|
||||
export interface SseEvent<T = unknown> extends SseFields {
|
||||
readonly [SSE_EVENT]: true;
|
||||
data: T;
|
||||
}
|
||||
|
||||
/** Type guard: true when a stream item was built by {@link sse}. */
|
||||
export function isSseEvent(item: unknown): item is SseEvent {
|
||||
return typeof item === 'object' && item !== null && (item as Record<symbol, unknown>)[SSE_EVENT] === true;
|
||||
}
|
||||
|
||||
// The SSE wire format is line-based, so a newline inside a field value ends the field — and a
|
||||
// value that reaches `id:` from a request (a cursor, a page token) would let a caller append
|
||||
// arbitrary fields, or whole events, to somebody else's stream. Rejected rather than stripped:
|
||||
// a silently-shortened id is echoed back as `Last-Event-ID` and resumes from the wrong place,
|
||||
// which is the same invisible gap this feature exists to close. `pipeStream` catches this, emits
|
||||
// `stream:error` and writes an `error` frame, so the failure is loud and lands on the first event.
|
||||
function assertFieldSafe(field: string, value: string): void {
|
||||
if (!/[\r\n\0]/.test(value)) return;
|
||||
|
||||
throw new Error(
|
||||
`sse(): '${field}' may not contain a newline or a NUL — the SSE wire format is line-based, so ` +
|
||||
'one would end the field and let the rest of the value be read as further SSE fields. ' +
|
||||
`Received ${JSON.stringify(value)}.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tags a stream item with SSE fields, so an `@Sse` route can emit `id:`, `event:` and `retry:`
|
||||
* instead of a bare `data:` frame.
|
||||
*
|
||||
* The `id` is what makes an `EventSource` reconnect resumable: the browser sends the last id it
|
||||
* saw back as `Last-Event-ID`, and the handler decides what to do with it. green-tea carries the
|
||||
* marker in both directions and stores nothing — a source that can resume, resumes; one that
|
||||
* cannot keeps streaming from now, which is the honest behaviour for a live feed.
|
||||
*
|
||||
* On an `ndjson` or `negotiate`-to-ndjson route the payload is unwrapped and the SSE fields are
|
||||
* dropped, because NDJSON has no frame to carry them and no resumption protocol to use them.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* @Sse('/feed')
|
||||
* feed(@header('last-event-id') from: string) {
|
||||
* return (async function* () {
|
||||
* for await (const row of rows({ after: from })) yield sse(row, { id: row.seq });
|
||||
* })();
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function sse<T>(data: T, fields: SseFields = {}): SseEvent<T> {
|
||||
if (fields.id !== undefined) assertFieldSafe('id', fields.id);
|
||||
if (fields.event !== undefined) assertFieldSafe('event', fields.event);
|
||||
|
||||
// Browsers ignore a `retry:` that is not a base-10 integer, so a float would silently leave the
|
||||
// reconnection delay at the default rather than at the value the app asked for.
|
||||
if (fields.retry !== undefined && !Number.isInteger(fields.retry)) {
|
||||
throw new Error(`sse(): 'retry' must be a whole number of milliseconds, received ${fields.retry}.`);
|
||||
}
|
||||
|
||||
return { [SSE_EVENT]: true, data, ...fields };
|
||||
}
|
||||
|
||||
/**
|
||||
* Frames one item as an SSE event. Fields precede `data:` and `data:` closes the event.
|
||||
* `JSON.stringify` escapes newlines inside the payload, so the data line is single by construction.
|
||||
*/
|
||||
function sseFrame(item: unknown): string {
|
||||
if (!isSseEvent(item)) return `data: ${JSON.stringify(item)}\n\n`;
|
||||
let frame = '';
|
||||
|
||||
if (item.retry !== undefined) frame += `retry: ${item.retry}\n`;
|
||||
if (item.event !== undefined) frame += `event: ${item.event}\n`;
|
||||
if (item.id !== undefined) frame += `id: ${item.id}\n`;
|
||||
|
||||
return `${frame}data: ${JSON.stringify(item.data)}\n\n`;
|
||||
}
|
||||
|
||||
/** Server-Sent Events encoder: one JSON payload per `data:` event, with comment-line pings. */
|
||||
export const sseEncoder: StreamEncoder = {
|
||||
headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' },
|
||||
encode: (item) => `data: ${JSON.stringify(item)}\n\n`,
|
||||
encode: sseFrame,
|
||||
encodeError: (err) => `event: error\ndata: ${JSON.stringify({ error: messageOf(err) })}\n\n`,
|
||||
ping: () => ': ping\n\n',
|
||||
};
|
||||
@@ -22,6 +118,8 @@ export const sseEncoder: StreamEncoder = {
|
||||
/** Newline-delimited JSON encoder: one JSON object per line. */
|
||||
export const ndjsonEncoder: StreamEncoder = {
|
||||
headers: { 'content-type': 'application/x-ndjson' },
|
||||
encode: (item) => `${JSON.stringify(item)}\n`,
|
||||
// Unwrapped rather than serialized as-is: a `negotiate` route yields the same items to both
|
||||
// encoders, and an ndjson client asked for the payload, not green-tea's SSE envelope around it.
|
||||
encode: (item) => `${JSON.stringify(isSseEvent(item) ? item.data : item)}\n`,
|
||||
encodeError: (err) => `${JSON.stringify({ error: messageOf(err) })}\n`,
|
||||
};
|
||||
+2
-2
@@ -76,8 +76,8 @@ export type { Logger, LogLevel, LogFields } from './logger';
|
||||
export { channel, isAsyncIterable } from './channel';
|
||||
export type { Channel } from './channel';
|
||||
export { Rooms } from './rooms';
|
||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder } from './encoders';
|
||||
export { sse, isSseEvent, sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder, SseEvent, SseFields } from './encoders';
|
||||
|
||||
// HTTP, security & validation
|
||||
export type { RequestLimits } from './http';
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// `id:` on the wire, and the `Last-Event-ID` round-trip it exists to enable.
|
||||
//
|
||||
// `EventSource` reconnects on its own — that is the reason to pick SSE over a raw WebSocket. Until
|
||||
// an `id:` was written the browser had nothing to send back, so every reconnect restarted the
|
||||
// iterable from its beginning and lost the gap in silence. green-tea carries the marker both ways
|
||||
// and stores nothing: what the gap means is the handler's call, because only the source knows
|
||||
// whether it is replayable.
|
||||
import 'reflect-metadata';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ndjsonEncoder, sse, sseEncoder } from '../src/encoders';
|
||||
import { Module, Route, Sse } from '../src/metadata';
|
||||
import { header } from '../src/params';
|
||||
import { createApp } from '../src/app';
|
||||
|
||||
const frame = (item: unknown): string => String(sseEncoder.encode(item));
|
||||
|
||||
describe('sse() framing', () => {
|
||||
it('writes id: before data:', () => {
|
||||
expect(frame(sse({ t: 1 }, { id: '7' }))).toBe('id: 7\ndata: {"t":1}\n\n');
|
||||
});
|
||||
|
||||
it('writes every field it was given, fields before data', () => {
|
||||
expect(frame(sse({ t: 1 }, { id: '7', event: 'tick', retry: 5000 }))).toBe(
|
||||
'retry: 5000\nevent: tick\nid: 7\ndata: {"t":1}\n\n',
|
||||
);
|
||||
});
|
||||
|
||||
it('leaves a plain item exactly as it was', () => {
|
||||
// The whole point of the marker: an app that never calls sse() sees no change on the wire.
|
||||
expect(frame({ t: 1 })).toBe('data: {"t":1}\n\n');
|
||||
});
|
||||
|
||||
it('keeps an empty id, which is how the spec resets the client s last event id', () => {
|
||||
expect(frame(sse({ t: 1 }, { id: '' }))).toBe('id: \ndata: {"t":1}\n\n');
|
||||
});
|
||||
|
||||
it('cannot be talked into extra fields by a newline in the payload', () => {
|
||||
// JSON.stringify escapes the newline, so the data line stays single by construction.
|
||||
expect(frame({ note: 'a\nid: 99' })).toBe('data: {"note":"a\\nid: 99"}\n\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sse() rejects a field that would break the frame', () => {
|
||||
// An id is exactly the value most likely to come from a request — a cursor, a page token — so
|
||||
// this is a boundary, not a formatting nicety. Stripping would resume from the wrong place
|
||||
// silently, which is the bug this feature exists to close.
|
||||
for (const [label, id] of [
|
||||
['newline', 'a\nid: 99'],
|
||||
['carriage return', 'a\rid: 99'],
|
||||
['NUL', 'a\0b'],
|
||||
] as const) {
|
||||
it(`throws on a ${label} in id`, () => {
|
||||
expect(() => sse({ t: 1 }, { id })).toThrow(/may not contain a newline or a NUL/);
|
||||
});
|
||||
}
|
||||
|
||||
it('throws on a newline in event', () => {
|
||||
expect(() => sse({ t: 1 }, { event: 'a\ndata: fake' })).toThrow(/'event' may not contain/);
|
||||
});
|
||||
|
||||
it('throws on a fractional retry, which a browser would ignore', () => {
|
||||
expect(() => sse({ t: 1 }, { retry: 1.5 })).toThrow(/whole number of milliseconds/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ndjson', () => {
|
||||
it('unwraps the payload and drops the SSE fields', () => {
|
||||
// A `negotiate` route yields the same items to both encoders. NDJSON has no frame to carry
|
||||
// id/event/retry and no resumption protocol to use them, so the client gets what it asked for.
|
||||
expect(String(ndjsonEncoder.encode(sse({ t: 1 }, { id: '7' })))).toBe('{"t":1}\n');
|
||||
});
|
||||
|
||||
it('leaves a plain item alone', () => {
|
||||
expect(String(ndjsonEncoder.encode({ t: 1 }))).toBe('{"t":1}\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the Last-Event-ID round trip', () => {
|
||||
const app = (): ReturnType<typeof createApp> => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
// Reading the header needs nothing new — the envelope has always carried it. What was
|
||||
// missing was the `id:` that gives the browser something to put in it.
|
||||
@Sse('/feed') feed(@header('last-event-id') from: string) {
|
||||
const start = from ? Number(from) + 1 : 1;
|
||||
return (async function* () {
|
||||
for (let n = start; n < start + 2; n++) yield sse({ n }, { id: String(n) });
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
return createApp({ modules: [M] });
|
||||
};
|
||||
|
||||
it('serves ids, and resumes from the one the client sends back', async () => {
|
||||
const feed = app();
|
||||
|
||||
const first = await (await feed.fetch(new Request('http://x/feed'))).text();
|
||||
expect(first).toBe('id: 1\ndata: {"n":1}\n\nid: 2\ndata: {"n":2}\n\n');
|
||||
|
||||
// What EventSource does by itself on reconnect, spelled out.
|
||||
const resumed = await (
|
||||
await feed.fetch(new Request('http://x/feed', { headers: { 'last-event-id': '2' } }))
|
||||
).text();
|
||||
expect(resumed).toBe('id: 3\ndata: {"n":3}\n\nid: 4\ndata: {"n":4}\n\n');
|
||||
});
|
||||
|
||||
it('serves the same bytes over the Node adapter', async () => {
|
||||
// A different write path — `pipeStream` to a socket rather than a web ReadableStream — so
|
||||
// passing on `fetch` proves nothing about the runtime most apps deploy on.
|
||||
const feed = app();
|
||||
const server = await feed.listen(0);
|
||||
const { port } = server.address() as import('net').AddressInfo;
|
||||
|
||||
const res = await fetch(`http://127.0.0.1:${port}/feed`, { headers: { 'last-event-id': '9' } });
|
||||
expect(res.headers.get('content-type')).toBe('text/event-stream');
|
||||
expect(await res.text()).toBe('id: 10\ndata: {"n":10}\n\nid: 11\ndata: {"n":11}\n\n');
|
||||
|
||||
await feed.close();
|
||||
});
|
||||
|
||||
it('refuses an id that would inject fields, rather than writing it', async () => {
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Sse('/bad') bad() {
|
||||
return (async function* () {
|
||||
yield sse({ t: 1 }, { id: 'cursor\ndata: injected' });
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
const broken = createApp({ modules: [M] });
|
||||
const errors: unknown[] = [];
|
||||
broken.bus.on('stream:error', (e) => errors.push(e.error));
|
||||
|
||||
// The Node adapter turns a mid-stream throw into a bus event and a trailing `error` frame.
|
||||
const server = await broken.listen(0);
|
||||
const { port } = server.address() as import('net').AddressInfo;
|
||||
const body = await (await fetch(`http://127.0.0.1:${port}/bad`)).text();
|
||||
|
||||
// Not `toContain`: the rejection quotes the offending value, so the text appears inside the
|
||||
// error payload — escaped, on one line. The claim is that no *field* was injected.
|
||||
expect(body.split('\n')).not.toContain('data: injected');
|
||||
expect(body).toContain('event: error');
|
||||
expect(errors).toHaveLength(1);
|
||||
|
||||
await broken.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user