@distilled.cloud/core 1.0.0-rc.20 → 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.
Files changed (161) hide show
  1. package/README.md +33 -0
  2. package/lib/_bundle/aws.js +1 -1
  3. package/lib/_bundle/aws.js.map +1 -1
  4. package/lib/_bundle/base.js +2 -2
  5. package/lib/_bundle/base.js.map +1 -1
  6. package/lib/_bundle/graphql.js +2 -2
  7. package/lib/_bundle/graphql.js.map +1 -1
  8. package/lib/_bundle/grpc.js +2 -1
  9. package/lib/_bundle/grpc.js.map +1 -1
  10. package/lib/_bundle/rest.js +1 -1
  11. package/lib/_bundle/rest.js.map +1 -1
  12. package/lib/annotations.d.ts.map +1 -1
  13. package/lib/api.d.ts +71 -58
  14. package/lib/api.d.ts.map +1 -1
  15. package/lib/api.js +1 -1
  16. package/lib/category.d.ts +15 -12
  17. package/lib/category.d.ts.map +1 -1
  18. package/lib/chunks.d.ts.map +1 -1
  19. package/lib/config.d.ts +13 -0
  20. package/lib/config.d.ts.map +1 -1
  21. package/lib/crypto.d.ts.map +1 -1
  22. package/lib/error-category.d.ts.map +1 -1
  23. package/lib/errors.d.ts +35 -2
  24. package/lib/errors.d.ts.map +1 -1
  25. package/lib/errors.js +1 -1
  26. package/lib/graphql.d.ts +21 -4
  27. package/lib/graphql.d.ts.map +1 -1
  28. package/lib/graphql.types.d.ts +0 -1
  29. package/lib/graphql.types.d.ts.map +1 -1
  30. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -1
  31. package/lib/grpc-transport-cloudflare-http2.js +2 -2
  32. package/lib/grpc-transport-cloudflare-http2.js.map +1 -1
  33. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -1
  34. package/lib/grpc-transport-cloudflare-sockets.js +4 -4
  35. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -1
  36. package/lib/grpc-transport-node-http2.d.ts.map +1 -1
  37. package/lib/grpc-transport-node-http2.js +1 -1
  38. package/lib/grpc-transport-node-http2.js.map +1 -1
  39. package/lib/grpc-transport.d.ts +53 -18
  40. package/lib/grpc-transport.d.ts.map +1 -1
  41. package/lib/grpc-transport.js +1 -1
  42. package/lib/hpack.d.ts.map +1 -1
  43. package/lib/index.d.ts.map +1 -1
  44. package/lib/max-message-bytes.d.ts +42 -0
  45. package/lib/max-message-bytes.d.ts.map +1 -0
  46. package/lib/max-message-bytes.js +2 -0
  47. package/lib/max-message-bytes.js.map +1 -0
  48. package/lib/ndjson.d.ts +3 -0
  49. package/lib/ndjson.d.ts.map +1 -0
  50. package/lib/ndjson.js +2 -0
  51. package/lib/ndjson.js.map +1 -0
  52. package/lib/pagination.d.ts +4 -1
  53. package/lib/pagination.d.ts.map +1 -1
  54. package/lib/plain-values.d.ts +11 -0
  55. package/lib/plain-values.d.ts.map +1 -1
  56. package/lib/plain-values.js +1 -1
  57. package/lib/plain-values.js.map +1 -1
  58. package/lib/protobuf.d.ts +12 -19
  59. package/lib/protobuf.d.ts.map +1 -1
  60. package/lib/protobuf.js +1 -1
  61. package/lib/protocol-grpc.d.ts +47 -10
  62. package/lib/protocol-grpc.d.ts.map +1 -1
  63. package/lib/protocol-grpc.js +1 -1
  64. package/lib/protocol-http.d.ts +110 -8
  65. package/lib/protocol-http.d.ts.map +1 -1
  66. package/lib/protocol-http.js +1 -1
  67. package/lib/protocol-rest.d.ts +161 -37
  68. package/lib/protocol-rest.d.ts.map +1 -1
  69. package/lib/protocol-rest.js +1 -1
  70. package/lib/protocol.d.ts +113 -0
  71. package/lib/protocol.d.ts.map +1 -0
  72. package/lib/protocol.js +0 -0
  73. package/lib/query.d.ts.map +1 -1
  74. package/lib/response-validation-strict.d.ts.map +1 -1
  75. package/lib/response-validation.d.ts.map +1 -1
  76. package/lib/retry-after.d.ts +1 -1
  77. package/lib/retry-after.d.ts.map +1 -1
  78. package/lib/retry-state.d.ts +26 -0
  79. package/lib/retry-state.d.ts.map +1 -0
  80. package/lib/retry-state.js +2 -0
  81. package/lib/retry-state.js.map +1 -0
  82. package/lib/retry.d.ts +100 -20
  83. package/lib/retry.d.ts.map +1 -1
  84. package/lib/retry.js +1 -1
  85. package/lib/schema-lite-impl.d.ts +25 -4
  86. package/lib/schema-lite-impl.d.ts.map +1 -1
  87. package/lib/schema-lite-impl.js +1 -1
  88. package/lib/schema-lite-typed.d.ts.map +1 -1
  89. package/lib/schema-lite.d.ts +1 -0
  90. package/lib/schema-lite.d.ts.map +1 -1
  91. package/lib/schema-lite.js +1 -1
  92. package/lib/schema.d.ts.map +1 -1
  93. package/lib/sdk-error.d.ts +4 -0
  94. package/lib/sdk-error.d.ts.map +1 -1
  95. package/lib/send.d.ts +37 -0
  96. package/lib/send.d.ts.map +1 -0
  97. package/lib/send.js +2 -0
  98. package/lib/send.js.map +1 -0
  99. package/lib/sensitive.d.ts.map +1 -1
  100. package/lib/sensitive.js +1 -1
  101. package/lib/sensitive.js.map +1 -1
  102. package/lib/telemetry-debug.d.ts.map +1 -1
  103. package/lib/telemetry-debug.js +1 -1
  104. package/lib/telemetry-debug.js.map +1 -1
  105. package/lib/telemetry-hooks.d.ts.map +1 -1
  106. package/lib/telemetry-host-rules.d.ts.map +1 -1
  107. package/lib/telemetry-lambda-context.d.ts.map +1 -1
  108. package/lib/telemetry-message-context.d.ts.map +1 -1
  109. package/lib/telemetry-metrics.d.ts.map +1 -1
  110. package/lib/telemetry-metrics.js +1 -1
  111. package/lib/telemetry-metrics.js.map +1 -1
  112. package/lib/telemetry-name-template.d.ts.map +1 -1
  113. package/lib/telemetry-stream.d.ts.map +1 -1
  114. package/lib/telemetry-stream.js +1 -1
  115. package/lib/telemetry-stream.js.map +1 -1
  116. package/lib/telemetry-xray.d.ts.map +1 -1
  117. package/lib/telemetry.d.ts +29 -0
  118. package/lib/telemetry.d.ts.map +1 -1
  119. package/lib/telemetry.js +2 -2
  120. package/lib/telemetry.js.map +1 -1
  121. package/lib/token-cache.d.ts +31 -0
  122. package/lib/token-cache.d.ts.map +1 -0
  123. package/lib/token-cache.js +2 -0
  124. package/lib/token-cache.js.map +1 -0
  125. package/lib/trait.d.ts +24 -1
  126. package/lib/trait.d.ts.map +1 -1
  127. package/lib/trait.js +1 -1
  128. package/lib/unknown-error.d.ts.map +1 -1
  129. package/lib/xml.d.ts.map +1 -1
  130. package/package.json +3 -3
  131. package/src/api.ts +402 -209
  132. package/src/category.ts +21 -28
  133. package/src/config.ts +17 -1
  134. package/src/errors.ts +24 -2
  135. package/src/graphql.ts +65 -26
  136. package/src/graphql.types.ts +15 -0
  137. package/src/grpc-transport-cloudflare-http2.ts +374 -299
  138. package/src/grpc-transport-cloudflare-sockets.ts +150 -81
  139. package/src/grpc-transport-node-http2.ts +119 -46
  140. package/src/grpc-transport.ts +211 -42
  141. package/src/max-message-bytes.ts +58 -0
  142. package/src/ndjson.ts +55 -0
  143. package/src/pagination.ts +26 -15
  144. package/src/plain-values.ts +30 -1
  145. package/src/protobuf.ts +40 -5
  146. package/src/protocol-grpc.ts +518 -348
  147. package/src/protocol-http.ts +474 -100
  148. package/src/protocol-rest.ts +580 -140
  149. package/src/protocol.ts +150 -0
  150. package/src/response-validation-strict.ts +9 -3
  151. package/src/retry-after.ts +1 -1
  152. package/src/retry-state.ts +105 -0
  153. package/src/retry.ts +176 -47
  154. package/src/schema-lite-impl.ts +81 -10
  155. package/src/schema-lite.ts +1 -0
  156. package/src/sdk-error.ts +4 -0
  157. package/src/send.ts +156 -0
  158. package/src/sensitive.ts +49 -15
  159. package/src/telemetry.ts +2 -34
  160. package/src/token-cache.ts +117 -0
  161. package/src/trait.ts +34 -1
