@distilled.cloud/core 1.0.0-rc.17 → 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 (314) 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 +17 -0
  12. package/lib/annotations.d.ts.map +1 -0
  13. package/lib/annotations.js +2 -0
  14. package/lib/annotations.js.map +1 -0
  15. package/lib/api.d.ts +52 -1
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -1
  18. package/lib/category.d.ts.map +1 -1
  19. package/lib/config.d.ts +54 -13
  20. package/lib/config.d.ts.map +1 -1
  21. package/lib/config.js +1 -1
  22. package/lib/error-category.d.ts.map +1 -1
  23. package/lib/errors.d.ts +3 -13
  24. package/lib/errors.d.ts.map +1 -1
  25. package/lib/errors.js +1 -1
  26. package/lib/graphql.d.ts +26 -5
  27. package/lib/graphql.d.ts.map +1 -1
  28. package/lib/graphql.types.d.ts.map +1 -1
  29. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  30. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  31. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  32. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  33. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  34. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  35. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  36. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  37. package/lib/grpc-transport-node-http2.d.ts +19 -0
  38. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  39. package/lib/grpc-transport-node-http2.js +2 -0
  40. package/lib/grpc-transport-node-http2.js.map +1 -0
  41. package/lib/grpc-transport.d.ts +76 -0
  42. package/lib/grpc-transport.d.ts.map +1 -0
  43. package/lib/grpc-transport.js +1 -0
  44. package/lib/hpack.d.ts +34 -0
  45. package/lib/hpack.d.ts.map +1 -0
  46. package/lib/hpack.js +2 -0
  47. package/lib/hpack.js.map +1 -0
  48. package/lib/index.d.ts +6 -2
  49. package/lib/index.d.ts.map +1 -1
  50. package/lib/index.js +4 -0
  51. package/lib/pagination.d.ts +55 -3
  52. package/lib/pagination.d.ts.map +1 -1
  53. package/lib/pagination.js +1 -1
  54. package/lib/protobuf.d.ts +92 -0
  55. package/lib/protobuf.d.ts.map +1 -0
  56. package/lib/protobuf.js +1 -0
  57. package/lib/protocol-grpc.d.ts +86 -0
  58. package/lib/protocol-grpc.d.ts.map +1 -0
  59. package/lib/protocol-grpc.js +1 -0
  60. package/lib/protocol-http.d.ts +38 -9
  61. package/lib/protocol-http.d.ts.map +1 -1
  62. package/lib/protocol-http.js +1 -1
  63. package/lib/protocol-rest.d.ts +60 -42
  64. package/lib/protocol-rest.d.ts.map +1 -1
  65. package/lib/protocol-rest.js +1 -1
  66. package/lib/response-validation.d.ts +5 -4
  67. package/lib/response-validation.d.ts.map +1 -1
  68. package/lib/schema-lite-typed.js +1 -2
  69. package/lib/sdk-error.d.ts +27 -0
  70. package/lib/sdk-error.d.ts.map +1 -0
  71. package/lib/sdk-error.js +1 -0
  72. package/lib/sensitive.d.ts +28 -0
  73. package/lib/sensitive.d.ts.map +1 -0
  74. package/lib/sensitive.js +2 -0
  75. package/lib/sensitive.js.map +1 -0
  76. package/lib/telemetry-debug.d.ts +6 -0
  77. package/lib/telemetry-debug.d.ts.map +1 -0
  78. package/lib/telemetry-debug.js +2 -0
  79. package/lib/telemetry-debug.js.map +1 -0
  80. package/lib/telemetry-hooks.d.ts +32 -0
  81. package/lib/telemetry-hooks.d.ts.map +1 -0
  82. package/lib/telemetry-hooks.js +2 -0
  83. package/lib/telemetry-hooks.js.map +1 -0
  84. package/lib/telemetry-host-rules.d.ts +23 -0
  85. package/lib/telemetry-host-rules.d.ts.map +1 -0
  86. package/lib/telemetry-host-rules.js +2 -0
  87. package/lib/telemetry-host-rules.js.map +1 -0
  88. package/lib/telemetry-lambda-context.d.ts +17 -0
  89. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  90. package/lib/telemetry-lambda-context.js +2 -0
  91. package/lib/telemetry-lambda-context.js.map +1 -0
  92. package/lib/telemetry-message-context.d.ts +52 -0
  93. package/lib/telemetry-message-context.d.ts.map +1 -0
  94. package/lib/telemetry-message-context.js +2 -0
  95. package/lib/telemetry-message-context.js.map +1 -0
  96. package/lib/telemetry-metrics.d.ts +6 -0
  97. package/lib/telemetry-metrics.d.ts.map +1 -0
  98. package/lib/telemetry-metrics.js +2 -0
  99. package/lib/telemetry-metrics.js.map +1 -0
  100. package/lib/telemetry-name-template.d.ts +13 -0
  101. package/lib/telemetry-name-template.d.ts.map +1 -0
  102. package/lib/telemetry-name-template.js +2 -0
  103. package/lib/telemetry-name-template.js.map +1 -0
  104. package/lib/telemetry-stream.d.ts +11 -0
  105. package/lib/telemetry-stream.d.ts.map +1 -0
  106. package/lib/telemetry-stream.js +2 -0
  107. package/lib/telemetry-stream.js.map +1 -0
  108. package/lib/telemetry-xray.d.ts +28 -0
  109. package/lib/telemetry-xray.d.ts.map +1 -0
  110. package/lib/telemetry-xray.js +2 -0
  111. package/lib/telemetry-xray.js.map +1 -0
  112. package/lib/telemetry.d.ts +288 -0
  113. package/lib/telemetry.d.ts.map +1 -0
  114. package/lib/telemetry.js +3 -0
  115. package/lib/telemetry.js.map +1 -0
  116. package/lib/trait.d.ts +7 -0
  117. package/lib/trait.d.ts.map +1 -1
  118. package/lib/trait.js +1 -1
  119. package/lib/xml.d.ts.map +1 -1
  120. package/package.json +3 -5
  121. package/src/annotations.ts +53 -0
  122. package/src/api.ts +316 -43
  123. package/src/category.ts +21 -22
  124. package/src/config.ts +58 -29
  125. package/src/error-category.ts +12 -14
  126. package/src/errors.ts +11 -7
  127. package/src/graphql.ts +191 -63
  128. package/src/graphql.types.ts +5 -1
  129. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  130. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  131. package/src/grpc-transport-node-http2.ts +234 -0
  132. package/src/grpc-transport.ts +118 -0
  133. package/src/hpack.ts +331 -0
  134. package/src/index.ts +6 -2
  135. package/src/pagination.ts +193 -8
  136. package/src/protobuf.ts +1332 -0
  137. package/src/protocol-grpc.ts +641 -0
  138. package/src/protocol-http.ts +87 -67
  139. package/src/protocol-rest.ts +183 -191
  140. package/src/response-validation.ts +8 -5
  141. package/src/sdk-error.ts +33 -0
  142. package/src/sensitive.ts +154 -0
  143. package/src/telemetry-debug.ts +179 -0
  144. package/src/telemetry-hooks.ts +33 -0
  145. package/src/telemetry-host-rules.ts +39 -0
  146. package/src/telemetry-lambda-context.ts +46 -0
  147. package/src/telemetry-message-context.ts +170 -0
  148. package/src/telemetry-metrics.ts +69 -0
  149. package/src/telemetry-name-template.ts +26 -0
  150. package/src/telemetry-stream.ts +100 -0
  151. package/src/telemetry-xray.ts +66 -0
  152. package/src/telemetry.ts +832 -0
  153. package/src/trait.ts +10 -0
  154. package/src/xml.ts +10 -1
  155. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  156. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  157. package/lib/codegen/boolean-string-enums.js +0 -147
  158. package/lib/codegen/boolean-string-enums.js.map +0 -1
  159. package/lib/codegen/chunk.d.ts +0 -7
  160. package/lib/codegen/chunk.d.ts.map +0 -1
  161. package/lib/codegen/chunk.js +0 -139
  162. package/lib/codegen/chunk.js.map +0 -1
  163. package/lib/codegen/cli.d.ts +0 -80
  164. package/lib/codegen/cli.d.ts.map +0 -1
  165. package/lib/codegen/cli.js +0 -166
  166. package/lib/codegen/cli.js.map +0 -1
  167. package/lib/codegen/datafy.d.ts +0 -14
  168. package/lib/codegen/datafy.d.ts.map +0 -1
  169. package/lib/codegen/datafy.js +0 -853
  170. package/lib/codegen/datafy.js.map +0 -1
  171. package/lib/codegen/dedupe.d.ts +0 -5
  172. package/lib/codegen/dedupe.d.ts.map +0 -1
  173. package/lib/codegen/dedupe.js +0 -153
  174. package/lib/codegen/dedupe.js.map +0 -1
  175. package/lib/codegen/emit.d.ts +0 -125
  176. package/lib/codegen/emit.d.ts.map +0 -1
  177. package/lib/codegen/emit.js +0 -99
  178. package/lib/codegen/emit.js.map +0 -1
  179. package/lib/codegen/format.d.ts +0 -11
  180. package/lib/codegen/format.d.ts.map +0 -1
  181. package/lib/codegen/format.js +0 -32
  182. package/lib/codegen/format.js.map +0 -1
  183. package/lib/codegen/generated-at.d.ts +0 -29
  184. package/lib/codegen/generated-at.d.ts.map +0 -1
  185. package/lib/codegen/generated-at.js +0 -78
  186. package/lib/codegen/generated-at.js.map +0 -1
  187. package/lib/codegen/generator.d.ts +0 -353
  188. package/lib/codegen/generator.d.ts.map +0 -1
  189. package/lib/codegen/generator.js +0 -810
  190. package/lib/codegen/generator.js.map +0 -1
  191. package/lib/codegen/graph.d.ts +0 -36
  192. package/lib/codegen/graph.d.ts.map +0 -1
  193. package/lib/codegen/graph.js +0 -136
  194. package/lib/codegen/graph.js.map +0 -1
  195. package/lib/codegen/graphql-client.d.ts +0 -70
  196. package/lib/codegen/graphql-client.d.ts.map +0 -1
  197. package/lib/codegen/graphql-client.js +0 -439
  198. package/lib/codegen/graphql-client.js.map +0 -1
  199. package/lib/codegen/graphql.d.ts +0 -207
  200. package/lib/codegen/graphql.d.ts.map +0 -1
  201. package/lib/codegen/graphql.js +0 -786
  202. package/lib/codegen/graphql.js.map +0 -1
  203. package/lib/codegen/latin1.d.ts +0 -3
  204. package/lib/codegen/latin1.d.ts.map +0 -1
  205. package/lib/codegen/latin1.js +0 -126
  206. package/lib/codegen/latin1.js.map +0 -1
  207. package/lib/codegen/members.d.ts +0 -32
  208. package/lib/codegen/members.d.ts.map +0 -1
  209. package/lib/codegen/members.js +0 -62
  210. package/lib/codegen/members.js.map +0 -1
  211. package/lib/codegen/model-diff.d.ts +0 -10
  212. package/lib/codegen/model-diff.d.ts.map +0 -1
  213. package/lib/codegen/model-diff.js +0 -67
  214. package/lib/codegen/model-diff.js.map +0 -1
  215. package/lib/codegen/naming.d.ts +0 -29
  216. package/lib/codegen/naming.d.ts.map +0 -1
  217. package/lib/codegen/naming.js +0 -74
  218. package/lib/codegen/naming.js.map +0 -1
  219. package/lib/codegen/openapi-cli.d.ts +0 -52
  220. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  221. package/lib/codegen/openapi-cli.js +0 -84
  222. package/lib/codegen/openapi-cli.js.map +0 -1
  223. package/lib/codegen/openapi.d.ts +0 -209
  224. package/lib/codegen/openapi.d.ts.map +0 -1
  225. package/lib/codegen/openapi.js +0 -1548
  226. package/lib/codegen/openapi.js.map +0 -1
  227. package/lib/codegen/operations.d.ts +0 -24
  228. package/lib/codegen/operations.d.ts.map +0 -1
  229. package/lib/codegen/operations.js +0 -56
  230. package/lib/codegen/operations.js.map +0 -1
  231. package/lib/codegen/pagination.d.ts +0 -39
  232. package/lib/codegen/pagination.d.ts.map +0 -1
  233. package/lib/codegen/pagination.js +0 -31
  234. package/lib/codegen/pagination.js.map +0 -1
  235. package/lib/codegen/patch-audit.d.ts +0 -84
  236. package/lib/codegen/patch-audit.d.ts.map +0 -1
  237. package/lib/codegen/patch-audit.js +0 -366
  238. package/lib/codegen/patch-audit.js.map +0 -1
  239. package/lib/codegen/patches.d.ts +0 -129
  240. package/lib/codegen/patches.d.ts.map +0 -1
  241. package/lib/codegen/patches.js +0 -472
  242. package/lib/codegen/patches.js.map +0 -1
  243. package/lib/codegen/prelude.d.ts +0 -15
  244. package/lib/codegen/prelude.d.ts.map +0 -1
  245. package/lib/codegen/prelude.js +0 -60
  246. package/lib/codegen/prelude.js.map +0 -1
  247. package/lib/codegen/privatize.d.ts +0 -21
  248. package/lib/codegen/privatize.d.ts.map +0 -1
  249. package/lib/codegen/privatize.js +0 -176
  250. package/lib/codegen/privatize.js.map +0 -1
  251. package/lib/codegen/proto.d.ts +0 -121
  252. package/lib/codegen/proto.d.ts.map +0 -1
  253. package/lib/codegen/proto.js +0 -960
  254. package/lib/codegen/proto.js.map +0 -1
  255. package/lib/codegen/pure.d.ts +0 -6
  256. package/lib/codegen/pure.d.ts.map +0 -1
  257. package/lib/codegen/pure.js +0 -91
  258. package/lib/codegen/pure.js.map +0 -1
  259. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  260. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  261. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  262. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  263. package/lib/codegen/spec-path.d.ts +0 -16
  264. package/lib/codegen/spec-path.d.ts.map +0 -1
  265. package/lib/codegen/spec-path.js +0 -101
  266. package/lib/codegen/spec-path.js.map +0 -1
  267. package/lib/codegen/table.d.ts +0 -5
  268. package/lib/codegen/table.d.ts.map +0 -1
  269. package/lib/codegen/table.js +0 -249
  270. package/lib/codegen/table.js.map +0 -1
  271. package/lib/debug.d.ts +0 -2
  272. package/lib/debug.d.ts.map +0 -1
  273. package/lib/debug.js +0 -1
  274. package/lib/json-patch.d.ts +0 -58
  275. package/lib/json-patch.d.ts.map +0 -1
  276. package/lib/json-patch.js +0 -2
  277. package/lib/json-patch.js.map +0 -1
  278. package/lib/schema-lite-typed.js.map +0 -1
  279. package/lib/testing.d.ts +0 -40
  280. package/lib/testing.d.ts.map +0 -1
  281. package/lib/testing.js +0 -2
  282. package/lib/testing.js.map +0 -1
  283. package/src/codegen/boolean-string-enums.ts +0 -155
  284. package/src/codegen/chunk.ts +0 -147
  285. package/src/codegen/cli.ts +0 -293
  286. package/src/codegen/datafy.ts +0 -874
  287. package/src/codegen/dedupe.ts +0 -173
  288. package/src/codegen/emit.ts +0 -200
  289. package/src/codegen/format.ts +0 -49
  290. package/src/codegen/generated-at.ts +0 -88
  291. package/src/codegen/generator.ts +0 -1229
  292. package/src/codegen/graph.ts +0 -151
  293. package/src/codegen/graphql-client.ts +0 -545
  294. package/src/codegen/graphql.ts +0 -1145
  295. package/src/codegen/latin1.ts +0 -131
  296. package/src/codegen/members.ts +0 -79
  297. package/src/codegen/model-diff.ts +0 -67
  298. package/src/codegen/naming.ts +0 -85
  299. package/src/codegen/openapi-cli.ts +0 -141
  300. package/src/codegen/openapi.ts +0 -1845
  301. package/src/codegen/operations.ts +0 -73
  302. package/src/codegen/pagination.ts +0 -64
  303. package/src/codegen/patch-audit.ts +0 -480
  304. package/src/codegen/patches.ts +0 -581
  305. package/src/codegen/prelude.ts +0 -70
  306. package/src/codegen/privatize.ts +0 -200
  307. package/src/codegen/proto.ts +0 -1092
  308. package/src/codegen/pure.ts +0 -94
  309. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  310. package/src/codegen/spec-path.ts +0 -112
  311. package/src/codegen/table.ts +0 -254
  312. package/src/debug.ts +0 -8
  313. package/src/json-patch.ts +0 -273
  314. package/src/testing.ts +0 -74
