@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
@@ -18,17 +18,24 @@
18
18
  *
19
19
  * Each request opens its own connection and uses one stream on it: workerd
20
20
  * ties a socket to the request that opened it, so connections are never
21
- * pooled across events. The body streams as it arrives and the trailers
22
- * settle when it ends.
21
+ * pooled across events. The exchange is Effect code: the body is an Effect
22
+ * `Stream` that reads frames off the socket in the caller's fiber and closes
23
+ * it when the stream ends or the reader stops, and the trailers settle when
24
+ * it ends.
23
25
  */
26
+ import * as Deferred from "effect/Deferred";
24
27
  import * as Effect from "effect/Effect";
25
28
  import * as HttpClient from "effect/http/HttpClient";
26
29
  import * as HttpClientError from "effect/http/HttpClientError";
27
30
  import type * as HttpClientRequest from "effect/http/HttpClientRequest";
28
31
  import type * as Layer from "effect/Layer";
32
+ import * as Stream from "effect/Stream";
29
33
  import {
30
34
  isResponseStatus,
31
35
  layer as transportLayer,
36
+ type Reply,
37
+ hasNoBody,
38
+ resetTrailers,
32
39
  respond,
33
40
  type Trailers,
34
41
  } from "./grpc-transport.ts";
@@ -38,20 +45,33 @@ import { encode, type HeaderField, makeDecoder } from "./hpack.ts";
38
45
  type Connect = (
39
46
  address: { hostname: string; port: number },
40
47
  options: { secureTransport: "on" | "off"; allowHalfOpen: boolean },
41
- ) => {
48
+ ) => Socket;
49
+
50
+ interface Socket {
42
51
  readonly readable: ReadableStream<Uint8Array>;
43
52
  readonly writable: WritableStream<Uint8Array>;
44
53
  close(): Promise<void>;
45
- };
54
+ }
46
55
 
47
56
  // A non-literal specifier keeps bundlers from resolving it for runtimes
48
57
  // other than workerd, which resolves its built-in modules at runtime.
58
+ /** Run `f`, failing with what it throws as is. */
59
+ const attempt = <A>(f: () => A): Effect.Effect<A, unknown> =>
60
+ Effect.try({ try: f, catch: (cause) => cause });
61
+
62
+ /** Await `f`, failing with what it rejects with as is. */
63
+ const attemptPromise = <A>(f: () => PromiseLike<A>): Effect.Effect<A, unknown> =>
64
+ Effect.tryPromise({ try: () => f(), catch: (cause) => cause });
65
+
49
66
  const SOCKETS_MODULE = "cloudflare:sockets";
50
- let sockets: Promise<Connect> | undefined;
51
- const connectFn = () =>
52
- (sockets ??= (import(SOCKETS_MODULE) as Promise<{ connect: Connect }>).then(
53
- (module) => module.connect,
54
- ));
67
+ let connectFn: Connect | undefined;
68
+ const loadConnect: Effect.Effect<Connect, unknown> = /*@__PURE__*/ Effect.suspend(() =>
69
+ connectFn !== undefined
70
+ ? Effect.succeed(connectFn)
71
+ : attemptPromise(() => import(SOCKETS_MODULE) as Promise<{ connect: Connect }>).pipe(
72
+ Effect.map((module) => (connectFn = module.connect)),
73
+ ),
74
+ );
55
75
 
56
76
  /** Headers HTTP/2 forbids or derives itself. */
57
77
  const CONNECTION_HEADERS = new Set([
@@ -175,319 +195,374 @@ const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unk
175
195
  }),
176
196
  });
177
197
 