@@ -15,18 +15,23 @@
15
15
  *
16
16
  * Each request opens its own socket with `connection: close`: workerd ties
17
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.
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.
22
24
  */
25
+ import * as Deferred from "effect/Deferred";
23
26
  import * as Effect from "effect/Effect";
24
27
  import * as HttpClient from "effect/http/HttpClient";
25
28
  import * as HttpClientError from "effect/http/HttpClientError";
26
29
  import type * as HttpClientRequest from "effect/http/HttpClientRequest";
27
30
  import type * as Layer from "effect/Layer";
31
+ import * as Stream from "effect/Stream";
28
32
  import {
29
33
  isResponseStatus,
34
+ hasNoBody,
30
35
  layer as transportLayer,
31
36
  respond,
32
37
  type Trailers,
@@ -36,20 +41,33 @@ import {
36
41
  type Connect = (
37
42
  address: { hostname: string; port: number },
38
43
  options: { secureTransport: "on" | "off"; allowHalfOpen: boolean },
39
- ) => {
44
+ ) => Socket;
45
+
46
+ interface Socket {
40
47
  readonly readable: ReadableStream<Uint8Array>;
41
48
  readonly writable: WritableStream<Uint8Array>;
42
49
  close(): Promise<void>;
43
- };
50
+ }
44
51
 
45
52
  // A non-literal specifier keeps bundlers from resolving it for runtimes
46
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
+
47
62
  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
- ));
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
+ );
53
71
 
