diff --git a/events.ts b/events.ts index c25d41f..7926817 100644 --- a/events.ts +++ b/events.ts @@ -22,8 +22,6 @@ import { createChannel } from "./channel.ts"; * broadcasting status events to multiple listeners while ensuring that all listeners receive * the events as they occur. For more details, see the documentation for `createChannel`. * - * @see {@link createChannel} for more information on how channels are implemented and their benefits. - * * ## Key Features: * - Allows multiple listeners to concurrently listen to status events using `for await...of`. * - Ensures that all listeners receive events, though their processing order may be influenced by backpressure. diff --git a/split-by.ts b/split-by.ts index 121effd..08c70bf 100644 --- a/split-by.ts +++ b/split-by.ts @@ -15,17 +15,17 @@ const sourceStream = new ReadableStream({ // Split the stream into even and odd numbers const [evenStream, oddStream] = splitStream(sourceStream, num => num % 2 === 0); -// const evenStreamReader = evenStream.getReader(); -// const oddStreamReader = oddStream.getReader(); +const evenStreamReader = evenStream.getReader(); +const oddStreamReader = oddStream.getReader(); // Helper function to read from a stream -async function readStream(stream: ReadableStream, name: string) { - const reader = stream.getReader(); +async function readStream(stream: ReadableStream | ReadableStreamDefaultReader, name: string) { + const reader = 'getReader' in stream ? stream?.getReader?.() : stream; try { while (true) { const { value, done } = await reader.read(); - console.log({ name, value, done}) if (done) break; + console.log(`${name} received: ${value}`); await new Promise(resolve => setTimeout(resolve, 300)); } @@ -37,21 +37,42 @@ async function readStream(stream: ReadableStream, name: string) { // Read from both streams concurrently Promise.all([ - readStream(evenStream, "Even Stream"), - // readStream(oddStreamReader, "Odd Stream") -]).then(() => console.log("All streams processed")); + readStream(evenStreamReader, "Even Stream"), + readStream(oddStreamReader, "Odd Stream") +]).then(() => console.log("All streams processed", { evenStream, oddStream })); // Demonstrate cancellation after a delay setTimeout(async () => { - // console.log("Cancelling streams"); - // await Promise.all([ - // evenStreamReader.cancel("Demo cancellation"), - // oddStreamReader.cancel("Demo cancellation") - // ]); -}, 2000); - -// // Use AsyncDisposable feature + console.log("Cancelling streams"); + await Promise.all([ + evenStreamReader.cancel("Demo cancellation"), + oddStreamReader.cancel("Demo cancellation") + ]); +}, 1000); + + +// Use AsyncDisposable feature // (async () => { // await using streams = splitStream(sourceStream, num => num % 2 === 0); +// const [evenStream, oddStream] = streams; + +// // const evenStreamReader = evenStream.getReader(); +// // const oddStreamReader = oddStream.getReader(); + +// // Read from both streams concurrently +// await Promise.all([ +// readStream(evenStream, "Even Stream"), +// readStream(oddStream, "Odd Stream") +// ]).then(() => console.log("All streams processed", { evenStream, oddStream })); + +// // Demonstrate cancellation after a delay +// // setTimeout(async () => { +// // console.log("Cancelling streams"); +// // await Promise.all([ +// // evenStreamReader.cancel("Demo cancellation"), +// // oddStreamReader.cancel("Demo cancellation") +// // ]); +// // }, 1000); + // // ... use streams ... // })(); \ No newline at end of file diff --git a/split.ts b/split.ts index ea04054..8574c95 100644 --- a/split.ts +++ b/split.ts @@ -1,40 +1,65 @@ /** - * Context object to hold shared state between splitStream and readFromSource. + * Context object to hold shared state between `splitStream` and `readFromSource`. + * + * This context tracks the source reader, the predicate used for splitting, and the state of + * the two target queues. Each queue corresponds to one of the resulting `ReadableStream`s. + * + * ### State Variables: + * - `source`: A `ReadableStreamDefaultReader` for the original source stream. + * - `predicate`: A function to determine which queue a chunk should be routed to. + * - `queues`: An array of two objects, each containing: + * - `readable`: The `ReadableStream` linked to this queue. + * - `writer`: A `WritableStreamDefaultWriter` to enqueue chunks into this queue. + * - `size`: The current number of chunks buffered in this queue. + * - `closed`: Whether this queue has been fully closed. + * - `sourceDone`: Indicates if the source stream has ended. + * + * The `splitStream` mechanism uses these variables to track the progress of reading from + * the source and distributing chunks. As chunks flow from the source, `predicate` decides + * which queue they belong to. When the source completes, both queues are closed. */ export interface SplitStreamContext { source: ReadableStreamDefaultReader | null; predicate: ((chunk: T | F) => boolean) | null; queues: [ - { readable: ReadableStream | null, writer: WritableStreamDefaultWriter | null, size: number }, - { readable: ReadableStream | null, writer: WritableStreamDefaultWriter | null, size: number }, + { readable: ReadableStream | null, writer: WritableStreamDefaultWriter | null, size: number, closed: boolean }, + { readable: ReadableStream | null, writer: WritableStreamDefaultWriter | null, size: number, closed: boolean }, ]; - readInProgress: boolean; sourceDone: boolean; } /** - * Splits a source ReadableStream into two separate ReadableStreams based on a predicate function. + * Splits a source `ReadableStream` into two separate `ReadableStreams` based on a predicate function. * * ### Predicate-Based Splitting: - * - The source stream is evaluated chunk by chunk using the provided predicate function. - * - Chunks that satisfy the predicate are routed to the first stream. - * - Chunks that do not satisfy the predicate are routed to the second stream. + * Each chunk from the source stream is evaluated using the provided predicate function. + * - If `predicate(chunk)` returns `true`, the chunk is routed into the first resulting stream. + * - If `predicate(chunk)` returns `false`, the chunk is routed into the second resulting stream. * - * ### Disposal: - * - Each resulting stream supports multiple readers and will automatically handle resource cleanup once all consumers have finished reading. - * - The channels used to manage the streams are properly disposed of when the streams are closed or no longer needed. + * ### Backpressure and Flow Control: + * Internally, two `TransformStream`s are used as queues (`highWaterMark: Infinity`) to + * allow buffering multiple chunks. Each resulting stream pulls chunks on-demand, + * triggering reads from the source only as needed. * - * @template T The type of data contained in the source stream. - * @param source The original source ReadableStream to be split. - * @param predicate A function that evaluates each chunk and returns a boolean. `true` means the chunk goes to the first stream, `false` means it goes to the second stream. - * @returns An array containing two ReadableStreams: - * - The first stream contains chunks that satisfied the predicate. - * - The second stream contains chunks that did not satisfy the predicate. + * ### Lifecycle and Resource Management: + * - When the source is exhausted (`sourceDone = true`), both target streams will eventually + * close once all buffered chunks are read. + * - Cancelling either resulting stream triggers cleanup of resources and may also lead to + * cancellation of the source if both streams are fully released. + * + * @template T The type of chunks that pass the predicate. + * @template F The type of chunks that do not pass the predicate. + * + * @param sourceStream The original source `ReadableStream` to be split. + * @param predicate A function that evaluates each chunk. `true` routes the chunk to the first stream, `false` to the second. + * @returns A tuple of two `ReadableStream`s: + * - The first contains chunks where `predicate(chunk) === true`. + * - The second contains chunks where `predicate(chunk) === false`. * * @example * ```ts - * import { splitByStream } from "./stream.ts" - * + * import { splitStream } from "./stream.ts"; + * * // Example source stream with numbers * const sourceStream = new ReadableStream({ * start(controller) { @@ -47,7 +72,7 @@ export interface SplitStreamContext { * }); * * const isEven = (value: number) => value % 2 === 0; - * const [evenStream, oddStream] = splitByStream(sourceStream, isEven); + * const [evenStream, oddStream] = splitStream(sourceStream, isEven); * * // Reading from the even stream * const evenReader = evenStream.getReader(); @@ -57,46 +82,106 @@ export interface SplitStreamContext { * const oddReader = oddStream.getReader(); * oddReader.read().then(({ value }) => console.log("Odd:", value)); // Logs: 1 * ``` + * + * @example + * ```ts + * // A more complex example tracking state changes: + * // Consider a source producing: [10, 15, 20, 25, 2] + * // Predicate: chunk > 10 + * // Initially: sourceDone = false, queues = [{size: 0, closed: false}, {size: 0, closed: false}] + * + * const source = new ReadableStream({ + * start(controller) { + * [10, 15, 20, 25, 2].forEach(n => controller.enqueue(n)); + * controller.close(); // After enqueuing all + * } + * }); + * + * const isGreaterThan10 = (val: number) => val > 10; + * const [above10Stream, atOrBelow10Stream] = splitStream(source, isGreaterThan10); + * + * // Reading from above10Stream: + * // 1st pull: queue empty, triggers readFromSource -> reads 10 + * // predicate(10) = false -> goes to atOrBelow10 queue: size=1 + * // above10 queue still empty, tries another readFromSource -> reads 15 + * // predicate(15) = true -> goes to above10 queue: size=1 + * // now above10 pull can dequeue 15 + * + * // After more pulls: + * // Chunks >10 (15,20,25) go to above10: eventually above10: size will track these until read + * // Chunks ≤10 (10,2) go to atOrBelow10 + * // When source is done: sourceDone = true, no more reads + * // Reading continues until all sizes are down to zero, and both queues close + * + * const r1 = above10Stream.getReader(); + * const r2 = atOrBelow10Stream.getReader(); + * + * async function readAll(reader: ReadableStreamDefaultReader, label: string) { + * let result; + * while (!(result = await reader.read()).done) { + * console.log(`${label} got: ${result.value}`); + * } + * console.log(`${label} done`); + * } + * + * await Promise.all([readAll(r1, "Above10"), readAll(r2, "AtOrBelow10")]); + * // Output: + * // AtOrBelow10 got: 10 + * // Above10 got: 15 + * // Above10 got: 20 + * // Above10 got: 25 + * // AtOrBelow10 got: 2 + * // Above10 done + * // AtOrBelow10 done + * ``` */ export function splitStream( sourceStream: ReadableStream, predicate: (chunk: T | F) => boolean ): - & readonly [ReadableStream - // , ReadableStream - ] + & readonly [ReadableStream, ReadableStream] & AsyncDisposable { - // Create TransformStreams to act as minimal queues - const { writable: queue1, readable: readable1 } = new TransformStream(); - const { writable: queue2, readable: readable2 } = new TransformStream(); + // Create TransformStreams to act as minimal queues. + // We use highWaterMark = Infinity so we don't block writes due to backpressure too early. + const { writable: queue1, readable: readable1 } = new TransformStream(undefined, undefined, { highWaterMark: Infinity }); + const { writable: queue2, readable: readable2 } = new TransformStream(undefined, undefined, { highWaterMark: Infinity }); const context: SplitStreamContext = { source: sourceStream.getReader(), predicate, queues: [ - { readable: readable1, writer: queue1.getWriter(), size: 0 }, - { readable: readable2, writer: queue2.getWriter(), size: 0 }, + { readable: readable1, writer: queue1.getWriter(), size: 0, closed: false }, + { readable: readable2, writer: queue2.getWriter(), size: 0, closed: false }, ], - readInProgress: false, sourceDone: false, }; const trueStream = createPullStream(context, { index: 0 }); - // const falseStream = createPullStream(context, { index: 1 }); - - return Object.assign([trueStream, - // falseStream + const falseStream = createPullStream(context, { index: 1 }); + return Object.assign([ + trueStream, + falseStream ] as const, { async [Symbol.asyncDispose]() { await Promise.all([ trueStream.cancel("Symbol.asyncDispose"), - // falseStream.cancel("Symbol.asyncDispose"), + falseStream.cancel("Symbol.asyncDispose"), ]); }, }) } +/** + * Creates a `ReadableStream` that, upon each pull, attempts to ensure there is data available in the corresponding queue. + * It triggers `readFromSource` if needed to fetch more chunks and routes them through the predicate. + * + * @internal + * + * @param context The shared `SplitStreamContext`. + * @param param0 The index of the queue to connect this pull stream to. + * @returns A `ReadableStream` that will yield only the filtered chunks for this queue. + */ function createPullStream(context: SplitStreamContext, { index: currentQueueIndex }: { index: number }): ReadableStream { const queue = context.queues[currentQueueIndex]; const readable = queue.readable as ReadableStream | null; @@ -104,108 +189,129 @@ function createPullStream(context: SplitStreamContext return new ReadableStream({ async pull(controller) { if (context.sourceDone) { + // If the source is done and no more data is expected, close the stream. controller.close(); return; } - // Always trigger a read after pulling, whether we got a value or not - // if (!context.readInProgress && !context.sourceDone) { + // If the queue is empty and source is not done, try reading more from source. while (queue.size === 0 && !context.sourceDone) { await readFromSource(context); } - // } const reader = readable?.getReader(); try { - const { value, done } = await reader?.read() ?? { value: undefined, done: true, error: "Something went wrong" }; + // Attempt to read a chunk from the queue + const { value, done } = await reader?.read() ?? { value: undefined, done: true }; - console.log({ value, done }) if (done) { - if (!context.sourceDone) { - // If this queue is empty but source isn't done, trigger another read - if (!context.readInProgress) { - await readFromSource(context); - } - - return; // Don't close the controller, wait for more data - } + // If this queue is empty but source isn't done, + // don't close the readable stream, wait for more data + if (!context.sourceDone) return; + // Otherwise close the readable stream if source is also done controller.close(); } else { + // Retrieve chunk and add it to the stream; decrement total size of queue controller.enqueue(value as V); queue.size--; } - - // Always trigger a read after pulling, whether we got a value or not - // if (!context.readInProgress && !context.sourceDone) { - // readFromSource(context); - // } } catch (error) { + // If an error occurs while reading, report it to the consumer controller.error(error); } finally { - reader?.releaseLock(); + // Always release the reader lock after use + reader?.releaseLock?.(); } }, async cancel(reason) { - // Handle cancellation if needed + // Called when the consumer cancels reading. await readable?.cancel(reason); - const allQueuesCancelled = context.queues.every((queue, currentQueueIndex) => { + // Mark this queue as closed and release resources + const allQueuesCancelled = context.queues.every((queue) => { if ((queue?.readable as V) === readable) { - context.queues[currentQueueIndex].writer?.releaseLock(); - - context.queues[currentQueueIndex].readable = null; - context.queues[currentQueueIndex].writer = null; + try { + queue.writer?.releaseLock(); + queue.closed = true; + } finally { + queue.readable = null; + queue.writer = null; + } } return queue?.readable === null; }); + // If all queues are cancelled, we can safely cancel the source reader if (allQueuesCancelled && context.source) { - if (!context.sourceDone) { - await context.source?.cancel(reason); - } - - context.source?.releaseLock(); + try { + if (!context.sourceDone) { + await context.source?.cancel?.(reason); + } - context.sourceDone = true; - context.source = null; + context.source?.releaseLock?.(); + } finally { + context.sourceDone = true; + context.source = null; + } } } }); } +/** + * Reads a single chunk from the source stream and routes it to the appropriate queue. + * If the source is done, it closes all queues and marks the source as done. + * + * Non-exported function. Internally used by `createPullStream` to ensure data availability. + * + * ### Steps: + * 1. Attempt to read from `context.source`. + * 2. If `done` is true, mark `sourceDone` and close all queues. + * 3. If `done` is false, use `predicate` to determine which queue to write the chunk to. + * 4. Increase the `size` counter of the chosen queue. + * + * @param context The shared `SplitStreamContext`. + */ async function readFromSource(context: SplitStreamContext) { const { source, predicate } = context; - if (context.readInProgress || context.sourceDone) return; + if (context.sourceDone) return; try { - while (!context.sourceDone) { - const { value, done } = await source?.read() ?? { value: undefined, done: true }; - console.log({ value, done, readFromSource: true }); - - if (done) { - context.sourceDone = true; - await Promise.all([ - context.queues.map((queue) => queue?.writer?.close()) - ]); - break; - } + const { value, done } = (await source?.read()) ?? { value: undefined, done: true }; + if (done) { + // No more chunks from source, mark as done and close queues + context.sourceDone = true; + return await Promise.all( + context.queues.map(async (queue) => { + if (queue.closed) return; + queue.closed = true; - if (predicate?.(value)) { - await context.queues[0]?.writer?.write(value as T); - context.queues[0].size++; - break; - } else { - await context.queues[1]?.writer?.write(value as F); - context.queues[1].size++; - break; - } + try { + await queue?.writer?.close(); + queue.writer?.releaseLock(); + } finally { + queue.readable = null; + queue.writer = null; + } + }) + ); + } + + // Route chunk based on predicate + if (predicate?.(value)) { + await context.queues[0]?.writer?.write(value as T); + context.queues[0].size++; + } else { + await context.queues[1]?.writer?.write(value as F); + context.queues[1].size++; } } catch (error) { + // If an error occurs reading from source, abort both queues console.log("Error reading from source", error); - await Promise.all([ + await Promise.all( context.queues.map((queue) => queue?.writer?.abort(error)) - ]); + ); } } diff --git a/split_test.ts b/split_test.ts new file mode 100644 index 0000000..18a4953 --- /dev/null +++ b/split_test.ts @@ -0,0 +1,635 @@ +/** + * @fileoverview + * This file provides a suite of tests for the `splitStream` function. The goal is to ensure that the splitting + * behavior is correct under various conditions, including normal operation, empty sources, error scenarios, + * and cancellation/cleanup behaviors. + * + * ### Key Testing Strategies: + * 1. **Data-Driven (Test Tables)**: + * We use parameterized test cases defined in arrays, providing input streams, predicates, and expected outputs. + * This ensures comprehensive coverage of scenarios without excessive boilerplate. + * + * 2. **Isolation and Determinism**: + * Each test creates its own source stream to avoid interference. We use deterministic input data + * and avoid fixed delays. Instead, we rely on naturally completing streams and checking conditions. + * + * 3. **State Tracking**: + * We test the stream's behavior when: + * - The source ends normally. + * - The predicate routes chunks to both streams. + * - One or both resulting streams are canceled early. + * - Errors occur while reading from the source. + * - Attempting to read when the source is done or queues are empty. + * + * 4. **Logging and Assertions**: + * For debugging, tests may log progress. Assertions ensure stable expectations: even in tricky scenarios, + * the output and state of the streams are as intended. + * + * ### Tools: + * - `@libs/testing` for test runner. + * - `@std/expect` for assertions. + * - `splitStream` function (imported from the stream splitting module). + * - Helper functions and stable test inputs to ensure reproducibility. + */ + + +/** + * @fileoverview + * Tests for the `splitStream` function to ensure reliable and predictable splitting of chunks + * from a given source `ReadableStream` into two output streams based on a predicate. + * + * ### Test Strategies: + * - **Data-Driven (Test Tables)**: + * Using arrays of input/output scenarios to thoroughly validate even/odd splits, empty sources, + * all-passing/all-failing predicates, and more complex object-based scenarios. + * + * - **Edge Cases & Error Handling**: + * Test sources that end immediately (empty), sources that error out, + * and behavior when canceling or disposing streams. + * + * - **Synchronization & No Flaky Delays**: + * We avoid fixed delays. Instead, tests rely on deterministic inputs or + * event-driven checks. The code should run consistently regardless of timing variances. + * + * - **Documentation & Reproducibility**: + * Each test is documented, and scenarios are traceable to ensure maintainability and clarity. + */ + +import { test } from "@libs/testing"; +import { expect } from "@std/expect"; +import { splitStream } from "./split.ts"; // Adjust path as needed +import { iterableFromStream } from "./utils.ts"; // Helper to read entire streams easily + +/** + * Helper to create a ReadableStream from an array of values. + * Ensures a deterministic, static input source for testing. + */ +function createArrayStream(values: T[]): ReadableStream { + return new ReadableStream({ + start(controller) { + for (const v of values) { + controller.enqueue(v); + } + controller.close(); + }, + }); +} + +/** + * Helper to simulate an error in the source stream. + * Once it has enqueued half of the provided values, it throws an error. + */ +function createErrorStream(values: T[]): ReadableStream { + return new ReadableStream({ + start(controller) { + let index = 0; + for (const v of values) { + if (index === Math.floor(values.length / 2)) { + // Simulate an error mid-way + controller.error(new Error("Simulated source error")); + return; + } + controller.enqueue(v); + index++; + } + controller.close(); + }, + }); +} + +/** + * Data-Driven Tests (Test Table): + * Each entry includes: + * - name: a descriptive test name + * - input: array of input chunks + * - predicate: function to split chunks + * - expectedFirst: expected chunks in the first stream + * - expectedSecond: expected chunks in the second stream + * + * These scenarios cover normal operation, empty sources, and diverse splitting logic. + */ +const testCases = [ + { + name: "Split even/odd numbers", + input: [1,2,3,4], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [2,4], + expectedSecond: [1,3] + }, + { + name: "Empty source", + input: [] as number[], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [] as number[], + expectedSecond: [] as number[] + }, + { + name: "All chunks match predicate", + input: [2,4,6], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [2,4,6], + expectedSecond: [] + }, + { + name: "No chunks match predicate", + input: [1,3,5], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [], + expectedSecond: [1,3,5] + } +]; + +/** + * @testtable + * Validate basic behavior of splitStream using various input arrays and predicates. + */ +for (const { name, input, predicate, expectedFirst, expectedSecond } of testCases) { + test("deno")( `splitStream - ${name}`, async () => { + const source = createArrayStream(input); + const [evenStream, oddStream] = splitStream(source, predicate); + + const resultFirst = await iterableFromStream(evenStream); + const resultSecond = await iterableFromStream(oddStream); + + expect(resultFirst).toEqual(expectedFirst); + expect(resultSecond).toEqual(expectedSecond); + }); +} + +/** + * @test + * Tests the behavior when the source encounters an error during reading. + * The expected behavior: Both resulting streams should abort once the error is encountered. + */ +test("deno")("splitStream - error in source", async () => { + const source = createErrorStream([1,2,3,4,5,6]); + const [streamA, streamB] = splitStream(source, (num: number) => num > 3); + + const resultsA: number[] = []; + const resultsB: number[] = []; + + let errorCaught = false; + + // Attempt to read both streams concurrently + await Promise.allSettled([ + (async () => { + try { + for await (const val of streamA) { + resultsA.push(val); + } + } catch (err) { + errorCaught = true; + } + })(), + (async () => { + try { + for await (const val of streamB) { + resultsB.push(val); + } + } catch (err) { + errorCaught = true; + } + })() + ]); + + // Since the source errors mid-way, we only get a subset of values. + // The first half is enqueued, the error occurs, and both streams end abruptly. + // Depending on when error is raised, we might have some chunks or none after the error point. + expect(errorCaught).toBe(true); + expect(resultsA.length + resultsB.length).toBeLessThanOrEqual(3); // Only got up to half before error +}); + +/** + * @test + * Tests cancellation behavior: cancel one of the resulting streams early and ensure the other can still be read. + */ +test("deno")("splitStream - cancel one resulting stream early", async () => { + const source = createArrayStream([1,2,3,4,5]); + const [evenStream, oddStream] = splitStream(source, (num: number) => num % 2 === 0); + + // Cancel the evenStream immediately + const evenReader = evenStream.getReader(); + await evenReader.cancel("No need for even numbers"); + + // The oddStream should still provide odd values + const oddValues = await iterableFromStream(oddStream); + expect(oddValues).toEqual([1,3,5]); +}); + +/** + * @test + * Ensures that if we try to read from one of the streams after the source is already done, it simply closes. + */ +test("deno")("splitStream - read after source done", async () => { + const source = createArrayStream([10,11]); + const [streamTrue, streamFalse] = splitStream(source, (num: number) => num > 10); + + // Read all from true stream first + const trueValues = await iterableFromStream(streamTrue); + expect(trueValues).toEqual([11]); + + // Source is done now. If we read from false stream afterward: + const falseValues = await iterableFromStream(streamFalse); + expect(falseValues).toEqual([10]); +}); + +/** + * @test + * Attempt multiple reads in parallel on the same resulting stream to check stability. + * We don't want to cause deadlocks or race conditions. + */ +test("deno")("splitStream - parallel reads on the same resulting stream", async () => { + const source = createArrayStream([0,1,2,3,4,5]); + const [evenStream] = splitStream(source, (num: number) => num % 2 === 0); + + // Attempt concurrent reads: + const readPromise1 = iterableFromStream(evenStream); + const readPromise2 = iterableFromStream(evenStream); + + // Both attempts will read the same stream. The second will start reading after the first finishes or simultaneously. + // Depending on the implementation, one reader might lock the stream and the other might get no data. + const [res1, res2] = await Promise.all([readPromise1, readPromise2]); + + // At least one should have the data. Another might see an empty array due to locking rules. + // The even numbers: [0,2,4] + // We can accept that one gets the data and the other is empty or that both share results depending on implementation. + // For a properly implemented splitStream, each returned stream is independent and can be read fully. + // Since we only returned evenStream, there's only one resulting stream. If multiple readers are attempted, + // typically only one can read the data (locked by first reader). + + // Check that at least one got the correct data. + const combined = [...res1, ...res2]; + expect(combined.sort()).toEqual([0,2,4]); +}); + +/** + * @test + * Test disposing of both resulting streams using Symbol.asyncDispose and ensuring cleanup. + */ +test("deno")("splitStream - async disposal of resulting streams", async () => { + const source = createArrayStream([5,6,7,8]); + const [streamA, streamB] = splitStream(source, (n: number) => n < 7); + + // Dispose both using Symbol.asyncDispose: + await streamA[Symbol.asyncDispose](); + await streamB[Symbol.asyncDispose](); + + // Attempt reading after disposal should fail + try { + await iterableFromStream(streamA); + expect(false).toBe(true); // Should not reach here + } catch (error) { + expect(error).toBeDefined(); + } + + try { + await iterableFromStream(streamB); + expect(false).toBe(true); // Should not reach here + } catch (error) { + expect(error).toBeDefined(); + } +}); + +/** + * @test + * Test table with complex decision logic (decision table testing): + * + * Conditions: + * - Input: a series of objects with a property `type`. + * - Predicate: checks if `type` is "allowed". + * - Expected result: allowed objects in one stream, disallowed in the other. + * + * We can represent multiple conditions in a decision table: + */ + +interface Obj { type: "allowed" | "forbidden"; value: number; } + +const decisionTestCases = [ + { + name: "All allowed", + input: [{type: "allowed", value:1}, {type:"allowed", value:2}] as Obj[], + predicate: (obj: Obj) => obj.type === "allowed", + expectedFirst: [{type:"allowed", value:1},{type:"allowed", value:2}], + expectedSecond: [] + }, + { + name: "All forbidden", + input: [{type: "forbidden", value:1}, {type:"forbidden", value:2}] as Obj[], + predicate: (obj: Obj) => obj.type === "allowed", + expectedFirst: [], + expectedSecond: [{type:"forbidden", value:1},{type:"forbidden", value:2}] + }, + { + name: "Mixed types", + input: [ + {type:"allowed", value:1}, + {type:"forbidden", value:2}, + {type:"allowed", value:3}, + {type:"forbidden", value:4}, + ] as Obj[], + predicate: (obj: Obj) => obj.type === "allowed", + expectedFirst: [{type:"allowed", value:1},{type:"allowed", value:3}], + expectedSecond: [{type:"forbidden", value:2},{type:"forbidden", value:4}], + }, +]; + +for (const {name, input, predicate, expectedFirst, expectedSecond} of decisionTestCases) { + test("deno")(`splitStream - decision table: ${name}`, async () => { + const source = createArrayStream(input); + const [allowedStream, forbiddenStream] = splitStream(source, predicate); + + const resAllowed = await iterableFromStream(allowedStream); + const resForbidden = await iterableFromStream(forbiddenStream); + + expect(resAllowed).toEqual(expectedFirst); + expect(resForbidden).toEqual(expectedSecond); + }); +} + +/** + * @test + * Testing synchronization and concurrency: + * Attempt reading from one resulting stream with dynamic checks (no fixed delays) and ensure no flaky behavior. + * We'll do this by waiting for the first chunk to appear instead of sleeping. + */ +test("deno")("splitStream - dynamic wait (no fixed delay)", async () => { + const source = new ReadableStream({ + start(controller) { + // Enqueue asynchronously + setTimeout(() => controller.enqueue(42), 10); + setTimeout(() => controller.close(), 20); + } + }); + + const [matches, others] = splitStream(source, (x) => x === 42); + + // Check the 'matches' stream dynamically: + const matchesReader = matches.getReader(); + const result = await matchesReader.read(); + // This read will wait until chunk is available (dynamic wait, no sleeps) + + expect(result.value).toBe(42); + expect(result.done).toBe(false); + + const secondRead = await matchesReader.read(); + expect(secondRead.done).toBe(true); + + // The 'others' stream should be empty + const othersResult = await iterableFromStream(others); + expect(othersResult).toEqual([]); +}); + +/** + * By following these comprehensive tests—using data-driven approaches, decision tables, and careful synchronization— + * we've demonstrated how to create robust and reliable tests for `splitStream`. Each test scenario documents the + * expected behavior, thereby improving clarity, reproducibility, and maintainability of the test suite. + */ + + +/** + * Data-driven test scenarios covering basic cases: + * - Even/odd splitting + * - Empty sources + * - All true / all false predicate matches + */ +const basicTestCases = [ + { + name: "Even/Odd split with [1,2,3,4]", + input: [1,2,3,4], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [2,4], + expectedSecond: [1,3] + }, + { + name: "Empty source", + input: [] as number[], + predicate: (num: number) => num > 10, + expectedFirst: [] as number[], + expectedSecond: [] as number[] + }, + { + name: "All chunks match predicate", + input: [2,4,6], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [2,4,6], + expectedSecond: [] + }, + { + name: "No chunks match predicate", + input: [1,3,5], + predicate: (num: number) => num % 2 === 0, + expectedFirst: [], + expectedSecond: [1,3,5] + } +]; + +/** + * @testtable + * Validate `splitStream` with a variety of numeric inputs and predicates. + */ +for (const { name, input, predicate, expectedFirst, expectedSecond } of basicTestCases) { + test("deno")(`splitStream - ${name}`, async () => { + const source = createArrayStream(input); + const [streamTrue, streamFalse] = splitStream(source, predicate); + + const resultFirst = await iterableFromStream(streamTrue); + const resultSecond = await iterableFromStream(streamFalse); + + expect(resultFirst).toEqual(expectedFirst); + expect(resultSecond).toEqual(expectedSecond); + }); +} + +/** + * @test + * Test behavior when the source errors out midway. + * Both streams should encounter this error and stop providing new data. + */ +test("deno")("splitStream - error in source stream", async () => { + const source = createErrorStream([1,2,3,4,5,6]); + const [aStream, bStream] = splitStream(source, (num: number) => num > 3); + + const resultsA: number[] = []; + const resultsB: number[] = []; + let errorCaught = false; + + await Promise.allSettled([ + (async () => { + try { + for await (const v of aStream) { + resultsA.push(v); + } + } catch (_) { + errorCaught = true; + } + })(), + (async () => { + try { + for await (const v of bStream) { + resultsB.push(v); + } + } catch (_) { + errorCaught = true; + } + })() + ]); + + expect(errorCaught).toBe(true); + // We only read up until half before error occurred, so combined we should have fewer than full set + expect(resultsA.length + resultsB.length).toBeLessThanOrEqual(3); +}); + +/** + * @test + * Cancelling one resulting stream should not prevent reading from the other. + * Ensure that when we cancel the first stream, the second can still be read fully. + */ +test("deno")("splitStream - cancel one stream early", async () => { + const source = createArrayStream([10,11,12,13,14]); + const [gt12Stream, ltEqual12Stream] = splitStream(source, (num: number) => num > 12); + + // Cancel the gt12Stream immediately + const gt12Reader = gt12Stream.getReader(); + await gt12Reader.cancel("No need for values > 12"); + + const remainValues = await iterableFromStream(ltEqual12Stream); + // Values ≤ 12: [10,11,12] + expect(remainValues).toEqual([10,11,12]); +}); + +/** + * @test + * Read after the source is done should just close the streams gracefully. + */ +test("deno")("splitStream - read after source done", async () => { + const source = createArrayStream([1,2]); + const [evenStream, oddStream] = splitStream(source, (num) => num % 2 === 0); + + // Read even first + const evenVals = await iterableFromStream(evenStream); + expect(evenVals).toEqual([2]); + + // Now read odd - source done, but odd should yield [1] + const oddVals = await iterableFromStream(oddStream); + expect(oddVals).toEqual([1]); +}); + +/** + * @test + * Complex, object-based decision table testing: + * Predicate splits objects by `type: "allowed"` vs `type: "forbidden"`. + */ +interface Obj { type: "allowed" | "forbidden"; value: number; } + +const decisionTestCases = [ + { + name: "All allowed", + input: [{type:"allowed", value:1},{type:"allowed", value:2}] as Obj[], + predicate: (obj: Obj) => obj.type === "allowed", + expectedFirst: [{type:"allowed", value:1},{type:"allowed", value:2}], + expectedSecond: [] + }, + { + name: "All forbidden", + input: [{type:"forbidden", value:1},{type:"forbidden", value:2}] as Obj[], + predicate: (obj: Obj) => obj.type === "allowed", + expectedFirst: [], + expectedSecond: [{type:"forbidden", value:1},{type:"forbidden", value:2}] + }, + { + name: "Mixed", + input: [ + {type:"allowed", value:10}, + {type:"forbidden", value:20}, + {type:"allowed", value:30}, + {type:"forbidden", value:40}, + ] as Obj[], + predicate: (obj: Obj) => obj.type === "allowed", + expectedFirst: [{type:"allowed", value:10},{type:"allowed", value:30}], + expectedSecond: [{type:"forbidden", value:20},{type:"forbidden", value:40}], + } +]; + +for (const {name, input, predicate, expectedFirst, expectedSecond} of decisionTestCases) { + test("deno")(`splitStream - decision table: ${name}`, async () => { + const source = createArrayStream(input); + const [allowedStream, forbiddenStream] = splitStream(source, predicate); + + const resAllowed = await iterableFromStream(allowedStream); + const resForbidden = await iterableFromStream(forbiddenStream); + + expect(resAllowed).toEqual(expectedFirst); + expect(resForbidden).toEqual(expectedSecond); + }); +} + +/** + * @test + * Test disposal using Symbol.asyncDispose on both resulting streams. + * After disposal, attempts to read should fail. + */ +test("deno")("splitStream - async disposal", async () => { + const source = createArrayStream([5,6]); + const [s1, s2] = splitStream(source, (n) => n < 6); + + await s1[Symbol.asyncDispose](); + await s2[Symbol.asyncDispose](); + + await expect(async () => { + await iterableFromStream(s1); + }).rejects.toThrow(); + + await expect(async () => { + await iterableFromStream(s2); + }).rejects.toThrow(); +}); + +/** + * @test + * Ensuring no flakes: dynamically wait for data without fixed delays. + * Source asynchronously enqueues a single chunk, no fixed sleeps. + */ +test("deno")("splitStream - dynamic wait (no fixed delays)", async () => { + const source = new ReadableStream({ + start(controller) { + // enqueue after a short async tick + queueMicrotask(() => { + controller.enqueue(42); + controller.close(); + }); + } + }); + + const [matches, others] = splitStream(source, (x) => x === 42); + + const matchesRes = await iterableFromStream(matches); + expect(matchesRes).toEqual([42]); + + const othersRes = await iterableFromStream(others); + expect(othersRes).toEqual([]); +}); + +/** + * @test + * Attempt reading from one stream after another stream is fully drained and ensure no conflicts or deadlocks. + */ +test("deno")("splitStream - sequential reading of both streams", async () => { + const source = createArrayStream([10,11,12,13]); + const [ge12Stream, lt12Stream] = splitStream(source, (n) => n >= 12); + + // Read ge12 first + const ge12Vals = await iterableFromStream(ge12Stream); + expect(ge12Vals).toEqual([12,13]); + + // Now read lt12 + const lt12Vals = await iterableFromStream(lt12Stream); + expect(lt12Vals).toEqual([10,11]); +}); + +/** + * These tests collectively ensure: + * - Correct splitting of data under normal and edge conditions. + * - Stable behavior on source completion, errors, and cancellations. + * - Proper synchronization and no flaky, timing-dependent failures. + * - Comprehensive coverage via test tables (basic and decision table testing). + */