@distilled.cloud/core 1.0.0-rc.18 → 1.0.0-rc.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/_bundle/base.js +2 -2
- package/lib/_bundle/base.js.map +1 -1
- package/lib/_bundle/graphql.js +2 -2
- package/lib/_bundle/graphql.js.map +1 -1
- package/lib/_bundle/grpc.js +2 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +1 -1
- package/lib/_bundle/rest.js.map +1 -1
- package/lib/_bundle/xml.js +1 -1
- package/lib/_bundle/xml.js.map +1 -1
- package/lib/annotations.d.ts +2 -0
- package/lib/annotations.d.ts.map +1 -1
- package/lib/annotations.js +1 -1
- package/lib/annotations.js.map +1 -1
- package/lib/api.d.ts +37 -1
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -1
- package/lib/errors.d.ts +1 -0
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -1
- package/lib/graphql.d.ts +12 -5
- package/lib/graphql.d.ts.map +1 -1
- package/lib/graphql.types.d.ts.map +1 -1
- package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-http2.js +6 -0
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.js +5 -0
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
- package/lib/grpc-transport-node-http2.d.ts +19 -0
- package/lib/grpc-transport-node-http2.d.ts.map +1 -0
- package/lib/grpc-transport-node-http2.js +2 -0
- package/lib/grpc-transport-node-http2.js.map +1 -0
- package/lib/grpc-transport.d.ts +76 -0
- package/lib/grpc-transport.d.ts.map +1 -0
- package/lib/grpc-transport.js +1 -0
- package/lib/hpack.d.ts +34 -0
- package/lib/hpack.d.ts.map +1 -0
- package/lib/hpack.js +2 -0
- package/lib/hpack.js.map +1 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -0
- package/lib/pagination.d.ts +22 -2
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -1
- package/lib/protobuf.d.ts +92 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +86 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +11 -6
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-rest.d.ts +12 -8
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/response-validation.d.ts +1 -1
- package/lib/response-validation.d.ts.map +1 -1
- package/lib/sdk-error.d.ts +27 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/sensitive.d.ts +28 -0
- package/lib/sensitive.d.ts.map +1 -0
- package/lib/sensitive.js +2 -0
- package/lib/sensitive.js.map +1 -0
- package/lib/telemetry-debug.d.ts +2 -10
- package/lib/telemetry-debug.d.ts.map +1 -1
- package/lib/telemetry-debug.js +1 -1
- package/lib/telemetry-debug.js.map +1 -1
- package/lib/telemetry-stream.d.ts +3 -1
- package/lib/telemetry-stream.d.ts.map +1 -1
- package/lib/telemetry-stream.js +1 -1
- package/lib/telemetry-stream.js.map +1 -1
- package/lib/telemetry.d.ts +23 -4
- package/lib/telemetry.d.ts.map +1 -1
- package/lib/telemetry.js +2 -2
- package/lib/telemetry.js.map +1 -1
- package/lib/trait.d.ts +7 -0
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -1
- package/lib/xml.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/annotations.ts +16 -0
- package/src/api.ts +199 -25
- package/src/errors.ts +4 -0
- package/src/graphql.ts +68 -45
- package/src/graphql.types.ts +5 -1
- package/src/grpc-transport-cloudflare-http2.ts +494 -0
- package/src/grpc-transport-cloudflare-sockets.ts +299 -0
- package/src/grpc-transport-node-http2.ts +234 -0
- package/src/grpc-transport.ts +118 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +3 -0
- package/src/pagination.ts +75 -3
- package/src/protobuf.ts +1332 -0
- package/src/protocol-grpc.ts +641 -0
- package/src/protocol-http.ts +30 -30
- package/src/protocol-rest.ts +49 -118
- package/src/response-validation.ts +4 -2
- package/src/sdk-error.ts +33 -0
- package/src/sensitive.ts +154 -0
- package/src/telemetry-debug.ts +65 -21
- package/src/telemetry-stream.ts +16 -7
- package/src/telemetry.ts +91 -27
- package/src/trait.ts +10 -0
- package/src/xml.ts +10 -1
- package/lib/debug.d.ts +0 -2
- package/lib/debug.d.ts.map +0 -1
- package/lib/debug.js +0 -1
- package/src/debug.ts +0 -11
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gRPC (binary protobuf) protocol for proto-sourced SDKs.
|
|
3
|
+
*
|
|
4
|
+
* Proto SDKs are generated as REST-shaped operations: each RPC is
|
|
5
|
+
* `POST /<package>.<Service>/<Method>` with a proto3 JSON body. Servers that
|
|
6
|
+
* accept JSON (Connect, grpc-gateway) use {@link makeRestProtocol} directly.
|
|
7
|
+
* Servers that only speak gRPC use this protocol, which builds the request
|
|
8
|
+
* with the REST protocol and speaks gRPC on the wire:
|
|
9
|
+
*
|
|
10
|
+
* - **Request**: the proto3 JSON body is transcoded to one protobuf message
|
|
11
|
+
* ({@link encodeMessage}) in one gRPC frame, sent as `application/grpc`.
|
|
12
|
+
* - **Transport**: the call goes through the `HttpClient` the
|
|
13
|
+
* `GrpcTransport` reference holds, or the caller's `HttpClient` when it
|
|
14
|
+
* holds none (see `@distilled.cloud/core/grpc-transport`). Plain `fetch`
|
|
15
|
+
* works where a proxy bridges HTTP/1.1 to gRPC (envoy).
|
|
16
|
+
* - **Status**: the call's `grpc-status` is read from the trailers, or from
|
|
17
|
+
* the headers of a trailers-only reply. A transport that can't see
|
|
18
|
+
* trailers (`fetch`) leaves only the headers; a reply with message frames
|
|
19
|
+
* and no status there is treated as OK.
|
|
20
|
+
* - **Errors**: a non-zero status becomes the operation's typed error. The
|
|
21
|
+
* REST decoder receives `{ code, status, message }` (`{ code: 5, status:
|
|
22
|
+
* "NOT_FOUND", ... }`) with the HTTP status grpc-gateway maps the code to
|
|
23
|
+
* (`NOT_FOUND` -> 404, `UNAVAILABLE` -> 503, ...), so error matchers key on
|
|
24
|
+
* the numeric gRPC `code`, and categories and retries follow the HTTP
|
|
25
|
+
* status.
|
|
26
|
+
* - **Response**: protobuf messages are transcoded back to proto3 JSON and
|
|
27
|
+
* decoded by the operation's output schema, so schemas, sensitive values
|
|
28
|
+
* and response validation behave exactly as for REST.
|
|
29
|
+
*
|
|
30
|
+
* A server-streaming method's output is `{ items: [message, ...] }`. Calling
|
|
31
|
+
* the operation collects the whole stream; its `.stream(input)` (see
|
|
32
|
+
* `API.makeStreaming`) emits each message as it arrives, and stopping the
|
|
33
|
+
* stream cancels the call.
|
|
34
|
+
*
|
|
35
|
+
* {@link Deadline} bounds calls in its scope: it is sent as `grpc-timeout`
|
|
36
|
+
* and enforced here, and a call that runs past it fails with
|
|
37
|
+
* `DEADLINE_EXCEEDED` (code 4).
|
|
38
|
+
*/
|
|
39
|
+
import * as Context from "effect/Context";
|
|
40
|
+
import * as Duration from "effect/Duration";
|
|
41
|
+
import * as Effect from "effect/Effect";
|
|
42
|
+
import type * as HttpBody from "effect/http/HttpBody";
|
|
43
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
44
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
45
|
+
import * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
46
|
+
import * as Layer from "effect/Layer";
|
|
47
|
+
import * as Stream from "effect/Stream";
|
|
48
|
+
import * as API from "./api.ts";
|
|
49
|
+
import { GrpcTransport, hasTrailers, trailersOf } from "./grpc-transport.ts";
|
|
50
|
+
import {
|
|
51
|
+
decodeMessage,
|
|
52
|
+
encodeMessage,
|
|
53
|
+
frame,
|
|
54
|
+
FrameReader,
|
|
55
|
+
type ProtoDescriptors,
|
|
56
|
+
} from "./protobuf.ts";
|
|
57
|
+
import { InvalidInput, matchTypedError } from "./protocol-http.ts";
|
|
58
|
+
import { makeRestProtocol, type RestProtocolOptions } from "./protocol-rest.ts";
|
|
59
|
+
import { SdkError } from "./sdk-error.ts";
|
|
60
|
+
import * as Telemetry from "./telemetry.ts";
|
|
61
|
+
|
|
62
|
+
/** gRPC status code -> name. */
|
|
63
|
+
export const GRPC_STATUS_NAMES: Readonly<Record<number, string>> = {
|
|
64
|
+
0: "OK",
|
|
65
|
+
1: "CANCELLED",
|
|
66
|
+
2: "UNKNOWN",
|
|
67
|
+
3: "INVALID_ARGUMENT",
|
|
68
|
+
4: "DEADLINE_EXCEEDED",
|
|
69
|
+
5: "NOT_FOUND",
|
|
70
|
+
6: "ALREADY_EXISTS",
|
|
71
|
+
7: "PERMISSION_DENIED",
|
|
72
|
+
8: "RESOURCE_EXHAUSTED",
|
|
73
|
+
9: "FAILED_PRECONDITION",
|
|
74
|
+
10: "ABORTED",
|
|
75
|
+
11: "OUT_OF_RANGE",
|
|
76
|
+
12: "UNIMPLEMENTED",
|
|
77
|
+
13: "INTERNAL",
|
|
78
|
+
14: "UNAVAILABLE",
|
|
79
|
+
15: "DATA_LOSS",
|
|
80
|
+
16: "UNAUTHENTICATED",
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** gRPC status code -> HTTP status (grpc-gateway's mapping). */
|
|
84
|
+
export const GRPC_HTTP_STATUS: Readonly<Record<number, number>> = {
|
|
85
|
+
0: 200,
|
|
86
|
+
1: 499,
|
|
87
|
+
2: 500,
|
|
88
|
+
3: 400,
|
|
89
|
+
4: 504,
|
|
90
|
+
5: 404,
|
|
91
|
+
6: 409,
|
|
92
|
+
7: 403,
|
|
93
|
+
8: 429,
|
|
94
|
+
9: 400,
|
|
95
|
+
10: 409,
|
|
96
|
+
11: 400,
|
|
97
|
+
12: 501,
|
|
98
|
+
13: 500,
|
|
99
|
+
14: 503,
|
|
100
|
+
15: 500,
|
|
101
|
+
16: 401,
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The deadline of gRPC calls in its scope, from when each call starts.
|
|
106
|
+
* `undefined` (the default) sets none.
|
|
107
|
+
*
|
|
108
|
+
* ```ts
|
|
109
|
+
* router.taskExecWait(input).pipe(Effect.provideService(Deadline, "30 seconds"));
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
export const Deadline = /*@__PURE__*/ Context.Reference<Duration.Input | undefined>(
|
|
113
|
+
"@distilled.cloud/core/protocol-grpc/Deadline",
|
|
114
|
+
{ defaultValue: () => undefined },
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
export interface GrpcProtocolOptions<C> extends RestProtocolOptions<C> {
|
|
118
|
+
/** The SDK's generated descriptors (`src/descriptors.ts`). */
|
|
119
|
+
readonly descriptors: ProtoDescriptors;
|
|
120
|
+
/**
|
|
121
|
+
* The error for a non-zero status no typed error matched, from its gRPC
|
|
122
|
+
* code. By default the REST decoder classifies it by the HTTP status the
|
|
123
|
+
* code maps to (`UNAVAILABLE` -> `ServiceUnavailable`, which retries), which
|
|
124
|
+
* keeps retries working but merges codes that share a status
|
|
125
|
+
* (`INVALID_ARGUMENT`, `FAILED_PRECONDITION` and `OUT_OF_RANGE` are all
|
|
126
|
+
* `BadRequest`).
|
|
127
|
+
*/
|
|
128
|
+
readonly statusError?: (info: StatusInfo) => unknown;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A non-OK gRPC status, as `statusError` receives it. */
|
|
132
|
+
export interface StatusInfo {
|
|
133
|
+
readonly code: number;
|
|
134
|
+
readonly message: string;
|
|
135
|
+
/** `google.rpc.Status.details` from `grpc-status-details-bin`, as proto3 JSON `Any`s. */
|
|
136
|
+
readonly details: ReadonlyArray<unknown>;
|
|
137
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** gRPC's mapping of an HTTP status, for a reply that carries no gRPC status. */
|
|
141
|
+
export const HTTP_GRPC_STATUS: Readonly<Record<number, number>> = {
|
|
142
|
+
400: 13,
|
|
143
|
+
401: 16,
|
|
144
|
+
403: 7,
|
|
145
|
+
404: 12,
|
|
146
|
+
429: 14,
|
|
147
|
+
502: 14,
|
|
148
|
+
503: 14,
|
|
149
|
+
504: 14,
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const STATUS_DESCRIPTORS: ProtoDescriptors = {
|
|
153
|
+
messages: {
|
|
154
|
+
"google.rpc.Status": [
|
|
155
|
+
[1, "code", "int32"],
|
|
156
|
+
[2, "message", "string"],
|
|
157
|
+
[3, "details", "message", "google.protobuf.Any", 1],
|
|
158
|
+
],
|
|
159
|
+
},
|
|
160
|
+
enums: {},
|
|
161
|
+
methods: {},
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** The details of `grpc-status-details-bin` (base64, padding optional). */
|
|
165
|
+
const detailsOf = (raw: string | undefined): ReadonlyArray<unknown> => {
|
|
166
|
+
if (!raw) return [];
|
|
167
|
+
try {
|
|
168
|
+
const padded = raw.padEnd(raw.length + ((4 - (raw.length % 4)) % 4), "=");
|
|
169
|
+
const bin = atob(padded.replace(/-/g, "+").replace(/_/g, "/"));
|
|
170
|
+
const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
171
|
+
const status = decodeMessage(STATUS_DESCRIPTORS, "google.rpc.Status", bytes) as {
|
|
172
|
+
readonly details: ReadonlyArray<unknown>;
|
|
173
|
+
};
|
|
174
|
+
return status.details;
|
|
175
|
+
} catch {
|
|
176
|
+
// Malformed details don't hide the status itself.
|
|
177
|
+
return [];
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
type Headers = Readonly<Record<string, string | undefined>>;
|
|
182
|
+
|
|
183
|
+
const textDecoder = /*@__PURE__*/ new TextDecoder();
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The SDK can't make the call (a broken descriptor table, or a REST
|
|
187
|
+
* encode/decode result gRPC can't use). Protocol effects are typed
|
|
188
|
+
* `never`; SdkError is part of every operation's declared error channel.
|
|
189
|
+
*/
|
|
190
|
+
const sdkFailure = (message: string): Effect.Effect<never> =>
|
|
191
|
+
Effect.fail(new SdkError({ message })) as Effect.Effect<never>;
|
|
192
|
+
|
|
193
|
+
const methodPath = (url: string): string => {
|
|
194
|
+
try {
|
|
195
|
+
return new URL(url).pathname;
|
|
196
|
+
} catch {
|
|
197
|
+
return url;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
/** The JSON a REST request carries, or `undefined` for an empty body. */
|
|
202
|
+
const jsonBody = (body: HttpBody.Uint8Array | HttpBody.Raw | HttpBody.Empty): unknown => {
|
|
203
|
+
switch (body._tag) {
|
|
204
|
+
case "Empty":
|
|
205
|
+
return undefined;
|
|
206
|
+
case "Uint8Array": {
|
|
207
|
+
const text = textDecoder.decode(body.body);
|
|
208
|
+
return text ? JSON.parse(text) : undefined;
|
|
209
|
+
}
|
|
210
|
+
case "Raw":
|
|
211
|
+
return typeof body.body === "string" && body.body ? JSON.parse(body.body) : body.body;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const jsonResponse = (
|
|
216
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
217
|
+
status: number,
|
|
218
|
+
headers: Record<string, string>,
|
|
219
|
+
value: unknown,
|
|
220
|
+
): HttpClientResponse.HttpClientResponse =>
|
|
221
|
+
HttpClientResponse.fromWeb(
|
|
222
|
+
request,
|
|
223
|
+
new Response(JSON.stringify(value), {
|
|
224
|
+
status,
|
|
225
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
226
|
+
}),
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
const plainHeaders = (headers: Headers) => {
|
|
230
|
+
const out: Record<string, string> = {};
|
|
231
|
+
for (const key in headers) {
|
|
232
|
+
const v = headers[key];
|
|
233
|
+
if (v !== undefined && key !== "content-length" && key !== "content-type") out[key] = v;
|
|
234
|
+
}
|
|
235
|
+
return out;
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const statusOf = (value: string | undefined): number | undefined =>
|
|
239
|
+
value === undefined || value === "" ? undefined : Number(value);
|
|
240
|
+
|
|
241
|
+
/** `text` percent-decoded, or as sent when it is not percent-encoded. */
|
|
242
|
+
const percentDecoded = (text: string): string => {
|
|
243
|
+
try {
|
|
244
|
+
return decodeURIComponent(text);
|
|
245
|
+
} catch {
|
|
246
|
+
return text;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const messageOf = (raw: string | undefined, status: number): string =>
|
|
251
|
+
percentDecoded(raw ?? "") || GRPC_STATUS_NAMES[status] || `gRPC status ${status}`;
|
|
252
|
+
|
|
253
|
+
/** A `grpc-timeout` value for `ms` (at most 8 digits per the spec). */
|
|
254
|
+
const grpcTimeout = (ms: number): string => {
|
|
255
|
+
const rounded = Math.max(1, Math.ceil(ms));
|
|
256
|
+
if (rounded < 1e8) return `${rounded}m`;
|
|
257
|
+
const seconds = Math.ceil(rounded / 1000);
|
|
258
|
+
return seconds < 1e8 ? `${seconds}S` : `${Math.min(99_999_999, Math.ceil(seconds / 3600))}H`;
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
type DecodeArgs = Omit<Parameters<API.ProtocolShape["decode"]>[0], "response">;
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* A gRPC protocol over the given REST protocol options. See the module
|
|
265
|
+
* documentation for the wire behavior.
|
|
266
|
+
*/
|
|
267
|
+
export const makeGrpcProtocol = <C>(options: GrpcProtocolOptions<C>): Layer.Layer<API.Protocol> =>
|
|
268
|
+
Layer.effect(
|
|
269
|
+
API.Protocol,
|
|
270
|
+
Effect.map(Effect.service(API.Protocol), (rest) => {
|
|
271
|
+
const d = options.descriptors;
|
|
272
|
+
const methodOf = (url: string) => d.methods[methodPath(url)];
|
|
273
|
+
|
|
274
|
+
/** The REST request as one gRPC frame of protobuf. */
|
|
275
|
+
const encode: API.ProtocolShape["encode"] = (args) =>
|
|
276
|
+
Effect.flatMap(rest.encode(args), (request) => {
|
|
277
|
+
const method = methodOf(request.url);
|
|
278
|
+
if (!method) return sdkFailure(`no gRPC descriptor for ${request.url}`);
|
|
279
|
+
const body = request.body;
|
|
280
|
+
if (body._tag !== "Empty" && body._tag !== "Uint8Array" && body._tag !== "Raw") {
|
|
281
|
+
return sdkFailure(`gRPC requests need a JSON body, got ${body._tag}`);
|
|
282
|
+
}
|
|
283
|
+
let payload: Uint8Array;
|
|
284
|
+
try {
|
|
285
|
+
payload = encodeMessage(d, method[0], jsonBody(body) ?? {});
|
|
286
|
+
} catch (cause) {
|
|
287
|
+
// The encode channel is typed `never`; InvalidInput is part of
|
|
288
|
+
// every operation's declared error channel.
|
|
289
|
+
return Effect.fail(
|
|
290
|
+
new InvalidInput({
|
|
291
|
+
member: method[0],
|
|
292
|
+
message: cause instanceof Error ? cause.message : String(cause),
|
|
293
|
+
}),
|
|
294
|
+
) as unknown as Effect.Effect<HttpClientRequest.HttpClientRequest>;
|
|
295
|
+
}
|
|
296
|
+
return Effect.succeed(
|
|
297
|
+
request.pipe(
|
|
298
|
+
HttpClientRequest.bodyUint8Array(frame(payload), "application/grpc"),
|
|
299
|
+
HttpClientRequest.setHeader("te", "trailers"),
|
|
300
|
+
),
|
|
301
|
+
);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
/** A gRPC status as the operation's typed error. */
|
|
305
|
+
const failWith = (
|
|
306
|
+
args: DecodeArgs,
|
|
307
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
308
|
+
headers: Headers,
|
|
309
|
+
status: number,
|
|
310
|
+
message: string | undefined,
|
|
311
|
+
details: ReadonlyArray<unknown> = [],
|
|
312
|
+
): Effect.Effect<never> => {
|
|
313
|
+
const httpStatus = GRPC_HTTP_STATUS[status] ?? 500;
|
|
314
|
+
const body = {
|
|
315
|
+
code: status,
|
|
316
|
+
status: GRPC_STATUS_NAMES[status] ?? String(status),
|
|
317
|
+
message: messageOf(message, status),
|
|
318
|
+
details,
|
|
319
|
+
};
|
|
320
|
+
if (options.statusError !== undefined) {
|
|
321
|
+
const plain = plainHeaders(headers);
|
|
322
|
+
const typed = matchTypedError(
|
|
323
|
+
args.errors,
|
|
324
|
+
httpStatus,
|
|
325
|
+
[{ code: status, message: body.message }],
|
|
326
|
+
{ body, headers: plain },
|
|
327
|
+
);
|
|
328
|
+
return Effect.fail(
|
|
329
|
+
typed ??
|
|
330
|
+
options.statusError({ code: status, message: body.message, details, headers: plain }),
|
|
331
|
+
) as Effect.Effect<never>;
|
|
332
|
+
}
|
|
333
|
+
return Effect.flatMap(
|
|
334
|
+
rest.decode({
|
|
335
|
+
...args,
|
|
336
|
+
response: jsonResponse(request, httpStatus, plainHeaders(headers), body),
|
|
337
|
+
}),
|
|
338
|
+
() => sdkFailure(`gRPC status ${status} decoded as a success`),
|
|
339
|
+
);
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* The call's failure, if any, once its body has ended. The status is in
|
|
344
|
+
* the trailers, or in the headers of a trailers-only reply (one with no
|
|
345
|
+
* body); a status in the headers of a reply with a body is ignored. A
|
|
346
|
+
* transport that reads trailers must deliver one; over `fetch`, which
|
|
347
|
+
* can't, a reply with messages and no status is OK.
|
|
348
|
+
*/
|
|
349
|
+
const endOf = (
|
|
350
|
+
args: DecodeArgs,
|
|
351
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
352
|
+
trailers: Readonly<Record<string, string>>,
|
|
353
|
+
sawBody: boolean,
|
|
354
|
+
): Effect.Effect<void> => {
|
|
355
|
+
const headers = response.headers as Headers;
|
|
356
|
+
const readsTrailers = hasTrailers(response);
|
|
357
|
+
const source =
|
|
358
|
+
trailers["grpc-status"] !== undefined
|
|
359
|
+
? trailers
|
|
360
|
+
: !sawBody || !readsTrailers
|
|
361
|
+
? headers
|
|
362
|
+
: undefined;
|
|
363
|
+
const status = statusOf(source?.["grpc-status"]);
|
|
364
|
+
if (source === undefined || status === undefined) {
|
|
365
|
+
if (readsTrailers) {
|
|
366
|
+
return failWith(
|
|
367
|
+
args,
|
|
368
|
+
response.request,
|
|
369
|
+
headers,
|
|
370
|
+
13,
|
|
371
|
+
"server ended the call without a grpc-status",
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
return sawBody
|
|
375
|
+
? Effect.void
|
|
376
|
+
: failWith(
|
|
377
|
+
args,
|
|
378
|
+
response.request,
|
|
379
|
+
headers,
|
|
380
|
+
2,
|
|
381
|
+
"gRPC response carried no message and no grpc-status",
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
return status === 0
|
|
385
|
+
? Effect.void
|
|
386
|
+
: failWith(
|
|
387
|
+
args,
|
|
388
|
+
response.request,
|
|
389
|
+
headers,
|
|
390
|
+
status,
|
|
391
|
+
source["grpc-message"],
|
|
392
|
+
detailsOf(source["grpc-status-details-bin"]),
|
|
393
|
+
);
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
/** A malformed frame (compressed, truncated): gRPC's INTERNAL. */
|
|
397
|
+
const badFrame = (
|
|
398
|
+
args: DecodeArgs,
|
|
399
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
400
|
+
cause: unknown,
|
|
401
|
+
) =>
|
|
402
|
+
failWith(
|
|
403
|
+
args,
|
|
404
|
+
response.request,
|
|
405
|
+
response.headers as Headers,
|
|
406
|
+
13,
|
|
407
|
+
cause instanceof Error ? cause.message : String(cause),
|
|
408
|
+
);
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* A reply that isn't gRPC: a status other than 200, or another content
|
|
412
|
+
* type. The REST decoder classifies a non-200 by its HTTP status; with
|
|
413
|
+
* `statusError`, it maps as gRPC specifies (503 -> UNAVAILABLE, ...).
|
|
414
|
+
*/
|
|
415
|
+
const notGrpc = (
|
|
416
|
+
args: DecodeArgs,
|
|
417
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
418
|
+
): Effect.Effect<never> | undefined => {
|
|
419
|
+
const headers = response.headers as Headers;
|
|
420
|
+
const isGrpc = (headers["content-type"] ?? "").startsWith("application/grpc");
|
|
421
|
+
if (response.status === 200 && isGrpc) return undefined;
|
|
422
|
+
if (response.status !== 200 && options.statusError === undefined) {
|
|
423
|
+
return rest.decode({ ...args, response }) as Effect.Effect<never>;
|
|
424
|
+
}
|
|
425
|
+
if (response.status !== 200) {
|
|
426
|
+
return failWith(
|
|
427
|
+
args,
|
|
428
|
+
response.request,
|
|
429
|
+
headers,
|
|
430
|
+
HTTP_GRPC_STATUS[response.status] ?? 2,
|
|
431
|
+
`HTTP ${response.status}`,
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
return failWith(
|
|
435
|
+
args,
|
|
436
|
+
response.request,
|
|
437
|
+
headers,
|
|
438
|
+
2,
|
|
439
|
+
`unexpected content-type ${JSON.stringify(headers["content-type"] ?? "")}`,
|
|
440
|
+
);
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
/** A reply value decoded by the operation's output schema. */
|
|
444
|
+
const succeedWith = (
|
|
445
|
+
args: DecodeArgs,
|
|
446
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
447
|
+
headers: Headers,
|
|
448
|
+
value: unknown,
|
|
449
|
+
) =>
|
|
450
|
+
rest.decode({
|
|
451
|
+
...args,
|
|
452
|
+
response: jsonResponse(request, 200, plainHeaders(headers), value),
|
|
453
|
+
});
|
|
454
|
+
|
|
455
|
+
const parseFailure = (body: unknown, cause: unknown): Effect.Effect<never> =>
|
|
456
|
+
Effect.fail(options.parseError({ body, cause })) as Effect.Effect<never>;
|
|
457
|
+
|
|
458
|
+
const deadlineMillis = (context: Context.Context<any>): number | undefined => {
|
|
459
|
+
const deadline = Context.get(context, Deadline);
|
|
460
|
+
return deadline === undefined ? undefined : Duration.toMillis(deadline);
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
/** Send a call through the transport in scope, with the deadline in scope. */
|
|
464
|
+
const send = (
|
|
465
|
+
context: Context.Context<any>,
|
|
466
|
+
operation: API.PreparedOperation,
|
|
467
|
+
input: unknown,
|
|
468
|
+
ms: number | undefined,
|
|
469
|
+
) =>
|
|
470
|
+
Effect.flatMap(
|
|
471
|
+
encode({ input, inputAst: operation.inputAst, config: operation.config }),
|
|
472
|
+
(encoded) => {
|
|
473
|
+
const request =
|
|
474
|
+
ms === undefined
|
|
475
|
+
? encoded
|
|
476
|
+
: HttpClientRequest.setHeader(encoded, "grpc-timeout", grpcTimeout(ms));
|
|
477
|
+
const client =
|
|
478
|
+
Context.get(context, GrpcTransport) ?? Context.get(context, HttpClient.HttpClient);
|
|
479
|
+
return Telemetry.execute(context, client, request);
|
|
480
|
+
},
|
|
481
|
+
);
|
|
482
|
+
|
|
483
|
+
/** Decode a whole reply (its body read to the end). */
|
|
484
|
+
const decode: API.ProtocolShape["decode"] = (args) => {
|
|
485
|
+
const { response } = args;
|
|
486
|
+
const failed = notGrpc(args, response);
|
|
487
|
+
if (failed) return failed;
|
|
488
|
+
const headers = response.headers as Headers;
|
|
489
|
+
const request = response.request;
|
|
490
|
+
const method = methodOf(request.url);
|
|
491
|
+
if (!method) return sdkFailure(`no gRPC descriptor for ${request.url}`);
|
|
492
|
+
// Protocol effects carry no error type: callers see the operation's.
|
|
493
|
+
return Effect.flatMap(response.arrayBuffer as Effect.Effect<ArrayBuffer>, (buffer) =>
|
|
494
|
+
Effect.flatMap(trailersOf(response), (trailers) => {
|
|
495
|
+
const reader = new FrameReader();
|
|
496
|
+
let frames: Uint8Array[];
|
|
497
|
+
try {
|
|
498
|
+
frames = reader.push(new Uint8Array(buffer));
|
|
499
|
+
} catch (cause) {
|
|
500
|
+
return Effect.flatMap(endOf(args, response, trailers, true), () =>
|
|
501
|
+
badFrame(args, response, cause),
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
return Effect.flatMap(endOf(args, response, trailers, buffer.byteLength > 0), () => {
|
|
505
|
+
if (reader.rest !== 0) return badFrame(args, response, "truncated gRPC frame");
|
|
506
|
+
const [, responseType, stream] = method;
|
|
507
|
+
if (!stream && frames.length !== 1) {
|
|
508
|
+
return failWith(
|
|
509
|
+
args,
|
|
510
|
+
request,
|
|
511
|
+
headers,
|
|
512
|
+
12,
|
|
513
|
+
`expected one response message, got ${frames.length}`,
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
let value: unknown;
|
|
517
|
+
try {
|
|
518
|
+
value = stream
|
|
519
|
+
? { items: frames.map((f) => decodeMessage(d, responseType, f)) }
|
|
520
|
+
: decodeMessage(d, responseType, frames[0]!);
|
|
521
|
+
} catch (cause) {
|
|
522
|
+
return parseFailure(buffer, cause);
|
|
523
|
+
}
|
|
524
|
+
return succeedWith(args, request, headers, value);
|
|
525
|
+
});
|
|
526
|
+
}),
|
|
527
|
+
);
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
const deadlineExceeded = (args: DecodeArgs, url: string) =>
|
|
531
|
+
failWith(args, HttpClientRequest.post(url), {}, 4, "Deadline Exceeded");
|
|
532
|
+
|
|
533
|
+
return API.Protocol.of({
|
|
534
|
+
encode,
|
|
535
|
+
decode,
|
|
536
|
+
call: (operation, input) =>
|
|
537
|
+
Effect.withFiber((fiber) => {
|
|
538
|
+
const context = fiber.context as Context.Context<any>;
|
|
539
|
+
const args: DecodeArgs = {
|
|
540
|
+
outputAst: operation.outputAst,
|
|
541
|
+
errors: operation.errors,
|
|
542
|
+
config: operation.config,
|
|
543
|
+
};
|
|
544
|
+
const ms = deadlineMillis(context);
|
|
545
|
+
const run = Effect.flatMap(
|
|
546
|
+
send(
|
|
547
|
+
context,
|
|
548
|
+
operation,
|
|
549
|
+
input,
|
|
550
|
+
ms,
|
|
551
|
+
) as Effect.Effect<HttpClientResponse.HttpClientResponse>,
|
|
552
|
+
(response) => decode({ ...args, response }),
|
|
553
|
+
);
|
|
554
|
+
return ms === undefined
|
|
555
|
+
? run
|
|
556
|
+
: Effect.timeoutOrElse(run, {
|
|
557
|
+
duration: ms,
|
|
558
|
+
orElse: () => deadlineExceeded(args, ""),
|
|
559
|
+
});
|
|
560
|
+
}),
|
|
561
|
+
stream: (operation, input) =>
|
|
562
|
+
Stream.unwrap(
|
|
563
|
+
Effect.withFiber((fiber) => {
|
|
564
|
+
const context = fiber.context as Context.Context<any>;
|
|
565
|
+
const args: DecodeArgs = {
|
|
566
|
+
outputAst: operation.outputAst,
|
|
567
|
+
errors: operation.errors,
|
|
568
|
+
config: operation.config,
|
|
569
|
+
};
|
|
570
|
+
const ms = deadlineMillis(context);
|
|
571
|
+
const messages = Effect.map(
|
|
572
|
+
send(
|
|
573
|
+
context,
|
|
574
|
+
operation,
|
|
575
|
+
input,
|
|
576
|
+
ms,
|
|
577
|
+
) as Effect.Effect<HttpClientResponse.HttpClientResponse>,
|
|
578
|
+
(response) => streamReply(args, response),
|
|
579
|
+
);
|
|
580
|
+
const stream = Stream.unwrap(messages);
|
|
581
|
+
return Effect.succeed(
|
|
582
|
+
ms === undefined
|
|
583
|
+
? stream
|
|
584
|
+
: Stream.interruptWhen(
|
|
585
|
+
stream,
|
|
586
|
+
Effect.flatMap(Effect.sleep(ms), () => deadlineExceeded(args, "")),
|
|
587
|
+
),
|
|
588
|
+
);
|
|
589
|
+
}),
|
|
590
|
+
),
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
/** Each message of a server stream, decoded as it arrives. */
|
|
594
|
+
function streamReply(
|
|
595
|
+
args: DecodeArgs,
|
|
596
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
597
|
+
): Stream.Stream<unknown, unknown> {
|
|
598
|
+
const headers = response.headers as Headers;
|
|
599
|
+
const request = response.request;
|
|
600
|
+
const failed = notGrpc(args, response);
|
|
601
|
+
if (failed) return Stream.fromEffect(failed);
|
|
602
|
+
const method = methodOf(request.url);
|
|
603
|
+
if (!method) return Stream.fromEffect(sdkFailure(`no gRPC descriptor for ${request.url}`));
|
|
604
|
+
const [, responseType] = method;
|
|
605
|
+
const reader = new FrameReader();
|
|
606
|
+
const item = (payload: Uint8Array) => {
|
|
607
|
+
let value: unknown;
|
|
608
|
+
try {
|
|
609
|
+
value = decodeMessage(d, responseType, payload);
|
|
610
|
+
} catch (cause) {
|
|
611
|
+
return parseFailure(payload, cause);
|
|
612
|
+
}
|
|
613
|
+
return Effect.map(
|
|
614
|
+
succeedWith(args, request, headers, { items: [value] }),
|
|
615
|
+
(decoded) => (decoded as { readonly items: ReadonlyArray<unknown> }).items[0],
|
|
616
|
+
);
|
|
617
|
+
};
|
|
618
|
+
const messages = Stream.flatMap(response.stream, (chunk) =>
|
|
619
|
+
Stream.fromIterableEffect(
|
|
620
|
+
Effect.suspend(() => {
|
|
621
|
+
if (chunk.length > 0) sawBody = true;
|
|
622
|
+
let frames: Uint8Array[];
|
|
623
|
+
try {
|
|
624
|
+
frames = reader.push(chunk);
|
|
625
|
+
} catch (cause) {
|
|
626
|
+
return badFrame(args, response, cause);
|
|
627
|
+
}
|
|
628
|
+
return Effect.forEach(frames, item);
|
|
629
|
+
}),
|
|
630
|
+
),
|
|
631
|
+
);
|
|
632
|
+
let sawBody = false;
|
|
633
|
+
const end = Effect.flatMap(trailersOf(response), (trailers) =>
|
|
634
|
+
Effect.flatMap(endOf(args, response, trailers, sawBody), () =>
|
|
635
|
+
reader.rest !== 0 ? badFrame(args, response, "truncated gRPC frame") : Effect.void,
|
|
636
|
+
),
|
|
637
|
+
);
|
|
638
|
+
return Stream.concat(messages, Stream.drain(Stream.fromEffect(end)));
|
|
639
|
+
}
|
|
640
|
+
}),
|
|
641
|
+
).pipe(Layer.provide(makeRestProtocol(options)));
|