@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.
Files changed (112) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/grpc.js +2 -0
  6. package/lib/_bundle/grpc.js.map +1 -0
  7. package/lib/_bundle/rest.js +1 -1
  8. package/lib/_bundle/rest.js.map +1 -1
  9. package/lib/_bundle/xml.js +1 -1
  10. package/lib/_bundle/xml.js.map +1 -1
  11. package/lib/annotations.d.ts +2 -0
  12. package/lib/annotations.d.ts.map +1 -1
  13. package/lib/annotations.js +1 -1
  14. package/lib/annotations.js.map +1 -1
  15. package/lib/api.d.ts +37 -1
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -1
  18. package/lib/errors.d.ts +1 -0
  19. package/lib/errors.d.ts.map +1 -1
  20. package/lib/errors.js +1 -1
  21. package/lib/graphql.d.ts +12 -5
  22. package/lib/graphql.d.ts.map +1 -1
  23. package/lib/graphql.types.d.ts.map +1 -1
  24. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  25. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  26. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  27. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  28. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  29. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  30. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  31. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  32. package/lib/grpc-transport-node-http2.d.ts +19 -0
  33. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  34. package/lib/grpc-transport-node-http2.js +2 -0
  35. package/lib/grpc-transport-node-http2.js.map +1 -0
  36. package/lib/grpc-transport.d.ts +76 -0
  37. package/lib/grpc-transport.d.ts.map +1 -0
  38. package/lib/grpc-transport.js +1 -0
  39. package/lib/hpack.d.ts +34 -0
  40. package/lib/hpack.d.ts.map +1 -0
  41. package/lib/hpack.js +2 -0
  42. package/lib/hpack.js.map +1 -0
  43. package/lib/index.d.ts +3 -0
  44. package/lib/index.d.ts.map +1 -1
  45. package/lib/index.js +3 -0
  46. package/lib/pagination.d.ts +22 -2
  47. package/lib/pagination.d.ts.map +1 -1
  48. package/lib/pagination.js +1 -1
  49. package/lib/protobuf.d.ts +92 -0
  50. package/lib/protobuf.d.ts.map +1 -0
  51. package/lib/protobuf.js +1 -0
  52. package/lib/protocol-grpc.d.ts +86 -0
  53. package/lib/protocol-grpc.d.ts.map +1 -0
  54. package/lib/protocol-grpc.js +1 -0
  55. package/lib/protocol-http.d.ts +11 -6
  56. package/lib/protocol-http.d.ts.map +1 -1
  57. package/lib/protocol-rest.d.ts +12 -8
  58. package/lib/protocol-rest.d.ts.map +1 -1
  59. package/lib/response-validation.d.ts +1 -1
  60. package/lib/response-validation.d.ts.map +1 -1
  61. package/lib/sdk-error.d.ts +27 -0
  62. package/lib/sdk-error.d.ts.map +1 -0
  63. package/lib/sdk-error.js +1 -0
  64. package/lib/sensitive.d.ts +28 -0
  65. package/lib/sensitive.d.ts.map +1 -0
  66. package/lib/sensitive.js +2 -0
  67. package/lib/sensitive.js.map +1 -0
  68. package/lib/telemetry-debug.d.ts +2 -10
  69. package/lib/telemetry-debug.d.ts.map +1 -1
  70. package/lib/telemetry-debug.js +1 -1
  71. package/lib/telemetry-debug.js.map +1 -1
  72. package/lib/telemetry-stream.d.ts +3 -1
  73. package/lib/telemetry-stream.d.ts.map +1 -1
  74. package/lib/telemetry-stream.js +1 -1
  75. package/lib/telemetry-stream.js.map +1 -1
  76. package/lib/telemetry.d.ts +23 -4
  77. package/lib/telemetry.d.ts.map +1 -1
  78. package/lib/telemetry.js +2 -2
  79. package/lib/telemetry.js.map +1 -1
  80. package/lib/trait.d.ts +7 -0
  81. package/lib/trait.d.ts.map +1 -1
  82. package/lib/trait.js +1 -1
  83. package/lib/xml.d.ts.map +1 -1
  84. package/package.json +3 -3
  85. package/src/annotations.ts +16 -0
  86. package/src/api.ts +199 -25
  87. package/src/errors.ts +4 -0
  88. package/src/graphql.ts +68 -45
  89. package/src/graphql.types.ts +5 -1
  90. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  91. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  92. package/src/grpc-transport-node-http2.ts +234 -0
  93. package/src/grpc-transport.ts +118 -0
  94. package/src/hpack.ts +331 -0
  95. package/src/index.ts +3 -0
  96. package/src/pagination.ts +75 -3
  97. package/src/protobuf.ts +1332 -0
  98. package/src/protocol-grpc.ts +641 -0
  99. package/src/protocol-http.ts +30 -30
  100. package/src/protocol-rest.ts +49 -118
  101. package/src/response-validation.ts +4 -2
  102. package/src/sdk-error.ts +33 -0
  103. package/src/sensitive.ts +154 -0
  104. package/src/telemetry-debug.ts +65 -21
  105. package/src/telemetry-stream.ts +16 -7
  106. package/src/telemetry.ts +91 -27
  107. package/src/trait.ts +10 -0
  108. package/src/xml.ts +10 -1
  109. package/lib/debug.d.ts +0 -2
  110. package/lib/debug.d.ts.map +0 -1
  111. package/lib/debug.js +0 -1
  112. package/src/debug.ts +0 -11
