-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmockStreamingFetch.ts
More file actions
259 lines (234 loc) · 10.8 KB
/
mockStreamingFetch.ts
File metadata and controls
259 lines (234 loc) · 10.8 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
import type {Page} from '@playwright/test';
export interface MockStreamingOptions {
/** Interval between data chunks in ms (default: 200) */
chunkIntervalMs?: number;
/**
* When set, the stream will send this many data chunks followed by a
* QueryResponse chunk and then close. When omitted the stream runs
* indefinitely (useful for "stop" / abort tests).
*/
totalChunks?: number;
/**
* When set, the stream will send data chunks and then a QueryResponse
* with error/issues fields, simulating a server-side query error.
* Takes precedence over normal completion when both totalChunks and
* errorAfterChunks are set.
*/
errorAfterChunks?: number;
/**
* When true, the SessionCreated part is delivered in two halves with a
* 100 ms pause between them, simulating a partial network delivery.
* Useful for verifying that `readPartText` correctly accumulates bytes
* when the body arrives across multiple ReadableStream chunks.
*/
splitSessionPart?: boolean;
}
/**
* Monkey-patches `window.fetch` in the browser context to intercept streaming
* query requests (`/viewer/query?…schema=multipart`) and return a controlled
* `ReadableStream` that delivers multipart chunks at a steady pace.
*
* The mock reproduces the real YDB multipart format:
* --boundary\r\nContent-Type: …\r\nContent-Length: …\r\n\r\n{JSON}\r\n
*
* This keeps the main thread responsive (Safari freezes during high-frequency
* real streaming) while exercising the full streaming / abort flow.
*
* Must be called **after** the page has loaded and **before** the query is run.
*/
export async function setupMockStreamingFetch(
page: Page,
options: MockStreamingOptions = {},
): Promise<void> {
const chunkIntervalMs = options.chunkIntervalMs ?? 200;
const totalChunks = options.totalChunks ?? null;
const errorAfterChunks = options.errorAfterChunks ?? null;
const splitSessionPart = options.splitSessionPart ?? false;
await page.evaluate(
({
chunkIntervalMs: interval,
totalChunks: total,
errorAfterChunks: errorAfter,
splitSessionPart: splitSession,
}) => {
const originalFetch = window.fetch;
(window as unknown as Record<string, unknown>).__originalFetch = originalFetch;
window.fetch = function (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
let url: string;
if (typeof input === 'string') {
url = input;
} else if (input instanceof URL) {
url = input.href;
} else {
url = input.url;
}
const isStreamingQuery =
url.includes('/viewer/query') && url.includes('schema=multipart');
if (!isStreamingQuery) {
return originalFetch.call(window, input, init);
}
return Promise.resolve(createMockStreamingResponse(init?.signal));
};
function createMockStreamingResponse(signal?: AbortSignal | null): Response {
const encoder = new TextEncoder();
const BOUNDARY = 'boundary';
const sessionJSON = JSON.stringify({
version: 10,
meta: {
node_id: 1,
event: 'SessionCreated',
query_id: 'mock-query-1',
session_id: 'mock-session-1',
},
});
const queryResponseJSON = JSON.stringify({
status: 'SUCCESS',
meta: {event: 'QueryResponse'},
});
const errorResponseJSON = JSON.stringify({
error: {
severity: 1,
message: 'Mock streaming error',
},
issues: [
{
severity: 1,
message: 'Mock streaming error',
},
],
status: 'GENERIC_ERROR',
meta: {event: 'QueryResponse'},
});
function dataChunkJSON(seqNo: number): string {
return JSON.stringify({
result: {
rows: [[String(seqNo + 1)]],
columns: seqNo === 0 ? [{name: 'x', type: 'Uint64'}] : undefined,
},
meta: {seq_no: seqNo + 1, result_index: 0, event: 'StreamData'},
});
}
function encodePart(json: string): Uint8Array {
const jsonBytes = encoder.encode(json);
const header = `--${BOUNDARY}\r\nContent-Type: application/json\r\nContent-Length: ${jsonBytes.byteLength}\r\n\r\n`;
const headerBytes = encoder.encode(header);
const suffix = encoder.encode('\r\n');
const part = new Uint8Array(
headerBytes.byteLength + jsonBytes.byteLength + suffix.byteLength,
);
part.set(headerBytes, 0);
part.set(jsonBytes, headerBytes.byteLength);
part.set(suffix, headerBytes.byteLength + jsonBytes.byteLength);
return part;
}
function encodeClosingBoundary(): Uint8Array {
return encoder.encode(`--${BOUNDARY}--\r\n`);
}
// Determine how the stream should end
const shouldError = errorAfter !== null;
const chunkLimit = shouldError ? errorAfter : total;
let intervalId: number | undefined;
let splitTimeoutId: ReturnType<typeof setTimeout> | undefined;
let chunkIndex = 0;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const sessionPart = encodePart(sessionJSON);
const startDataChunks = () => {
intervalId = window.setInterval(() => {
try {
// Check if we should terminate
if (chunkLimit !== null && chunkIndex >= chunkLimit) {
window.clearInterval(intervalId);
const responseJSON = shouldError
? errorResponseJSON
: queryResponseJSON;
controller.enqueue(encodePart(responseJSON));
controller.enqueue(encodeClosingBoundary());
controller.close();
return;
}
controller.enqueue(encodePart(dataChunkJSON(chunkIndex)));
chunkIndex++;
} catch (error) {
window.clearInterval(intervalId);
try {
controller.error(
error instanceof Error
? error
: new Error(String(error)),
);
} catch {
// stream may already be errored/closed
}
}
}, interval);
};
if (splitSession) {
const mid = Math.floor(sessionPart.byteLength / 2);
controller.enqueue(sessionPart.subarray(0, mid));
splitTimeoutId = setTimeout(() => {
try {
controller.enqueue(sessionPart.subarray(mid));
} catch {
return;
}
startDataChunks();
}, 100);
} else {
controller.enqueue(sessionPart);
startDataChunks();
}
if (signal) {
const onAbort = () => {
window.clearInterval(intervalId);
clearTimeout(splitTimeoutId);
try {
controller.error(
new DOMException(
'The operation was aborted.',
'AbortError',
),
);
} catch {
// stream may already be errored/closed
}
};
if (signal.aborted) {
onAbort();
return;
}
signal.addEventListener('abort', onAbort, {once: true});
}
},
cancel() {
window.clearInterval(intervalId);
clearTimeout(splitTimeoutId);
},
});
return new Response(stream, {
status: 200,
headers: {
'Content-Type': `multipart/form-data; boundary=${BOUNDARY}`,
},
});
}
},
{chunkIntervalMs, totalChunks, errorAfterChunks, splitSessionPart},
);
}
/**
* Restores the original `window.fetch` that was captured by `setupMockStreamingFetch`.
* Safe to call even if the mock was never installed (no-op in that case).
*/
export async function cleanupMockStreamingFetch(page: Page): Promise<void> {
await page.evaluate(() => {
const w = window as unknown as Record<string, unknown>;
if (typeof w.__originalFetch === 'function') {
window.fetch = w.__originalFetch as typeof window.fetch;
delete w.__originalFetch;
}
});
}