import type { ICoreResponse } from '../core_base/types.js'; import { discardBody } from '../core_base/body.js'; import { ServerSentEventParser, checkServerSentEventLimits, streamServerSentEvents, type IServerSentEvent, type IServerSentEventLimits, } from '../core_base/sse.js'; export interface IEventStreamReconnectOptions { /** * Reconnections in a row without an event in between; when the next one would exceed it, the * iteration rejects with an EventStreamError (`reconnect_failed`). Default: 5; `Infinity` * reconnects for as long as the stream is read. */ maxAttempts?: number; /** Reconnection time in milliseconds until the server sets one with `retry`. Default: 3000 */ initialDelay?: number; /** Upper bound of every delay in milliseconds, the server's `retry` included. Default: 60000 */ maxDelay?: number; /** * The share of every delay that is random, from 0 to 1: a delay `d` becomes a random time * between `d * (1 - jitter)` and `d`, so that clients of one server do not reconnect in lockstep * after it restarted. Default: 0, the exact delay. */ jitter?: number; /** * Whether a response with this status (any but 200, which opens the stream, and 204, which ends * it) is retried like a failed connection instead of ending the iteration with an * EventStreamError (`unexpected_status`). Default: no status is retried, as in a browser's * EventSource, which fails the connection for good. For a server that answers 503 while it * starts: `(status) => status === 502 || status === 503`. */ retryStatus?: (status: number) => boolean; } /** * Options of `eventStream()`. `maxLineLength` and `maxEventSize` bound what one line and one event * may hold; a stream over them fails its connection with a ServerSentEventLimitError, which * `reconnect` retries. */ export interface IEventStreamOptions extends IServerSentEventLimits { /** Ends the stream: the iteration rejects with the signal's reason and the connection closes */ signal?: AbortSignal; /** Sent as `Last-Event-ID` with the first connection, to resume a stream read earlier */ lastEventId?: string; /** * Reconnect when the connection ends or fails, as a browser's EventSource does: after the * stream's reconnection time, with `Last-Event-ID`. Default: false, the iteration ends with the * connection. */ reconnect?: boolean | IEventStreamReconnectOptions; /** * Milliseconds each connection may take until the response head arrived: connecting, the TLS * handshake and the wait for the head. A connection that takes longer fails with an * EventStreamError (`connect_timeout`), which `reconnect` retries. The stream itself has no time * limit (see `timeout()` for an inactivity timeout). Default: none. */ connectTimeout?: number; } export type TEventStreamErrorCode = /** The response status was not 200 (a 204 ends the stream without an error) */ | 'unexpected_status' /** The response was not `text/event-stream` */ | 'unexpected_content_type' /** The reconnections allowed by `maxAttempts` failed; `cause` is the last failure */ | 'reconnect_failed' /** The response head did not arrive within `connectTimeout` */ | 'connect_timeout'; /** * An event stream that cannot be read, or could not be reconnected. */ export class EventStreamError extends Error { public readonly code: TEventStreamErrorCode; /** The stream URL without user name and password */ public readonly url: string; /** The response status, for `unexpected_status` and `unexpected_content_type` */ public readonly status: number | null; /** The response content type, for `unexpected_content_type` */ public readonly contentType: string | null; constructor( init: { code: TEventStreamErrorCode; url: string; status?: number; contentType?: string | null; attempts?: number; timeout?: number; }, cause?: unknown, ) { const messages: Record = { unexpected_status: `The event stream ${init.url} answered with status ${init.status}.`, unexpected_content_type: `The event stream ${init.url} answered with content type ${init.contentType ?? '(none)'}, not text/event-stream.`, reconnect_failed: `The event stream ${init.url} could not be reconnected (${init.attempts} attempts).`, connect_timeout: `The event stream ${init.url} did not answer within ${init.timeout} ms.`, }; super(messages[init.code], cause === undefined ? undefined : { cause }); this.name = 'EventStreamError'; this.code = init.code; this.url = init.url; this.status = init.status ?? null; this.contentType = init.contentType ?? null; } } interface IReconnectPolicy { maxAttempts: number; initialDelay: number; maxDelay: number; jitter: number; retryStatus: (status: number) => boolean; } const resolveReconnect = (reconnect: IEventStreamOptions['reconnect']): IReconnectPolicy | null => { if (!reconnect) { return null; } const options = reconnect === true ? {} : reconnect; const policy: IReconnectPolicy = { maxAttempts: options.maxAttempts ?? 5, initialDelay: options.initialDelay ?? 3000, maxDelay: options.maxDelay ?? 60_000, jitter: options.jitter ?? 0, retryStatus: options.retryStatus ?? (() => false), }; if (!(policy.maxAttempts >= 0) || (policy.maxAttempts !== Infinity && !Number.isInteger(policy.maxAttempts))) { throw new TypeError('reconnect.maxAttempts must be a non-negative integer or Infinity.'); } for (const key of ['initialDelay', 'maxDelay'] as const) { if (!Number.isFinite(policy[key]) || policy[key] < 0) { throw new TypeError(`reconnect.${key} must be a non-negative number of milliseconds.`); } } if (!(policy.jitter >= 0 && policy.jitter <= 1)) { throw new TypeError('reconnect.jitter must be a number from 0 to 1.'); } if (typeof policy.retryStatus !== 'function') { throw new TypeError('reconnect.retryStatus must be a function.'); } return policy; }; /** * Checks the options of an event stream; throws a TypeError for invalid values. */ export const checkEventStreamOptions = (options: IEventStreamOptions): void => { if (options.lastEventId !== undefined && (typeof options.lastEventId !== 'string' || /[\r\n\u0000]/.test(options.lastEventId))) { throw new TypeError('lastEventId must be a string without CR, LF or NUL.'); } resolveReconnect(options.reconnect); checkServerSentEventLimits(options); if ( options.connectTimeout !== undefined && !(Number.isFinite(options.connectTimeout) && options.connectTimeout > 0) ) { throw new TypeError('connectTimeout must be a positive number of milliseconds.'); } }; const sleep = (milliseconds: number, signal: AbortSignal | undefined): Promise => new Promise((resolve, reject) => { const onAbort = (): void => { clearTimeout(timer); reject(signal?.reason); }; const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, milliseconds); signal?.addEventListener('abort', onAbort, { once: true }); }); /** * Connects once. The connection gets its own signal, aborted when the caller's signal aborts or * `connectTimeout` runs out before the response arrived. The promise settles only once the * transport settled: a response that arrives after the abort is cancelled first, so its connection * is closed when the promise rejects. */ const connectOnce = ( connect: (headers: Record, signal: AbortSignal) => Promise, headers: Record, signal: AbortSignal | undefined, connectTimeout: number | undefined, url: string, ): Promise => { const attempt = new AbortController(); return new Promise((resolve, reject) => { let ended: { error: unknown } | null = null; const end = (error: unknown): void => { if (!ended) { ended = { error }; attempt.abort(error); } }; const onAbort = (): void => end(signal?.reason); signal?.addEventListener('abort', onAbort, { once: true }); const timer = connectTimeout === undefined ? null : setTimeout( () => end(new EventStreamError({ code: 'connect_timeout', url, timeout: connectTimeout })), connectTimeout, ); const settle = (): void => { signal?.removeEventListener('abort', onAbort); if (timer !== null) { clearTimeout(timer); } }; connect(headers, attempt.signal).then( (response) => { settle(); if (!ended) { resolve(response); return; } const { error } = ended; void discardBody(response.stream(), null).then(() => reject(error)); }, (error: unknown) => { settle(); reject(ended ? ended.error : error); }, ); }); }; const headerValue = (value: string | string[] | undefined): string | null => value === undefined ? null : Array.isArray(value) ? value.join(', ') : value; /** * Reads an event stream through `connect`, which sends the configured request with the given extra * headers and signal, and reconnects as `options.reconnect` allows. */ export async function* readEventStream( connect: (headers: Record, signal: AbortSignal) => Promise, url: string, options: IEventStreamOptions, ): AsyncGenerator { checkEventStreamOptions(options); const { signal } = options; const policy = resolveReconnect(options.reconnect); const parser = new ServerSentEventParser({ lastEventId: options.lastEventId, maxLineLength: options.maxLineLength, maxEventSize: options.maxEventSize, }); let failures = 0; let lastFailure: unknown = undefined; for (;;) { signal?.throwIfAborted(); if (policy && failures > 0) { if (failures > policy.maxAttempts) { throw new EventStreamError( { code: 'reconnect_failed', url, attempts: failures - 1 }, lastFailure, ); } const base = parser.reconnectionTime ?? policy.initialDelay; const delay = Math.min(base * 2 ** (failures - 1), policy.maxDelay); await sleep(delay * (1 - policy.jitter * Math.random()), signal); } const headers: Record = { accept: 'text/event-stream', 'cache-control': 'no-store', }; if (parser.lastEventId !== '') { headers['last-event-id'] = parser.lastEventId; } let response: ICoreResponse; try { response = await connectOnce(connect, headers, signal, options.connectTimeout, url); } catch (error) { if (signal?.aborted) { throw signal.reason; } if (!policy) { throw error; } lastFailure = error; failures++; continue; } const contentType = headerValue(response.headers['content-type']); if (response.status === 204) { await discardBody(response.stream(), headerValue(response.headers['content-length'])); return; } if (response.status !== 200) { await discardBody(response.stream(), headerValue(response.headers['content-length'])); const error = new EventStreamError({ code: 'unexpected_status', url, status: response.status }); if (!policy?.retryStatus(response.status)) { throw error; } lastFailure = error; failures++; continue; } if (contentType?.split(';')[0].trim().toLowerCase() !== 'text/event-stream') { await discardBody(response.stream(), headerValue(response.headers['content-length'])); throw new EventStreamError({ code: 'unexpected_content_type', url, status: response.status, contentType, }); } const body = response.stream(); let delivered = false; let failure: { error: unknown } | null = null; try { if (body) { for await (const event of streamServerSentEvents(body, parser, signal)) { delivered = true; yield event; } } } catch (error) { if (signal?.aborted) { throw signal.reason; } failure = { error }; } if (!policy) { if (failure) { throw failure.error; } return; } lastFailure = failure ? failure.error : new Error(`The event stream ${url} ended.`); failures = delivered ? 1 : failures + 1; } }