@@ -0,0 +1,299 @@
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 body streams as it arrives (`content-length`, chunked,
19
+ * or until the server closes); chunked trailers, where gRPC puts
20
+ * `grpc-status`, settle when it ends. The server must accept gRPC over
21
+ * HTTP/1.1, as a bridging proxy (envoy) does.
22
+ */
23
+ import * as Effect from "effect/Effect";
24
+ import * as HttpClient from "effect/http/HttpClient";
25
+ import * as HttpClientError from "effect/http/HttpClientError";
26
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
27
+ import type * as Layer from "effect/Layer";
28
+ import {
29
+ isResponseStatus,
30
+ layer as transportLayer,
31
+ respond,
32
+ type Trailers,
33
+ } from "./grpc-transport.ts";
34
+
35
+ /** The part of `cloudflare:sockets` this transport uses. */
36
+ type Connect = (
37
+ address: { hostname: string; port: number },
38
+ options: { secureTransport: "on" | "off"; allowHalfOpen: boolean },
39
+ ) => {
40
+ readonly readable: ReadableStream<Uint8Array>;
41
+ readonly writable: WritableStream<Uint8Array>;
42
+ close(): Promise<void>;
43
+ };
44
+
45
+ // A non-literal specifier keeps bundlers from resolving it for runtimes
46
+ // other than workerd, which resolves its built-in modules at runtime.
47
+ const SOCKETS_MODULE = "cloudflare:sockets";
48
+ let sockets: Promise<Connect> | undefined;
49
+ const connectFn = () =>
50
+ (sockets ??= (import(SOCKETS_MODULE) as Promise<{ connect: Connect }>).then(
51
+ (module) => module.connect,
52
+ ));
53
+
54
+ /** Headers this transport sets itself. */
55
+ const FRAMING_HEADERS = new Set([
56
+ "host",
57
+ "connection",
58
+ "keep-alive",
59
+ "content-length",
60
+ "transfer-encoding",
61
+ "upgrade",
62
+ ]);
63
+
64
+ const encoder = /*@__PURE__*/ new TextEncoder();
65
+ const decoder = /*@__PURE__*/ new TextDecoder();
66
+
67
+ const concat = (a: Uint8Array, b: Uint8Array): Uint8Array<ArrayBufferLike> => {
68
+ if (a.length === 0) return b;
69
+ const out = new Uint8Array(a.length + b.length);
70
+ out.set(a);
71
+ out.set(b, a.length);
72
+ return out;
73
+ };
74
+
75
+ const indexOf = (bytes: Uint8Array, pattern: readonly number[], from = 0): number => {
76
+ outer: for (let i = from; i + pattern.length <= bytes.length; i++) {
77
+ for (let j = 0; j < pattern.length; j++) if (bytes[i + j] !== pattern[j]) continue outer;
78
+ return i;
79
+ }
80
+ return -1;
81
+ };
82
+
83
+ const CRLF = [13, 10] as const;
84
+ const CRLFCRLF = [13, 10, 13, 10] as const;
85
+
86
+ const parseHeaderLines = (lines: ReadonlyArray<string>): Record<string, string> => {
87
+ // A map, so a header named like something every object has (`constructor`,
88
+ // `__proto__`) is a header like any other.
89
+ const joined = new Map<string, string>();
90
+ for (const line of lines) {
91
+ const colon = line.indexOf(":");
92
+ if (colon <= 0) continue;
93
+ const key = line.slice(0, colon).trim().toLowerCase();
94
+ const value = line.slice(colon + 1).trim();
95
+ const previous = joined.get(key);
96
+ joined.set(key, previous === undefined ? value : `${previous}, ${value}`);
97
+ }
98
+ return Object.fromEntries(joined);
99
+ };
100
+
101
+ class ProtocolViolation extends Error {}
102
+
103
+ /**
104
+ * The body framing of an HTTP/1.1 response: hands back the payload bytes in
105
+ * `input` and whether the body has ended; a chunked body's trailers land in
106
+ * `trailers`.
107
+ */
108
+ interface BodyDecoder {
109
+ feed(input: Uint8Array): { readonly data: Uint8Array[]; readonly done: boolean };
110
+ /** The peer closed the connection. */
111
+ end(): boolean;
112
+ readonly trailers: Record<string, string>;
113
+ }
114
+
115
+ const lengthDecoder = (length: number): BodyDecoder => {
116
+ let left = length;
117
+ return {
118
+ trailers: {},
119
+ feed(input) {
120
+ const take = input.subarray(0, left);
121
+ left -= take.length;
122
+ return { data: take.length > 0 ? [take] : [], done: left === 0 };
123
+ },
124
+ end: () => left === 0,
125
+ };
126
+ };
127
+
128
+ const untilCloseDecoder = (): BodyDecoder => ({
129
+ trailers: {},
130
+ feed: (input) => ({ data: input.length > 0 ? [input] : [], done: false }),
131
+ end: () => true,
132
+ });
133
+
134
+ const chunkedDecoder = (): BodyDecoder => {
135
+ let buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
136
+ let state: "size" | "data" | "trailers" | "done" = "size";
137
+ let left = 0;
138
+ let trailers: Record<string, string> = {};
139
+ return {
140
+ get trailers() {
141
+ return trailers;
142
+ },
143
+ feed(input) {
144
+ buf = concat(buf, input);
145
+ const data: Uint8Array[] = [];
146
+ for (;;) {
147
+ if (state === "size") {
148
+ const eol = indexOf(buf, CRLF);
149
+ if (eol < 0) break;
150
+ const size = Number.parseInt(decoder.decode(buf.subarray(0, eol)).split(";")[0]!, 16);
151
+ if (Number.isNaN(size)) throw new ProtocolViolation("invalid chunk size");
152
+ buf = buf.subarray(eol + 2);
153
+ if (size === 0) state = "trailers";
154
+ else {
155
+ state = "data";
156
+ left = size;
157
+ }
158
+ } else if (state === "data") {
159
+ if (buf.length < left + 2) {
160
+ // Hand over what arrived; keep the rest of the chunk pending.
161
+ const take = buf.subarray(0, Math.min(buf.length, left));
162
+ if (take.length > 0) data.push(take.slice());
163
+ left -= take.length;
164
+ buf = buf.subarray(take.length);
165
+ break;
166
+ }
167
+ if (left > 0) data.push(buf.slice(0, left));
168
+ buf = buf.subarray(left + 2);
169
+ left = 0;
170
+ state = "size";
171
+ } else if (state === "trailers") {
172
+ if (buf[0] === 13 && buf[1] === 10) {
173
+ state = "done";
174
+ break;
175
+ }
176
+ const end = indexOf(buf, CRLFCRLF);
177
+ if (end < 0) break;
178
+ trailers = parseHeaderLines(decoder.decode(buf.subarray(0, end)).split("\r\n"));
179
+ state = "done";
180
+ break;
181
+ } else break;
182
+ }
183
+ return { data, done: state === "done" };
184
+ },
185
+ end: () => state === "done",
186
+ };
187
+ };
188
+
189
+ const decoderFor = (headers: Record<string, string>): BodyDecoder =>
190
+ (headers["transfer-encoding"] ?? "").toLowerCase().includes("chunked")
191
+ ? chunkedDecoder()
192
+ : headers["content-length"] !== undefined
193
+ ? lengthDecoder(Number(headers["content-length"]))
194
+ : untilCloseDecoder();
195
+
196
+ const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unknown) =>
197
+ new HttpClientError.HttpClientError({
198
+ reason: new HttpClientError.TransportError({
199
+ request,
200
+ cause,
201
+ description: "request over cloudflare:sockets failed",
202
+ }),
203
+ });
204
+
205
+ /** Send `request` and read the response head; the body streams afterwards. */
206
+ const send = async (
207
+ request: HttpClientRequest.HttpClientRequest,
208
+ url: URL,
209
+ signal: AbortSignal,
210
+ ) => {
211
+ const connect = await connectFn();
212
+ const tls = url.protocol === "https:";
213
+ const socket = connect(
214
+ { hostname: url.hostname, port: Number(url.port || (tls ? 443 : 80)) },
215
+ { secureTransport: tls ? "on" : "off", allowHalfOpen: false },
216
+ );
217
+ const close = () => void socket.close().catch(() => undefined);
218
+ signal.addEventListener("abort", close, { once: true });
219
+
220
+ const body = request.body._tag === "Uint8Array" ? request.body.body : new Uint8Array(0);
221
+ const head = [`${request.method} ${url.pathname}${url.search} HTTP/1.1`, `host: ${url.host}`];
222
+ for (const [key, value] of Object.entries(request.headers)) {
223
+ if (!FRAMING_HEADERS.has(key)) head.push(`${key}: ${value}`);
224
+ }
225
+ head.push(`content-length: ${body.length}`, "connection: close", "", "");
226
+ const writer = socket.writable.getWriter();
227
+ await writer.write(concat(encoder.encode(head.join("\r\n")), body));
228
+ writer.releaseLock();
229
+
230
+ const reader = socket.readable.getReader();
231
+ let buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
232
+ let end = -1;
233
+ while ((end = indexOf(buf, CRLFCRLF)) < 0) {
234
+ const { value, done } = await reader.read();
235
+ if (done) throw new ProtocolViolation("connection closed before the response headers");
236
+ buf = concat(buf, value);
237
+ }
238
+ const [statusLine = "", ...lines] = decoder.decode(buf.subarray(0, end)).split("\r\n");
239
+ const status = Number(statusLine.split(" ")[1] ?? 0);
240
+ if (!isResponseStatus(status)) throw new ProtocolViolation(`invalid HTTP status ${status}`);
241
+ const headers = parseHeaderLines(lines);
242
+ const framing = decoderFor(headers);
243
+
244
+ let resolveTrailers!: (t: Trailers) => void;
245
+ const trailers = new Promise<Trailers>((resolve) => (resolveTrailers = resolve));
246
+ const finish = () => {
247
+ signal.removeEventListener("abort", close);
248
+ resolveTrailers(framing.trailers);
249
+ close();
250
+ };
251
+ let pending: Uint8Array | undefined = buf.subarray(end + 4);
252
+ const stream = new ReadableStream<Uint8Array>({
253
+ async pull(controller) {
254
+ for (;;) {
255
+ let input: Uint8Array;
256
+ if (pending !== undefined) {
257
+ input = pending;
258
+ pending = undefined;
259
+ } else {
260
+ const { value, done } = await reader.read();
261
+ if (done) {
262
+ finish();
263
+ if (framing.end()) controller.close();
264
+ else controller.error(new ProtocolViolation("connection closed mid-body"));
265
+ return;
266
+ }
267
+ input = value;
268
+ }
269
+ const { data, done } = framing.feed(input);
270
+ for (const chunk of data) controller.enqueue(chunk);
271
+ if (done) {
272
+ finish();
273
+ controller.close();
274
+ return;
275
+ }
276
+ if (data.length > 0) return;
277
+ }
278
+ },
279
+ cancel() {
280
+ finish();
281
+ },
282
+ });
283
+ // HTTP/1.1: a bridging proxy may drop the trailers.
284
+ return { status, headers, body: stream, trailers, reliableTrailers: false };
285
+ };
286
+
287
+ /** An `HttpClient` that sends each request over its own `cloudflare:sockets` socket. */
288
+ export const client: HttpClient.HttpClient = /*@__PURE__*/ HttpClient.make((request, url, signal) =>
289
+ Effect.map(
290
+ Effect.tryPromise({
291
+ try: () => send(request, url, signal),
292
+ catch: (cause) => transportError(request, cause),
293
+ }),
294
+ (reply) => respond(request, reply),
295
+ ),
296
+ );
297
+
298
+ /** Send gRPC calls over `cloudflare:sockets` in this scope. */
299
+ export const layer: Layer.Layer<never> = /*@__PURE__*/ transportLayer(client);
@@ -0,0 +1,234 @@
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 streams as it arrives and the trailers
15
+ * settle when it ends. `node:http2` is found on first use (no static
16
+ * import), so the module loads in any runtime and only a call needs Node.
17
+ */
18
+ import * as Effect from "effect/Effect";
19
+ import * as HttpClient from "effect/http/HttpClient";
20
+ import * as HttpClientError from "effect/http/HttpClientError";
21
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
22
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
23
+ import type * as Layer from "effect/Layer";
24
+ import {
25
+ isResponseStatus,
26
+ layer as transportLayer,
27
+ respond,
28
+ type Trailers,
29
+ } from "./grpc-transport.ts";
30
+
31
+ type Http2 = typeof import("node:http2");
32
+ type Net = typeof import("node:net");
33
+ type Session = import("node:http2").ClientHttp2Session;
34
+ type IncomingHeaders = import("node:http2").IncomingHttpHeaders;
35
+
36
+ const builtin = <A>(id: string): A | undefined =>
37
+ (
38
+ globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }
39
+ ).process?.getBuiltinModule?.(id) as A | undefined;
40
+
41
+ const http2Module = (): Http2 | undefined => builtin<Http2>("node:http2");
42
+
43
+ const sessions = new Map<string, { session: Session; active: number }>();
44
+
45
+ /** Where a session connects: an origin over TCP, or a Unix domain socket. */
46
+ type Target = { readonly origin: string } | { readonly socketPath: string };
47
+
48
+ const keyOf = (target: Target) =>
49
+ "socketPath" in target ? `unix:${target.socketPath}` : target.origin;
50
+
51
+ const connect = (http2: Http2, target: Target): Session => {
52
+ if (!("socketPath" in target)) return http2.connect(target.origin);
53
+ const net = builtin<Net>("node:net");
54
+ if (net === undefined) throw new Error("node:net is not available in this runtime");
55
+ // The authority is only the `:authority` pseudo-header; the socket is the transport.
56
+ return http2.connect("http://localhost", {
57
+ createConnection: () => net.connect(target.socketPath),
58
+ });
59
+ };
60
+
61
+ const sessionFor = (http2: Http2, target: Target) => {
62
+ const key = keyOf(target);
63
+ const existing = sessions.get(key);
64
+ if (existing && !existing.session.closed && !existing.session.destroyed) return existing;
65
+ const entry = { session: connect(http2, target), active: 0 };
66
+ entry.session.unref();
67
+ const drop = () => {
68
+ if (sessions.get(key) === entry) sessions.delete(key);
69
+ };
70
+ entry.session.on("error", drop);
71
+ entry.session.on("close", drop);
72
+ entry.session.on("goaway", drop);
73
+ sessions.set(key, entry);
74
+ return entry;
75
+ };
76
+
77
+ /** Headers HTTP/2 forbids or derives itself. */
78
+ const CONNECTION_HEADERS = new Set([
79
+ "host",
80
+ "connection",
81
+ "keep-alive",
82
+ "content-length",
83
+ "transfer-encoding",
84
+ "upgrade",
85
+ ]);
86
+
87
+ const plain = (incoming: IncomingHeaders): Record<string, string> => {
88
+ const out: Record<string, string> = {};
89
+ for (const [key, value] of Object.entries(incoming)) {
90
+ if (key.startsWith(":") || value === undefined) continue;
91
+ out[key] = Array.isArray(value) ? value.join(", ") : String(value);
92
+ }
93
+ return out;
94
+ };
95
+
96
+ const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unknown) =>
97
+ new HttpClientError.HttpClientError({
98
+ reason: new HttpClientError.TransportError({
99
+ request,
100
+ cause,
101
+ description: "HTTP/2 request failed",
102
+ }),
103
+ });
104
+
105
+ const bodyOf = (request: HttpClientRequest.HttpClientRequest): Uint8Array | undefined =>
106
+ request.body._tag === "Uint8Array" ? request.body.body : undefined;
107
+
108
+ /**
109
+ * An `HttpClient` that sends each request as an HTTP/2 stream, to the
110
+ * request's origin or to `socketPath`.
111
+ */
112
+ const make = (socketPath: string | undefined): HttpClient.HttpClient =>
113
+ HttpClient.make((request, url, signal) =>
114
+ Effect.callback<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>(
115
+ (resume) => {
116
+ const http2 = http2Module();
117
+ if (http2 === undefined) {
118
+ resume(
119
+ Effect.fail(
120
+ transportError(request, new Error("node:http2 is not available in this runtime")),
121
+ ),
122
+ );
123
+ return;
124
+ }
125
+ let entry: { session: Session; active: number };
126
+ try {
127
+ entry = sessionFor(
128
+ http2,
129
+ socketPath === undefined ? { origin: url.origin } : { socketPath },
130
+ );
131
+ } catch (error) {
132
+ resume(Effect.fail(transportError(request, error)));
133
+ return;
134
+ }
135
+ if (entry.active++ === 0) entry.session.ref();
136
+ let settled = false;
137
+ const settle = () => {
138
+ if (settled) return;
139
+ settled = true;
140
+ if (--entry.active === 0 && !entry.session.destroyed) entry.session.unref();
141
+ };
142
+ const headers: Record<string, string> = {};
143
+ for (const [key, value] of Object.entries(request.headers)) {
144
+ if (!CONNECTION_HEADERS.has(key)) headers[key] = value;
145
+ }
146
+ const stream = entry.session.request({
147
+ ":method": request.method,
148
+ ":path": `${url.pathname}${url.search}`,
149
+ ...headers,
150
+ });
151
+ const onAbort = () => stream.close(http2.constants.NGHTTP2_CANCEL);
152
+ if (signal.aborted) onAbort();
153
+ else signal.addEventListener("abort", onAbort, { once: true });
154
+
155
+ let trailers: Trailers = {};
156
+ let resolveTrailers!: (t: Trailers) => void;
157
+ const trailersDone = new Promise<Trailers>((resolve) => (resolveTrailers = resolve));
158
+ stream.on("trailers", (incoming) => (trailers = plain(incoming)));
159
+
160
+ let started = false;
161
+ stream.on("response", (incoming) => {
162
+ started = true;
163
+ let open = true;
164
+ const body = new ReadableStream<Uint8Array>({
165
+ start(controller) {
166
+ stream.on("data", (chunk: Uint8Array) => {
167
+ if (open) controller.enqueue(new Uint8Array(chunk));
168
+ });
169
+ stream.on("end", () => {
170
+ if (open) controller.close();
171
+ open = false;
172
+ resolveTrailers(trailers);
173
+ });
174
+ stream.on("error", (error) => {
175
+ if (open) controller.error(error);
176
+ open = false;
177
+ resolveTrailers(trailers);
178
+ });
179
+ stream.on("close", () => {
180
+ settle();
181
+ signal.removeEventListener("abort", onAbort);
182
+ resolveTrailers(trailers);
183
+ });
184
+ },
185
+ cancel() {
186
+ open = false;
187
+ stream.close(http2.constants.NGHTTP2_CANCEL);
188
+ },
189
+ });
190
+ const status = Number(incoming[":status"] ?? 0);
191
+ if (!isResponseStatus(status)) {
192
+ stream.close(http2.constants.NGHTTP2_CANCEL);
193
+ resume(
194
+ Effect.fail(transportError(request, new Error(`invalid HTTP status ${status}`))),
195
+ );
196
+ return;
197
+ }
198
+ resume(
199
+ Effect.succeed(
200
+ respond(request, { status, headers: plain(incoming), body, trailers: trailersDone }),
201
+ ),
202
+ );
203
+ });
204
+ stream.on("error", (error) => {
205
+ if (started) return;
206
+ settle();
207
+ signal.removeEventListener("abort", onAbort);
208
+ resume(Effect.fail(transportError(request, error)));
209
+ });
210
+ const body = bodyOf(request);
211
+ stream.end(body === undefined ? undefined : body);
212
+ },
213
+ ),
214
+ );
215
+
216
+ /** An `HttpClient` that sends each request as an HTTP/2 stream. */
217
+ export const client: HttpClient.HttpClient = /*@__PURE__*/ make(undefined);
218
+
219
+ /**
220
+ * An `HttpClient` that sends each request as an HTTP/2 stream over the Unix
221
+ * domain socket at `path`, whatever the request's host. Requests share one
222
+ * session per socket.
223
+ *
224
+ * ```ts
225
+ * program.pipe(Effect.provide(NodeHttp2.unixLayer("/run/modal.sock")));
226
+ * ```
227
+ */
228
+ export const unixSocket = (path: string): HttpClient.HttpClient => make(path);
229
+
230
+ /** Send gRPC calls over HTTP/2 in this scope. */
231
+ export const layer: Layer.Layer<never> = /*@__PURE__*/ transportLayer(client);
232
+
233
+ /** Send gRPC calls over HTTP/2 on the Unix domain socket at `path` in this scope. */
234
+ export const unixLayer = (path: string): Layer.Layer<never> => transportLayer(unixSocket(path));
@@ -0,0 +1,118 @@
1
+ /**
2
+ * How gRPC calls reach a server.
3
+ *
4
+ * A transport is an Effect `HttpClient`: it sends the request
5
+ * `protocol-grpc` builds (`POST`, `application/grpc`, one frame) and returns
6
+ * the response with its body as a stream, so a server-streaming call reads
7
+ * each message as it arrives. gRPC puts the call's status in the trailers;
8
+ * a transport that can read them hands them over with {@link respond}, and
9
+ * the protocol reads them with {@link trailersOf} once the body has ended.
10
+ *
11
+ * By default `protocol-grpc` sends through the caller's `HttpClient`
12
+ * (`fetch`), which works where a proxy bridges HTTP/1.1 to gRPC (envoy) and
13
+ * puts the status in the headers. Provide a different transport for one
14
+ * scope with {@link layer}:
15
+ *
16
+ * - `@distilled.cloud/core/grpc-transport-node-http2` speaks HTTP/2 with
17
+ * `node:http2`, for servers that offer nothing else;
18
+ * - `@distilled.cloud/core/grpc-transport-cloudflare-sockets` speaks HTTP/1.1
19
+ * over a `cloudflare:sockets` TLS socket, for a Cloudflare Worker calling a
20
+ * gRPC server that is itself behind Cloudflare (a Worker's `fetch` to such
21
+ * a site takes Cloudflare's internal path, which resets gRPC upstreams);
22
+ * - `@distilled.cloud/core/grpc-transport-cloudflare-http2` speaks HTTP/2
23
+ * over a `cloudflare:sockets` socket, for a Cloudflare Worker calling a
24
+ * server that offers nothing else (workerd has no working `node:http2`).
25
+ *
26
+ * None is imported by this module, so a bundle only carries the ones it
27
+ * provides.
28
+ */
29
+ import * as Context from "effect/Context";
30
+ import * as Effect from "effect/Effect";
31
+ import type * as HttpClient from "effect/http/HttpClient";
32
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
33
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
34
+ import * as Layer from "effect/Layer";
35
+
36
+ /**
37
+ * The `HttpClient` gRPC calls go through. `undefined` (the default) sends
38
+ * through the caller's `HttpClient`.
39
+ */
40
+ export const GrpcTransport = /*@__PURE__*/ Context.Reference<HttpClient.HttpClient | undefined>(
41
+ "@distilled.cloud/core/GrpcTransport",
42
+ { defaultValue: () => undefined },
43
+ );
44
+
45
+ /** Send gRPC calls in this scope through `client`. */
46
+ export const layer = (client: HttpClient.HttpClient): Layer.Layer<never> =>
47
+ Layer.succeed(GrpcTransport, client);
48
+
49
+ /** Header and trailer names are lowercase; values as received. */
50
+ export type Trailers = Readonly<Record<string, string>>;
51
+
52
+ // Keyed by the request the transport sent, which a response keeps as
53
+ // `response.request` through the wrappers `HttpClient` puts around it.
54
+ const trailersByRequest = /*@__PURE__*/ new WeakMap<
55
+ HttpClientRequest.HttpClientRequest,
56
+ { readonly trailers: Promise<Trailers>; readonly reliable: boolean }
57
+ >();
58
+
59
+ /**
60
+ * Whether `status` is a final HTTP status a response can carry (200 to 599).
61
+ * A transport fails the call with a transport error for any other.
62
+ */
63
+ export const isResponseStatus = (status: number): boolean =>
64
+ Number.isInteger(status) && status >= 200 && status <= 599;
65
+
66
+ /**
67
+ * Build a transport's response: the status, the headers, the body as it
68
+ * arrives, and the trailers, which settle once the body has ended.
69
+ */
70
+ export const respond = (
71
+ request: HttpClientRequest.HttpClientRequest,
72
+ reply: {
73
+ readonly status: number;
74
+ readonly headers: Trailers;
75
+ readonly body: ReadableStream<Uint8Array>;
76
+ readonly trailers: Promise<Trailers>;
77
+ /**
78
+ * Whether the trailers always arrive. HTTP/2 delivers them end to end;
79
+ * over HTTP/1.1 a bridging proxy may drop them, so the protocol then
80
+ * treats a reply with messages and no status as OK.
81
+ * @default true
82
+ */
83
+ readonly reliableTrailers?: boolean;
84
+ },
85
+ ): HttpClientResponse.HttpClientResponse => {
86
+ // `Response` refuses a body on these, so the transport's is let go.
87
+ const bodiless = reply.status === 204 || reply.status === 205 || reply.status === 304;
88
+ if (bodiless) void reply.body.cancel().catch(() => undefined);
89
+ const response = HttpClientResponse.fromWeb(
90
+ request,
91
+ new Response(bodiless ? null : reply.body, { status: reply.status, headers: reply.headers }),
92
+ );
93
+ trailersByRequest.set(request, {
94
+ trailers: reply.trailers,
95
+ reliable: reply.reliableTrailers ?? true,
96
+ });
97
+ return response;
98
+ };
99
+
100
+ /**
101
+ * Whether `response` came from a transport whose trailers always arrive
102
+ * ({@link respond} with `reliableTrailers`), so a missing status is an error.
103
+ */
104
+ export const hasTrailers = (response: HttpClientResponse.HttpClientResponse): boolean =>
105
+ trailersByRequest.get(response.request)?.reliable === true;
106
+
107
+ /**
108
+ * The trailers of a response a transport built with {@link respond}, read
109
+ * after its body; empty for any other response (`fetch` exposes none).
110
+ */
111
+ export const trailersOf = (
112
+ response: HttpClientResponse.HttpClientResponse,
113
+ ): Effect.Effect<Trailers> => {
114
+ const entry = trailersByRequest.get(response.request);
115
+ return entry === undefined
116
+ ? Effect.succeed({})
117
+ : Effect.tryPromise(() => entry.trailers).pipe(Effect.orElseSucceed((): Trailers => ({})));
118
+ };