-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathflushable-stream.test.ts
More file actions
376 lines (292 loc) · 11 KB
/
flushable-stream.test.ts
File metadata and controls
376 lines (292 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import { describe, expect, it } from 'vitest';
import {
createFlushableState,
flushablePipe,
LOCK_POLL_INTERVAL_MS,
pollReadableLock,
pollWritableLock,
} from './flushable-stream.js';
describe('flushable stream behavior', () => {
it('promise should resolve when writable stream lock is released (polling)', async () => {
// Test the pattern: user writes, releases lock, polling detects it, promise resolves
const chunks: string[] = [];
let streamClosed = false;
// Create a simple mock for the sink
const mockSink = new WritableStream<string>({
write(chunk) {
chunks.push(chunk);
},
close() {
streamClosed = true;
},
});
// Create a TransformStream like we do in getStepRevivers
const { readable, writable } = new TransformStream<string, string>();
const state = createFlushableState();
// Start piping in background
flushablePipe(readable, mockSink, state).catch(() => {
// Errors handled via state.reject
});
// Start polling for lock release
pollWritableLock(writable, state);
// Simulate user interaction - write and release lock
const userWriter = writable.getWriter();
await userWriter.write('chunk1');
await userWriter.write('chunk2');
// Release lock without closing stream
userWriter.releaseLock();
// Wait for pipe to process + polling interval
await new Promise((r) => setTimeout(r, LOCK_POLL_INTERVAL_MS + 50));
// The promise should resolve
await expect(
Promise.race([
state.promise,
new Promise((_, r) => setTimeout(() => r(new Error('timeout')), 400)),
])
).resolves.toBeUndefined();
// Chunks should have been written
expect(chunks).toContain('chunk1');
expect(chunks).toContain('chunk2');
// Stream should NOT be closed (user only released lock)
expect(streamClosed).toBe(false);
});
it('promise should resolve when writable stream closes naturally', async () => {
const chunks: string[] = [];
let streamClosed = false;
const mockSink = new WritableStream<string>({
write(chunk) {
chunks.push(chunk);
},
close() {
streamClosed = true;
},
});
const { readable, writable } = new TransformStream<string, string>();
const state = createFlushableState();
// Start piping in background
flushablePipe(readable, mockSink, state).catch(() => {
// Errors handled via state.reject
});
// Start polling (won't trigger since stream will close first)
pollWritableLock(writable, state);
// User writes and then closes the stream
const userWriter = writable.getWriter();
await userWriter.write('data');
await userWriter.close();
// Wait a tick for the pipe to process
await new Promise((r) => setTimeout(r, 50));
// The promise should resolve
await expect(
Promise.race([
state.promise,
new Promise((_, r) => setTimeout(() => r(new Error('timeout')), 200)),
])
).resolves.toBeUndefined();
// Chunks should have been written
expect(chunks).toContain('data');
// Stream should be closed (user closed it)
expect(streamClosed).toBe(true);
});
it('should handle abort signal propagating back up flushablePipe when reader disconnects early', async () => {
const chunks: string[] = [];
let sinkAborted = false;
// Create a sink that aborts (representing a dropped connection)
const mockSink = new WritableStream<string>({
write(chunk) {
chunks.push(chunk);
},
abort(reason) {
sinkAborted = true;
},
});
const { readable, writable } = new TransformStream<string, string>();
const state = createFlushableState();
// Start piping in background
const pipePromise = flushablePipe(readable, mockSink, state);
pollWritableLock(writable, state);
const userWriter = writable.getWriter();
await userWriter.write('valid chunk');
// Simulate a stream error / drop on the readable side (which aborts the pipe)
const error = new Error('Client disconnected');
readable.cancel(error);
// Write should fail because the underlying pipe broke
await expect(userWriter.write('another')).rejects.toThrow();
// State promise should reject with the cancellation error
await expect(state.promise).rejects.toThrow('Client disconnected');
// Ensure the sink received the abort signal
expect(sinkAborted).toBe(true);
});
it('should handle write errors during pipe operations', async () => {
const chunks: string[] = [];
// Create a sink that throws on write
const mockSink = new WritableStream<string>({
write(chunk) {
chunks.push(chunk);
if (chunk === 'error') {
throw new Error('Write failed');
}
},
});
const { readable, writable } = new TransformStream<string, string>();
const state = createFlushableState();
// Store the flushablePipe promise so we can await it to ensure
// all internal rejections are handled before the test ends
const pipePromise = flushablePipe(readable, mockSink, state).catch(() => {
// Errors handled via state.reject
});
pollWritableLock(writable, state);
// Write data that will cause an error
const userWriter = writable.getWriter();
await userWriter.write('chunk1');
// The write that triggers the error may reject on the userWriter side too
// since the error propagates back through the transform stream
await userWriter.write('error').catch(() => {
// Expected - error propagates back through the transform stream
});
// Wait for the pipe promise to settle to ensure all internal
// promise rejections are handled before the test ends
await pipePromise;
// The promise should be rejected
await expect(state.promise).rejects.toThrow('Write failed');
// First chunk should have been written before error
expect(chunks).toContain('chunk1');
});
it('should test with pollReadableLock', async () => {
// Create a readable stream that we can control
let controller: ReadableStreamDefaultController<string>;
const source = new ReadableStream<string>({
start(c) {
controller = c;
},
});
const chunks: string[] = [];
const mockSink = new WritableStream<string>({
write(chunk) {
chunks.push(chunk);
},
});
const state = createFlushableState();
// Start piping in background
flushablePipe(source, mockSink, state).catch(() => {
// Errors handled via state.reject
});
// Start polling for readable lock release
pollReadableLock(source, state);
// Enqueue some data and then close
controller?.enqueue('data1');
controller?.enqueue('data2');
controller?.close();
// Wait for the pipe to complete
await new Promise((r) => setTimeout(r, 100));
// The promise should resolve
await expect(state.promise).resolves.toBeUndefined();
// Chunks should have been written
expect(chunks).toContain('data1');
expect(chunks).toContain('data2');
});
it('should handle concurrent writes correctly', async () => {
const chunks: string[] = [];
const mockSink = new WritableStream<string>({
write(chunk) {
chunks.push(chunk);
},
});
const { readable, writable } = new TransformStream<string, string>();
const state = createFlushableState();
// Start piping in background
flushablePipe(readable, mockSink, state).catch(() => {
// Errors handled via state.reject
});
pollWritableLock(writable, state);
// Perform multiple concurrent writes
const userWriter = writable.getWriter();
await Promise.all([
userWriter.write('chunk1'),
userWriter.write('chunk2'),
userWriter.write('chunk3'),
]);
userWriter.releaseLock();
// Wait for polling to detect lock release
await new Promise((r) => setTimeout(r, LOCK_POLL_INTERVAL_MS + 50));
// Promise should resolve
await expect(state.promise).resolves.toBeUndefined();
// All chunks should be written
expect(chunks).toHaveLength(3);
expect(chunks).toContain('chunk1');
expect(chunks).toContain('chunk2');
expect(chunks).toContain('chunk3');
});
it('should prevent multiple simultaneous polling operations on writable', async () => {
const { readable, writable } = new TransformStream<string, string>();
const mockSink = new WritableStream<string>();
const state = createFlushableState();
// Start piping in background
flushablePipe(readable, mockSink, state).catch(() => {});
// Start polling multiple times
pollWritableLock(writable, state);
pollWritableLock(writable, state);
pollWritableLock(writable, state);
// Should only have one interval active
expect(state.writablePollingInterval).toBeDefined();
// Write and release to clean up
const userWriter = writable.getWriter();
await userWriter.write('data');
userWriter.releaseLock();
// Wait for cleanup
await new Promise((r) => setTimeout(r, LOCK_POLL_INTERVAL_MS + 50));
});
it('should prevent multiple simultaneous polling operations on readable', async () => {
let controller: ReadableStreamDefaultController<string>;
const source = new ReadableStream<string>({
start(c) {
controller = c;
},
});
const mockSink = new WritableStream<string>();
const state = createFlushableState();
// Start piping in background
flushablePipe(source, mockSink, state).catch(() => {});
// Start polling multiple times
pollReadableLock(source, state);
pollReadableLock(source, state);
pollReadableLock(source, state);
// Should only have one interval active
expect(state.readablePollingInterval).toBeDefined();
// Close to clean up
controller?.close();
// Wait for cleanup
await new Promise((r) => setTimeout(r, 100));
});
it('should handle stream ending while pending operations are in flight', async () => {
const chunks: string[] = [];
let writeDelay = 0;
const mockSink = new WritableStream<string>({
async write(chunk) {
// Simulate slow write
await new Promise((r) => setTimeout(r, writeDelay));
chunks.push(chunk);
},
});
const { readable, writable } = new TransformStream<string, string>();
const state = createFlushableState();
// Start piping in background
flushablePipe(readable, mockSink, state).catch(() => {});
pollWritableLock(writable, state);
const userWriter = writable.getWriter();
// Write first chunk normally
await userWriter.write('fast');
// Set delay for next write
writeDelay = 100;
// Start slow write and immediately close
const slowWrite = userWriter.write('slow');
await userWriter.close();
// Wait for everything to complete
await slowWrite;
await new Promise((r) => setTimeout(r, 150));
// Promise should resolve
await expect(state.promise).resolves.toBeUndefined();
// Both chunks should have been written
expect(chunks).toContain('fast');
expect(chunks).toContain('slow');
});
});