@@ -0,0 +1,494 @@
1
+ /**
2
+ * A gRPC transport over HTTP/2 on a `cloudflare:sockets` socket, for a
3
+ * Cloudflare Worker calling a gRPC server that speaks only HTTP/2.
4
+ *
5
+ * workerd has no working `node:http2`, and a Worker's `fetch` reads no
6
+ * trailers, so this module speaks HTTP/2 itself (RFC 9113) over a plain TLS
7
+ * socket.
8
+ *
9
+ * ```ts
10
+ * import * as CloudflareHttp2 from "@distilled.cloud/core/grpc-transport-cloudflare-http2";
11
+ *
12
+ * program.pipe(Effect.provide(CloudflareHttp2.layer));
13
+ * ```
14
+ *
15
+ * `cloudflare:sockets` offers no ALPN, so the connection starts with the
16
+ * HTTP/2 preface straight after the TLS handshake. The server must accept
17
+ * that, as gRPC servers that serve nothing but HTTP/2 do.
18
+ *
19
+ * Each request opens its own connection and uses one stream on it: workerd
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.
23
+ */
24
+ import * as Effect from "effect/Effect";
25
+ import * as HttpClient from "effect/http/HttpClient";
26
+ import * as HttpClientError from "effect/http/HttpClientError";
27
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
28
+ import type * as Layer from "effect/Layer";
29
+ import {
30
+ isResponseStatus,
31
+ layer as transportLayer,
32
+ respond,
33
+ type Trailers,
34
+ } from "./grpc-transport.ts";
35
+ import { encode, type HeaderField, makeDecoder } from "./hpack.ts";
36
+
37
+ /** The part of `cloudflare:sockets` this transport uses. */
38
+ type Connect = (
39
+ address: { hostname: string; port: number },
40
+ options: { secureTransport: "on" | "off"; allowHalfOpen: boolean },
41
+ ) => {
42
+ readonly readable: ReadableStream<Uint8Array>;
43
+ readonly writable: WritableStream<Uint8Array>;
44
+ close(): Promise<void>;
45
+ };
46
+
47
+ // A non-literal specifier keeps bundlers from resolving it for runtimes
48
+ // other than workerd, which resolves its built-in modules at runtime.
49
+ 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
+ ));
55
+
56
+ /** Headers HTTP/2 forbids or derives itself. */
57
+ const CONNECTION_HEADERS = new Set([
58
+ "host",
59
+ "connection",
60
+ "keep-alive",
61
+ "content-length",
62
+ "transfer-encoding",
63
+ "upgrade",
64
+ ]);
65
+
66
+ // RFC 9113 section 6: frame types.
67
+ const DATA = 0;
68
+ const HEADERS = 1;
69
+ const RST_STREAM = 3;
70
+ const SETTINGS = 4;
71
+ const PUSH_PROMISE = 5;
72
+ const PING = 6;
73
+ const GOAWAY = 7;
74
+ const WINDOW_UPDATE = 8;
75
+ const CONTINUATION = 9;
76
+
77
+ // Frame flags.
78
+ const END_STREAM = 0x1;
79
+ const ACK = 0x1;
80
+ const END_HEADERS = 0x4;
81
+ const PADDED = 0x8;
82
+ const PRIORITY = 0x20;
83
+
84
+ // Settings.
85
+ const SETTINGS_ENABLE_PUSH = 2;
86
+ const SETTINGS_INITIAL_WINDOW_SIZE = 4;
87
+ const SETTINGS_MAX_FRAME_SIZE = 5;
88
+
89
+ /** The largest flow-control window and the largest frame HTTP/2 allows. */
90
+ const MAX_WINDOW = 0x7fffffff;
91
+ const MAX_FRAME_LIMIT = 0xffffff;
92
+
93
+ /** The flow-control window and frame size both ends start with. */
94
+ const DEFAULT_WINDOW = 65_535;
95
+ const DEFAULT_MAX_FRAME = 16_384;
96
+ /** How much reply this end lets the server send before it has been read. */
97
+ const RECEIVE_WINDOW = 1_048_576;
98
+ /** Read octets are handed back to the server in steps of this size. */
99
+ const WINDOW_STEP = 65_536;
100
+
101
+ /** The one stream of a connection. Client streams are odd. */
102
+ const STREAM = 1;
103
+
104
+ const PREFACE = /*@__PURE__*/ new TextEncoder().encode("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
105
+
106
+ class ProtocolViolation extends Error {}
107
+
108
+ const concat = (parts: ReadonlyArray<Uint8Array>): Uint8Array<ArrayBufferLike> => {
109
+ if (parts.length === 1) return parts[0]!;
110
+ let length = 0;
111
+ for (const part of parts) length += part.length;
112
+ const out = new Uint8Array(length);
113
+ let at = 0;
114
+ for (const part of parts) {
115
+ out.set(part, at);
116
+ at += part.length;
117
+ }
118
+ return out;
119
+ };
120
+
121
+ const uint32 = (bytes: Uint8Array, at: number): number =>
122
+ bytes[at]! * 0x1000000 + ((bytes[at + 1]! << 16) | (bytes[at + 2]! << 8) | bytes[at + 3]!);
123
+
124
+ const frame = (type: number, flags: number, stream: number, payload: Uint8Array): Uint8Array => {
125
+ const out = new Uint8Array(9 + payload.length);
126
+ out[0] = (payload.length >>> 16) & 0xff;
127
+ out[1] = (payload.length >>> 8) & 0xff;
128
+ out[2] = payload.length & 0xff;
129
+ out[3] = type;
130
+ out[4] = flags;
131
+ out[5] = (stream >>> 24) & 0x7f;
132
+ out[6] = (stream >>> 16) & 0xff;
133
+ out[7] = (stream >>> 8) & 0xff;
134
+ out[8] = stream & 0xff;
135
+ out.set(payload, 9);
136
+ return out;
137
+ };
138
+
139
+ const uint32Payload = (value: number): Uint8Array =>
140
+ Uint8Array.of((value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff);
141
+
142
+ const settings = (entries: ReadonlyArray<readonly [id: number, value: number]>): Uint8Array => {
143
+ const payload = new Uint8Array(entries.length * 6);
144
+ entries.forEach(([id, value], index) => {
145
+ payload[index * 6] = id >>> 8;
146
+ payload[index * 6 + 1] = id & 0xff;
147
+ payload.set(uint32Payload(value), index * 6 + 2);
148
+ });
149
+ return frame(SETTINGS, 0, 0, payload);
150
+ };
151
+
152
+ /** A header block as one HEADERS frame, continued when it outgrows a frame. */
153
+ const headerFrames = (block: Uint8Array, endStream: boolean): Uint8Array[] => {
154
+ const frames: Uint8Array[] = [];
155
+ for (let at = 0; at < block.length; at += DEFAULT_MAX_FRAME) {
156
+ const last = at + DEFAULT_MAX_FRAME >= block.length;
157
+ frames.push(
158
+ frame(
159
+ at === 0 ? HEADERS : CONTINUATION,
160
+ (last ? END_HEADERS : 0) | (at === 0 && endStream ? END_STREAM : 0),
161
+ STREAM,
162
+ block.subarray(at, at + DEFAULT_MAX_FRAME),
163
+ ),
164
+ );
165
+ }
166
+ return frames;
167
+ };
168
+
169
+ const transportError = (request: HttpClientRequest.HttpClientRequest, cause: unknown) =>
170
+ new HttpClientError.HttpClientError({
171
+ reason: new HttpClientError.TransportError({
172
+ request,
173
+ cause,
174
+ description: "HTTP/2 request over cloudflare:sockets failed",
175
+ }),
176
+ });
177
+
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
+ );
195
+ let closed = false;
196
+ const close = () => {
197
+ if (closed) return;
198
+ closed = true;
199
+ signal.removeEventListener("abort", close);
200
+ void socket.close().catch(() => undefined);
201
+ };
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
+ });
212
+ };
213
+
214
+ /** One request and its response on stream 1 of a fresh connection. */
215
+ const exchange = async (
216
+ request: HttpClientRequest.HttpClientRequest,
217
+ 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
+ );
309
+ }
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
+ }
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
+ }
346
+ }
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;
361
+ }
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)})`);
366
+ }
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})`);
376
+ }
377
+ return;
378
+ }
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
+ );
436
+
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;
444
+ }
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
+ }
457
+
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;
471
+ }
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
+ },
481
+ });
482
+ return { status, headers: responseHeaders, body: stream, trailers: trailersDone };
483
+ };
484
+
485
+ /** An `HttpClient` that sends each request as an HTTP/2 stream on its own `cloudflare:sockets` socket. */
486
+ 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
+ }),
491
+ );
492
+
493
+ /** Send gRPC calls over HTTP/2 on `cloudflare:sockets` in this scope. */
494
+ export const layer: Layer.Layer<never> = /*@__PURE__*/ transportLayer(client);