-
Notifications
You must be signed in to change notification settings - Fork 83
/
grpc-web-transport.ts
387 lines (374 loc) · 12.1 KB
/
grpc-web-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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Copyright 2021-2024 The Connect Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import type {
BinaryReadOptions,
BinaryWriteOptions,
DescMessage,
JsonReadOptions,
JsonWriteOptions,
MessageInitShape,
MessageShape,
DescMethodUnary,
DescMethodStreaming,
} from "@bufbuild/protobuf";
import type {
Interceptor,
StreamResponse,
Transport,
UnaryRequest,
UnaryResponse,
ContextValues,
} from "@connectrpc/connect";
import { createContextValues, ConnectError, Code } from "@connectrpc/connect";
import {
compressedFlag,
createClientMethodSerializers,
createEnvelopeReadableStream,
createMethodUrl,
encodeEnvelope,
runStreamingCall,
runUnaryCall,
} from "@connectrpc/connect/protocol";
import {
headerGrpcStatus,
requestHeader,
trailerFlag,
trailerParse,
validateResponse,
validateTrailer,
} from "@connectrpc/connect/protocol-grpc-web";
import { assertFetchApi } from "./assert-fetch-api.js";
/**
* Options used to configure the gRPC-web transport.
*
* See createGrpcWebTransport().
*/
export interface GrpcWebTransportOptions {
/**
* Base URI for all HTTP requests.
*
* Requests will be made to <baseUrl>/<package>.<service>/method
*
* Example: `baseUrl: "https://example.com/my-api"`
*
* This will make a `POST /my-api/my_package.MyService/Foo` to
* `example.com` via HTTPS.
*
* If your API is served from the same domain as your site, use
* `baseUrl: window.location.origin` or simply "/".
*/
baseUrl: string;
/**
* By default, clients use the binary format for gRPC-web, because
* not all gRPC-web implementations support JSON.
*/
useBinaryFormat?: boolean;
/**
* Interceptors that should be applied to all calls running through
* this transport. See the Interceptor type for details.
*/
interceptors?: Interceptor[];
/**
* Options for the JSON format.
* By default, unknown fields are ignored.
*/
jsonOptions?: Partial<JsonReadOptions & JsonWriteOptions>;
/**
* Options for the binary wire format.
*/
binaryOptions?: Partial<BinaryReadOptions & BinaryWriteOptions>;
/**
* Optional override of the fetch implementation used by the transport.
*
* This option can be used to set fetch options such as "credentials".
*/
fetch?: typeof globalThis.fetch;
/**
* The timeout in milliseconds to apply to all requests.
*
* This can be overridden on a per-request basis by passing a timeoutMs.
*/
defaultTimeoutMs?: number;
}
const fetchOptions: RequestInit = {
redirect: "error",
};
/**
* Create a Transport for the gRPC-web protocol. The protocol encodes
* trailers in the response body and makes unary and server-streaming
* methods available to web browsers. It uses the fetch API to make
* HTTP requests.
*
* Note that this transport does not implement the grpc-web-text format,
* which applies base64 encoding to the request and response bodies to
* support reading streaming responses from an XMLHttpRequest.
*/
export function createGrpcWebTransport(
options: GrpcWebTransportOptions,
): Transport {
assertFetchApi();
const useBinaryFormat = options.useBinaryFormat ?? true;
return {
async unary<I extends DescMessage, O extends DescMessage>(
method: DescMethodUnary<I, O>,
signal: AbortSignal | undefined,
timeoutMs: number | undefined,
header: Headers,
message: MessageInitShape<I>,
contextValues?: ContextValues,
): Promise<UnaryResponse<I, O>> {
const { serialize, parse } = createClientMethodSerializers(
method,
useBinaryFormat,
options.jsonOptions,
options.binaryOptions,
);
timeoutMs =
timeoutMs === undefined
? options.defaultTimeoutMs
: timeoutMs <= 0
? undefined
: timeoutMs;
return await runUnaryCall<I, O>({
interceptors: options.interceptors,
signal,
timeoutMs,
req: {
stream: false,
service: method.parent,
method,
requestMethod: "POST",
url: createMethodUrl(options.baseUrl, method),
header: requestHeader(useBinaryFormat, timeoutMs, header, false),
contextValues: contextValues ?? createContextValues(),
message,
},
next: async (req: UnaryRequest<I, O>): Promise<UnaryResponse<I, O>> => {
const fetch = options.fetch ?? globalThis.fetch;
const response = await fetch(req.url, {
...fetchOptions,
method: req.requestMethod,
headers: req.header,
signal: req.signal,
body: encodeEnvelope(0, serialize(req.message)),
});
const { headerError } = validateResponse(
response.status,
response.headers,
);
if (!response.body) {
if (headerError !== undefined) throw headerError;
throw "missing response body";
}
const reader = createEnvelopeReadableStream(
response.body,
).getReader();
let trailer: Headers | undefined;
let message: MessageShape<O> | undefined;
for (;;) {
const r = await reader.read();
if (r.done) {
break;
}
const { flags, data } = r.value;
if ((flags & compressedFlag) === compressedFlag) {
throw new ConnectError(
`protocol error: received unsupported compressed output`,
Code.Internal,
);
}
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);
continue;
}
if (message !== undefined) {
throw new ConnectError("extra message", Code.Unimplemented);
}
message = parse(data);
}
if (trailer === undefined) {
if (headerError !== undefined) throw headerError;
throw new ConnectError(
"missing trailer",
response.headers.has(headerGrpcStatus)
? Code.Unimplemented
: Code.Unknown,
);
}
validateTrailer(trailer, response.headers);
if (message === undefined) {
throw new ConnectError(
"missing message",
trailer.has(headerGrpcStatus) ? Code.Unimplemented : Code.Unknown,
);
}
return {
stream: false,
service: method.parent,
method,
header: response.headers,
message,
trailer,
};
},
});
},
async stream<I extends DescMessage, O extends DescMessage>(
method: DescMethodStreaming<I, O>,
signal: AbortSignal | undefined,
timeoutMs: number | undefined,
header: HeadersInit | undefined,
input: AsyncIterable<MessageInitShape<I>>,
contextValues?: ContextValues,
): Promise<StreamResponse<I, O>> {
const { serialize, parse } = createClientMethodSerializers(
method,
useBinaryFormat,
options.jsonOptions,
options.binaryOptions,
);
async function* parseResponseBody(
body: ReadableStream<Uint8Array>,
foundStatus: boolean,
trailerTarget: Headers,
header: Headers,
signal: AbortSignal,
) {
const reader = createEnvelopeReadableStream(body).getReader();
if (foundStatus) {
// A grpc-status: 0 response header was present. This is a "trailers-only"
// response (a response without a body and no trailers).
//
// The spec seems to disallow a trailers-only response for status 0 - we are
// lenient and only verify that the body is empty.
//
// > [...] Trailers-Only is permitted for calls that produce an immediate error.
// See https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
if (!(await reader.read()).done) {
throw "extra data for trailers-only";
}
return;
}
let trailerReceived = false;
for (;;) {
const result = await reader.read();
if (result.done) {
break;
}
const { flags, data } = result.value;
if ((flags & trailerFlag) === trailerFlag) {
if (trailerReceived) {
throw "extra trailer";
}
trailerReceived = true;
const trailer = trailerParse(data);
validateTrailer(trailer, header);
trailer.forEach((value, key) => trailerTarget.set(key, value));
continue;
}
if (trailerReceived) {
throw "extra message";
}
yield parse(data);
}
// Node wil not throw an AbortError on `read` if the
// signal is aborted before `getReader` is called.
// As a work around we check at the end and throw.
//
// Ref: https://github.com/nodejs/undici/issues/1940
if ("throwIfAborted" in signal) {
// We assume that implementations without `throwIfAborted` (old
// browsers) do honor aborted signals on `read`.
signal.throwIfAborted();
}
if (!trailerReceived) {
throw "missing trailer";
}
}
async function createRequestBody(
input: AsyncIterable<MessageShape<I>>,
): Promise<Uint8Array> {
if (method.methodKind != "server_streaming") {
throw "The fetch API does not support streaming request bodies";
}
const r = await input[Symbol.asyncIterator]().next();
if (r.done == true) {
throw "missing request message";
}
return encodeEnvelope(0, serialize(r.value));
}
timeoutMs =
timeoutMs === undefined
? options.defaultTimeoutMs
: timeoutMs <= 0
? undefined
: timeoutMs;
return runStreamingCall<I, O>({
interceptors: options.interceptors,
signal,
timeoutMs,
req: {
stream: true,
service: method.parent,
method,
requestMethod: "POST",
url: createMethodUrl(options.baseUrl, method),
header: requestHeader(useBinaryFormat, timeoutMs, header, false),
contextValues: contextValues ?? createContextValues(),
message: input,
},
next: async (req) => {
const fetch = options.fetch ?? globalThis.fetch;
const fRes = await fetch(req.url, {
...fetchOptions,
method: req.requestMethod,
headers: req.header,
signal: req.signal,
body: await createRequestBody(req.message),
});
const { foundStatus, headerError } = validateResponse(
fRes.status,
fRes.headers,
);
if (headerError != undefined) {
throw headerError;
}
if (!fRes.body) {
throw "missing response body";
}
const trailer = new Headers();
const res: StreamResponse<I, O> = {
...req,
header: fRes.headers,
trailer,
message: parseResponseBody(
fRes.body,
foundStatus,
trailer,
fRes.headers,
req.signal,
),
};
return res;
},
});
},
};
}