-
Notifications
You must be signed in to change notification settings - Fork 83
/
connect-transport.ts
382 lines (366 loc) · 11.1 KB
/
connect-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
// 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,
JsonValue,
JsonWriteOptions,
MessageInitShape,
MessageShape,
DescMethodUnary,
DescMethodStreaming,
} from "@bufbuild/protobuf";
import { fromJson } from "@bufbuild/protobuf";
import type {
Interceptor,
StreamResponse,
Transport,
UnaryRequest,
UnaryResponse,
ContextValues,
} from "@connectrpc/connect";
import {
Code,
ConnectError,
appendHeaders,
createContextValues,
} from "@connectrpc/connect";
import {
createClientMethodSerializers,
createEnvelopeReadableStream,
createMethodUrl,
getJsonOptions,
encodeEnvelope,
runStreamingCall,
runUnaryCall,
compressedFlag,
} from "@connectrpc/connect/protocol";
import {
endStreamFlag,
endStreamFromJson,
errorFromJson,
requestHeader,
trailerDemux,
transformConnectPostToGetRequest,
validateResponse,
} from "@connectrpc/connect/protocol-connect";
import { assertFetchApi } from "./assert-fetch-api.js";
import { MethodOptions_IdempotencyLevel } from "@bufbuild/protobuf/wkt";
/**
* Options used to configure the Connect transport.
*
* See createConnectTransport().
*/
export interface ConnectTransportOptions {
/**
* 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, connect-web clients use the JSON format.
*/
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;
/**
* Controls whether or not Connect GET requests should be used when
* available, on side-effect free methods. Defaults to false.
*/
useHttpGet?: boolean;
/**
* 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 Connect protocol, which makes unary and
* server-streaming methods available to web browsers. It uses the fetch
* API to make HTTP requests.
*/
export function createConnectTransport(
options: ConnectTransportOptions,
): Transport {
assertFetchApi();
const useBinaryFormat = options.useBinaryFormat ?? false;
return {
async unary<I extends DescMessage, O extends DescMessage>(
method: DescMethodUnary<I, O>,
signal: AbortSignal | undefined,
timeoutMs: number | undefined,
header: HeadersInit | undefined,
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(
method.methodKind,
useBinaryFormat,
timeoutMs,
header,
false,
),
contextValues: contextValues ?? createContextValues(),
message,
},
next: async (req: UnaryRequest<I, O>): Promise<UnaryResponse<I, O>> => {
const useGet =
options.useHttpGet === true &&
method.idempotency ===
MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS;
let body: BodyInit | null = null;
if (useGet) {
req = transformConnectPostToGetRequest(
req,
serialize(req.message),
useBinaryFormat,
);
} else {
body = serialize(req.message);
}
const fetch = options.fetch ?? globalThis.fetch;
const response = await fetch(req.url, {
...fetchOptions,
method: req.requestMethod,
headers: req.header,
signal: req.signal,
body,
});
const { isUnaryError, unaryError } = validateResponse(
method.methodKind,
useBinaryFormat,
response.status,
response.headers,
);
if (isUnaryError) {
throw errorFromJson(
(await response.json()) as JsonValue,
appendHeaders(...trailerDemux(response.headers)),
unaryError,
);
}
const [demuxedHeader, demuxedTrailer] = trailerDemux(
response.headers,
);
return {
stream: false,
service: method.parent,
method,
header: demuxedHeader,
message: useBinaryFormat
? parse(new Uint8Array(await response.arrayBuffer()))
: fromJson(
method.output,
(await response.json()) as JsonValue,
getJsonOptions(options.jsonOptions),
),
trailer: demuxedTrailer,
};
},
});
},
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>,
trailerTarget: Headers,
header: Headers,
signal: AbortSignal,
) {
const reader = createEnvelopeReadableStream(body).getReader();
let endStreamReceived = false;
for (;;) {
const result = await reader.read();
if (result.done) {
break;
}
const { flags, data } = result.value;
if ((flags & compressedFlag) === compressedFlag) {
throw new ConnectError(
`protocol error: received unsupported compressed output`,
Code.Internal,
);
}
if ((flags & endStreamFlag) === endStreamFlag) {
endStreamReceived = true;
const endStream = endStreamFromJson(data);
if (endStream.error) {
const error = endStream.error;
header.forEach((value, key) => {
error.metadata.append(key, value);
});
throw error;
}
endStream.metadata.forEach((value, key) =>
trailerTarget.set(key, value),
);
continue;
}
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 (!endStreamReceived) {
throw "missing EndStreamResponse";
}
}
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 await runStreamingCall<I, O>({
interceptors: options.interceptors,
timeoutMs,
signal,
req: {
stream: true,
service: method.parent,
method,
requestMethod: "POST",
url: createMethodUrl(options.baseUrl, method),
header: requestHeader(
method.methodKind,
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),
});
validateResponse(
method.methodKind,
useBinaryFormat,
fRes.status,
fRes.headers,
);
if (fRes.body === null) {
throw "missing response body";
}
const trailer = new Headers();
const res: StreamResponse<I, O> = {
...req,
header: fRes.headers,
trailer,
message: parseResponseBody(
fRes.body,
trailer,
fRes.headers,
req.signal,
),
};
return res;
},
});
},
};
}