178
- /** Send `request` and read the response head; the body streams afterwards. */
179
- const send = async (
180
- request: HttpClientRequest.HttpClientRequest,
181
- url: URL,
182
- signal: AbortSignal,
183
- ) => {
184
- // A gRPC request is one frame of octets. Any other body would be left
185
- // behind, so it is refused before a connection is opened.
186
- if (request.body._tag !== "Uint8Array" && request.body._tag !== "Empty") {
187
- throw new ProtocolViolation(`a ${request.body._tag} request body cannot be sent`);
188
- }
189
- const connect = await connectFn();
190
- const tls = url.protocol === "https:";
191
- const socket = connect(
192
- { hostname: url.hostname, port: Number(url.port || (tls ? 443 : 80)) },
193
- { secureTransport: tls ? "on" : "off", allowHalfOpen: false },
194
- );
198
+ /**
199
+ * Close `socket` once, from whichever comes first: the body ends, its reader
200
+ * stops, the exchange fails, or `signal` aborts.
201
+ */
202
+ const closer = (socket: Socket, signal: AbortSignal): Effect.Effect<void> => {
195
203
  let closed = false;
196
- const close = () => {
197
- if (closed) return;
204
+ const markClosed = () => {
205
+ if (closed) return false;
198
206
  closed = true;
199
- signal.removeEventListener("abort", close);
200
- void socket.close().catch(() => undefined);
207
+ signal.removeEventListener("abort", onAbort);
208
+ return true;
201
209
  };
202
- signal.addEventListener("abort", close);
203
- // A call that fails before it returns a body leaves no one to close the
204
- // socket. That includes a head `Response` refuses (a header name that is
205
- // no token).
206
- return exchange(request, url, socket, close)
207
- .then((reply) => respond(request, reply))
208
- .catch((cause: unknown) => {
209
- close();
210
- throw cause;
211
- });
210
+ const onAbort = () => {
211
+ // Only for a response nobody reads any more (dropped unread, or its
212
+ // scope closed): no fiber is left to run the close in, and no reader to
213
+ // see that a close failed, which only happens to a socket that already
214
+ // failed.
215
+ if (markClosed()) void socket.close().catch(() => undefined);
216
+ };
217
+ signal.addEventListener("abort", onAbort, { once: true });
218
+ return Effect.suspend(() =>
219
+ markClosed()
220
+ ? attemptPromise(() => socket.close()).pipe(
221
+ Effect.ignore({ log: "Debug", message: "closing a cloudflare:sockets socket failed" }),
222
+ )
223
+ : Effect.void,
224
+ );
212
225
  };
213
226
 
227
+ /** Send `request` and read the response head; the body streams afterwards. */
228
+ const send = (request: HttpClientRequest.HttpClientRequest, url: URL, signal: AbortSignal) =>
229
+ Effect.gen(function* () {
230
+ // A gRPC request is one frame of octets. Any other body would be left
231
+ // behind, so it is refused before a connection is opened.
232
+ if (request.body._tag !== "Uint8Array" && request.body._tag !== "Empty") {
233
+ return yield* Effect.fail(
234
+ new ProtocolViolation(`a ${request.body._tag} request body cannot be sent`),
235
+ );
236
+ }
237
+ const connect = yield* loadConnect;
238
+ const tls = url.protocol === "https:";
239
+ const socket = yield* attempt(() =>
240
+ connect(
241
+ { hostname: url.hostname, port: Number(url.port || (tls ? 443 : 80)) },
242
+ { secureTransport: tls ? "on" : "off", allowHalfOpen: false },
243
+ ),
244
+ );
245
+ const close = closer(socket, signal);
246
+ // A call that fails before it returns a body leaves no one else to close the socket.
247
+ return yield* exchange(request, url, socket, close).pipe(
248
+ Effect.flatMap((reply) => respond(request, reply)),
249
+ Effect.onError(() => close),
250
+ );
251
+ });
252
+
214
253
  /** One request and its response on stream 1 of a fresh connection. */
215
- const exchange = async (
254
+ const exchange = (
216
255
  request: HttpClientRequest.HttpClientRequest,
217
256
  url: URL,
218
- socket: ReturnType<Connect>,
219
- close: () => void,
220
- ) => {
221
- const tls = url.protocol === "https:";
222
- const writer = socket.writable.getWriter();
223
- const reader = socket.readable.getReader();
224
- const hpack = makeDecoder();
225
- // What the server lets this end send.
226
- let sendWindow = DEFAULT_WINDOW;
227
- let streamSendWindow = DEFAULT_WINDOW;
228
- let peerInitialWindow = DEFAULT_WINDOW;
229
- let peerMaxFrame = DEFAULT_MAX_FRAME;
230
- // Reply octets read and not yet handed back to the server's windows.
231
- let unacknowledged = 0;
232
-
233
- let responseHeaders: Record<string, string> | undefined;
234
- let status = 0;
235
- let trailers: Record<string, string> = {};
236
- /** The server ended the stream; nothing more arrives on it. */
237
- let ended = false;
238
- let failure: { readonly cause: unknown } | undefined;
239
- const chunks: Uint8Array[] = [];
240
-
241
- // A header block arriving over HEADERS and CONTINUATION frames.
242
- let block: { readonly fragments: Uint8Array[]; readonly endStream: boolean } | undefined;
243
- let buffered: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
244
-
245
- // The first failure ends the stream, so there is never a second.
246
- const fail = (message: string) => {
247
- failure = { cause: new ProtocolViolation(message) };
248
- ended = true;
249
- };
250
-
251
- const onHeaders = (fields: ReadonlyArray<HeaderField>, endStream: boolean) => {
252
- // A map, so a header named like something every object has (`constructor`,
253
- // `__proto__`) is a header like any other.
254
- const joined = new Map<string, string>();
255
- let pseudoStatus: string | undefined;
256
- for (const [name, value] of fields) {
257
- if (name === ":status") pseudoStatus = value;
258
- else if (!name.startsWith(":")) {
259
- const previous = joined.get(name);
260
- joined.set(name, previous === undefined ? value : `${previous}, ${value}`);
261
- }
262
- }
263
- const headers: Record<string, string> = Object.fromEntries(joined);
264
- if (responseHeaders === undefined) {
265
- const code = /^[0-9]{3}$/.test(pseudoStatus ?? "") ? Number(pseudoStatus) : Number.NaN;
266
- // An interim response (100 Continue) precedes the real one.
267
- if (code >= 100 && code < 200 && !endStream) return;
268
- if (!isResponseStatus(code)) {
269
- return fail(`invalid HTTP status ${pseudoStatus ?? "(none)"}`);
270
- }
271
- status = code;
272
- responseHeaders = headers;
273
- } else {
274
- // RFC 9113 section 8.1: a second header block is the trailers.
275
- if (!endStream) return fail("the trailers do not end the stream");
276
- trailers = headers;
277
- }
278
- if (endStream) ended = true;
279
- };
280
-
281
- const onFrame = async (type: number, flags: number, stream: number, payload: Uint8Array) => {
282
- // RFC 9113 section 6.10: nothing may come between the frames of a block.
283
- if (block !== undefined && (type !== CONTINUATION || stream !== STREAM)) {
284
- return fail("a header block was interrupted by another frame");
285
- }
286
- // Push is disabled, so the server has no other stream to send these on.
287
- if (stream !== STREAM && (type === DATA || type === HEADERS || type === CONTINUATION)) {
288
- return fail(`a frame on stream ${stream}, which this end did not open`);
289
- }
290
- switch (type) {
291
- case DATA: {
292
- if (responseHeaders === undefined) return fail("DATA before the response headers");
293
- const start = (flags & PADDED) !== 0 ? 1 : 0;
294
- const end = payload.length - (start === 1 ? (payload[0] ?? 0) : 0);
295
- if (end < start) return fail("DATA padding exceeds the frame");
296
- if (end > start) chunks.push(payload.subarray(start, end));
297
- if ((flags & END_STREAM) !== 0) ended = true;
298
- // Padding counts against the window too.
299
- unacknowledged += payload.length;
300
- if (unacknowledged >= WINDOW_STEP && !ended) {
301
- const increment = uint32Payload(unacknowledged);
302
- unacknowledged = 0;
303
- await writer.write(
304
- concat([
305
- frame(WINDOW_UPDATE, 0, 0, increment),
306
- frame(WINDOW_UPDATE, 0, STREAM, increment),
307
- ]),
308
- );
257
+ socket: Socket,
258
+ close: Effect.Effect<void>,
259
+ ): Effect.Effect<Reply, unknown> =>
260
+ Effect.suspend(() => {
261
+ const tls = url.protocol === "https:";
262
+ const writer = socket.writable.getWriter();
263
+ const reader = socket.readable.getReader();
264
+ const write = (bytes: Uint8Array) => attemptPromise(() => writer.write(bytes));
265
+ const read = attemptPromise(() => reader.read());
266
+ const hpack = makeDecoder();
267
+ // What the server lets this end send.
268
+ let sendWindow = DEFAULT_WINDOW;
269
+ let streamSendWindow = DEFAULT_WINDOW;
270
+ let peerInitialWindow = DEFAULT_WINDOW;
271
+ let peerMaxFrame = DEFAULT_MAX_FRAME;
272
+ // Reply octets read and not yet handed back to the server's windows.
273
+ let unacknowledged = 0;
274
+
275
+ let responseHeaders: Record<string, string> | undefined;
276
+ let status = 0;
277
+ let trailers: Record<string, string> = {};
278
+ /** The server ended the stream; nothing more arrives on it. */
279
+ let ended = false;
280
+ let failure: { readonly cause: unknown } | undefined;
281
+ const chunks: Uint8Array[] = [];
282
+
283
+ // A header block arriving over HEADERS and CONTINUATION frames.
284
+ let block: { readonly fragments: Uint8Array[]; readonly endStream: boolean } | undefined;
285
+ let buffered: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
286
+
287
+ // The first failure ends the stream, so there is never a second.
288
+ const fail = (message: string) => {
289
+ failure = { cause: new ProtocolViolation(message) };
290
+ ended = true;
291
+ };
292
+
293
+ const onHeaders = (fields: ReadonlyArray<HeaderField>, endStream: boolean) => {
294
+ // A map, so a header named like something every object has (`constructor`,
295
+ // `__proto__`) is a header like any other.
296
+ const joined = new Map<string, string>();
297
+ let pseudoStatus: string | undefined;
298
+ for (const [name, value] of fields) {
299
+ if (name === ":status") pseudoStatus = value;
300
+ else if (!name.startsWith(":")) {
301
+ const previous = joined.get(name);
302
+ joined.set(name, previous === undefined ? value : `${previous}, ${value}`);
309
303
  }
310
- return;
311
- }
312
- case HEADERS: {
313
- const padded = (flags & PADDED) !== 0;
314
- const start = (padded ? 1 : 0) + ((flags & PRIORITY) !== 0 ? 5 : 0);
315
- const end = payload.length - (padded ? (payload[0] ?? 0) : 0);
316
- if (start > end) return fail("HEADERS padding or priority exceeds the frame");
317
- block = {
318
- fragments: [payload.subarray(start, end)],
319
- endStream: (flags & END_STREAM) !== 0,
320
- };
321
- break;
322
304
  }
323
- case CONTINUATION: {
324
- if (block === undefined) return fail("CONTINUATION without a header block");
325
- block.fragments.push(payload);
326
- break;
327
- }
328
- case SETTINGS: {
329
- if ((flags & ACK) !== 0) return;
330
- if (payload.length % 6 !== 0) return fail("malformed SETTINGS");
331
- for (let at = 0; at < payload.length; at += 6) {
332
- const id = (payload[at]! << 8) | payload[at + 1]!;
333
- const value = uint32(payload, at + 2);
334
- if (id === SETTINGS_INITIAL_WINDOW_SIZE) {
335
- if (value > MAX_WINDOW) return fail("SETTINGS_INITIAL_WINDOW_SIZE exceeds the limit");
336
- // The change applies to the stream's window as it stands, which
337
- // may leave it negative.
338
- streamSendWindow += value - peerInitialWindow;
339
- peerInitialWindow = value;
340
- } else if (id === SETTINGS_MAX_FRAME_SIZE) {
341
- if (value < DEFAULT_MAX_FRAME || value > MAX_FRAME_LIMIT) {
342
- return fail("SETTINGS_MAX_FRAME_SIZE is out of range");
343
- }
344
- peerMaxFrame = value;
345
- }
305
+ const headers: Record<string, string> = Object.fromEntries(joined);
306
+ if (responseHeaders === undefined) {
307
+ const code = /^[0-9]{3}$/.test(pseudoStatus ?? "") ? Number(pseudoStatus) : Number.NaN;
308
+ // An interim response (100 Continue) precedes the real one.
309
+ if (code >= 100 && code < 200 && !endStream) return;
310
+ if (!isResponseStatus(code)) {
311
+ return fail(`invalid HTTP status ${pseudoStatus ?? "(none)"}`);
346
312
  }
347
- await writer.write(frame(SETTINGS, ACK, 0, new Uint8Array(0)));
348
- return;
349
- }
350
- case PING: {
351
- if (payload.length !== 8) return fail("malformed PING");
352
- if ((flags & ACK) === 0) await writer.write(frame(PING, ACK, 0, payload));
353
- return;
354
- }
355
- case WINDOW_UPDATE: {
356
- if (payload.length !== 4) return fail("malformed WINDOW_UPDATE");
357
- const increment = uint32(payload, 0) % 0x80000000;
358
- if (stream === 0) sendWindow += increment;
359
- else if (stream === STREAM) streamSendWindow += increment;
360
- return;
313
+ status = code;
314
+ responseHeaders = headers;
315
+ } else {
316
+ // RFC 9113 section 8.1: a second header block is the trailers.
317
+ if (!endStream) return fail("the trailers do not end the stream");
318
+ trailers = headers;
361
319
  }
362
- case RST_STREAM: {
363
- if (payload.length !== 4) return fail("malformed RST_STREAM");
364
- if (stream === STREAM) {
365
- fail(`the server reset the stream (HTTP/2 error ${uint32(payload, 0)})`);
320
+ if (endStream) ended = true;
321
+ };
322
+
323
+ const onFrame = (
324
+ type: number,
325
+ flags: number,
326
+ stream: number,
327
+ payload: Uint8Array,
328
+ ): Effect.Effect<void, unknown> =>
329
+ Effect.gen(function* () {
330
+ // RFC 9113 section 6.10: nothing may come between the frames of a block.
331
+ if (block !== undefined && (type !== CONTINUATION || stream !== STREAM)) {
332
+ return fail("a header block was interrupted by another frame");
366
333
  }
367
- return;
368
- }
369
- case GOAWAY: {
370
- if (payload.length < 8) return fail("malformed GOAWAY");
371
- const lastStream = uint32(payload, 0) % 0x80000000;
372
- const code = uint32(payload, 4);
373
- // A graceful shutdown (code 0) that still covers this stream lets it finish.
374
- if (code !== 0 || lastStream < STREAM) {
375
- fail(`the server closed the connection (HTTP/2 error ${code})`);
334
+ // Push is disabled, so the server has no other stream to send these on.
335
+ if (stream !== STREAM && (type === DATA || type === HEADERS || type === CONTINUATION)) {
336
+ return fail(`a frame on stream ${stream}, which this end did not open`);
376
337
  }
377
- return;
338
+ switch (type) {
339
+ case DATA: {
340
+ if (responseHeaders === undefined) return fail("DATA before the response headers");
341
+ const start = (flags & PADDED) !== 0 ? 1 : 0;
342
+ const end = payload.length - (start === 1 ? (payload[0] ?? 0) : 0);
343
+ if (end < start) return fail("DATA padding exceeds the frame");
344
+ if (end > start) chunks.push(payload.subarray(start, end));
345
+ if ((flags & END_STREAM) !== 0) ended = true;
346
+ // Padding counts against the window too.
347
+ unacknowledged += payload.length;
348
+ if (unacknowledged >= WINDOW_STEP && !ended) {
349
+ const increment = uint32Payload(unacknowledged);
350
+ unacknowledged = 0;
351
+ yield* write(
352
+ concat([
353
+ frame(WINDOW_UPDATE, 0, 0, increment),
354
+ frame(WINDOW_UPDATE, 0, STREAM, increment),
355
+ ]),
356
+ );
357
+ }
358
+ return;
359
+ }
360
+ case HEADERS: {
361
+ const padded = (flags & PADDED) !== 0;
362
+ const start = (padded ? 1 : 0) + ((flags & PRIORITY) !== 0 ? 5 : 0);
363
+ const end = payload.length - (padded ? (payload[0] ?? 0) : 0);
364
+ if (start > end) return fail("HEADERS padding or priority exceeds the frame");
365
+ block = {
366
+ fragments: [payload.subarray(start, end)],
367
+ endStream: (flags & END_STREAM) !== 0,
368
+ };
369
+ break;
370
+ }
371
+ case CONTINUATION: {
372
+ if (block === undefined) return fail("CONTINUATION without a header block");
373
+ block.fragments.push(payload);
374
+ break;
375
+ }
376
+ case SETTINGS: {
377
+ if ((flags & ACK) !== 0) return;
378
+ if (payload.length % 6 !== 0) return fail("malformed SETTINGS");
379
+ for (let at = 0; at < payload.length; at += 6) {
380
+ const id = (payload[at]! << 8) | payload[at + 1]!;
381
+ const value = uint32(payload, at + 2);
382
+ if (id === SETTINGS_INITIAL_WINDOW_SIZE) {
383
+ if (value > MAX_WINDOW)
384
+ return fail("SETTINGS_INITIAL_WINDOW_SIZE exceeds the limit");
385
+ // The change applies to the stream's window as it stands, which
386
+ // may leave it negative.
387
+ streamSendWindow += value - peerInitialWindow;
388
+ peerInitialWindow = value;
389
+ } else if (id === SETTINGS_MAX_FRAME_SIZE) {
390
+ if (value < DEFAULT_MAX_FRAME || value > MAX_FRAME_LIMIT) {
391
+ return fail("SETTINGS_MAX_FRAME_SIZE is out of range");
392
+ }
393
+ peerMaxFrame = value;
394
+ }
395
+ }
396
+ yield* write(frame(SETTINGS, ACK, 0, new Uint8Array(0)));
397
+ return;
398
+ }
399
+ case PING: {
400
+ if (payload.length !== 8) return fail("malformed PING");
401
+ if ((flags & ACK) === 0) yield* write(frame(PING, ACK, 0, payload));
402
+ return;
403
+ }
404
+ case WINDOW_UPDATE: {
405
+ if (payload.length !== 4) return fail("malformed WINDOW_UPDATE");
406
+ const increment = uint32(payload, 0) % 0x80000000;
407
+ if (stream === 0) sendWindow += increment;
408
+ else if (stream === STREAM) streamSendWindow += increment;
409
+ return;
410
+ }
411
+ case RST_STREAM: {
412
+ if (payload.length !== 4) return fail("malformed RST_STREAM");
413
+ if (stream !== STREAM) return;
414
+ // A reset ends the call with the gRPC status its code maps to;
415
+ // before the response headers, as a reply of trailers alone.
416
+ if (responseHeaders === undefined) {
417
+ status = 200;
418
+ responseHeaders = { "content-type": "application/grpc" };
419
+ }
420
+ trailers = { ...resetTrailers(uint32(payload, 0)) };
421
+ ended = true;
422
+ return;
423
+ }
424
+ case GOAWAY: {
425
+ if (payload.length < 8) return fail("malformed GOAWAY");
426
+ const lastStream = uint32(payload, 0) % 0x80000000;
427
+ const code = uint32(payload, 4);
428
+ // A graceful shutdown (code 0) that still covers this stream lets it finish.
429
+ if (code !== 0 || lastStream < STREAM) {
430
+ fail(`the server closed the connection (HTTP/2 error ${code})`);
431
+ }
432
+ return;
433
+ }
434
+ case PUSH_PROMISE:
435
+ return fail("the server pushed a stream with push disabled");
436
+ default:
437
+ // PRIORITY and frames this end doesn't know are ignored.
438
+ return;
439
+ }
440
+ if ((flags & END_HEADERS) === 0) return;
441
+ const complete = block;
442
+ block = undefined;
443
+ const fields = yield* attempt(() => hpack.decode(concat(complete.fragments)));
444
+ onHeaders(fields, complete.endStream);
445
+ });
446
+
447
+ /**
448
+ * Read from the socket and handle the complete frames that arrived, up to
449
+ * the end of the stream: the connection carries nothing else, so what
450
+ * follows is never read. Only called while the stream is open.
451
+ */
452
+ const step: Effect.Effect<void, unknown> = Effect.gen(function* () {
453
+ const { value, done } = yield* read;
454
+ if (done) return fail("connection closed before the response ended");
455
+ buffered = buffered.length === 0 ? value : concat([buffered, value]);
456
+ while (buffered.length >= 9) {
457
+ const length = (buffered[0]! << 16) | (buffered[1]! << 8) | buffered[2]!;
458
+ // This end never raises SETTINGS_MAX_FRAME_SIZE.
459
+ if (length > DEFAULT_MAX_FRAME) return fail(`a ${length}-octet frame exceeds the limit`);
460
+ if (buffered.length < 9 + length) break;
461
+ const payload = buffered.subarray(9, 9 + length);
462
+ const type = buffered[3]!;
463
+ const flags = buffered[4]!;
464
+ const stream = uint32(buffered, 5) % 0x80000000;
465
+ buffered = buffered.subarray(9 + length);
466
+ yield* onFrame(type, flags, stream, payload);
467
+ if (ended) return;
378
468
  }
379
- case PUSH_PROMISE:
380
- return fail("the server pushed a stream with push disabled");
381
- default:
382
- // PRIORITY and frames this end doesn't know are ignored.
383
- return;
384
- }
385
- if ((flags & END_HEADERS) === 0) return;
386
- const complete = block;
387
- block = undefined;
388
- onHeaders(hpack.decode(concat(complete.fragments)), complete.endStream);
389
- };
390
-
391
- /**
392
- * Read from the socket and handle the complete frames that arrived, up to
393
- * the end of the stream: the connection carries nothing else, so what
394
- * follows is never read. Only called while the stream is open.
395
- */
396
- const step = async () => {
397
- const { value, done } = await reader.read();
398
- if (done) return fail("connection closed before the response ended");
399
- buffered = buffered.length === 0 ? value : concat([buffered, value]);
400
- while (buffered.length >= 9) {
401
- const length = (buffered[0]! << 16) | (buffered[1]! << 8) | buffered[2]!;
402
- // This end never raises SETTINGS_MAX_FRAME_SIZE.
403
- if (length > DEFAULT_MAX_FRAME) return fail(`a ${length}-octet frame exceeds the limit`);
404
- if (buffered.length < 9 + length) break;
405
- const payload = buffered.subarray(9, 9 + length);
406
- const type = buffered[3]!;
407
- const flags = buffered[4]!;
408
- const stream = uint32(buffered, 5) % 0x80000000;
409
- buffered = buffered.subarray(9 + length);
410
- await onFrame(type, flags, stream, payload);
411
- if (ended) return;
412
- }
413
- };
414
-
415
- const body = request.body._tag === "Uint8Array" ? request.body.body : new Uint8Array(0);
416
- const fields: HeaderField[] = [
417
- [":method", request.method],
418
- [":scheme", tls ? "https" : "http"],
419
- [":path", `${url.pathname}${url.search}`],
420
- [":authority", url.host],
421
- ];
422
- for (const [key, value] of Object.entries(request.headers)) {
423
- if (!CONNECTION_HEADERS.has(key)) fields.push([key, value]);
424
- }
425
- await writer.write(
426
- concat([
427
- PREFACE,
428
- settings([
429
- [SETTINGS_ENABLE_PUSH, 0],
430
- [SETTINGS_INITIAL_WINDOW_SIZE, RECEIVE_WINDOW],
431
- ]),
432
- frame(WINDOW_UPDATE, 0, 0, uint32Payload(RECEIVE_WINDOW - DEFAULT_WINDOW)),
433
- ...headerFrames(encode(fields), body.length === 0),
434
- ]),
435
- );
469
+ });
436
470
 
437
- // The body goes out as far as the server's windows allow; a full window
438
- // waits for the server's WINDOW_UPDATE.
439
- for (let at = 0; at < body.length && !ended;) {
440
- const size = Math.min(sendWindow, streamSendWindow, peerMaxFrame, body.length - at);
441
- if (size <= 0) {
442
- await step();
443
- continue;
471
+ const body = request.body._tag === "Uint8Array" ? request.body.body : new Uint8Array(0);
472
+ const fields: HeaderField[] = [
473
+ [":method", request.method],
474
+ [":scheme", tls ? "https" : "http"],
475
+ [":path", `${url.pathname}${url.search}`],
476
+ [":authority", url.host],
477
+ ];
478
+ for (const [key, value] of Object.entries(request.headers)) {
479
+ if (!CONNECTION_HEADERS.has(key)) fields.push([key, value]);
444
480
  }
445
- const last = at + size === body.length;
446
- await writer.write(frame(DATA, last ? END_STREAM : 0, STREAM, body.subarray(at, at + size)));
447
- sendWindow -= size;
448
- streamSendWindow -= size;
449
- at += size;
450
- }
451
-
452
- while (responseHeaders === undefined) {
453
- // Before its headers a stream only ends by failing.
454
- if (failure !== undefined) throw failure.cause;
455
- await step();
456
- }
481
+ return Effect.gen(function* () {
482
+ yield* write(
483
+ concat([
484
+ PREFACE,
485
+ settings([
486
+ [SETTINGS_ENABLE_PUSH, 0],
487
+ [SETTINGS_INITIAL_WINDOW_SIZE, RECEIVE_WINDOW],
488
+ ]),
489
+ frame(WINDOW_UPDATE, 0, 0, uint32Payload(RECEIVE_WINDOW - DEFAULT_WINDOW)),
490
+ ...headerFrames(encode(fields), body.length === 0),
491
+ ]),
492
+ );
493
+
494
+ // The body goes out as far as the server's windows allow; a full window
495
+ // waits for the server's WINDOW_UPDATE.
496
+ for (let at = 0; at < body.length && !ended;) {
497
+ const size = Math.min(sendWindow, streamSendWindow, peerMaxFrame, body.length - at);
498
+ if (size <= 0) {
499
+ yield* step;
500
+ continue;
501
+ }
502
+ const last = at + size === body.length;
503
+ yield* write(frame(DATA, last ? END_STREAM : 0, STREAM, body.subarray(at, at + size)));
504
+ sendWindow -= size;
505
+ streamSendWindow -= size;
506
+ at += size;
507
+ }
457
508
 
458
- let resolveTrailers!: (t: Trailers) => void;
459
- const trailersDone = new Promise<Trailers>((resolve) => (resolveTrailers = resolve));
460
- const finish = () => {
461
- resolveTrailers(trailers);
462
- close();
463
- };
464
- const stream = new ReadableStream<Uint8Array>({
465
- async pull(controller) {
466
- try {
467
- while (chunks.length === 0 && !ended) await step();
468
- } catch (error) {
469
- failure = { cause: error };
470
- ended = true;
509
+ while (responseHeaders === undefined) {
510
+ // Before its headers a stream only ends by failing.
511
+ if (failure !== undefined) return yield* Effect.fail(failure.cause);
512
+ yield* step;
471
513
  }
472
- for (const chunk of chunks.splice(0)) controller.enqueue(chunk);
473
- if (!ended) return;
474
- finish();
475
- if (failure === undefined) controller.close();
476
- else controller.error(failure.cause);
477
- },
478
- cancel() {
479
- finish();
480
- },
514
+ const head = responseHeaders;
515
+ // A stream that already ended, or a reply with no body, needs the socket no more.
516
+ if (ended || hasNoBody(status)) yield* close;
517
+
518
+ const trailersDone = yield* Deferred.make<Trailers, unknown>();
519
+ /** The next reply octets, or `undefined` once the stream has ended. */
520
+ const next: Effect.Effect<Uint8Array[] | undefined, unknown> = Effect.gen(function* () {
521
+ for (;;) {
522
+ // What arrived before a failure is handed over before the failure.
523
+ if (chunks.length > 0) return chunks.splice(0);
524
+ if (ended) {
525
+ if (failure !== undefined) return yield* Effect.fail(failure.cause);
526
+ yield* Deferred.succeed(trailersDone, trailers);
527
+ return undefined;
528
+ }
529
+ yield* Effect.catch(step, (cause) =>
530
+ Effect.sync(() => {
531
+ failure = { cause };
532
+ ended = true;
533
+ }),
534
+ );
535
+ }
536
+ });
537
+ const stream = Stream.unfold(undefined, () =>
538
+ Effect.map(next, (data) => (data === undefined ? undefined : ([data, undefined] as const))),
539
+ ).pipe(
540
+ Stream.flattenIterable,
541
+ Stream.ensuring(
542
+ Effect.suspend(() =>
543
+ Effect.andThen(
544
+ // Settles nothing once the stream ended well.
545
+ Deferred.fail(
546
+ trailersDone,
547
+ failure?.cause ?? new ProtocolViolation("the body was not read to its end"),
548
+ ),
549
+ close,
550
+ ),
551
+ ),
552
+ ),
553
+ );
554
+ return {
555
+ status,
556
+ headers: head,
557
+ body: stream,
558
+ trailers: Deferred.await(trailersDone),
559
+ } satisfies Reply;
560
+ });
481
561
  });
482
- return { status, headers: responseHeaders, body: stream, trailers: trailersDone };
483
- };
484
562
 
485
563
  /** An `HttpClient` that sends each request as an HTTP/2 stream on its own `cloudflare:sockets` socket. */
486
564
  export const client: HttpClient.HttpClient = /*@__PURE__*/ HttpClient.make((request, url, signal) =>
487
- Effect.tryPromise({
488
- try: () => send(request, url, signal),
489
- catch: (cause) => transportError(request, cause),
490
- }),
565
+ Effect.mapError(send(request, url, signal), (cause) => transportError(request, cause)),
491
566
  );
492
567
 
493
568
  /** Send gRPC calls over HTTP/2 on `cloudflare:sockets` in this scope. */