-
Notifications
You must be signed in to change notification settings - Fork 37
/
transport.ts
357 lines (308 loc) · 10.7 KB
/
transport.ts
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
// Derived from https://raw.githubusercontent.com/connectrpc/examples-es/refs/heads/main/react-native
import {Message, MethodKind} from '@bufbuild/protobuf';
import type {
AnyMessage,
MethodInfo,
PartialMessage,
ServiceType,
} from '@bufbuild/protobuf';
import type {
ContextValues,
StreamRequest,
StreamResponse,
Transport,
UnaryRequest,
UnaryResponse,
} from '@connectrpc/connect';
import {Code, ConnectError, createContextValues} from '@connectrpc/connect';
import {GrpcWebTransportOptions} from '@connectrpc/connect-web';
import {
createClientMethodSerializers,
createMethodUrl,
createWritableIterable,
encodeEnvelope,
runStreamingCall,
runUnaryCall,
} from '@connectrpc/connect/protocol';
import {
requestHeader,
trailerFlag,
trailerParse,
validateResponse,
validateTrailer,
} from '@connectrpc/connect/protocol-grpc-web';
class AbortError extends Error {
name = 'AbortError';
}
interface FetchXHRResponse {
status: number;
headers: Headers;
body: Uint8Array;
}
function parseHeaders(allHeaders: string): Headers {
return allHeaders
.trim()
.split(/[\r\n]+/)
.reduce((memo, header) => {
const [key, value] = header.split(': ');
memo.append(key, value);
return memo;
}, new Headers());
}
function extractDataChunks(initialData: Uint8Array) {
let buffer = initialData;
let dataChunks: {flags: number; data: Uint8Array}[] = [];
while (buffer.byteLength >= 5) {
let length = 0;
let flags = buffer[0];
for (let i = 1; i < 5; i++) {
length = (length << 8) + buffer[i]; // eslint-disable-line no-bitwise
}
const data = buffer.subarray(5, 5 + length);
buffer = buffer.subarray(5 + length);
dataChunks.push({flags, data});
}
return dataChunks;
}
export function createXHRGrpcWebTransport(
options: GrpcWebTransportOptions,
): Transport {
const useBinaryFormat = options.useBinaryFormat ?? true;
return {
async unary<
I extends Message<I> = AnyMessage,
O extends Message<O> = AnyMessage,
>(
service: ServiceType,
method: MethodInfo<I, O>,
signal: AbortSignal | undefined,
timeoutMs: number | undefined,
header: Headers,
message: PartialMessage<I>,
contextValues?: ContextValues,
): Promise<UnaryResponse<I, O>> {
const {serialize, parse} = createClientMethodSerializers(
method,
useBinaryFormat,
options.jsonOptions,
options.binaryOptions,
);
return await runUnaryCall<I, O>({
signal,
interceptors: options.interceptors,
req: {
stream: false,
service,
method,
url: createMethodUrl(options.baseUrl, service, method),
init: {
method: 'POST',
mode: 'cors',
},
header: requestHeader(useBinaryFormat, timeoutMs, header, false),
contextValues: contextValues ?? createContextValues(),
message,
},
next: async (req: UnaryRequest<I, O>): Promise<UnaryResponse<I, O>> => {
function fetchXHR(): Promise<FetchXHRResponse> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(req.init.method ?? 'POST', req.url);
function onAbort() {
xhr.abort();
}
req.signal.addEventListener('abort', onAbort);
xhr.addEventListener('abort', () => {
reject(new AbortError('Request aborted'));
});
xhr.addEventListener('load', () => {
resolve({
status: xhr.status,
headers: parseHeaders(xhr.getAllResponseHeaders()),
body: new Uint8Array(xhr.response),
});
});
xhr.addEventListener('error', () => {
reject(new Error('Network Error'));
});
xhr.addEventListener('loadend', () => {
req.signal.removeEventListener('abort', onAbort);
});
xhr.responseType = 'arraybuffer';
req.header.forEach((value: string, key: string) =>
xhr.setRequestHeader(key, value),
);
xhr.send(encodeEnvelope(0, serialize(req.message)));
});
}
const response = await fetchXHR();
validateResponse(response.status, response.headers);
const chunks = extractDataChunks(response.body);
let trailer: Headers | undefined;
let message: O | undefined;
chunks.forEach(({flags, data}) => {
if (flags === trailerFlag) {
if (trailer !== undefined) {
throw 'extra trailer';
}
// Unary responses require exactly one response message, but in
// case of an error, it is perfectly valid to have a response body
// that only contains error trailers.
trailer = trailerParse(data);
return;
}
if (message !== undefined) {
throw 'extra message';
}
message = parse(data);
});
if (trailer === undefined) {
throw 'missing trailer';
}
validateTrailer(trailer, response.headers);
if (message === undefined) {
throw 'missing message';
}
return {
stream: false,
header: response.headers,
message,
trailer,
service,
method,
} satisfies UnaryResponse<I, O>;
},
});
},
async stream<
I extends Message<I> = AnyMessage,
O extends Message<O> = AnyMessage,
>(
service: ServiceType,
method: MethodInfo<I, O>,
signal: AbortSignal | undefined,
timeoutMs: number | undefined,
header: Headers,
input: AsyncIterable<PartialMessage<I>>,
contextValues?: ContextValues,
): Promise<StreamResponse<I, O>> {
if (method.kind != MethodKind.ServerStreaming) {
throw 'client streaming not supported; use WebRTC';
}
const {serialize, parse} = createClientMethodSerializers(
method,
useBinaryFormat,
options.jsonOptions,
options.binaryOptions,
);
return await runStreamingCall<I, O>({
signal,
interceptors: options.interceptors,
req: {
stream: true as const,
service,
method,
url: createMethodUrl(options.baseUrl, service, method),
init: {
method: 'POST',
mode: 'cors',
},
header: requestHeader(useBinaryFormat, timeoutMs, header, false),
contextValues: contextValues ?? createContextValues(),
message: input,
},
next: async (
streamReq: StreamRequest<I, O>,
): Promise<StreamResponse<I, O>> => {
let respStream = createWritableIterable<O>();
let trailers = new Headers();
function fetchXHR(): Promise<FetchXHRResponse> {
let index = 0;
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
function onAbort() {
xhr.abort();
}
streamReq.signal.addEventListener('abort', onAbort);
xhr.addEventListener('abort', () => {
reject(new AbortError('Request aborted'));
});
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
resolve({
status: xhr.status,
headers: parseHeaders(xhr.getAllResponseHeaders()),
body: new Uint8Array(),
});
}
});
xhr.addEventListener('loadend', ev => {
const rawData = new Uint8Array(xhr.response);
streamReq.signal.removeEventListener('abort', onAbort);
const chunks = extractDataChunks(rawData);
let trailer: Headers | undefined;
let message: O | undefined;
let respStreamWriteProm: Promise<void> | undefined;
chunks.forEach(({flags, data}) => {
if (flags === trailerFlag) {
if (trailer !== undefined) {
throw 'extra trailer';
}
trailer = trailerParse(data);
trailer.forEach((value: string, key: string) => {
trailers.append(key, value);
});
} else {
respStreamWriteProm = respStreamWriteProm
? respStreamWriteProm
.then(() => respStream.write(parse(data)))
.catch(console.error) // eslint-disable-line no-console
: respStream.write(parse(data)).catch(console.error); // eslint-disable-line no-console
}
});
if (trailer === undefined) {
throw 'missing trailer';
}
validateTrailer(trailer, response.headers);
if (respStreamWriteProm) {
respStreamWriteProm.finally(() => {
respStream.close();
});
} else {
respStream.close();
}
});
xhr.addEventListener('error', () => {
reject(new Error('Network Error'));
});
xhr.open(streamReq.init.method ?? 'POST', streamReq.url);
streamReq.header.forEach((value: string, key: string) => {
xhr.setRequestHeader(key, value);
});
// This is incomplete since client streaming is not supported
const sendMessages = async (messages: AsyncIterable<I>) => {
let count = 0;
for await (const msg of streamReq.message) {
count += 1;
xhr.send(encodeEnvelope(0, serialize(msg)));
}
};
sendMessages(streamReq.message).catch(error => {
console.error('error sending streaming message', error); // eslint-disable-line no-console
});
});
}
const response = await fetchXHR();
validateResponse(response.status, response.headers);
return {
...streamReq,
header: response.headers,
trailer: trailers,
message: respStream,
} satisfies StreamResponse<I, O>;
},
});
},
};
}