54
72
  /** Headers this transport sets itself. */
55
73
  const FRAMING_HEADERS = new Set([
@@ -202,97 +220,148 @@ const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unk
202
220
  }),
203
221
  });
204
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
+
205
252
  /** Send `request` and read the response head; the body streams afterwards. */
206
- const send = async (
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 = (
207
269
  request: HttpClientRequest.HttpClientRequest,
208
270
  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();
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();
229
284
 
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);
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>();
243
306
 
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 (;;) {
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) {
255
312
  let input: Uint8Array;
256
313
  if (pending !== undefined) {
257
314
  input = pending;
258
315
  pending = undefined;
259
316
  } else {
260
- const { value, done } = await reader.read();
317
+ const { value, done } = yield* read;
261
318
  if (done) {
262
- finish();
263
- if (framing.end()) controller.close();
264
- else controller.error(new ProtocolViolation("connection closed mid-body"));
265
- return;
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;
266
325
  }
267
326
  input = value;
268
327
  }
269
- const { data, done } = framing.feed(input);
270
- for (const chunk of data) controller.enqueue(chunk);
328
+ const { data, done } = yield* attempt(() => framing.feed(input));
271
329
  if (done) {
272
- finish();
273
- controller.close();
274
- return;
330
+ finished = true;
331
+ yield* Deferred.succeed(trailers, framing.trailers);
332
+ return data;
275
333
  }
276
- if (data.length > 0) return;
334
+ if (data.length > 0) return data;
277
335
  }
278
- },
279
- cancel() {
280
- finish();
281
- },
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
+ });
282
360
  });
