@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.21
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/LICENSE +201 -0
- package/README.md +33 -0
- package/lib/_bundle/aws.js +2 -0
- package/lib/_bundle/aws.js.map +1 -0
- package/lib/_bundle/base.js +5 -0
- package/lib/_bundle/base.js.map +1 -0
- package/lib/_bundle/graphql.js +3 -0
- package/lib/_bundle/graphql.js.map +1 -0
- package/lib/_bundle/grpc.js +3 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +2 -0
- package/lib/_bundle/rest.js.map +1 -0
- package/lib/_bundle/xml.js +4 -0
- package/lib/_bundle/xml.js.map +1 -0
- package/lib/annotations.d.ts +17 -0
- package/lib/annotations.d.ts.map +1 -0
- package/lib/annotations.js +2 -0
- package/lib/annotations.js.map +1 -0
- package/lib/api.d.ts +220 -51
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -178
- package/lib/category.d.ts +19 -16
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +1 -280
- package/lib/chunks.d.ts +3 -0
- package/lib/chunks.d.ts.map +1 -0
- package/lib/chunks.js +1 -0
- package/lib/config.d.ts +81 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +1 -0
- package/lib/crypto.d.ts +76 -0
- package/lib/crypto.d.ts.map +1 -0
- package/lib/crypto.js +1 -0
- package/lib/error-category.d.ts +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +1 -46
- package/lib/errors.d.ts +99 -74
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -186
- package/lib/graphql.d.ts +420 -0
- package/lib/graphql.d.ts.map +1 -0
- package/lib/graphql.js +1 -0
- package/lib/graphql.types.d.ts +11 -0
- package/lib/graphql.types.d.ts.map +1 -0
- package/lib/graphql.types.js +1 -0
- 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 +111 -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 +32 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +17 -0
- package/lib/max-message-bytes.d.ts +42 -0
- package/lib/max-message-bytes.d.ts.map +1 -0
- package/lib/max-message-bytes.js +2 -0
- package/lib/max-message-bytes.js.map +1 -0
- package/lib/ndjson.d.ts +3 -0
- package/lib/ndjson.d.ts.map +1 -0
- package/lib/ndjson.js +2 -0
- package/lib/ndjson.js.map +1 -0
- package/lib/pagination.d.ts +105 -25
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -182
- package/lib/plain-values.d.ts +21 -0
- package/lib/plain-values.d.ts.map +1 -0
- package/lib/plain-values.js +2 -0
- package/lib/plain-values.js.map +1 -0
- package/lib/protobuf.d.ts +85 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +123 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +206 -25
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -554
- package/lib/protocol-rest.d.ts +258 -64
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -242
- package/lib/protocol.d.ts +113 -0
- package/lib/protocol.d.ts.map +1 -0
- package/lib/protocol.js +0 -0
- package/lib/query.d.ts +29 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +1 -0
- package/lib/response-validation-strict.d.ts +48 -0
- package/lib/response-validation-strict.d.ts.map +1 -0
- package/lib/response-validation-strict.js +1 -0
- package/lib/response-validation.d.ts +86 -0
- package/lib/response-validation.d.ts.map +1 -0
- package/lib/response-validation.js +1 -0
- package/lib/retry-after.d.ts +4 -4
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-after.js +1 -112
- package/lib/retry-state.d.ts +26 -0
- package/lib/retry-state.d.ts.map +1 -0
- package/lib/retry-state.js +2 -0
- package/lib/retry-state.js.map +1 -0
- package/lib/retry.d.ts +141 -42
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -210
- package/lib/schema-lite-impl.d.ts +179 -0
- package/lib/schema-lite-impl.d.ts.map +1 -0
- package/lib/schema-lite-impl.js +1 -0
- package/lib/schema-lite-typed.d.ts +41 -0
- package/lib/schema-lite-typed.d.ts.map +1 -0
- package/lib/schema-lite-typed.js +1 -0
- package/lib/schema-lite.d.ts +41 -0
- package/lib/schema-lite.d.ts.map +1 -0
- package/lib/schema-lite.js +1 -0
- package/lib/schema.d.ts +21 -7
- package/lib/schema.d.ts.map +1 -1
- package/lib/schema.js +1 -48
- package/lib/sdk-error.d.ts +31 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/send.d.ts +37 -0
- package/lib/send.d.ts.map +1 -0
- package/lib/send.js +2 -0
- package/lib/send.js.map +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 +6 -0
- package/lib/telemetry-debug.d.ts.map +1 -0
- package/lib/telemetry-debug.js +2 -0
- package/lib/telemetry-debug.js.map +1 -0
- package/lib/telemetry-hooks.d.ts +32 -0
- package/lib/telemetry-hooks.d.ts.map +1 -0
- package/lib/telemetry-hooks.js +2 -0
- package/lib/telemetry-hooks.js.map +1 -0
- package/lib/telemetry-host-rules.d.ts +23 -0
- package/lib/telemetry-host-rules.d.ts.map +1 -0
- package/lib/telemetry-host-rules.js +2 -0
- package/lib/telemetry-host-rules.js.map +1 -0
- package/lib/telemetry-lambda-context.d.ts +17 -0
- package/lib/telemetry-lambda-context.d.ts.map +1 -0
- package/lib/telemetry-lambda-context.js +2 -0
- package/lib/telemetry-lambda-context.js.map +1 -0
- package/lib/telemetry-message-context.d.ts +52 -0
- package/lib/telemetry-message-context.d.ts.map +1 -0
- package/lib/telemetry-message-context.js +2 -0
- package/lib/telemetry-message-context.js.map +1 -0
- package/lib/telemetry-metrics.d.ts +6 -0
- package/lib/telemetry-metrics.d.ts.map +1 -0
- package/lib/telemetry-metrics.js +2 -0
- package/lib/telemetry-metrics.js.map +1 -0
- package/lib/telemetry-name-template.d.ts +13 -0
- package/lib/telemetry-name-template.d.ts.map +1 -0
- package/lib/telemetry-name-template.js +2 -0
- package/lib/telemetry-name-template.js.map +1 -0
- package/lib/telemetry-stream.d.ts +11 -0
- package/lib/telemetry-stream.d.ts.map +1 -0
- package/lib/telemetry-stream.js +2 -0
- package/lib/telemetry-stream.js.map +1 -0
- package/lib/telemetry-xray.d.ts +28 -0
- package/lib/telemetry-xray.d.ts.map +1 -0
- package/lib/telemetry-xray.js +2 -0
- package/lib/telemetry-xray.js.map +1 -0
- package/lib/telemetry.d.ts +317 -0
- package/lib/telemetry.d.ts.map +1 -0
- package/lib/telemetry.js +3 -0
- package/lib/telemetry.js.map +1 -0
- package/lib/token-cache.d.ts +31 -0
- package/lib/token-cache.d.ts.map +1 -0
- package/lib/token-cache.js +2 -0
- package/lib/token-cache.js.map +1 -0
- package/lib/trait.d.ts +94 -20
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -107
- package/lib/unknown-error.d.ts +18 -0
- package/lib/unknown-error.d.ts.map +1 -0
- package/lib/unknown-error.js +1 -0
- package/lib/xml.d.ts +44 -0
- package/lib/xml.d.ts.map +1 -0
- package/lib/xml.js +1 -0
- package/package.json +13 -13
- package/src/annotations.ts +53 -0
- package/src/api.ts +1597 -234
- package/src/category.ts +97 -134
- package/src/chunks.ts +30 -0
- package/src/config.ts +261 -0
- package/src/crypto.ts +202 -0
- package/src/error-category.ts +16 -29
- package/src/errors.ts +99 -77
- package/src/graphql.ts +1817 -0
- package/src/graphql.types.ts +120 -0
- package/src/grpc-transport-cloudflare-http2.ts +569 -0
- package/src/grpc-transport-cloudflare-sockets.ts +368 -0
- package/src/grpc-transport-node-http2.ts +307 -0
- package/src/grpc-transport.ts +287 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +31 -0
- package/src/max-message-bytes.ts +58 -0
- package/src/ndjson.ts +55 -0
- package/src/pagination.ts +379 -94
- package/src/plain-values.ts +70 -0
- package/src/protobuf.ts +1367 -0
- package/src/protocol-grpc.ts +811 -0
- package/src/protocol-http.ts +1045 -371
- package/src/protocol-rest.ts +908 -255
- package/src/protocol.ts +150 -0
- package/src/query.ts +39 -0
- package/src/response-validation-strict.ts +333 -0
- package/src/response-validation.ts +161 -0
- package/src/retry-after.ts +8 -14
- package/src/retry-state.ts +105 -0
- package/src/retry.ts +260 -145
- package/src/schema-lite-impl.ts +621 -0
- package/src/schema-lite-typed.ts +44 -0
- package/src/schema-lite.ts +45 -0
- package/src/schema.ts +259 -15
- package/src/sdk-error.ts +37 -0
- package/src/send.ts +156 -0
- package/src/sensitive.ts +188 -0
- package/src/telemetry-debug.ts +179 -0
- package/src/telemetry-hooks.ts +33 -0
- package/src/telemetry-host-rules.ts +39 -0
- package/src/telemetry-lambda-context.ts +46 -0
- package/src/telemetry-message-context.ts +170 -0
- package/src/telemetry-metrics.ts +69 -0
- package/src/telemetry-name-template.ts +26 -0
- package/src/telemetry-stream.ts +100 -0
- package/src/telemetry-xray.ts +66 -0
- package/src/telemetry.ts +800 -0
- package/src/token-cache.ts +117 -0
- package/src/trait.ts +139 -67
- package/src/unknown-error.ts +38 -0
- package/src/xml.ts +346 -0
- package/lib/api.js.map +0 -1
- package/lib/category.js.map +0 -1
- package/lib/codegen/cli.d.ts +0 -29
- package/lib/codegen/cli.d.ts.map +0 -1
- package/lib/codegen/cli.js +0 -165
- package/lib/codegen/cli.js.map +0 -1
- package/lib/codegen/emit.d.ts +0 -129
- package/lib/codegen/emit.d.ts.map +0 -1
- package/lib/codegen/emit.js +0 -105
- package/lib/codegen/emit.js.map +0 -1
- package/lib/codegen/format.d.ts +0 -23
- package/lib/codegen/format.d.ts.map +0 -1
- package/lib/codegen/format.js +0 -28
- package/lib/codegen/format.js.map +0 -1
- package/lib/codegen/generator.d.ts +0 -334
- package/lib/codegen/generator.d.ts.map +0 -1
- package/lib/codegen/generator.js +0 -691
- package/lib/codegen/generator.js.map +0 -1
- package/lib/codegen/graph.d.ts +0 -36
- package/lib/codegen/graph.d.ts.map +0 -1
- package/lib/codegen/graph.js +0 -136
- package/lib/codegen/graph.js.map +0 -1
- package/lib/codegen/members.d.ts +0 -25
- package/lib/codegen/members.d.ts.map +0 -1
- package/lib/codegen/members.js +0 -55
- package/lib/codegen/members.js.map +0 -1
- package/lib/codegen/naming.d.ts +0 -29
- package/lib/codegen/naming.d.ts.map +0 -1
- package/lib/codegen/naming.js +0 -74
- package/lib/codegen/naming.js.map +0 -1
- package/lib/codegen/openapi-cli.d.ts +0 -38
- package/lib/codegen/openapi-cli.d.ts.map +0 -1
- package/lib/codegen/openapi-cli.js +0 -107
- package/lib/codegen/openapi-cli.js.map +0 -1
- package/lib/codegen/openapi.d.ts +0 -115
- package/lib/codegen/openapi.d.ts.map +0 -1
- package/lib/codegen/openapi.js +0 -1220
- package/lib/codegen/openapi.js.map +0 -1
- package/lib/codegen/operations.d.ts +0 -24
- package/lib/codegen/operations.d.ts.map +0 -1
- package/lib/codegen/operations.js +0 -56
- package/lib/codegen/operations.js.map +0 -1
- package/lib/codegen/pagination.d.ts +0 -39
- package/lib/codegen/pagination.d.ts.map +0 -1
- package/lib/codegen/pagination.js +0 -33
- package/lib/codegen/pagination.js.map +0 -1
- package/lib/codegen/prelude.d.ts +0 -15
- package/lib/codegen/prelude.d.ts.map +0 -1
- package/lib/codegen/prelude.js +0 -60
- package/lib/codegen/prelude.js.map +0 -1
- package/lib/error-category.js.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/json-patch.d.ts +0 -44
- package/lib/json-patch.d.ts.map +0 -1
- package/lib/json-patch.js +0 -174
- package/lib/json-patch.js.map +0 -1
- package/lib/pagination.js.map +0 -1
- package/lib/protocol-http.js.map +0 -1
- package/lib/protocol-rest.js.map +0 -1
- package/lib/retry-after.js.map +0 -1
- package/lib/retry.js.map +0 -1
- package/lib/schema.js.map +0 -1
- package/lib/trait.js.map +0 -1
- package/src/codegen/cli.ts +0 -268
- package/src/codegen/emit.ts +0 -207
- package/src/codegen/format.ts +0 -47
- package/src/codegen/generator.ts +0 -1153
- package/src/codegen/graph.ts +0 -151
- package/src/codegen/members.ts +0 -71
- package/src/codegen/naming.ts +0 -86
- package/src/codegen/openapi-cli.ts +0 -166
- package/src/codegen/openapi.ts +0 -1450
- package/src/codegen/operations.ts +0 -76
- package/src/codegen/pagination.ts +0 -71
- package/src/codegen/prelude.ts +0 -70
- package/src/json-patch.ts +0 -222
|
@@ -0,0 +1,811 @@
|
|
|
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 restProtocol} 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. `grpcProtocol(options)`
|
|
9
|
+
* builds a core protocol (core/protocol):
|
|
10
|
+
*
|
|
11
|
+
* - **Request**: the proto3 JSON body is transcoded to one protobuf message
|
|
12
|
+
* ({@link encodeMessage}) in one gRPC frame, sent as `application/grpc`.
|
|
13
|
+
* - **Transport**: the call goes through the `HttpClient` the
|
|
14
|
+
* `GrpcTransport` reference holds, or the caller's `HttpClient` when it
|
|
15
|
+
* holds none (see `@distilled.cloud/core/grpc-transport`). Plain `fetch`
|
|
16
|
+
* works where a proxy bridges HTTP/1.1 to gRPC (envoy).
|
|
17
|
+
* - **gRPC-Web**: with `web: true` the request is sent as
|
|
18
|
+
* `application/grpc-web+proto`, which servers such as `tonic-web` answer
|
|
19
|
+
* over HTTP/1.1. The reply's trailers arrive as the last frame of its body,
|
|
20
|
+
* so plain `fetch` sees every status.
|
|
21
|
+
* - **Status**: the call's `grpc-status` is read from the trailers, or from
|
|
22
|
+
* the headers of a trailers-only reply. A transport that can't see
|
|
23
|
+
* trailers (`fetch`) leaves only the headers; a reply with message frames
|
|
24
|
+
* and no status there is treated as OK.
|
|
25
|
+
* - **Errors**: a non-zero status becomes the operation's typed error. The
|
|
26
|
+
* REST decoder receives `{ code, status, message }` (`{ code: 5, status:
|
|
27
|
+
* "NOT_FOUND", ... }`) with the HTTP status grpc-gateway maps the code to
|
|
28
|
+
* (`NOT_FOUND` -> 404, `UNAVAILABLE` -> 503, ...), so error matchers key on
|
|
29
|
+
* the numeric gRPC `code`, and categories and retries follow the HTTP
|
|
30
|
+
* status.
|
|
31
|
+
* - **Response**: protobuf messages are transcoded back to proto3 JSON and
|
|
32
|
+
* decoded by the operation's output schema, so schemas, sensitive values
|
|
33
|
+
* and response validation behave exactly as for REST.
|
|
34
|
+
*
|
|
35
|
+
* A server-streaming method's output is `{ items: [message, ...] }`. Calling
|
|
36
|
+
* the operation collects the whole stream; its `.stream(input)` (see
|
|
37
|
+
* `API.makeStreaming`) emits each message as it arrives, and stopping the
|
|
38
|
+
* stream cancels the call.
|
|
39
|
+
*
|
|
40
|
+
* {@link Deadline} bounds calls in its scope: it is sent as `grpc-timeout`
|
|
41
|
+
* and enforced here, and a call that runs past it fails with
|
|
42
|
+
* `DEADLINE_EXCEEDED` (code 4).
|
|
43
|
+
*/
|
|
44
|
+
import * as Context from "effect/Context";
|
|
45
|
+
import * as Duration from "effect/Duration";
|
|
46
|
+
import * as Effect from "effect/Effect";
|
|
47
|
+
import type * as HttpBody from "effect/http/HttpBody";
|
|
48
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
49
|
+
import type * as HttpClientError from "effect/http/HttpClientError";
|
|
50
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
51
|
+
import * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
52
|
+
import * as Stream from "effect/Stream";
|
|
53
|
+
import { GrpcTransport, hasTrailers, trailersOf } from "./grpc-transport.ts";
|
|
54
|
+
import * as MaxMessageBytes from "./max-message-bytes.ts";
|
|
55
|
+
import {
|
|
56
|
+
decodeMessage,
|
|
57
|
+
encodeMessage,
|
|
58
|
+
frame,
|
|
59
|
+
FrameReader,
|
|
60
|
+
FrameTooLargeError,
|
|
61
|
+
type ProtoDescriptors,
|
|
62
|
+
} from "./protobuf.ts";
|
|
63
|
+
import { InvalidInput, matchTypedError } from "./protocol-http.ts";
|
|
64
|
+
import {
|
|
65
|
+
restProtocolMethods,
|
|
66
|
+
type RestParseErrorInfo,
|
|
67
|
+
type RestProtocolError,
|
|
68
|
+
type RestProtocolOptions,
|
|
69
|
+
} from "./protocol-rest.ts";
|
|
70
|
+
import type {
|
|
71
|
+
DeclaredError,
|
|
72
|
+
DecodeArgs as ProtocolDecodeArgs,
|
|
73
|
+
EncodeArgs,
|
|
74
|
+
Operation,
|
|
75
|
+
Protocol,
|
|
76
|
+
} from "./protocol.ts";
|
|
77
|
+
import { SdkError } from "./sdk-error.ts";
|
|
78
|
+
import * as Send from "./send.ts";
|
|
79
|
+
|
|
80
|
+
/** gRPC status code -> name. */
|
|
81
|
+
export const GRPC_STATUS_NAMES: Readonly<Record<number, string>> = {
|
|
82
|
+
0: "OK",
|
|
83
|
+
1: "CANCELLED",
|
|
84
|
+
2: "UNKNOWN",
|
|
85
|
+
3: "INVALID_ARGUMENT",
|
|
86
|
+
4: "DEADLINE_EXCEEDED",
|
|
87
|
+
5: "NOT_FOUND",
|
|
88
|
+
6: "ALREADY_EXISTS",
|
|
89
|
+
7: "PERMISSION_DENIED",
|
|
90
|
+
8: "RESOURCE_EXHAUSTED",
|
|
91
|
+
9: "FAILED_PRECONDITION",
|
|
92
|
+
10: "ABORTED",
|
|
93
|
+
11: "OUT_OF_RANGE",
|
|
94
|
+
12: "UNIMPLEMENTED",
|
|
95
|
+
13: "INTERNAL",
|
|
96
|
+
14: "UNAVAILABLE",
|
|
97
|
+
15: "DATA_LOSS",
|
|
98
|
+
16: "UNAUTHENTICATED",
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** gRPC status code -> HTTP status (grpc-gateway's mapping). */
|
|
102
|
+
export const GRPC_HTTP_STATUS: Readonly<Record<number, number>> = {
|
|
103
|
+
0: 200,
|
|
104
|
+
1: 499,
|
|
105
|
+
2: 500,
|
|
106
|
+
3: 400,
|
|
107
|
+
4: 504,
|
|
108
|
+
5: 404,
|
|
109
|
+
6: 409,
|
|
110
|
+
7: 403,
|
|
111
|
+
8: 429,
|
|
112
|
+
9: 400,
|
|
113
|
+
10: 409,
|
|
114
|
+
11: 400,
|
|
115
|
+
12: 501,
|
|
116
|
+
13: 500,
|
|
117
|
+
14: 503,
|
|
118
|
+
15: 500,
|
|
119
|
+
16: 401,
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The deadline of gRPC calls in its scope, from when each call starts.
|
|
124
|
+
* `undefined` (the default) sets none.
|
|
125
|
+
*
|
|
126
|
+
* ```ts
|
|
127
|
+
* router.taskExecWait(input).pipe(Effect.provideService(Deadline, "30 seconds"));
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
export const Deadline = /*@__PURE__*/ Context.Reference<Duration.Input | undefined>(
|
|
131
|
+
"@distilled.cloud/core/protocol-grpc/Deadline",
|
|
132
|
+
{ defaultValue: () => undefined },
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* What this module's own code fails with, whatever the options: the errors
|
|
137
|
+
* every gRPC protocol declares. They are the REST protocol's: a message the
|
|
138
|
+
* descriptors can't encode (`InvalidInput`), a request or reply gRPC can't
|
|
139
|
+
* use (`SdkError`), the transport, a body or its trailers
|
|
140
|
+
* (`HttpClientError`), and a 5xx status that neither the operation nor its
|
|
141
|
+
* service declares (`InternalServerError`).
|
|
142
|
+
*/
|
|
143
|
+
export type GrpcProtocolError = RestProtocolError;
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Options of {@link grpcProtocol}: the REST protocol's (see
|
|
147
|
+
* {@link RestProtocolOptions} for the type parameters) and gRPC's own.
|
|
148
|
+
* `StatusError` is what `statusError` returns.
|
|
149
|
+
*/
|
|
150
|
+
export interface GrpcProtocolOptions<
|
|
151
|
+
Credentials,
|
|
152
|
+
CredentialsError,
|
|
153
|
+
CredentialsRequirements,
|
|
154
|
+
RouteError,
|
|
155
|
+
ClassifiedError,
|
|
156
|
+
UnknownError,
|
|
157
|
+
ParseError,
|
|
158
|
+
StatusError,
|
|
159
|
+
> extends RestProtocolOptions<
|
|
160
|
+
Credentials,
|
|
161
|
+
CredentialsError,
|
|
162
|
+
CredentialsRequirements,
|
|
163
|
+
RouteError,
|
|
164
|
+
ClassifiedError,
|
|
165
|
+
UnknownError,
|
|
166
|
+
ParseError
|
|
167
|
+
> {
|
|
168
|
+
/** The SDK's generated descriptors (`src/descriptors.ts`). */
|
|
169
|
+
readonly descriptors: ProtoDescriptors;
|
|
170
|
+
/**
|
|
171
|
+
* The error for a non-zero status no typed error matched, from its gRPC
|
|
172
|
+
* code. By default the REST decoder classifies it by the HTTP status the
|
|
173
|
+
* code maps to (`UNAVAILABLE` -> `ServiceUnavailable`, which retries), which
|
|
174
|
+
* keeps retries working but merges codes that share a status
|
|
175
|
+
* (`INVALID_ARGUMENT`, `FAILED_PRECONDITION` and `OUT_OF_RANGE` are all
|
|
176
|
+
* `BadRequest`).
|
|
177
|
+
*/
|
|
178
|
+
readonly statusError?: (info: StatusInfo) => StatusError;
|
|
179
|
+
/**
|
|
180
|
+
* Send gRPC-Web (`application/grpc-web+proto`) instead of gRPC, for a
|
|
181
|
+
* server that answers HTTP/1.1 only that way (`tonic-web`). The reply
|
|
182
|
+
* carries its trailers in its body, so `fetch` sees every status.
|
|
183
|
+
*/
|
|
184
|
+
readonly web?: boolean;
|
|
185
|
+
/**
|
|
186
|
+
* The largest message the server may send, when neither the call's
|
|
187
|
+
* `maxMessageBytes` nor the `MaxMessageBytes` layer sets one. Default
|
|
188
|
+
* `DEFAULT_MAX_MESSAGE_BYTES` (16 MiB). See `max-message-bytes.ts`.
|
|
189
|
+
*/
|
|
190
|
+
readonly maxMessageBytes?: number;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** A non-OK gRPC status, as `statusError` receives it. */
|
|
194
|
+
export interface StatusInfo {
|
|
195
|
+
readonly code: number;
|
|
196
|
+
readonly message: string;
|
|
197
|
+
/** `google.rpc.Status.details` from `grpc-status-details-bin`, as proto3 JSON `Any`s. */
|
|
198
|
+
readonly details: ReadonlyArray<unknown>;
|
|
199
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** gRPC's mapping of an HTTP status, for a reply that carries no gRPC status. */
|
|
203
|
+
export const HTTP_GRPC_STATUS: Readonly<Record<number, number>> = {
|
|
204
|
+
400: 13,
|
|
205
|
+
401: 16,
|
|
206
|
+
403: 7,
|
|
207
|
+
404: 12,
|
|
208
|
+
429: 14,
|
|
209
|
+
502: 14,
|
|
210
|
+
503: 14,
|
|
211
|
+
504: 14,
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const STATUS_DESCRIPTORS: ProtoDescriptors = {
|
|
215
|
+
messages: {
|
|
216
|
+
"google.rpc.Status": [
|
|
217
|
+
[1, "code", "int32"],
|
|
218
|
+
[2, "message", "string"],
|
|
219
|
+
[3, "details", "message", "google.protobuf.Any", 1],
|
|
220
|
+
],
|
|
221
|
+
},
|
|
222
|
+
enums: {},
|
|
223
|
+
methods: {},
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
/** The details of `grpc-status-details-bin` (base64, padding optional). */
|
|
227
|
+
const detailsOf = (raw: string | undefined): ReadonlyArray<unknown> => {
|
|
228
|
+
if (!raw) return [];
|
|
229
|
+
try {
|
|
230
|
+
const padded = raw.padEnd(raw.length + ((4 - (raw.length % 4)) % 4), "=");
|
|
231
|
+
const bin = atob(padded.replace(/-/g, "+").replace(/_/g, "/"));
|
|
232
|
+
const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
233
|
+
const status = decodeMessage(STATUS_DESCRIPTORS, "google.rpc.Status", bytes) as {
|
|
234
|
+
readonly details: ReadonlyArray<unknown>;
|
|
235
|
+
};
|
|
236
|
+
return status.details;
|
|
237
|
+
} catch {
|
|
238
|
+
// Malformed details don't hide the status itself.
|
|
239
|
+
return [];
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
type Headers = Readonly<Record<string, string | undefined>>;
|
|
244
|
+
|
|
245
|
+
const textDecoder = /*@__PURE__*/ new TextDecoder();
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The SDK can't make the call (a broken descriptor table, or a REST
|
|
249
|
+
* encode/decode result gRPC can't use).
|
|
250
|
+
*/
|
|
251
|
+
const sdkFailure = (message: string): Effect.Effect<never, SdkError> =>
|
|
252
|
+
Effect.fail(new SdkError({ message }));
|
|
253
|
+
|
|
254
|
+
const methodPath = (url: string): string => {
|
|
255
|
+
try {
|
|
256
|
+
return new URL(url).pathname;
|
|
257
|
+
} catch {
|
|
258
|
+
return url;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/** The JSON a REST request carries, or `undefined` for an empty body. */
|
|
263
|
+
const jsonBody = (body: HttpBody.Uint8Array | HttpBody.Raw | HttpBody.Empty): unknown => {
|
|
264
|
+
switch (body._tag) {
|
|
265
|
+
case "Empty":
|
|
266
|
+
return undefined;
|
|
267
|
+
case "Uint8Array": {
|
|
268
|
+
const text = textDecoder.decode(body.body);
|
|
269
|
+
return text ? JSON.parse(text) : undefined;
|
|
270
|
+
}
|
|
271
|
+
case "Raw":
|
|
272
|
+
return typeof body.body === "string" && body.body ? JSON.parse(body.body) : body.body;
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const jsonResponse = (
|
|
277
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
278
|
+
status: number,
|
|
279
|
+
headers: Record<string, string>,
|
|
280
|
+
value: unknown,
|
|
281
|
+
): HttpClientResponse.HttpClientResponse =>
|
|
282
|
+
HttpClientResponse.fromWeb(
|
|
283
|
+
request,
|
|
284
|
+
new Response(JSON.stringify(value), {
|
|
285
|
+
status,
|
|
286
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
287
|
+
}),
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
const plainHeaders = (headers: Headers) => {
|
|
291
|
+
const out: Record<string, string> = {};
|
|
292
|
+
for (const key in headers) {
|
|
293
|
+
const v = headers[key];
|
|
294
|
+
if (v !== undefined && key !== "content-length" && key !== "content-type") out[key] = v;
|
|
295
|
+
}
|
|
296
|
+
return out;
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
/** A gRPC-Web reply, whose trailers are the last frame of its body. */
|
|
300
|
+
const isWeb = (headers: Headers): boolean =>
|
|
301
|
+
(headers["content-type"] ?? "").startsWith("application/grpc-web");
|
|
302
|
+
|
|
303
|
+
const statusOf = (value: string | undefined): number | undefined =>
|
|
304
|
+
value === undefined || value === "" ? undefined : Number(value);
|
|
305
|
+
|
|
306
|
+
/** `text` percent-decoded, or as sent when it is not percent-encoded. */
|
|
307
|
+
const percentDecoded = (text: string): string => {
|
|
308
|
+
try {
|
|
309
|
+
return decodeURIComponent(text);
|
|
310
|
+
} catch {
|
|
311
|
+
return text;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
const messageOf = (raw: string | undefined, status: number): string =>
|
|
316
|
+
percentDecoded(raw ?? "") || GRPC_STATUS_NAMES[status] || `gRPC status ${status}`;
|
|
317
|
+
|
|
318
|
+
/** A `grpc-timeout` value for `ms` (at most 8 digits per the spec). */
|
|
319
|
+
const grpcTimeout = (ms: number): string => {
|
|
320
|
+
const rounded = Math.max(1, Math.ceil(ms));
|
|
321
|
+
if (rounded < 1e8) return `${rounded}m`;
|
|
322
|
+
const seconds = Math.ceil(rounded / 1000);
|
|
323
|
+
return seconds < 1e8 ? `${seconds}S` : `${Math.min(99_999_999, Math.ceil(seconds / 3600))}H`;
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
type DecodeArgs = Omit<ProtocolDecodeArgs, "response">;
|
|
327
|
+
|
|
328
|
+
/** The options {@link grpcMethods} reads; the REST methods read the rest. */
|
|
329
|
+
interface GrpcOptions<ParseError, StatusError> {
|
|
330
|
+
readonly descriptors: ProtoDescriptors;
|
|
331
|
+
readonly statusError?: (info: StatusInfo) => StatusError;
|
|
332
|
+
readonly web?: boolean;
|
|
333
|
+
readonly maxMessageBytes?: number;
|
|
334
|
+
readonly parseError: (info: RestParseErrorInfo) => ParseError;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The gRPC methods over the REST protocol `rest`. See the module
|
|
339
|
+
* documentation for the wire behavior.
|
|
340
|
+
*/
|
|
341
|
+
const grpcMethods = <RestError, Requirements, ParseError, StatusError>(
|
|
342
|
+
rest: Protocol<RestError, Requirements>,
|
|
343
|
+
options: GrpcOptions<ParseError, StatusError>,
|
|
344
|
+
): Protocol<RestError | ParseError | StatusError | GrpcProtocolError, Requirements> => {
|
|
345
|
+
/** What building the request fails with. */
|
|
346
|
+
type EncodeError = RestError | InvalidInput | SdkError;
|
|
347
|
+
/** Everything a call fails with. */
|
|
348
|
+
type Failure =
|
|
349
|
+
| DeclaredError
|
|
350
|
+
| RestError
|
|
351
|
+
| ParseError
|
|
352
|
+
| StatusError
|
|
353
|
+
| InvalidInput
|
|
354
|
+
| SdkError
|
|
355
|
+
| HttpClientError.HttpClientError;
|
|
356
|
+
|
|
357
|
+
const d = options.descriptors;
|
|
358
|
+
const methodOf = (url: string) => d.methods[methodPath(url)];
|
|
359
|
+
|
|
360
|
+
/** The REST request as one gRPC frame of protobuf. */
|
|
361
|
+
const encode = (
|
|
362
|
+
args: EncodeArgs,
|
|
363
|
+
): Effect.Effect<HttpClientRequest.HttpClientRequest, EncodeError, Requirements> =>
|
|
364
|
+
Effect.flatMap(
|
|
365
|
+
rest.encode(args),
|
|
366
|
+
(request): Effect.Effect<HttpClientRequest.HttpClientRequest, InvalidInput | SdkError> => {
|
|
367
|
+
const method = methodOf(request.url);
|
|
368
|
+
if (!method) return sdkFailure(`no gRPC descriptor for ${request.url}`);
|
|
369
|
+
const body = request.body;
|
|
370
|
+
if (body._tag !== "Empty" && body._tag !== "Uint8Array" && body._tag !== "Raw") {
|
|
371
|
+
return sdkFailure(`gRPC requests need a JSON body, got ${body._tag}`);
|
|
372
|
+
}
|
|
373
|
+
let payload: Uint8Array;
|
|
374
|
+
try {
|
|
375
|
+
payload = encodeMessage(d, method[0], jsonBody(body) ?? {});
|
|
376
|
+
} catch (cause) {
|
|
377
|
+
return Effect.fail(
|
|
378
|
+
new InvalidInput({
|
|
379
|
+
member: method[0],
|
|
380
|
+
message: cause instanceof Error ? cause.message : String(cause),
|
|
381
|
+
}),
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
return Effect.succeed(
|
|
385
|
+
options.web
|
|
386
|
+
? request.pipe(
|
|
387
|
+
HttpClientRequest.bodyUint8Array(frame(payload), "application/grpc-web+proto"),
|
|
388
|
+
HttpClientRequest.setHeader("x-grpc-web", "1"),
|
|
389
|
+
)
|
|
390
|
+
: request.pipe(
|
|
391
|
+
HttpClientRequest.bodyUint8Array(frame(payload), "application/grpc"),
|
|
392
|
+
HttpClientRequest.setHeader("te", "trailers"),
|
|
393
|
+
),
|
|
394
|
+
);
|
|
395
|
+
},
|
|
396
|
+
);
|
|
397
|
+
|
|
398
|
+
/** A gRPC status as the operation's typed error. */
|
|
399
|
+
const failWith = (
|
|
400
|
+
args: DecodeArgs,
|
|
401
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
402
|
+
headers: Headers,
|
|
403
|
+
status: number,
|
|
404
|
+
message: string | undefined,
|
|
405
|
+
details: ReadonlyArray<unknown> = [],
|
|
406
|
+
): Effect.Effect<never, Failure, Requirements> => {
|
|
407
|
+
const httpStatus = GRPC_HTTP_STATUS[status] ?? 500;
|
|
408
|
+
const body = {
|
|
409
|
+
code: status,
|
|
410
|
+
status: GRPC_STATUS_NAMES[status] ?? String(status),
|
|
411
|
+
message: messageOf(message, status),
|
|
412
|
+
details,
|
|
413
|
+
};
|
|
414
|
+
if (options.statusError !== undefined) {
|
|
415
|
+
const plain = plainHeaders(headers);
|
|
416
|
+
const typed = matchTypedError(
|
|
417
|
+
args.errors,
|
|
418
|
+
httpStatus,
|
|
419
|
+
[{ code: status, message: body.message }],
|
|
420
|
+
{ body, headers: plain },
|
|
421
|
+
);
|
|
422
|
+
return Effect.fail(
|
|
423
|
+
typed ??
|
|
424
|
+
options.statusError({ code: status, message: body.message, details, headers: plain }),
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
return Effect.flatMap(
|
|
428
|
+
rest.decode({
|
|
429
|
+
...args,
|
|
430
|
+
response: jsonResponse(request, httpStatus, plainHeaders(headers), body),
|
|
431
|
+
}),
|
|
432
|
+
() => sdkFailure(`gRPC status ${status} decoded as a success`),
|
|
433
|
+
);
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* The call's failure, if any, once its body has ended. The status is in
|
|
438
|
+
* the trailers, or in the headers of a trailers-only reply (one with no
|
|
439
|
+
* body); a status in the headers of a reply with a body is ignored. A
|
|
440
|
+
* transport that reads trailers must deliver one, and so must a
|
|
441
|
+
* gRPC-Web reply, in its trailer frame; over `fetch`, which can't read
|
|
442
|
+
* trailers, a gRPC reply with messages and no status is OK.
|
|
443
|
+
*/
|
|
444
|
+
const endOf = (
|
|
445
|
+
args: DecodeArgs,
|
|
446
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
447
|
+
trailers: Readonly<Record<string, string>>,
|
|
448
|
+
sawBody: boolean,
|
|
449
|
+
): Effect.Effect<void, Failure, Requirements> => {
|
|
450
|
+
const headers = response.headers as Headers;
|
|
451
|
+
const readsTrailers = hasTrailers(response) || isWeb(headers);
|
|
452
|
+
const source =
|
|
453
|
+
trailers["grpc-status"] !== undefined
|
|
454
|
+
? trailers
|
|
455
|
+
: !sawBody || !readsTrailers
|
|
456
|
+
? headers
|
|
457
|
+
: undefined;
|
|
458
|
+
const status = statusOf(source?.["grpc-status"]);
|
|
459
|
+
if (source === undefined || status === undefined) {
|
|
460
|
+
if (readsTrailers) {
|
|
461
|
+
return failWith(
|
|
462
|
+
args,
|
|
463
|
+
response.request,
|
|
464
|
+
headers,
|
|
465
|
+
13,
|
|
466
|
+
"server ended the call without a grpc-status",
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
return sawBody
|
|
470
|
+
? Effect.void
|
|
471
|
+
: failWith(
|
|
472
|
+
args,
|
|
473
|
+
response.request,
|
|
474
|
+
headers,
|
|
475
|
+
2,
|
|
476
|
+
"gRPC response carried no message and no grpc-status",
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
return status === 0
|
|
480
|
+
? Effect.void
|
|
481
|
+
: failWith(
|
|
482
|
+
args,
|
|
483
|
+
response.request,
|
|
484
|
+
headers,
|
|
485
|
+
status,
|
|
486
|
+
source["grpc-message"],
|
|
487
|
+
detailsOf(source["grpc-status-details-bin"]),
|
|
488
|
+
);
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
/** A malformed frame (compressed, truncated): gRPC's INTERNAL. */
|
|
492
|
+
const badFrame = (
|
|
493
|
+
args: DecodeArgs,
|
|
494
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
495
|
+
cause: unknown,
|
|
496
|
+
) =>
|
|
497
|
+
failWith(
|
|
498
|
+
args,
|
|
499
|
+
response.request,
|
|
500
|
+
response.headers as Headers,
|
|
501
|
+
13,
|
|
502
|
+
cause instanceof Error ? cause.message : String(cause),
|
|
503
|
+
);
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* A reply that isn't gRPC: a status other than 200, or another content
|
|
507
|
+
* type. The REST decoder classifies a non-200 by its HTTP status (so a
|
|
508
|
+
* status under 400 is its value); with `statusError`, it maps as gRPC
|
|
509
|
+
* specifies (503 -> UNAVAILABLE, ...).
|
|
510
|
+
*/
|
|
511
|
+
const notGrpc = (
|
|
512
|
+
args: DecodeArgs,
|
|
513
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
514
|
+
): Effect.Effect<unknown, Failure, Requirements> | undefined => {
|
|
515
|
+
const headers = response.headers as Headers;
|
|
516
|
+
const isGrpc = (headers["content-type"] ?? "").startsWith("application/grpc");
|
|
517
|
+
if (response.status === 200 && isGrpc) return undefined;
|
|
518
|
+
if (response.status !== 200 && options.statusError === undefined) {
|
|
519
|
+
return rest.decode({ ...args, response });
|
|
520
|
+
}
|
|
521
|
+
if (response.status !== 200) {
|
|
522
|
+
return failWith(
|
|
523
|
+
args,
|
|
524
|
+
response.request,
|
|
525
|
+
headers,
|
|
526
|
+
HTTP_GRPC_STATUS[response.status] ?? 2,
|
|
527
|
+
`HTTP ${response.status}`,
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
return failWith(
|
|
531
|
+
args,
|
|
532
|
+
response.request,
|
|
533
|
+
headers,
|
|
534
|
+
2,
|
|
535
|
+
`unexpected content-type ${JSON.stringify(headers["content-type"] ?? "")}`,
|
|
536
|
+
);
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
/** A reply value decoded by the operation's output schema. */
|
|
540
|
+
const succeedWith = (
|
|
541
|
+
args: DecodeArgs,
|
|
542
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
543
|
+
headers: Headers,
|
|
544
|
+
value: unknown,
|
|
545
|
+
) =>
|
|
546
|
+
rest.decode({
|
|
547
|
+
...args,
|
|
548
|
+
response: jsonResponse(request, 200, plainHeaders(headers), value),
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
const parseFailure = (body: unknown, cause: unknown): Effect.Effect<never, ParseError> =>
|
|
552
|
+
Effect.fail(options.parseError({ body, cause }));
|
|
553
|
+
|
|
554
|
+
const deadlineMillis = (context: Context.Context<any>): number | undefined => {
|
|
555
|
+
const deadline = Context.get(context, Deadline);
|
|
556
|
+
return deadline === undefined ? undefined : Duration.toMillis(deadline);
|
|
557
|
+
};
|
|
558
|
+
|
|
559
|
+
/** Send a call through the transport in scope, with the deadline in scope. */
|
|
560
|
+
const send = (
|
|
561
|
+
context: Context.Context<any>,
|
|
562
|
+
operation: Operation,
|
|
563
|
+
input: unknown,
|
|
564
|
+
ms: number | undefined,
|
|
565
|
+
) =>
|
|
566
|
+
Effect.flatMap(
|
|
567
|
+
encode({ input, inputAst: operation.inputAst, config: operation.config }),
|
|
568
|
+
(encoded) => {
|
|
569
|
+
const request =
|
|
570
|
+
ms === undefined
|
|
571
|
+
? encoded
|
|
572
|
+
: HttpClientRequest.setHeader(encoded, "grpc-timeout", grpcTimeout(ms));
|
|
573
|
+
const client =
|
|
574
|
+
Context.get(context, GrpcTransport) ?? Context.get(context, HttpClient.HttpClient);
|
|
575
|
+
return Send.send(context, client, request);
|
|
576
|
+
},
|
|
577
|
+
);
|
|
578
|
+
|
|
579
|
+
/** The call's message size limit, or `InvalidInput` for a bad `maxMessageBytes`. */
|
|
580
|
+
const limitOf = (
|
|
581
|
+
context: Context.Context<any>,
|
|
582
|
+
input: unknown,
|
|
583
|
+
): Effect.Effect<number, InvalidInput> => {
|
|
584
|
+
const limit = MaxMessageBytes.resolve(context, input, options.maxMessageBytes);
|
|
585
|
+
return typeof limit === "number"
|
|
586
|
+
? Effect.succeed(limit)
|
|
587
|
+
: Effect.fail(new InvalidInput({ member: "maxMessageBytes", message: limit.invalid }));
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
/** A frame the reader refused: over the size limit (the SDK's parse error), or malformed. */
|
|
591
|
+
const frameFailure = (
|
|
592
|
+
args: DecodeArgs,
|
|
593
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
594
|
+
cause: unknown,
|
|
595
|
+
): Effect.Effect<never, Failure, Requirements> =>
|
|
596
|
+
cause instanceof FrameTooLargeError
|
|
597
|
+
? parseFailure(undefined, cause.message)
|
|
598
|
+
: badFrame(args, response, cause);
|
|
599
|
+
|
|
600
|
+
/** Decode a whole reply (its body read to the end), with the limit in scope. */
|
|
601
|
+
const decode = (args: ProtocolDecodeArgs): Effect.Effect<unknown, Failure, Requirements> =>
|
|
602
|
+
Effect.withFiber((fiber) =>
|
|
603
|
+
Effect.flatMap(limitOf(fiber.context as Context.Context<any>, undefined), (limit) =>
|
|
604
|
+
decodeWith(args, limit),
|
|
605
|
+
),
|
|
606
|
+
);
|
|
607
|
+
|
|
608
|
+
/** Decode a whole reply (its body read to the end). */
|
|
609
|
+
const decodeWith = (
|
|
610
|
+
args: ProtocolDecodeArgs,
|
|
611
|
+
limit: number,
|
|
612
|
+
): Effect.Effect<unknown, Failure, Requirements> => {
|
|
613
|
+
const { response } = args;
|
|
614
|
+
const failed = notGrpc(args, response);
|
|
615
|
+
if (failed) return failed;
|
|
616
|
+
const headers = response.headers as Headers;
|
|
617
|
+
const request = response.request;
|
|
618
|
+
const method = methodOf(request.url);
|
|
619
|
+
if (!method) return sdkFailure(`no gRPC descriptor for ${request.url}`);
|
|
620
|
+
// A body or trailers read that fails (reset or abort mid-body) fails the
|
|
621
|
+
// call with its `HttpClientError`, a protocol error.
|
|
622
|
+
return Effect.flatMap(response.arrayBuffer, (buffer) =>
|
|
623
|
+
Effect.flatMap(
|
|
624
|
+
trailersOf(response),
|
|
625
|
+
(trailers): Effect.Effect<unknown, Failure, Requirements> => {
|
|
626
|
+
const reader = new FrameReader(limit);
|
|
627
|
+
let frames: Uint8Array[];
|
|
628
|
+
try {
|
|
629
|
+
frames = reader.push(new Uint8Array(buffer));
|
|
630
|
+
} catch (cause) {
|
|
631
|
+
return Effect.flatMap(endOf(args, response, trailers, true), () =>
|
|
632
|
+
frameFailure(args, response, cause),
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
const all = { ...trailers, ...reader.trailers };
|
|
636
|
+
return Effect.flatMap(
|
|
637
|
+
endOf(args, response, all, buffer.byteLength > 0),
|
|
638
|
+
(): Effect.Effect<unknown, Failure, Requirements> => {
|
|
639
|
+
if (reader.rest !== 0) return badFrame(args, response, "truncated gRPC frame");
|
|
640
|
+
const [, responseType, stream] = method;
|
|
641
|
+
if (!stream && frames.length !== 1) {
|
|
642
|
+
return failWith(
|
|
643
|
+
args,
|
|
644
|
+
request,
|
|
645
|
+
headers,
|
|
646
|
+
12,
|
|
647
|
+
`expected one response message, got ${frames.length}`,
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
let value: unknown;
|
|
651
|
+
try {
|
|
652
|
+
value = stream
|
|
653
|
+
? { items: frames.map((f) => decodeMessage(d, responseType, f)) }
|
|
654
|
+
: decodeMessage(d, responseType, frames[0]!);
|
|
655
|
+
} catch (cause) {
|
|
656
|
+
return parseFailure(buffer, cause);
|
|
657
|
+
}
|
|
658
|
+
return succeedWith(args, request, headers, value);
|
|
659
|
+
},
|
|
660
|
+
);
|
|
661
|
+
},
|
|
662
|
+
),
|
|
663
|
+
);
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
const deadlineExceeded = (args: DecodeArgs, url: string) =>
|
|
667
|
+
failWith(args, HttpClientRequest.post(url), {}, 4, "Deadline Exceeded");
|
|
668
|
+
|
|
669
|
+
return {
|
|
670
|
+
encode,
|
|
671
|
+
decode,
|
|
672
|
+
call: (operation, input) =>
|
|
673
|
+
Effect.withFiber((fiber) => {
|
|
674
|
+
const context = fiber.context as Context.Context<any>;
|
|
675
|
+
const args: DecodeArgs = {
|
|
676
|
+
outputAst: operation.outputAst,
|
|
677
|
+
errors: operation.errors,
|
|
678
|
+
config: operation.config,
|
|
679
|
+
};
|
|
680
|
+
const ms = deadlineMillis(context);
|
|
681
|
+
const run = Effect.flatMap(limitOf(context, input), (limit) =>
|
|
682
|
+
Effect.flatMap(send(context, operation, input, ms), (response) =>
|
|
683
|
+
decodeWith({ ...args, response }, limit),
|
|
684
|
+
),
|
|
685
|
+
);
|
|
686
|
+
return ms === undefined
|
|
687
|
+
? run
|
|
688
|
+
: Effect.timeoutOrElse(run, {
|
|
689
|
+
duration: ms,
|
|
690
|
+
orElse: () => deadlineExceeded(args, ""),
|
|
691
|
+
});
|
|
692
|
+
}),
|
|
693
|
+
stream: (operation, input) =>
|
|
694
|
+
Stream.unwrap(
|
|
695
|
+
Effect.withFiber((fiber) => {
|
|
696
|
+
const context = fiber.context as Context.Context<any>;
|
|
697
|
+
const args: DecodeArgs = {
|
|
698
|
+
outputAst: operation.outputAst,
|
|
699
|
+
errors: operation.errors,
|
|
700
|
+
config: operation.config,
|
|
701
|
+
};
|
|
702
|
+
const ms = deadlineMillis(context);
|
|
703
|
+
const messages = Effect.flatMap(limitOf(context, input), (limit) =>
|
|
704
|
+
Effect.map(send(context, operation, input, ms), (response) =>
|
|
705
|
+
streamReply(args, response, limit),
|
|
706
|
+
),
|
|
707
|
+
);
|
|
708
|
+
const stream = Stream.unwrap(messages);
|
|
709
|
+
return Effect.succeed(
|
|
710
|
+
ms === undefined
|
|
711
|
+
? stream
|
|
712
|
+
: Stream.interruptWhen(
|
|
713
|
+
stream,
|
|
714
|
+
Effect.flatMap(Effect.sleep(ms), () => deadlineExceeded(args, "")),
|
|
715
|
+
),
|
|
716
|
+
);
|
|
717
|
+
}),
|
|
718
|
+
),
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
/** Each message of a server stream, decoded as it arrives. */
|
|
722
|
+
function streamReply(
|
|
723
|
+
args: DecodeArgs,
|
|
724
|
+
response: HttpClientResponse.HttpClientResponse,
|
|
725
|
+
limit: number,
|
|
726
|
+
): Stream.Stream<unknown, Failure, Requirements> {
|
|
727
|
+
const headers = response.headers as Headers;
|
|
728
|
+
const request = response.request;
|
|
729
|
+
const failed = notGrpc(args, response);
|
|
730
|
+
if (failed) return Stream.fromEffect(failed);
|
|
731
|
+
const method = methodOf(request.url);
|
|
732
|
+
if (!method) return Stream.fromEffect(sdkFailure(`no gRPC descriptor for ${request.url}`));
|
|
733
|
+
const [, responseType] = method;
|
|
734
|
+
const reader = new FrameReader(limit);
|
|
735
|
+
const item = (payload: Uint8Array): Effect.Effect<unknown, Failure, Requirements> => {
|
|
736
|
+
let value: unknown;
|
|
737
|
+
try {
|
|
738
|
+
value = decodeMessage(d, responseType, payload);
|
|
739
|
+
} catch (cause) {
|
|
740
|
+
return parseFailure(payload, cause);
|
|
741
|
+
}
|
|
742
|
+
return Effect.map(
|
|
743
|
+
succeedWith(args, request, headers, { items: [value] }),
|
|
744
|
+
(decoded) => (decoded as { readonly items: ReadonlyArray<unknown> }).items[0],
|
|
745
|
+
);
|
|
746
|
+
};
|
|
747
|
+
const messages = Stream.flatMap(response.stream, (chunk) =>
|
|
748
|
+
Stream.fromIterableEffect(
|
|
749
|
+
Effect.suspend((): Effect.Effect<ReadonlyArray<unknown>, Failure, Requirements> => {
|
|
750
|
+
if (chunk.length > 0) sawBody = true;
|
|
751
|
+
let frames: Uint8Array[];
|
|
752
|
+
try {
|
|
753
|
+
frames = reader.push(chunk);
|
|
754
|
+
} catch (cause) {
|
|
755
|
+
return frameFailure(args, response, cause);
|
|
756
|
+
}
|
|
757
|
+
return Effect.forEach(frames, item);
|
|
758
|
+
}),
|
|
759
|
+
),
|
|
760
|
+
);
|
|
761
|
+
let sawBody = false;
|
|
762
|
+
const end = Effect.flatMap(trailersOf(response), (trailers) =>
|
|
763
|
+
Effect.flatMap(endOf(args, response, { ...trailers, ...reader.trailers }, sawBody), () =>
|
|
764
|
+
reader.rest !== 0 ? badFrame(args, response, "truncated gRPC frame") : Effect.void,
|
|
765
|
+
),
|
|
766
|
+
);
|
|
767
|
+
return Stream.concat(messages, Stream.drain(Stream.fromEffect(end)));
|
|
768
|
+
}
|
|
769
|
+
};
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* The gRPC protocol (core/protocol), over the options of
|
|
773
|
+
* {@link restProtocol}. Assign the result to a module-level const in the
|
|
774
|
+
* provider's `protocol.ts`:
|
|
775
|
+
*
|
|
776
|
+
* export const ModalProtocol = grpcProtocol({ ... });
|
|
777
|
+
*
|
|
778
|
+
* A non-zero status becomes a class the operation or its service declares,
|
|
779
|
+
* as a failed REST response does (see {@link restProtocol}). The protocol
|
|
780
|
+
* declares what the options and {@link GrpcProtocolError} fail with.
|
|
781
|
+
*/
|
|
782
|
+
export const grpcProtocol = <
|
|
783
|
+
Credentials,
|
|
784
|
+
CredentialsError = never,
|
|
785
|
+
CredentialsRequirements = never,
|
|
786
|
+
RouteError = never,
|
|
787
|
+
ClassifiedError = never,
|
|
788
|
+
UnknownError = never,
|
|
789
|
+
ParseError = never,
|
|
790
|
+
StatusError = never,
|
|
791
|
+
>(
|
|
792
|
+
options: GrpcProtocolOptions<
|
|
793
|
+
Credentials,
|
|
794
|
+
CredentialsError,
|
|
795
|
+
CredentialsRequirements,
|
|
796
|
+
RouteError,
|
|
797
|
+
ClassifiedError,
|
|
798
|
+
UnknownError,
|
|
799
|
+
ParseError,
|
|
800
|
+
StatusError
|
|
801
|
+
>,
|
|
802
|
+
): Protocol<
|
|
803
|
+
| CredentialsError
|
|
804
|
+
| RouteError
|
|
805
|
+
| ClassifiedError
|
|
806
|
+
| UnknownError
|
|
807
|
+
| ParseError
|
|
808
|
+
| StatusError
|
|
809
|
+
| GrpcProtocolError,
|
|
810
|
+
CredentialsRequirements
|
|
811
|
+
> => grpcMethods(restProtocolMethods(options), options);
|