@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,368 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A gRPC transport over a `cloudflare:sockets` TLS socket (HTTP/1.1), for a
|
|
3
|
+
* Cloudflare Worker calling a gRPC server that is behind Cloudflare.
|
|
4
|
+
*
|
|
5
|
+
* A Worker's `fetch` to a site on Cloudflare takes Cloudflare's internal
|
|
6
|
+
* Worker-to-site path, which resets gRPC upstreams (`grpc-status: 14`,
|
|
7
|
+
* "upstream connect error ... remote reset"). A plain TLS socket from the
|
|
8
|
+
* same Worker reaches the server like any other client.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* import * as CloudflareSockets from "@distilled.cloud/core/grpc-transport-cloudflare-sockets";
|
|
12
|
+
*
|
|
13
|
+
* program.pipe(Effect.provide(CloudflareSockets.layer));
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Each request opens its own socket with `connection: close`: workerd ties
|
|
17
|
+
* a socket to the request that opened it, so sockets are never pooled
|
|
18
|
+
* across events. The exchange is Effect code: the body is an Effect `Stream`
|
|
19
|
+
* that reads the socket in the caller's fiber as it arrives (`content-length`,
|
|
20
|
+
* chunked, or until the server closes), and closes it when it ends or the
|
|
21
|
+
* reader stops; chunked trailers, where gRPC puts `grpc-status`, settle when
|
|
22
|
+
* it ends. The server must accept gRPC over HTTP/1.1, as a bridging proxy
|
|
23
|
+
* (envoy) does.
|
|
24
|
+
*/
|
|
25
|
+
import * as Deferred from "effect/Deferred";
|
|
26
|
+
import * as Effect from "effect/Effect";
|
|
27
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
28
|
+
import * as HttpClientError from "effect/http/HttpClientError";
|
|
29
|
+
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
30
|
+
import type * as Layer from "effect/Layer";
|
|
31
|
+
import * as Stream from "effect/Stream";
|
|
32
|
+
import {
|
|
33
|
+
isResponseStatus,
|
|
34
|
+
hasNoBody,
|
|
35
|
+
layer as transportLayer,
|
|
36
|
+
respond,
|
|
37
|
+
type Trailers,
|
|
38
|
+
} from "./grpc-transport.ts";
|
|
39
|
+
|
|
40
|
+
/** The part of `cloudflare:sockets` this transport uses. */
|
|
41
|
+
type Connect = (
|
|
42
|
+
address: { hostname: string; port: number },
|
|
43
|
+
options: { secureTransport: "on" | "off"; allowHalfOpen: boolean },
|
|
44
|
+
) => Socket;
|
|
45
|
+
|
|
46
|
+
interface Socket {
|
|
47
|
+
readonly readable: ReadableStream<Uint8Array>;
|
|
48
|
+
readonly writable: WritableStream<Uint8Array>;
|
|
49
|
+
close(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// A non-literal specifier keeps bundlers from resolving it for runtimes
|
|
53
|
+
// other than workerd, which resolves its built-in modules at runtime.
|
|
54
|
+
/** Run `f`, failing with what it throws as is. */
|
|
55
|
+
const attempt = <A>(f: () => A): Effect.Effect<A, unknown> =>
|
|
56
|
+
Effect.try({ try: f, catch: (cause) => cause });
|
|
57
|
+
|
|
58
|
+
/** Await `f`, failing with what it rejects with as is. */
|
|
59
|
+
const attemptPromise = <A>(f: () => PromiseLike<A>): Effect.Effect<A, unknown> =>
|
|
60
|
+
Effect.tryPromise({ try: () => f(), catch: (cause) => cause });
|
|
61
|
+
|
|
62
|
+
const SOCKETS_MODULE = "cloudflare:sockets";
|
|
63
|
+
let connectFn: Connect | undefined;
|
|
64
|
+
const loadConnect: Effect.Effect<Connect, unknown> = /*@__PURE__*/ Effect.suspend(() =>
|
|
65
|
+
connectFn !== undefined
|
|
66
|
+
? Effect.succeed(connectFn)
|
|
67
|
+
: attemptPromise(() => import(SOCKETS_MODULE) as Promise<{ connect: Connect }>).pipe(
|
|
68
|
+
Effect.map((module) => (connectFn = module.connect)),
|
|
69
|
+
),
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
/** Headers this transport sets itself. */
|
|
73
|
+
const FRAMING_HEADERS = new Set([
|
|
74
|
+
"host",
|
|
75
|
+
"connection",
|
|
76
|
+
"keep-alive",
|
|
77
|
+
"content-length",
|
|
78
|
+
"transfer-encoding",
|
|
79
|
+
"upgrade",
|
|
80
|
+
]);
|
|
81
|
+
|
|
82
|
+
const encoder = /*@__PURE__*/ new TextEncoder();
|
|
83
|
+
const decoder = /*@__PURE__*/ new TextDecoder();
|
|
84
|
+
|
|
85
|
+
const concat = (a: Uint8Array, b: Uint8Array): Uint8Array<ArrayBufferLike> => {
|
|
86
|
+
if (a.length === 0) return b;
|
|
87
|
+
const out = new Uint8Array(a.length + b.length);
|
|
88
|
+
out.set(a);
|
|
89
|
+
out.set(b, a.length);
|
|
90
|
+
return out;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const indexOf = (bytes: Uint8Array, pattern: readonly number[], from = 0): number => {
|
|
94
|
+
outer: for (let i = from; i + pattern.length <= bytes.length; i++) {
|
|
95
|
+
for (let j = 0; j < pattern.length; j++) if (bytes[i + j] !== pattern[j]) continue outer;
|
|
96
|
+
return i;
|
|
97
|
+
}
|
|
98
|
+
return -1;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const CRLF = [13, 10] as const;
|
|
102
|
+
const CRLFCRLF = [13, 10, 13, 10] as const;
|
|
103
|
+
|
|
104
|
+
const parseHeaderLines = (lines: ReadonlyArray<string>): Record<string, string> => {
|
|
105
|
+
// A map, so a header named like something every object has (`constructor`,
|
|
106
|
+
// `__proto__`) is a header like any other.
|
|
107
|
+
const joined = new Map<string, string>();
|
|
108
|
+
for (const line of lines) {
|
|
109
|
+
const colon = line.indexOf(":");
|
|
110
|
+
if (colon <= 0) continue;
|
|
111
|
+
const key = line.slice(0, colon).trim().toLowerCase();
|
|
112
|
+
const value = line.slice(colon + 1).trim();
|
|
113
|
+
const previous = joined.get(key);
|
|
114
|
+
joined.set(key, previous === undefined ? value : `${previous}, ${value}`);
|
|
115
|
+
}
|
|
116
|
+
return Object.fromEntries(joined);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
class ProtocolViolation extends Error {}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The body framing of an HTTP/1.1 response: hands back the payload bytes in
|
|
123
|
+
* `input` and whether the body has ended; a chunked body's trailers land in
|
|
124
|
+
* `trailers`.
|
|
125
|
+
*/
|
|
126
|
+
interface BodyDecoder {
|
|
127
|
+
feed(input: Uint8Array): { readonly data: Uint8Array[]; readonly done: boolean };
|
|
128
|
+
/** The peer closed the connection. */
|
|
129
|
+
end(): boolean;
|
|
130
|
+
readonly trailers: Record<string, string>;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const lengthDecoder = (length: number): BodyDecoder => {
|
|
134
|
+
let left = length;
|
|
135
|
+
return {
|
|
136
|
+
trailers: {},
|
|
137
|
+
feed(input) {
|
|
138
|
+
const take = input.subarray(0, left);
|
|
139
|
+
left -= take.length;
|
|
140
|
+
return { data: take.length > 0 ? [take] : [], done: left === 0 };
|
|
141
|
+
},
|
|
142
|
+
end: () => left === 0,
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const untilCloseDecoder = (): BodyDecoder => ({
|
|
147
|
+
trailers: {},
|
|
148
|
+
feed: (input) => ({ data: input.length > 0 ? [input] : [], done: false }),
|
|
149
|
+
end: () => true,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const chunkedDecoder = (): BodyDecoder => {
|
|
153
|
+
let buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
|
|
154
|
+
let state: "size" | "data" | "trailers" | "done" = "size";
|
|
155
|
+
let left = 0;
|
|
156
|
+
let trailers: Record<string, string> = {};
|
|
157
|
+
return {
|
|
158
|
+
get trailers() {
|
|
159
|
+
return trailers;
|
|
160
|
+
},
|
|
161
|
+
feed(input) {
|
|
162
|
+
buf = concat(buf, input);
|
|
163
|
+
const data: Uint8Array[] = [];
|
|
164
|
+
for (;;) {
|
|
165
|
+
if (state === "size") {
|
|
166
|
+
const eol = indexOf(buf, CRLF);
|
|
167
|
+
if (eol < 0) break;
|
|
168
|
+
const size = Number.parseInt(decoder.decode(buf.subarray(0, eol)).split(";")[0]!, 16);
|
|
169
|
+
if (Number.isNaN(size)) throw new ProtocolViolation("invalid chunk size");
|
|
170
|
+
buf = buf.subarray(eol + 2);
|
|
171
|
+
if (size === 0) state = "trailers";
|
|
172
|
+
else {
|
|
173
|
+
state = "data";
|
|
174
|
+
left = size;
|
|
175
|
+
}
|
|
176
|
+
} else if (state === "data") {
|
|
177
|
+
if (buf.length < left + 2) {
|
|
178
|
+
// Hand over what arrived; keep the rest of the chunk pending.
|
|
179
|
+
const take = buf.subarray(0, Math.min(buf.length, left));
|
|
180
|
+
if (take.length > 0) data.push(take.slice());
|
|
181
|
+
left -= take.length;
|
|
182
|
+
buf = buf.subarray(take.length);
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
if (left > 0) data.push(buf.slice(0, left));
|
|
186
|
+
buf = buf.subarray(left + 2);
|
|
187
|
+
left = 0;
|
|
188
|
+
state = "size";
|
|
189
|
+
} else if (state === "trailers") {
|
|
190
|
+
if (buf[0] === 13 && buf[1] === 10) {
|
|
191
|
+
state = "done";
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
const end = indexOf(buf, CRLFCRLF);
|
|
195
|
+
if (end < 0) break;
|
|
196
|
+
trailers = parseHeaderLines(decoder.decode(buf.subarray(0, end)).split("\r\n"));
|
|
197
|
+
state = "done";
|
|
198
|
+
break;
|
|
199
|
+
} else break;
|
|
200
|
+
}
|
|
201
|
+
return { data, done: state === "done" };
|
|
202
|
+
},
|
|
203
|
+
end: () => state === "done",
|
|
204
|
+
};
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const decoderFor = (headers: Record<string, string>): BodyDecoder =>
|
|
208
|
+
(headers["transfer-encoding"] ?? "").toLowerCase().includes("chunked")
|
|
209
|
+
? chunkedDecoder()
|
|
210
|
+
: headers["content-length"] !== undefined
|
|
211
|
+
? lengthDecoder(Number(headers["content-length"]))
|
|
212
|
+
: untilCloseDecoder();
|
|
213
|
+
|
|
214
|
+
const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unknown) =>
|
|
215
|
+
new HttpClientError.HttpClientError({
|
|
216
|
+
reason: new HttpClientError.TransportError({
|
|
217
|
+
request,
|
|
218
|
+
cause,
|
|
219
|
+
description: "request over cloudflare:sockets failed",
|
|
220
|
+
}),
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Close `socket` once, from whichever comes first: the body ends, its reader
|
|
225
|
+
* stops, the exchange fails, or `signal` aborts.
|
|
226
|
+
*/
|
|
227
|
+
const closer = (socket: Socket, signal: AbortSignal): Effect.Effect<void> => {
|
|
228
|
+
let closed = false;
|
|
229
|
+
const markClosed = () => {
|
|
230
|
+
if (closed) return false;
|
|
231
|
+
closed = true;
|
|
232
|
+
signal.removeEventListener("abort", onAbort);
|
|
233
|
+
return true;
|
|
234
|
+
};
|
|
235
|
+
const onAbort = () => {
|
|
236
|
+
// Only for a response nobody reads any more (dropped unread, or its
|
|
237
|
+
// scope closed): no fiber is left to run the close in, and no reader to
|
|
238
|
+
// see that a close failed, which only happens to a socket that already
|
|
239
|
+
// failed.
|
|
240
|
+
if (markClosed()) void socket.close().catch(() => undefined);
|
|
241
|
+
};
|
|
242
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
243
|
+
return Effect.suspend(() =>
|
|
244
|
+
markClosed()
|
|
245
|
+
? attemptPromise(() => socket.close()).pipe(
|
|
246
|
+
Effect.ignore({ log: "Debug", message: "closing a cloudflare:sockets socket failed" }),
|
|
247
|
+
)
|
|
248
|
+
: Effect.void,
|
|
249
|
+
);
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
/** Send `request` and read the response head; the body streams afterwards. */
|
|
253
|
+
const send = (request: HttpClientRequest.HttpClientRequest, url: URL, signal: AbortSignal) =>
|
|
254
|
+
Effect.gen(function* () {
|
|
255
|
+
const connect = yield* loadConnect;
|
|
256
|
+
const tls = url.protocol === "https:";
|
|
257
|
+
const socket = yield* attempt(() =>
|
|
258
|
+
connect(
|
|
259
|
+
{ hostname: url.hostname, port: Number(url.port || (tls ? 443 : 80)) },
|
|
260
|
+
{ secureTransport: tls ? "on" : "off", allowHalfOpen: false },
|
|
261
|
+
),
|
|
262
|
+
);
|
|
263
|
+
const close = closer(socket, signal);
|
|
264
|
+
// A call that fails before it returns a body leaves no one else to close the socket.
|
|
265
|
+
return yield* exchange(request, url, socket, close).pipe(Effect.onError(() => close));
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
const exchange = (
|
|
269
|
+
request: HttpClientRequest.HttpClientRequest,
|
|
270
|
+
url: URL,
|
|
271
|
+
socket: Socket,
|
|
272
|
+
close: Effect.Effect<void>,
|
|
273
|
+
) =>
|
|
274
|
+
Effect.gen(function* () {
|
|
275
|
+
const body = request.body._tag === "Uint8Array" ? request.body.body : new Uint8Array(0);
|
|
276
|
+
const head = [`${request.method} ${url.pathname}${url.search} HTTP/1.1`, `host: ${url.host}`];
|
|
277
|
+
for (const [key, value] of Object.entries(request.headers)) {
|
|
278
|
+
if (!FRAMING_HEADERS.has(key)) head.push(`${key}: ${value}`);
|
|
279
|
+
}
|
|
280
|
+
head.push(`content-length: ${body.length}`, "connection: close", "", "");
|
|
281
|
+
const writer = socket.writable.getWriter();
|
|
282
|
+
yield* attemptPromise(() => writer.write(concat(encoder.encode(head.join("\r\n")), body)));
|
|
283
|
+
writer.releaseLock();
|
|
284
|
+
|
|
285
|
+
const reader = socket.readable.getReader();
|
|
286
|
+
const read = attemptPromise(() => reader.read());
|
|
287
|
+
let buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
|
|
288
|
+
let end = -1;
|
|
289
|
+
while ((end = indexOf(buf, CRLFCRLF)) < 0) {
|
|
290
|
+
const { value, done } = yield* read;
|
|
291
|
+
if (done) {
|
|
292
|
+
return yield* Effect.fail(
|
|
293
|
+
new ProtocolViolation("connection closed before the response headers"),
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
buf = concat(buf, value);
|
|
297
|
+
}
|
|
298
|
+
const [statusLine = "", ...lines] = decoder.decode(buf.subarray(0, end)).split("\r\n");
|
|
299
|
+
const status = Number(statusLine.split(" ")[1] ?? 0);
|
|
300
|
+
if (!isResponseStatus(status)) {
|
|
301
|
+
return yield* Effect.fail(new ProtocolViolation(`invalid HTTP status ${status}`));
|
|
302
|
+
}
|
|
303
|
+
const headers = parseHeaderLines(lines);
|
|
304
|
+
const framing = decoderFor(headers);
|
|
305
|
+
const trailers = yield* Deferred.make<Trailers, unknown>();
|
|
306
|
+
|
|
307
|
+
let pending: Uint8Array | undefined = buf.subarray(end + 4);
|
|
308
|
+
let finished = false;
|
|
309
|
+
/** The next payload chunks, or `undefined` once the body has ended. */
|
|
310
|
+
const next: Effect.Effect<Uint8Array[] | undefined, unknown> = Effect.gen(function* () {
|
|
311
|
+
while (!finished) {
|
|
312
|
+
let input: Uint8Array;
|
|
313
|
+
if (pending !== undefined) {
|
|
314
|
+
input = pending;
|
|
315
|
+
pending = undefined;
|
|
316
|
+
} else {
|
|
317
|
+
const { value, done } = yield* read;
|
|
318
|
+
if (done) {
|
|
319
|
+
if (!framing.end()) {
|
|
320
|
+
return yield* Effect.fail(new ProtocolViolation("connection closed mid-body"));
|
|
321
|
+
}
|
|
322
|
+
finished = true;
|
|
323
|
+
yield* Deferred.succeed(trailers, framing.trailers);
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
input = value;
|
|
327
|
+
}
|
|
328
|
+
const { data, done } = yield* attempt(() => framing.feed(input));
|
|
329
|
+
if (done) {
|
|
330
|
+
finished = true;
|
|
331
|
+
yield* Deferred.succeed(trailers, framing.trailers);
|
|
332
|
+
return data;
|
|
333
|
+
}
|
|
334
|
+
if (data.length > 0) return data;
|
|
335
|
+
}
|
|
336
|
+
return undefined;
|
|
337
|
+
});
|
|
338
|
+
const stream = Stream.unfold(undefined, () =>
|
|
339
|
+
Effect.map(next, (data) => (data === undefined ? undefined : ([data, undefined] as const))),
|
|
340
|
+
).pipe(
|
|
341
|
+
Stream.flattenIterable,
|
|
342
|
+
Stream.ensuring(
|
|
343
|
+
Effect.andThen(
|
|
344
|
+
// Settles nothing once the body ended; else no trailers come.
|
|
345
|
+
Deferred.fail(trailers, new ProtocolViolation("the body was not read to its end")),
|
|
346
|
+
close,
|
|
347
|
+
),
|
|
348
|
+
),
|
|
349
|
+
);
|
|
350
|
+
// A reply with no body needs the socket no more.
|
|
351
|
+
if (hasNoBody(status)) yield* close;
|
|
352
|
+
// HTTP/1.1: a bridging proxy may drop the trailers.
|
|
353
|
+
return yield* respond(request, {
|
|
354
|
+
status,
|
|
355
|
+
headers,
|
|
356
|
+
body: stream,
|
|
357
|
+
trailers: Deferred.await(trailers),
|
|
358
|
+
reliableTrailers: false,
|
|
359
|
+
});
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
/** An `HttpClient` that sends each request over its own `cloudflare:sockets` socket. */
|
|
363
|
+
export const client: HttpClient.HttpClient = /*@__PURE__*/ HttpClient.make((request, url, signal) =>
|
|
364
|
+
Effect.mapError(send(request, url, signal), (cause) => transportError(request, cause)),
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
/** Send gRPC calls over `cloudflare:sockets` in this scope. */
|
|
368
|
+
export const layer: Layer.Layer<never> = /*@__PURE__*/ transportLayer(client);
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A gRPC transport over HTTP/2 with `node:http2`, for servers that offer
|
|
3
|
+
* nothing else (`fetch` in Node and Bun speaks HTTP/1.1).
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import * as NodeHttp2 from "@distilled.cloud/core/grpc-transport-node-http2";
|
|
7
|
+
*
|
|
8
|
+
* program.pipe(Effect.provide(NodeHttp2.layer));
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* Requests share one session per origin; an idle session doesn't keep the
|
|
12
|
+
* process alive. {@link unixSocket} sends them over a Unix domain socket
|
|
13
|
+
* instead (a gRPC server on a local socket, such as Modal's
|
|
14
|
+
* `unix:/run/modal.sock` inside its containers). The response body is an
|
|
15
|
+
* Effect `Stream` fed by the HTTP/2 stream as data arrives, up to 1 MiB ahead
|
|
16
|
+
* of the reader; past that the HTTP/2 stream stops reading until the reader
|
|
17
|
+
* catches up, so the server waits. The trailers settle when it ends, and
|
|
18
|
+
* fail when the stream fails or closes first. A stream the server resets
|
|
19
|
+
* ends the call with the gRPC status the reset's code maps to
|
|
20
|
+
* (`resetTrailers`). `node:http2` is found on first use (no static import),
|
|
21
|
+
* so the module loads in any runtime and only a call needs Node.
|
|
22
|
+
*/
|
|
23
|
+
import * as Cause from "effect/Cause";
|
|
24
|
+
import * as Deferred from "effect/Deferred";
|
|
25
|
+
import * as Effect from "effect/Effect";
|
|
26
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
27
|
+
import * as HttpClientError from "effect/http/HttpClientError";
|
|
28
|
+
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
29
|
+
import type * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
30
|
+
import type * as Layer from "effect/Layer";
|
|
31
|
+
import * as Queue from "effect/Queue";
|
|
32
|
+
import * as Stream from "effect/Stream";
|
|
33
|
+
import {
|
|
34
|
+
isResponseStatus,
|
|
35
|
+
hasNoBody,
|
|
36
|
+
layer as transportLayer,
|
|
37
|
+
resetReply,
|
|
38
|
+
resetTrailers,
|
|
39
|
+
respond,
|
|
40
|
+
type Trailers,
|
|
41
|
+
} from "./grpc-transport.ts";
|
|
42
|
+
|
|
43
|
+
type Http2 = typeof import("node:http2");
|
|
44
|
+
type Net = typeof import("node:net");
|
|
45
|
+
type Session = import("node:http2").ClientHttp2Session;
|
|
46
|
+
type IncomingHeaders = import("node:http2").IncomingHttpHeaders;
|
|
47
|
+
|
|
48
|
+
const builtin = <A>(id: string): A | undefined =>
|
|
49
|
+
(
|
|
50
|
+
globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }
|
|
51
|
+
).process?.getBuiltinModule?.(id) as A | undefined;
|
|
52
|
+
|
|
53
|
+
const http2Module = (): Http2 | undefined => builtin<Http2>("node:http2");
|
|
54
|
+
|
|
55
|
+
const sessions = new Map<string, { session: Session; active: number }>();
|
|
56
|
+
|
|
57
|
+
/** Where a session connects: an origin over TCP, or a Unix domain socket. */
|
|
58
|
+
type Target = { readonly origin: string } | { readonly socketPath: string };
|
|
59
|
+
|
|
60
|
+
const keyOf = (target: Target) =>
|
|
61
|
+
"socketPath" in target ? `unix:${target.socketPath}` : target.origin;
|
|
62
|
+
|
|
63
|
+
const connect = (http2: Http2, target: Target): Session => {
|
|
64
|
+
if (!("socketPath" in target)) return http2.connect(target.origin);
|
|
65
|
+
const net = builtin<Net>("node:net");
|
|
66
|
+
if (net === undefined) throw new Error("node:net is not available in this runtime");
|
|
67
|
+
// The authority is only the `:authority` pseudo-header; the socket is the transport.
|
|
68
|
+
return http2.connect("http://localhost", {
|
|
69
|
+
createConnection: () => net.connect(target.socketPath),
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const sessionFor = (http2: Http2, target: Target) => {
|
|
74
|
+
const key = keyOf(target);
|
|
75
|
+
const existing = sessions.get(key);
|
|
76
|
+
if (existing && !existing.session.closed && !existing.session.destroyed) return existing;
|
|
77
|
+
const entry = { session: connect(http2, target), active: 0 };
|
|
78
|
+
entry.session.unref();
|
|
79
|
+
const drop = () => {
|
|
80
|
+
if (sessions.get(key) === entry) sessions.delete(key);
|
|
81
|
+
};
|
|
82
|
+
entry.session.on("error", drop);
|
|
83
|
+
entry.session.on("close", drop);
|
|
84
|
+
entry.session.on("goaway", drop);
|
|
85
|
+
sessions.set(key, entry);
|
|
86
|
+
return entry;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** Headers HTTP/2 forbids or derives itself. */
|
|
90
|
+
const CONNECTION_HEADERS = new Set([
|
|
91
|
+
"host",
|
|
92
|
+
"connection",
|
|
93
|
+
"keep-alive",
|
|
94
|
+
"content-length",
|
|
95
|
+
"transfer-encoding",
|
|
96
|
+
"upgrade",
|
|
97
|
+
]);
|
|
98
|
+
|
|
99
|
+
const plain = (incoming: IncomingHeaders): Record<string, string> => {
|
|
100
|
+
const out: Record<string, string> = {};
|
|
101
|
+
for (const [key, value] of Object.entries(incoming)) {
|
|
102
|
+
if (key.startsWith(":") || value === undefined) continue;
|
|
103
|
+
out[key] = Array.isArray(value) ? value.join(", ") : String(value);
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unknown) =>
|
|
109
|
+
new HttpClientError.HttpClientError({
|
|
110
|
+
reason: new HttpClientError.TransportError({
|
|
111
|
+
request,
|
|
112
|
+
cause,
|
|
113
|
+
description: "HTTP/2 request failed",
|
|
114
|
+
}),
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const bodyOf = (request: HttpClientRequest.HttpClientRequest): Uint8Array | undefined =>
|
|
118
|
+
request.body._tag === "Uint8Array" ? request.body.body : undefined;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Body bytes received and not yet taken by the reader, past which the HTTP/2
|
|
122
|
+
* stream stops reading (so flow control holds the server back), and at or
|
|
123
|
+
* below which it reads again. grpc-js pauses and resumes the same way, and
|
|
124
|
+
* 1 MiB is grpc-java's default flow-control window. Node's own 64 KiB buffer
|
|
125
|
+
* halves the speed of a reader that takes the body in bursts.
|
|
126
|
+
*/
|
|
127
|
+
const HIGH_WATER = 1024 * 1024;
|
|
128
|
+
const LOW_WATER = HIGH_WATER / 4;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* An `HttpClient` that sends each request as an HTTP/2 stream, to the
|
|
132
|
+
* request's origin or to `socketPath`.
|
|
133
|
+
*/
|
|
134
|
+
const make = (socketPath: string | undefined): HttpClient.HttpClient =>
|
|
135
|
+
HttpClient.make((request, url, signal) =>
|
|
136
|
+
Effect.gen(function* () {
|
|
137
|
+
// Fed by the HTTP/2 stream's events from the moment it opens, and read
|
|
138
|
+
// as the response's body in the caller's fiber.
|
|
139
|
+
const chunks = yield* Queue.unbounded<Uint8Array, unknown>();
|
|
140
|
+
const trailers = yield* Deferred.make<Trailers, unknown>();
|
|
141
|
+
return yield* Effect.callback<
|
|
142
|
+
HttpClientResponse.HttpClientResponse,
|
|
143
|
+
HttpClientError.HttpClientError
|
|
144
|
+
>((resume) => {
|
|
145
|
+
const http2 = http2Module();
|
|
146
|
+
if (http2 === undefined) {
|
|
147
|
+
resume(
|
|
148
|
+
Effect.fail(
|
|
149
|
+
transportError(request, new Error("node:http2 is not available in this runtime")),
|
|
150
|
+
),
|
|
151
|
+
);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
let entry: { session: Session; active: number };
|
|
155
|
+
try {
|
|
156
|
+
entry = sessionFor(
|
|
157
|
+
http2,
|
|
158
|
+
socketPath === undefined ? { origin: url.origin } : { socketPath },
|
|
159
|
+
);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
resume(Effect.fail(transportError(request, error)));
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (entry.active++ === 0) entry.session.ref();
|
|
165
|
+
let settled = false;
|
|
166
|
+
const settle = () => {
|
|
167
|
+
if (settled) return;
|
|
168
|
+
settled = true;
|
|
169
|
+
if (--entry.active === 0 && !entry.session.destroyed) entry.session.unref();
|
|
170
|
+
};
|
|
171
|
+
const headers: Record<string, string> = {};
|
|
172
|
+
for (const [key, value] of Object.entries(request.headers)) {
|
|
173
|
+
if (!CONNECTION_HEADERS.has(key)) headers[key] = value;
|
|
174
|
+
}
|
|
175
|
+
const stream = entry.session.request({
|
|
176
|
+
":method": request.method,
|
|
177
|
+
":path": `${url.pathname}${url.search}`,
|
|
178
|
+
...headers,
|
|
179
|
+
});
|
|
180
|
+
// The response is dropped unread, its scope closed, or the call interrupted.
|
|
181
|
+
const onAbort = () => stream.close(http2.constants.NGHTTP2_CANCEL);
|
|
182
|
+
if (signal.aborted) onAbort();
|
|
183
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
184
|
+
|
|
185
|
+
let received: Trailers = {};
|
|
186
|
+
let ended = false;
|
|
187
|
+
let started = false;
|
|
188
|
+
/** The call already failed with a transport error. */
|
|
189
|
+
let failed = false;
|
|
190
|
+
const failWith = (cause: unknown) => {
|
|
191
|
+
Queue.failCauseUnsafe(chunks, Cause.fail(cause));
|
|
192
|
+
Deferred.doneUnsafe(trailers, Effect.fail(cause));
|
|
193
|
+
};
|
|
194
|
+
const fail = (cause: unknown) => {
|
|
195
|
+
failed = true;
|
|
196
|
+
if (started) return failWith(cause);
|
|
197
|
+
resume(Effect.fail(transportError(request, cause)));
|
|
198
|
+
};
|
|
199
|
+
stream.on("trailers", (incoming) => (received = plain(incoming)));
|
|
200
|
+
let buffered = 0;
|
|
201
|
+
stream.on("data", (chunk: Uint8Array) => {
|
|
202
|
+
buffered += chunk.length;
|
|
203
|
+
Queue.offerUnsafe(chunks, new Uint8Array(chunk));
|
|
204
|
+
if (buffered >= HIGH_WATER) stream.pause();
|
|
205
|
+
});
|
|
206
|
+
stream.on("end", () => {
|
|
207
|
+
ended = true;
|
|
208
|
+
Queue.endUnsafe(chunks);
|
|
209
|
+
Deferred.doneUnsafe(trailers, Effect.succeed(received));
|
|
210
|
+
});
|
|
211
|
+
// Every stream ends here, a reset included, which emits no `error` for
|
|
212
|
+
// NO_ERROR or CANCEL. As in grpc-js, the reset code decides the call.
|
|
213
|
+
stream.on("close", () => {
|
|
214
|
+
settle();
|
|
215
|
+
signal.removeEventListener("abort", onAbort);
|
|
216
|
+
if (failed) return;
|
|
217
|
+
// Node closes every stream of a lost connection with CANCEL; that is
|
|
218
|
+
// a transport failure, which retries, and no answer from the server.
|
|
219
|
+
if (entry.session.destroyed) {
|
|
220
|
+
if (!started || !ended) {
|
|
221
|
+
fail(new Error("the HTTP/2 connection closed before the response ended"));
|
|
222
|
+
}
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (!started) {
|
|
226
|
+
started = true;
|
|
227
|
+
resume(
|
|
228
|
+
respond(request, resetReply(stream.rstCode)).pipe(
|
|
229
|
+
Effect.mapError((cause) => transportError(request, cause)),
|
|
230
|
+
),
|
|
231
|
+
);
|
|
232
|
+
} else if (!ended) {
|
|
233
|
+
ended = true;
|
|
234
|
+
Queue.endUnsafe(chunks);
|
|
235
|
+
Deferred.doneUnsafe(trailers, Effect.succeed(resetTrailers(stream.rstCode)));
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
stream.on("response", (incoming) => {
|
|
240
|
+
started = true;
|
|
241
|
+
const status = Number(incoming[":status"] ?? 0);
|
|
242
|
+
if (!isResponseStatus(status)) {
|
|
243
|
+
stream.close(http2.constants.NGHTTP2_CANCEL);
|
|
244
|
+
resume(
|
|
245
|
+
Effect.fail(transportError(request, new Error(`invalid HTTP status ${status}`))),
|
|
246
|
+
);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
const body = Stream.fromQueue(chunks).pipe(
|
|
250
|
+
Stream.tap((chunk) =>
|
|
251
|
+
Effect.sync(() => {
|
|
252
|
+
buffered -= chunk.length;
|
|
253
|
+
if (buffered <= LOW_WATER && stream.isPaused()) stream.resume();
|
|
254
|
+
}),
|
|
255
|
+
),
|
|
256
|
+
// A reader that stops early lets the stream go.
|
|
257
|
+
Stream.ensuring(
|
|
258
|
+
Effect.sync(() => {
|
|
259
|
+
if (!ended) stream.close(http2.constants.NGHTTP2_CANCEL);
|
|
260
|
+
}),
|
|
261
|
+
),
|
|
262
|
+
);
|
|
263
|
+
if (hasNoBody(status)) stream.close(http2.constants.NGHTTP2_CANCEL);
|
|
264
|
+
resume(
|
|
265
|
+
respond(request, {
|
|
266
|
+
status,
|
|
267
|
+
headers: plain(incoming),
|
|
268
|
+
body,
|
|
269
|
+
trailers: Deferred.await(trailers),
|
|
270
|
+
}).pipe(
|
|
271
|
+
Effect.mapError((cause) => transportError(request, cause)),
|
|
272
|
+
Effect.tapError(() =>
|
|
273
|
+
Effect.sync(() => stream.close(http2.constants.NGHTTP2_CANCEL)),
|
|
274
|
+
),
|
|
275
|
+
),
|
|
276
|
+
);
|
|
277
|
+
});
|
|
278
|
+
stream.on("error", (error: Error & { code?: string }) => {
|
|
279
|
+
// The server's RST_STREAM: `close` follows with its code.
|
|
280
|
+
if (error.code === "ERR_HTTP2_STREAM_ERROR") return;
|
|
281
|
+
fail(error);
|
|
282
|
+
});
|
|
283
|
+
const body = bodyOf(request);
|
|
284
|
+
stream.end(body === undefined ? undefined : body);
|
|
285
|
+
});
|
|
286
|
+
}),
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
/** An `HttpClient` that sends each request as an HTTP/2 stream. */
|
|
290
|
+
export const client: HttpClient.HttpClient = /*@__PURE__*/ make(undefined);
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* An `HttpClient` that sends each request as an HTTP/2 stream over the Unix
|
|
294
|
+
* domain socket at `path`, whatever the request's host. Requests share one
|
|
295
|
+
* session per socket.
|
|
296
|
+
*
|
|
297
|
+
* ```ts
|
|
298
|
+
* program.pipe(Effect.provide(NodeHttp2.unixLayer("/run/modal.sock")));
|
|
299
|
+
* ```
|
|
300
|
+
*/
|
|
301
|
+
export const unixSocket = (path: string): HttpClient.HttpClient => make(path);
|
|
302
|
+
|
|
303
|
+
/** Send gRPC calls over HTTP/2 in this scope. */
|
|
304
|
+
export const layer: Layer.Layer<never> = /*@__PURE__*/ transportLayer(client);
|
|
305
|
+
|
|
306
|
+
/** Send gRPC calls over HTTP/2 on the Unix domain socket at `path` in this scope. */
|
|
307
|
+
export const unixLayer = (path: string): Layer.Layer<never> => transportLayer(unixSocket(path));
|