|
| 1 | +import type { Streamer } from '@workflow/world'; |
| 2 | +import { beforeAll, describe, expect, test } from 'vitest'; |
| 3 | +import { createStreamer } from './setup.js'; |
| 4 | + |
| 5 | +async function readText(stream: ReadableStream<Uint8Array>): Promise<string> { |
| 6 | + const reader = stream.getReader(); |
| 7 | + const chunks: Uint8Array[] = []; |
| 8 | + |
| 9 | + try { |
| 10 | + while (true) { |
| 11 | + const { done, value } = await reader.read(); |
| 12 | + if (done) break; |
| 13 | + if (value) chunks.push(value); |
| 14 | + } |
| 15 | + } finally { |
| 16 | + reader.releaseLock(); |
| 17 | + } |
| 18 | + |
| 19 | + const bytes = new Uint8Array(chunks.flatMap((chunk) => Array.from(chunk))); |
| 20 | + return new TextDecoder().decode(bytes); |
| 21 | +} |
| 22 | + |
| 23 | +function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> { |
| 24 | + let timeout: ReturnType<typeof setTimeout> | undefined; |
| 25 | + const timeoutPromise = new Promise<never>((_, reject) => { |
| 26 | + timeout = setTimeout(() => { |
| 27 | + reject(new Error(`Timed out after ${timeoutMs}ms`)); |
| 28 | + }, timeoutMs); |
| 29 | + }); |
| 30 | + return Promise.race([promise, timeoutPromise]).finally(() => { |
| 31 | + if (timeout) { |
| 32 | + clearTimeout(timeout); |
| 33 | + } |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +describe('streamer race conditions', () => { |
| 38 | + let streamer: Streamer; |
| 39 | + |
| 40 | + beforeAll(async () => { |
| 41 | + ({ streamer } = await createStreamer()); |
| 42 | + }); |
| 43 | + |
| 44 | + test('does not drop chunk when close happens immediately after write', async () => { |
| 45 | + const expected = 'Hello from webhook!'; |
| 46 | + const encoder = new TextEncoder(); |
| 47 | + |
| 48 | + for (let i = 0; i < 50; i++) { |
| 49 | + const id = `${Date.now()}-${i}`; |
| 50 | + const streamName = `test-stream-race-${id}`; |
| 51 | + const runId = `wrun_test-${id}`; |
| 52 | + |
| 53 | + const readable = await streamer.readFromStream(streamName); |
| 54 | + const readPromise = withTimeout(readText(readable), 5000); |
| 55 | + |
| 56 | + await streamer.writeToStream(streamName, runId, encoder.encode(expected)); |
| 57 | + await streamer.closeStream(streamName, runId); |
| 58 | + |
| 59 | + const result = await readPromise; |
| 60 | + expect(result).toBe(expected); |
| 61 | + } |
| 62 | + }); |
| 63 | +}); |
0 commit comments