283
- // HTTP/1.1: a bridging proxy may drop the trailers.
284
- return { status, headers, body: stream, trailers, reliableTrailers: false };
285
- };
286
361
 
287
362
  /** An `HttpClient` that sends each request over its own `cloudflare:sockets` socket. */
288
363
  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
- ),
364
+ Effect.mapError(send(request, url, signal), (cause) => transportError(request, cause)),
296
365
  );
297
366
 
298
367
  /** Send gRPC calls over `cloudflare:sockets` in this scope. */
@@ -11,19 +11,31 @@
11
11
  * Requests share one session per origin; an idle session doesn't keep the
12
12
  * process alive. {@link unixSocket} sends them over a Unix domain socket
13
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.
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.
17
22
  */
23
+ import * as Cause from "effect/Cause";
24
+ import * as Deferred from "effect/Deferred";
18
25
  import * as Effect from "effect/Effect";
19
26
  import * as HttpClient from "effect/http/HttpClient";
20
27
  import * as HttpClientError from "effect/http/HttpClientError";
21
28
  import type * as HttpClientRequest from "effect/http/HttpClientRequest";
22
29
  import type * as HttpClientResponse from "effect/http/HttpClientResponse";
23
30
  import type * as Layer from "effect/Layer";
31
+ import * as Queue from "effect/Queue";
32
+ import * as Stream from "effect/Stream";
24
33
  import {
25
34
  isResponseStatus,
35
+ hasNoBody,
26
36
  layer as transportLayer,
37
+ resetReply,
38
+ resetTrailers,
27
39
  respond,
28
40
  type Trailers,
29
41
  } from "./grpc-transport.ts";
@@ -105,14 +117,31 @@ const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unk
105
117
  const bodyOf = (request: HttpClientRequest.HttpClientRequest): Uint8Array | undefined =>
106
118
  request.body._tag === "Uint8Array" ? request.body.body : undefined;
107
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
+
108
130
  /**
109
131
  * An `HttpClient` that sends each request as an HTTP/2 stream, to the
110
132
  * request's origin or to `socketPath`.
111
133
  */
112
134
  const make = (socketPath: string | undefined): HttpClient.HttpClient =>
113
135
  HttpClient.make((request, url, signal) =>
114
- Effect.callback<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>(
115
- (resume) => {
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) => {
116
145
  const http2 = http2Module();
117
146
  if (http2 === undefined) {
118
147
  resume(
@@ -148,45 +177,67 @@ const make = (socketPath: string | undefined): HttpClient.HttpClient =>
148
177
  ":path": `${url.pathname}${url.search}`,
149
178
  ...headers,
150
179
  });
180
+ // The response is dropped unread, its scope closed, or the call interrupted.
151
181
  const onAbort = () => stream.close(http2.constants.NGHTTP2_CANCEL);
152
182
  if (signal.aborted) onAbort();
153
183
  else signal.addEventListener("abort", onAbort, { once: true });
154
184
 
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
-
185
+ let received: Trailers = {};
186
+ let ended = false;
160
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
+
161
239
  stream.on("response", (incoming) => {
162
240
  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
241
  const status = Number(incoming[":status"] ?? 0);
191
242
  if (!isResponseStatus(status)) {
192
243
  stream.close(http2.constants.NGHTTP2_CANCEL);
@@ -195,22 +246,44 @@ const make = (socketPath: string | undefined): HttpClient.HttpClient =>
195
246
  );
196
247
  return;
197
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);
198
264
  resume(
199
- Effect.succeed(
200
- respond(request, { status, headers: plain(incoming), body, trailers: trailersDone }),
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
+ ),
201
275
  ),
202
276
  );
203
277
  });
204
- stream.on("error", (error) => {
205
- if (started) return;
206
- settle();
207
- signal.removeEventListener("abort", onAbort);
208
- resume(Effect.fail(transportError(request, error)));
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);
209
282
  });
210
283
  const body = bodyOf(request);
211
284
  stream.end(body === undefined ? undefined : body);
212
- },
213
- ),
285
+ });
286
+ }),
214
287
  );
215
288
 
216
289
  /** An `HttpClient` that sends each request as an HTTP/2 stream. */