Add tests. Add exponential backoff contexts. Update error handling. Imrove Event Parser compatibility. Simplify SSE Session. Simplify Async Iterator.
This commit is contained in:
65
tests/helpers/sse-stream.ts
Normal file
65
tests/helpers/sse-stream.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
export type SseTestStreamOptions = {
|
||||
|
||||
/** Milliseconds to wait before enqueueing each chunk after the first. */
|
||||
chunkDelayMs?: number;
|
||||
|
||||
/**
|
||||
* When true, closes the body as soon as all initial chunks have been sent.
|
||||
* Use this to simulate a server that sends events and then ends the stream.
|
||||
*/
|
||||
closeWhenDone?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Test double for an SSE HTTP response body.
|
||||
*
|
||||
* Enqueues fixture chunks in order and stays open until {@link close} is called,
|
||||
* matching real servers that keep the connection alive after each event's trailing
|
||||
* `\n\n` frame boundary.
|
||||
*/
|
||||
export class SseTestStream {
|
||||
readonly stream: ReadableStream<Uint8Array>;
|
||||
|
||||
private controller: ReadableStreamDefaultController<Uint8Array> | null = null;
|
||||
|
||||
private closed = false;
|
||||
|
||||
/**
|
||||
* @param chunks - Fixture `raw` strings, whole or split, to simulate chunk boundaries.
|
||||
* @param options - Delivery timing and optional auto-close after the initial chunks.
|
||||
*/
|
||||
constructor(chunks: string[], options: SseTestStreamOptions = {}) {
|
||||
const { chunkDelayMs = 0, closeWhenDone = false } = options;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
this.stream = new ReadableStream({
|
||||
start: async (controller): Promise<void> => {
|
||||
this.controller = controller;
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
if (chunkDelayMs > 0 && i > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, chunkDelayMs));
|
||||
}
|
||||
|
||||
if (this.closed) return;
|
||||
|
||||
controller.enqueue(encoder.encode(chunks[i]!));
|
||||
}
|
||||
|
||||
if (closeWhenDone) {
|
||||
this.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the HTTP body the way a server closing the SSE connection would.
|
||||
*/
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
|
||||
this.closed = true;
|
||||
this.controller?.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user