@mark1russell7/service 0.8.19 → 0.8.20

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 (331) hide show
  1. package/build/backoff.d.ts +44 -2
  2. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  3. package/build/builder.js +499 -0
  4. package/build/builder.js.map +1 -0
  5. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  6. package/build/channel.d.ts +1 -1
  7. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  8. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  9. package/build/client/core.js.map +1 -0
  10. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  11. package/build/client/dial.js +52 -0
  12. package/build/client/dial.js.map +1 -0
  13. package/build/client/machine.js +29 -0
  14. package/build/client/machine.js.map +1 -0
  15. package/build/client/meets.d.ts +35 -0
  16. package/build/client/meets.js +78 -0
  17. package/build/client/meets.js.map +1 -0
  18. package/build/clock.d.ts +1 -1
  19. package/build/conformance.d.ts +122 -0
  20. package/build/conformance.js +470 -0
  21. package/build/conformance.js.map +1 -0
  22. package/build/contract.d.ts +28 -0
  23. package/build/contract.js +184 -0
  24. package/build/contract.js.map +1 -0
  25. package/build/description.d.ts +161 -0
  26. package/build/description.js +11 -0
  27. package/build/description.js.map +1 -0
  28. package/build/drains.js +35 -0
  29. package/build/drains.js.map +1 -0
  30. package/build/events.d.ts +25 -0
  31. package/build/fakes.d.ts +43 -0
  32. package/build/fakes.js +93 -0
  33. package/build/fakes.js.map +1 -0
  34. package/build/grpc/client.d.ts +153 -0
  35. package/build/grpc/client.js +474 -0
  36. package/build/grpc/client.js.map +1 -0
  37. package/build/grpc/connection.d.ts +97 -0
  38. package/build/grpc/connection.js +59 -0
  39. package/build/grpc/connection.js.map +1 -0
  40. package/build/grpc/machine.d.ts +12 -0
  41. package/build/grpc/machine.js +149 -0
  42. package/build/grpc/machine.js.map +1 -0
  43. package/build/grpc/meets.d.ts +14 -0
  44. package/build/grpc/meets.js +105 -0
  45. package/build/grpc/meets.js.map +1 -0
  46. package/build/grpc/starting.d.ts +33 -0
  47. package/build/grpc/starting.js +89 -0
  48. package/build/grpc/starting.js.map +1 -0
  49. package/build/grpc.d.ts +9 -303
  50. package/build/grpc.js +7 -854
  51. package/build/health.d.ts +93 -0
  52. package/build/health.js +223 -0
  53. package/build/health.js.map +1 -0
  54. package/build/heartbeat.d.ts +1 -1
  55. package/build/host/discovery.d.ts +61 -0
  56. package/build/host/discovery.js +113 -0
  57. package/build/host/discovery.js.map +1 -0
  58. package/build/host/env.d.ts +14 -0
  59. package/build/host/env.js +57 -0
  60. package/build/host/env.js.map +1 -0
  61. package/build/host/fakes.d.ts +82 -0
  62. package/build/host/fakes.js +239 -0
  63. package/build/host/fakes.js.map +1 -0
  64. package/build/host/group.d.ts +142 -0
  65. package/build/host/group.js +517 -0
  66. package/build/host/group.js.map +1 -0
  67. package/build/host/install.d.ts +96 -0
  68. package/build/host/install.js +330 -0
  69. package/build/host/install.js.map +1 -0
  70. package/build/host/lock.d.ts +78 -0
  71. package/build/host/lock.js +190 -0
  72. package/build/host/lock.js.map +1 -0
  73. package/build/host/logs.d.ts +26 -0
  74. package/build/host/logs.js +48 -0
  75. package/build/host/logs.js.map +1 -0
  76. package/build/host/node.d.ts +14 -0
  77. package/build/host/node.js +309 -0
  78. package/build/host/node.js.map +1 -0
  79. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  80. package/build/host/ports.js +17 -0
  81. package/build/host/ports.js.map +1 -0
  82. package/build/host/probes.d.ts +51 -0
  83. package/build/host/probes.js +139 -0
  84. package/build/host/probes.js.map +1 -0
  85. package/build/host/processes.d.ts +32 -0
  86. package/build/host/processes.js +63 -0
  87. package/build/host/processes.js.map +1 -0
  88. package/build/host/render.d.ts +84 -0
  89. package/build/host/render.js +235 -0
  90. package/build/host/render.js.map +1 -0
  91. package/build/host/watch.d.ts +90 -0
  92. package/build/host/watch.js +165 -0
  93. package/build/host/watch.js.map +1 -0
  94. package/build/host.d.ts +13 -671
  95. package/build/host.js +12 -2126
  96. package/build/http/answers.js +29 -0
  97. package/build/http/answers.js.map +1 -0
  98. package/build/http/fake-server.js +61 -0
  99. package/build/http/fake-server.js.map +1 -0
  100. package/build/http/outcome.d.ts +115 -0
  101. package/build/http/outcome.js +325 -0
  102. package/build/http/outcome.js.map +1 -0
  103. package/build/http/probes.d.ts +83 -0
  104. package/build/http/probes.js +232 -0
  105. package/build/http/probes.js.map +1 -0
  106. package/build/http/transport.d.ts +165 -0
  107. package/build/http/transport.js +517 -0
  108. package/build/http/transport.js.map +1 -0
  109. package/build/http-client/client.d.ts +121 -0
  110. package/build/http-client/client.js +330 -0
  111. package/build/http-client/client.js.map +1 -0
  112. package/build/http-client/connection.d.ts +78 -0
  113. package/build/http-client/connection.js +54 -0
  114. package/build/http-client/connection.js.map +1 -0
  115. package/build/http-client/machine.d.ts +14 -0
  116. package/build/http-client/machine.js +109 -0
  117. package/build/http-client/machine.js.map +1 -0
  118. package/build/http-client/meets.d.ts +11 -0
  119. package/build/http-client/meets.js +74 -0
  120. package/build/http-client/meets.js.map +1 -0
  121. package/build/http-client/session.d.ts +87 -0
  122. package/build/http-client/session.js +99 -0
  123. package/build/http-client/session.js.map +1 -0
  124. package/build/http-client/starting.d.ts +25 -0
  125. package/build/http-client/starting.js +65 -0
  126. package/build/http-client/starting.js.map +1 -0
  127. package/build/http-client.d.ts +9 -330
  128. package/build/http-client.js +8 -707
  129. package/build/http.d.ts +5 -353
  130. package/build/http.js +3 -1086
  131. package/build/identity.d.ts +16 -0
  132. package/build/identity.js +44 -0
  133. package/build/identity.js.map +1 -0
  134. package/build/index.d.ts +35 -412
  135. package/build/index.js +24 -3277
  136. package/build/knobs.d.ts +1 -0
  137. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  138. package/build/knobs.js.map +1 -0
  139. package/build/latch.d.ts +29 -0
  140. package/build/latch.js +122 -0
  141. package/build/latch.js.map +1 -0
  142. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  143. package/build/law.js +149 -0
  144. package/build/law.js.map +1 -0
  145. package/build/lifecycle.d.ts +144 -0
  146. package/build/lifecycle.js +411 -0
  147. package/build/lifecycle.js.map +1 -0
  148. package/build/limiter/machine.d.ts +40 -0
  149. package/build/limiter/machine.js +279 -0
  150. package/build/limiter/machine.js.map +1 -0
  151. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  152. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  153. package/build/limiter/policy.js.map +1 -0
  154. package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
  155. package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
  156. package/build/limiter/quota.js.map +1 -0
  157. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  158. package/build/limiter/store.js +145 -0
  159. package/build/limiter/store.js.map +1 -0
  160. package/build/limiter.d.ts +4 -3
  161. package/build/limiter.js +4 -2
  162. package/build/lint.d.ts +152 -0
  163. package/build/lint.js +576 -0
  164. package/build/lint.js.map +1 -0
  165. package/build/logger.d.ts +71 -0
  166. package/build/logger.js +183 -0
  167. package/build/logger.js.map +1 -0
  168. package/build/machines.d.ts +41 -0
  169. package/build/machines.js +451 -0
  170. package/build/machines.js.map +1 -0
  171. package/build/metrics.d.ts +53 -0
  172. package/build/metrics.js +111 -0
  173. package/build/metrics.js.map +1 -0
  174. package/build/mongodb/client.d.ts +131 -0
  175. package/build/mongodb/client.js +388 -0
  176. package/build/mongodb/client.js.map +1 -0
  177. package/build/mongodb/connection.d.ts +112 -0
  178. package/build/mongodb/connection.js +12 -0
  179. package/build/mongodb/connection.js.map +1 -0
  180. package/build/mongodb/machine.d.ts +14 -0
  181. package/build/mongodb/machine.js +122 -0
  182. package/build/mongodb/machine.js.map +1 -0
  183. package/build/mongodb/meets.d.ts +15 -0
  184. package/build/mongodb/meets.js +103 -0
  185. package/build/mongodb/meets.js.map +1 -0
  186. package/build/mongodb/starting.d.ts +29 -0
  187. package/build/mongodb/starting.js +77 -0
  188. package/build/mongodb/starting.js.map +1 -0
  189. package/build/mongodb.d.ts +8 -296
  190. package/build/mongodb.js +7 -682
  191. package/build/operation.d.ts +27 -0
  192. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  193. package/build/operation.js.map +1 -0
  194. package/build/otel.d.ts +2 -2
  195. package/build/pg/client.d.ts +96 -0
  196. package/build/pg/client.js +277 -0
  197. package/build/pg/client.js.map +1 -0
  198. package/build/pg/connection.d.ts +75 -0
  199. package/build/pg/connection.js +11 -0
  200. package/build/pg/connection.js.map +1 -0
  201. package/build/pg/machine.d.ts +13 -0
  202. package/build/pg/machine.js +111 -0
  203. package/build/pg/machine.js.map +1 -0
  204. package/build/pg/meets.d.ts +14 -0
  205. package/build/pg/meets.js +83 -0
  206. package/build/pg/meets.js.map +1 -0
  207. package/build/pg/starting.d.ts +26 -0
  208. package/build/pg/starting.js +62 -0
  209. package/build/pg/starting.js.map +1 -0
  210. package/build/pg.d.ts +8 -219
  211. package/build/pg.js +7 -525
  212. package/build/poller.d.ts +9 -0
  213. package/build/poller.js +152 -0
  214. package/build/poller.js.map +1 -0
  215. package/build/process.d.ts +114 -0
  216. package/build/process.js +170 -0
  217. package/build/process.js.map +1 -0
  218. package/build/profiles.d.ts +68 -0
  219. package/build/profiles.js +120 -0
  220. package/build/profiles.js.map +1 -0
  221. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  222. package/build/queue.js +279 -0
  223. package/build/queue.js.map +1 -0
  224. package/build/rabbitmq/client.d.ts +144 -0
  225. package/build/rabbitmq/client.js +426 -0
  226. package/build/rabbitmq/client.js.map +1 -0
  227. package/build/rabbitmq/connection.d.ts +91 -0
  228. package/build/rabbitmq/connection.js +15 -0
  229. package/build/rabbitmq/connection.js.map +1 -0
  230. package/build/rabbitmq/machine.d.ts +13 -0
  231. package/build/rabbitmq/machine.js +159 -0
  232. package/build/rabbitmq/machine.js.map +1 -0
  233. package/build/rabbitmq/meets.d.ts +12 -0
  234. package/build/rabbitmq/meets.js +96 -0
  235. package/build/rabbitmq/meets.js.map +1 -0
  236. package/build/rabbitmq/starting.d.ts +27 -0
  237. package/build/rabbitmq/starting.js +67 -0
  238. package/build/rabbitmq/starting.js.map +1 -0
  239. package/build/rabbitmq.d.ts +8 -283
  240. package/build/rabbitmq.js +7 -742
  241. package/build/redis/client.d.ts +86 -0
  242. package/build/redis/client.js +285 -0
  243. package/build/redis/client.js.map +1 -0
  244. package/build/redis/connection.d.ts +57 -0
  245. package/build/redis/connection.js +11 -0
  246. package/build/redis/connection.js.map +1 -0
  247. package/build/redis/limiter.d.ts +43 -0
  248. package/build/redis/limiter.js +164 -0
  249. package/build/redis/limiter.js.map +1 -0
  250. package/build/redis/machine.d.ts +12 -0
  251. package/build/redis/machine.js +144 -0
  252. package/build/redis/machine.js.map +1 -0
  253. package/build/redis/meets.d.ts +11 -0
  254. package/build/redis/meets.js +75 -0
  255. package/build/redis/meets.js.map +1 -0
  256. package/build/redis/operations.d.ts +5 -0
  257. package/build/redis/operations.js +114 -0
  258. package/build/redis/operations.js.map +1 -0
  259. package/build/redis.d.ts +10 -207
  260. package/build/redis.js +9 -771
  261. package/build/requests.d.ts +66 -0
  262. package/build/requests.js +279 -0
  263. package/build/requests.js.map +1 -0
  264. package/build/retrier.d.ts +62 -0
  265. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  266. package/build/retrier.js.map +1 -0
  267. package/build/routes.d.ts +35 -0
  268. package/build/routes.js +77 -0
  269. package/build/routes.js.map +1 -0
  270. package/build/rules.d.ts +19 -2
  271. package/build/stops.d.ts +51 -0
  272. package/build/stops.js +86 -0
  273. package/build/stops.js.map +1 -0
  274. package/build/testing.d.ts +8 -270
  275. package/build/testing.js +4 -1027
  276. package/build/testing.js.map +1 -1
  277. package/build/timing.d.ts +63 -0
  278. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  279. package/build/timing.js.map +1 -0
  280. package/build/units.d.ts +17 -0
  281. package/build/units.js +236 -0
  282. package/build/units.js.map +1 -0
  283. package/build/watchdog.d.ts +34 -0
  284. package/build/watchdog.js +53 -0
  285. package/build/watchdog.js.map +1 -0
  286. package/build/websocket/client.d.ts +136 -0
  287. package/build/websocket/client.js +422 -0
  288. package/build/websocket/client.js.map +1 -0
  289. package/build/websocket/connection.d.ts +83 -0
  290. package/build/websocket/connection.js +57 -0
  291. package/build/websocket/connection.js.map +1 -0
  292. package/build/websocket/machine.d.ts +12 -0
  293. package/build/websocket/machine.js +155 -0
  294. package/build/websocket/machine.js.map +1 -0
  295. package/build/websocket/meets.d.ts +14 -0
  296. package/build/websocket/meets.js +92 -0
  297. package/build/websocket/meets.js.map +1 -0
  298. package/build/websocket/starting.d.ts +25 -0
  299. package/build/websocket/starting.js +69 -0
  300. package/build/websocket/starting.js.map +1 -0
  301. package/build/websocket.d.ts +9 -264
  302. package/build/websocket.js +8 -774
  303. package/build/worker.d.ts +92 -0
  304. package/build/worker.js +153 -0
  305. package/build/worker.js.map +1 -0
  306. package/package.json +4 -3
  307. package/build/backoff-QTRGfkEK.d.ts +0 -45
  308. package/build/clock-DpVgpY4h.d.ts +0 -2
  309. package/build/grpc.js.map +0 -1
  310. package/build/host.js.map +0 -1
  311. package/build/http-client.js.map +0 -1
  312. package/build/http.js.map +0 -1
  313. package/build/index.js.map +0 -1
  314. package/build/knobs-BJcz6m01.js.map +0 -1
  315. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  316. package/build/limiter-DrM0PQV9.js.map +0 -1
  317. package/build/logger-B6drv9w0.d.ts +0 -488
  318. package/build/machine-BhVeHr_m.js.map +0 -1
  319. package/build/mongodb.js.map +0 -1
  320. package/build/operation-DF73RZOI.js.map +0 -1
  321. package/build/pg.js.map +0 -1
  322. package/build/policy-UYALkqVq.js.map +0 -1
  323. package/build/process-7R9M29wN.js +0 -437
  324. package/build/process-7R9M29wN.js.map +0 -1
  325. package/build/rabbitmq.js.map +0 -1
  326. package/build/redis.js.map +0 -1
  327. package/build/requests-DD2ALv0_.js +0 -583
  328. package/build/requests-DD2ALv0_.js.map +0 -1
  329. package/build/retrier-Dnjhvxol.js.map +0 -1
  330. package/build/timing-DZl36uXs.js.map +0 -1
  331. package/build/websocket.js.map +0 -1
@@ -0,0 +1,121 @@
1
+ import { CallContext } from "../call-context.js";
2
+ import { Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from "../client/core.js";
3
+ import { Judge } from "../client/dial.js";
4
+ import { Operation } from "../operation.js";
5
+ import { AgentFactory, HttpAgentOptions, HttpResponse } from "./connection.js";
6
+ import { Extent, Quantity } from "@mark1russell7/quantity";
7
+ /**
8
+ * These are the knobs of the client, each a time, by the names of the ordering law where the law
9
+ * has them. The runtime has no defaults, thus each knob is necessary. The constant
10
+ * `HTTP_CLIENT_STARTING_KNOBS` gives a declaration from the HTTP cells. The knobs that each client has come from the core.
11
+ */
12
+ export interface HttpClientKnobs extends ClientKnobs {
13
+ /** This time bounds the TCP connect of a new socket. The wrapper has this timer, because the agent has none. */
14
+ readonly connect_bound: Quantity;
15
+ /**
16
+ * This time bounds each call: from its start until the end of the body of its response. It also
17
+ * bounds the wait for a socket. The wrapper has this timer, because the agent has none.
18
+ */
19
+ readonly request_timeout: Quantity;
20
+ /**
21
+ * This time is the free socket timer of the agent (`timeout`). The agent closes a free socket at the
22
+ * smaller of this time and the hint of the server less `hint_buffer`. It must be below `server_idle_close` (O01).
23
+ */
24
+ readonly pool_idle_expiry: Extent;
25
+ /** This time is what the agent subtracts from the hint of the server (`agentKeepAliveTimeoutBuffer`). A hint at or below it gives no reuse. */
26
+ readonly hint_buffer: Quantity;
27
+ /**
28
+ * This time is when the server closes an idle connection, after its response. A Node server closes
29
+ * at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`. "infinite" is a server that keeps an idle
30
+ * connection with no bound. The client does not set it: `problems` compares it with `pool_idle_expiry` (O01).
31
+ */
32
+ readonly server_idle_close: Extent;
33
+ /** This time is the idle time of TCP keepalive (`keepAliveMsecs`), in whole seconds. The agent always turns keepalive on. */
34
+ readonly keepalive_idle: Extent;
35
+ /** The agent does not replace a connection at an age, thus this knob must be "infinite". */
36
+ readonly max_connection_age: Extent;
37
+ /** This time bounds the close of the client: the wait for the calls in flight, then a destroy of each socket. */
38
+ readonly close_bound: Quantity;
39
+ }
40
+ /** A check request is the request of the round-trip check, and of the first connection at the connect. */
41
+ export interface CheckRequest {
42
+ readonly method: string;
43
+ readonly path: string;
44
+ }
45
+ /**
46
+ * This request asks about the server, not about a resource (RFC 9110 §9.3.7). Thus it changes no
47
+ * state. A server that does not route it still answers with a status, and the status tells that it is alive.
48
+ */
49
+ export declare const OPTIONS_STAR: CheckRequest;
50
+ /** An HTTP client spec is the declaration of one HTTP client: the origin that it connects to, its pool, and its knobs. */
51
+ export interface HttpClientSpec extends ClientSpec<HttpClientKnobs> {
52
+ /** This count is the most sockets of the pool (`maxSockets`). It is also the most free sockets. */
53
+ readonly pool: {
54
+ readonly max: number;
55
+ };
56
+ /** This request is the request of the round-trip check and of the first connection. Without it, the client uses `OPTIONS *`. */
57
+ readonly check?: CheckRequest | undefined;
58
+ /**
59
+ * These operations add to the table of the client, or change it. The table names each method by
60
+ * its idempotency in RFC 9110. A caller can name an operation of its own, for example a POST with an `Idempotency-Key`.
61
+ */
62
+ readonly operations?: Readonly<Record<string, Operation>> | undefined;
63
+ }
64
+ /** These options make a client. Without them, it uses the agent of Node, the real clock, and a dial with `OPTIONS *`. */
65
+ export interface HttpClientOptions extends ClientOptions<AgentFactory> {
66
+ /**
67
+ * With this call context, each request gets the headers of the active context of its caller, for
68
+ * example `traceparent`. A header of the call with the same name stays. `callContext` of the entry `/otel` gives one.
69
+ */
70
+ readonly callContext?: CallContext | undefined;
71
+ }
72
+ /** An HTTP call is one request. A string body goes as UTF-8, with its `content-length`. */
73
+ export interface HttpCall {
74
+ readonly method: string;
75
+ readonly path: string;
76
+ readonly headers?: Readonly<Record<string, string>> | undefined;
77
+ readonly body?: string | Uint8Array | undefined;
78
+ /** This name is the operation of the call in the table. Without it, the operation is the method. */
79
+ readonly operation?: string | undefined;
80
+ }
81
+ /** An HTTP client is a dependency of a service: its declaration, its handle, its checks and its requests. */
82
+ export interface HttpClient extends Client<ClientStep, ClientJoin> {
83
+ /** This text is the state of the client, as `HTTP_CLIENT_MACHINE` names it. */
84
+ readonly status: string;
85
+ /**
86
+ * This method sends a request, and gives its outcome in three values. A whole response of each
87
+ * status is `ok`. The client sends again only an idempotent operation, one time at most, after an
88
+ * outcome that is not certain. The second try stays in the bound of the request.
89
+ */
90
+ request(call: HttpCall, options?: SendOptions): Promise<Sent<HttpResponse>>;
91
+ }
92
+ /**
93
+ * These operations are the methods of HTTP, by their idempotency in RFC 9110 §9.2.2. A second
94
+ * request of GET, HEAD, OPTIONS, TRACE, PUT or DELETE has the same effect as one. POST and PATCH do not.
95
+ */
96
+ export declare const HTTP_OPERATIONS: Readonly<Record<string, Operation>>;
97
+ /** This function gives the problems of a spec: the knobs that the agent cannot use. */
98
+ export declare const specProblems: (name: string, spec: HttpClientSpec) => string[];
99
+ /** This function gives the options of `new http.Agent` from a spec. Each timer of the agent comes from the declaration. */
100
+ export declare const agentOptions: (spec: HttpClientSpec) => HttpAgentOptions;
101
+ /** This function gives the bytes of the dial: `OPTIONS *` with the Host header, and a close after the answer. */
102
+ export declare const optionsRequest: (host: string, port: number) => string;
103
+ /** This judge reads the status line of the answer. Any status passes, because it tells that an HTTP server answered. */
104
+ export declare const statusJudge: Judge;
105
+ /** This dial function opens a TCP connection, sends `OPTIONS *`, and waits for the status line. It changes no state on the server. */
106
+ export declare const httpDial: DialFn;
107
+ /**
108
+ * This function makes an HTTP client, a dependency of a service over an `http.Agent` of Node.
109
+ * - It sets each timer of the agent from the declaration. The agent sends no request again by itself,
110
+ * and the client sends again only an idempotent operation of its table.
111
+ * - Its call is a request until the end of the body of its response. The wrapper has a timer for the
112
+ * connect and one for the call, because the agent has none.
113
+ * - It tells the outcome of a call in three values. A request that did not get a connected socket
114
+ * did not leave the client. A failure after that is not certain.
115
+ * - It destroys the socket of each call that is not `ok`, thus no later request gets that socket.
116
+ * - It records each new socket of the pool (D1). HTTP gives no id of a connection.
117
+ *
118
+ * The core of the clients gives the outcomes, the second try, the calls in flight and the timer of a
119
+ * call. It also gives the bounded close and the checks. This entry gives what the agent does in its own way.
120
+ */
121
+ export declare const httpClient: (name: string, spec: HttpClientSpec, options?: HttpClientOptions) => HttpClient;
@@ -0,0 +1,330 @@
1
+ import { realClock } from "../clock.js";
2
+ import { ageProblems, attachClient, clientBounds, clientProblems, clientRecorder, dialCheck, idleCloseProblem, inFlight, keepaliveOnProblems, localStateCheck, message, ms, notSent, operationTable, poolProblems, roundTripCheck, sendWithReissue, socketEnds, stepChecks, timeProblems, trackWithTimer, wholeProblems, withinBound, wrapperTimerProblems, zeroProblems } from "../client/core.js";
3
+ import { authority, helloDial, statusLineJudge } from "../client/dial.js";
4
+ import { nodeAgent } from "./connection.js";
5
+ import { httpClientMeetings } from "./meets.js";
6
+ // src/http-client/client.ts
7
+ /**
8
+ * This request asks about the server, not about a resource (RFC 9110 §9.3.7). Thus it changes no
9
+ * state. A server that does not route it still answers with a status, and the status tells that it is alive.
10
+ */
11
+ const OPTIONS_STAR = {
12
+ method: "OPTIONS",
13
+ path: "*"
14
+ };
15
+ /**
16
+ * These operations are the methods of HTTP, by their idempotency in RFC 9110 §9.2.2. A second
17
+ * request of GET, HEAD, OPTIONS, TRACE, PUT or DELETE has the same effect as one. POST and PATCH do not.
18
+ */
19
+ const HTTP_OPERATIONS = {
20
+ GET: { idempotent: true },
21
+ HEAD: { idempotent: true },
22
+ OPTIONS: { idempotent: true },
23
+ TRACE: { idempotent: true },
24
+ PUT: { idempotent: true },
25
+ DELETE: { idempotent: true },
26
+ POST: { idempotent: false },
27
+ PATCH: { idempotent: false }
28
+ };
29
+ /** This function gives the problems of a spec: the knobs that the agent cannot use. */
30
+ const specProblems = (name, spec) => {
31
+ const { knobs } = spec;
32
+ const problems = [
33
+ ...timeProblems(name, knobs),
34
+ ...wrapperTimerProblems(name, knobs, {
35
+ connect_bound: "a connect",
36
+ request_timeout: "a call"
37
+ }),
38
+ ...zeroProblems(name, "the agent", knobs, { bounded: ["pool_idle_expiry"] }),
39
+ ...keepaliveOnProblems(name, knobs, "the agent"),
40
+ ...wholeProblems(name, knobs, {
41
+ millis: [
42
+ "connect_bound",
43
+ "request_timeout",
44
+ "pool_idle_expiry",
45
+ "hint_buffer"
46
+ ],
47
+ seconds: ["keepalive_idle"]
48
+ }),
49
+ ...poolProblems(name, {
50
+ max: spec.pool.max,
51
+ min: 0
52
+ }),
53
+ ...ageProblems(name, knobs, "the agent does not replace a connection at an age")
54
+ ];
55
+ if (!Number.isFinite(ms(knobs.hint_buffer))) problems.push(`${name}'s hint_buffer is not a finite time: the agent subtracts it from the hint of the server`);
56
+ return problems;
57
+ };
58
+ /** This function gives the options of `new http.Agent` from a spec. Each timer of the agent comes from the declaration. */
59
+ const agentOptions = (spec) => {
60
+ const { knobs } = spec;
61
+ return {
62
+ keepAlive: true,
63
+ timeout: ms(knobs.pool_idle_expiry),
64
+ agentKeepAliveTimeoutBuffer: ms(knobs.hint_buffer),
65
+ keepAliveMsecs: ms(knobs.keepalive_idle),
66
+ maxSockets: spec.pool.max,
67
+ maxFreeSockets: spec.pool.max,
68
+ scheduling: "lifo"
69
+ };
70
+ };
71
+ /** This function gives the bytes of the dial: `OPTIONS *` with the Host header, and a close after the answer. */
72
+ const optionsRequest = (host, port) => `OPTIONS * HTTP/1.1\r\nHost: ${authority(host, port)}\r\nConnection: close\r\n\r\n`;
73
+ /** This judge reads the status line of the answer. Any status passes, because it tells that an HTTP server answered. */
74
+ const statusJudge = statusLineJudge(() => null);
75
+ /** This dial function opens a TCP connection, sends `OPTIONS *`, and waits for the status line. It changes no state on the server. */
76
+ const httpDial = (host, port, signal) => helloDial(optionsRequest(host, port), statusJudge)(host, port, signal);
77
+ /**
78
+ * This function makes an HTTP client, a dependency of a service over an `http.Agent` of Node.
79
+ * - It sets each timer of the agent from the declaration. The agent sends no request again by itself,
80
+ * and the client sends again only an idempotent operation of its table.
81
+ * - Its call is a request until the end of the body of its response. The wrapper has a timer for the
82
+ * connect and one for the call, because the agent has none.
83
+ * - It tells the outcome of a call in three values. A request that did not get a connected socket
84
+ * did not leave the client. A failure after that is not certain.
85
+ * - It destroys the socket of each call that is not `ok`, thus no later request gets that socket.
86
+ * - It records each new socket of the pool (D1). HTTP gives no id of a connection.
87
+ *
88
+ * The core of the clients gives the outcomes, the second try, the calls in flight and the timer of a
89
+ * call. It also gives the bounded close and the checks. This entry gives what the agent does in its own way.
90
+ */
91
+ const httpClient = (name, spec, options = {}) => {
92
+ const problems = specProblems(name, spec);
93
+ if (problems.length > 0) throw new Error(problems.join("; "));
94
+ const { knobs } = spec;
95
+ const clock = options.clock ?? realClock;
96
+ const create = options.create ?? nodeAgent;
97
+ const dial = options.dial ?? httpDial;
98
+ const operations = operationTable(HTTP_OPERATIONS, spec.operations);
99
+ const requestTimeout = ms(knobs.request_timeout);
100
+ const connectBound = ms(knobs.connect_bound);
101
+ const check = spec.check ?? OPTIONS_STAR;
102
+ let agent = null;
103
+ let status = "none";
104
+ const joins = [];
105
+ const flight = inFlight();
106
+ const waiting = /* @__PURE__ */ new Set();
107
+ const emit = clientRecorder(options.record, clock, name);
108
+ const record = (on, to = status, detail) => {
109
+ const from = status;
110
+ status = to;
111
+ emit(from, to, on, detail);
112
+ };
113
+ const closing = () => status === "closing" || status === "end";
114
+ /**
115
+ * This function makes one try of a call. The try waits for a socket of the agent: a free one, or a
116
+ * new one in `connect_bound`. A failure before the socket is ready is certain: the request did not
117
+ * leave the client. After that, the try waits for the whole response in the rest of `request_timeout`.
118
+ */
119
+ const attempt = async (call, signal) => {
120
+ const a = agent;
121
+ if (a === null) return notSent(`${name} has not connected`);
122
+ if (closing()) return notSent(`${name} is ${status}: the request did not leave the client`);
123
+ if (signal?.aborted) return notSent("the caller aborted the request before it left the client");
124
+ const started = clock.now();
125
+ const body = typeof call.body === "string" ? Buffer.from(call.body, "utf8") : call.body;
126
+ const headers = {
127
+ ...call.headers,
128
+ ...body === void 0 ? {} : { "content-length": String(body.byteLength) }
129
+ };
130
+ let socket;
131
+ let reused = false;
132
+ let left = false;
133
+ let ending = false;
134
+ let connectTimer = () => {};
135
+ let decide = () => {};
136
+ const leaving = new Promise((resolve) => {
137
+ let decided = false;
138
+ decide = (value) => {
139
+ if (decided) return;
140
+ decided = true;
141
+ resolve(value);
142
+ };
143
+ });
144
+ let deliver = null;
145
+ let early = null;
146
+ let settled = false;
147
+ const settleWith = (value, cause) => {
148
+ if (deliver === null) early ??= {
149
+ value,
150
+ cause
151
+ };
152
+ else deliver(value, cause);
153
+ };
154
+ let exchange = null;
155
+ const stop = (text) => {
156
+ if (left) return;
157
+ ending = true;
158
+ connectTimer();
159
+ exchange?.abort(new Error(text));
160
+ decide(notSent(text));
161
+ };
162
+ const ready = () => {
163
+ left = true;
164
+ connectTimer();
165
+ decide(true);
166
+ };
167
+ exchange = a.request({
168
+ host: spec.host,
169
+ port: spec.port,
170
+ method: call.method,
171
+ path: call.path,
172
+ headers,
173
+ body
174
+ }, {
175
+ socket(given, isReused) {
176
+ socket = given;
177
+ reused = isReused;
178
+ if (isReused) {
179
+ ready();
180
+ return;
181
+ }
182
+ connectTimer = clock.after(connectBound, () => {
183
+ if (left) return;
184
+ record("connect.failed", closing() ? status : "failing", "no connection in connect_bound");
185
+ stop("no connection in connect_bound: the request did not leave the client");
186
+ });
187
+ },
188
+ connect() {
189
+ const generation = joins.length + 1;
190
+ joins.push({
191
+ generation,
192
+ at: clock.now(),
193
+ ...socketEnds(socket)
194
+ });
195
+ record("join", closing() ? status : "ready", `socket ${generation}`);
196
+ ready();
197
+ }
198
+ });
199
+ exchange.response.then((response) => settleWith({
200
+ outcome: "ok",
201
+ value: response
202
+ }), (error) => {
203
+ const cause = error instanceof Error ? error : new Error(message(error));
204
+ if (!left) {
205
+ connectTimer();
206
+ if (!ending) record("connect.failed", closing() ? status : "failing", message(error));
207
+ decide(notSent(message(error)));
208
+ return;
209
+ }
210
+ if (settled) return;
211
+ if (reused) record("reuse.failed", status, message(error));
212
+ settleWith({
213
+ outcome: "indeterminate",
214
+ error: message(error)
215
+ }, cause);
216
+ });
217
+ const abandoned = () => stop("the caller abandoned the request before it left the client");
218
+ signal?.addEventListener("abort", abandoned, { once: true });
219
+ const queued = clock.after(requestTimeout, () => stop("no socket in request_timeout: the request did not leave the client"));
220
+ waiting.add(stop);
221
+ const got = await leaving;
222
+ signal?.removeEventListener("abort", abandoned);
223
+ queued();
224
+ waiting.delete(stop);
225
+ if (got !== true) return got;
226
+ const sent = exchange;
227
+ return trackWithTimer(flight, clock, Math.max(0, requestTimeout - (clock.now() - started)), signal, "the caller abandoned the request after it left the client", "no whole response in request_timeout: the server can have the request", (settle) => {
228
+ deliver = settle;
229
+ if (early !== null) settle(early.value, early.cause);
230
+ }, (value, cause) => {
231
+ settled = true;
232
+ if (value.outcome !== "ok") sent.abort(cause ?? new Error(value.error));
233
+ });
234
+ };
235
+ const request = (given, sendOptions = {}) => {
236
+ const call = options.callContext === void 0 ? given : {
237
+ ...given,
238
+ headers: {
239
+ ...options.callContext.headers(),
240
+ ...given.headers
241
+ }
242
+ };
243
+ const method = call.method.toUpperCase();
244
+ const named = call.operation ?? method;
245
+ return sendWithReissue({
246
+ clock,
247
+ bound: requestTimeout,
248
+ operation: operations[named],
249
+ options: sendOptions,
250
+ attempt: (signal) => attempt({
251
+ ...call,
252
+ method
253
+ }, signal),
254
+ onReissue: () => record("command.reissue", status, named)
255
+ });
256
+ };
257
+ const handle = {
258
+ async connect(signal) {
259
+ record("status.connecting", "connecting");
260
+ agent = await create(agentOptions(spec));
261
+ if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);
262
+ await request(check, {
263
+ signal,
264
+ reissue: false
265
+ });
266
+ },
267
+ async close() {
268
+ const a = agent;
269
+ if (a === null || closing()) return;
270
+ record("close.request", "closing");
271
+ for (const stop of [...waiting]) stop("the client closed before the request left");
272
+ if (!await withinBound(clock, ms(knobs.close_bound), flight.idle())) {
273
+ record("close.bound");
274
+ const open = a.sockets().length;
275
+ flight.settleAll("the client closed with the request in flight");
276
+ a.destroy();
277
+ record("close.destroy", status, `open sockets: ${open}`);
278
+ } else a.destroy();
279
+ record("status.end", "end");
280
+ }
281
+ };
282
+ const declaration = {
283
+ system: spec.system,
284
+ knobs: {
285
+ connect_bound: knobs.connect_bound,
286
+ request_timeout: knobs.request_timeout,
287
+ pool_idle_expiry: knobs.pool_idle_expiry,
288
+ hint_buffer: knobs.hint_buffer,
289
+ keepalive_idle: knobs.keepalive_idle,
290
+ idle_refresh_interval: knobs.keepalive_idle,
291
+ max_connection_age: knobs.max_connection_age,
292
+ close_bound: knobs.close_bound,
293
+ retrans_giveup_time: knobs.retrans_giveup_time
294
+ },
295
+ operations
296
+ };
297
+ const checks = (checkOptions) => stepChecks(name, checkOptions, {
298
+ "local-state": localStateCheck(() => status === "ready"),
299
+ "round-trip": roundTripCheck(async (sendOptions) => {
300
+ const sent = await request(check, sendOptions);
301
+ return sent.outcome === "ok" && sent.value.status >= 500 ? {
302
+ outcome: "error",
303
+ error: `the server answered ${sent.value.status}`,
304
+ reply: true,
305
+ attempts: sent.attempts
306
+ } : sent;
307
+ }),
308
+ dial: dialCheck(dial, spec.host, spec.port)
309
+ });
310
+ return {
311
+ name,
312
+ declaration,
313
+ handle,
314
+ meets: httpClientMeetings(name, knobs),
315
+ get status() {
316
+ return status;
317
+ },
318
+ joins,
319
+ request,
320
+ checks,
321
+ attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),
322
+ problems(description) {
323
+ const idle = idleCloseProblem(name, knobs.pool_idle_expiry, knobs.server_idle_close);
324
+ return [...clientProblems(name, description, clientBounds(knobs)), ...idle === null ? [] : [idle]];
325
+ }
326
+ };
327
+ };
328
+ export { HTTP_OPERATIONS, OPTIONS_STAR, agentOptions, httpClient, httpDial, optionsRequest, specProblems, statusJudge };
329
+
330
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/http-client/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport type { CallContext } from \"../call-context.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n ageProblems,\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n dialCheck,\n idleCloseProblem,\n inFlight,\n keepaliveOnProblems,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n trackWithTimer,\n wholeProblems,\n withinBound,\n wrapperTimerProblems,\n zeroProblems,\n} from \"../client/core.ts\";\nimport type { Judge } from \"../client/dial.ts\";\nimport { authority, helloDial, statusLineJudge } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { AgentExchange, AgentFactory, HttpAgent, HttpAgentOptions, HttpResponse, HttpSocket } from \"./connection.ts\";\nimport { nodeAgent } from \"./connection.ts\";\nimport { httpClientMeetings } from \"./meets.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law where the law\n * has them. The runtime has no defaults, thus each knob is necessary. The constant\n * `HTTP_CLIENT_STARTING_KNOBS` gives a declaration from the HTTP cells. The knobs that each client has come from the core.\n */\nexport interface HttpClientKnobs extends ClientKnobs {\n /** This time bounds the TCP connect of a new socket. The wrapper has this timer, because the agent has none. */\n readonly connect_bound: Quantity;\n /**\n * This time bounds each call: from its start until the end of the body of its response. It also\n * bounds the wait for a socket. The wrapper has this timer, because the agent has none.\n */\n readonly request_timeout: Quantity;\n /**\n * This time is the free socket timer of the agent (`timeout`). The agent closes a free socket at the\n * smaller of this time and the hint of the server less `hint_buffer`. It must be below `server_idle_close` (O01).\n */\n readonly pool_idle_expiry: Extent;\n /** This time is what the agent subtracts from the hint of the server (`agentKeepAliveTimeoutBuffer`). A hint at or below it gives no reuse. */\n readonly hint_buffer: Quantity;\n /**\n * This time is when the server closes an idle connection, after its response. A Node server closes\n * at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`. \"infinite\" is a server that keeps an idle\n * connection with no bound. The client does not set it: `problems` compares it with `pool_idle_expiry` (O01).\n */\n readonly server_idle_close: Extent;\n /** This time is the idle time of TCP keepalive (`keepAliveMsecs`), in whole seconds. The agent always turns keepalive on. */\n readonly keepalive_idle: Extent;\n /** The agent does not replace a connection at an age, thus this knob must be \"infinite\". */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client: the wait for the calls in flight, then a destroy of each socket. */\n readonly close_bound: Quantity;\n}\n\n/** A check request is the request of the round-trip check, and of the first connection at the connect. */\nexport interface CheckRequest {\n readonly method: string;\n readonly path: string;\n}\n\n/**\n * This request asks about the server, not about a resource (RFC 9110 §9.3.7). Thus it changes no\n * state. A server that does not route it still answers with a status, and the status tells that it is alive.\n */\nexport const OPTIONS_STAR: CheckRequest = { method: \"OPTIONS\", path: \"*\" };\n\n/** An HTTP client spec is the declaration of one HTTP client: the origin that it connects to, its pool, and its knobs. */\nexport interface HttpClientSpec extends ClientSpec<HttpClientKnobs> {\n /** This count is the most sockets of the pool (`maxSockets`). It is also the most free sockets. */\n readonly pool: { readonly max: number };\n /** This request is the request of the round-trip check and of the first connection. Without it, the client uses `OPTIONS *`. */\n readonly check?: CheckRequest | undefined;\n /**\n * These operations add to the table of the client, or change it. The table names each method by\n * its idempotency in RFC 9110. A caller can name an operation of its own, for example a POST with an `Idempotency-Key`.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses the agent of Node, the real clock, and a dial with `OPTIONS *`. */\nexport interface HttpClientOptions extends ClientOptions<AgentFactory> {\n /**\n * With this call context, each request gets the headers of the active context of its caller, for\n * example `traceparent`. A header of the call with the same name stays. `callContext` of the entry `/otel` gives one.\n */\n readonly callContext?: CallContext | undefined;\n}\n\n/** An HTTP call is one request. A string body goes as UTF-8, with its `content-length`. */\nexport interface HttpCall {\n readonly method: string;\n readonly path: string;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly body?: string | Uint8Array | undefined;\n /** This name is the operation of the call in the table. Without it, the operation is the method. */\n readonly operation?: string | undefined;\n}\n\n/** An HTTP client is a dependency of a service: its declaration, its handle, its checks and its requests. */\nexport interface HttpClient extends Client<ClientStep, ClientJoin> {\n /** This text is the state of the client, as `HTTP_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a request, and gives its outcome in three values. A whole response of each\n * status is `ok`. The client sends again only an idempotent operation, one time at most, after an\n * outcome that is not certain. The second try stays in the bound of the request.\n */\n request(call: HttpCall, options?: SendOptions): Promise<Sent<HttpResponse>>;\n}\n\n/**\n * These operations are the methods of HTTP, by their idempotency in RFC 9110 §9.2.2. A second\n * request of GET, HEAD, OPTIONS, TRACE, PUT or DELETE has the same effect as one. POST and PATCH do not.\n */\nexport const HTTP_OPERATIONS: Readonly<Record<string, Operation>> = {\n GET: { idempotent: true },\n HEAD: { idempotent: true },\n OPTIONS: { idempotent: true },\n TRACE: { idempotent: true },\n PUT: { idempotent: true },\n DELETE: { idempotent: true },\n POST: { idempotent: false },\n PATCH: { idempotent: false },\n};\n\n/** This function gives the problems of a spec: the knobs that the agent cannot use. */\nexport const specProblems = (name: string, spec: HttpClientSpec): string[] => {\n const { knobs } = spec;\n const problems = [\n ...timeProblems(name, knobs),\n // the agent has no timer of a connect or of a call\n ...wrapperTimerProblems(name, knobs, { connect_bound: \"a connect\", request_timeout: \"a call\" }),\n // the agent reads a timeout of 0 as no free socket timer, and then the hint of the server does not apply\n ...zeroProblems(name, \"the agent\", knobs, { bounded: [\"pool_idle_expiry\"] }),\n ...keepaliveOnProblems(name, knobs, \"the agent\"),\n // Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, { millis: [\"connect_bound\", \"request_timeout\", \"pool_idle_expiry\", \"hint_buffer\"], seconds: [\"keepalive_idle\"] }),\n ...poolProblems(name, { max: spec.pool.max, min: 0 }),\n ...ageProblems(name, knobs, \"the agent does not replace a connection at an age\"),\n ];\n if (!Number.isFinite(ms(knobs.hint_buffer))) problems.push(`${name}'s hint_buffer is not a finite time: the agent subtracts it from the hint of the server`);\n return problems;\n};\n\n/** This function gives the options of `new http.Agent` from a spec. Each timer of the agent comes from the declaration. */\nexport const agentOptions = (spec: HttpClientSpec): HttpAgentOptions => {\n const { knobs } = spec;\n return {\n keepAlive: true,\n timeout: ms(knobs.pool_idle_expiry),\n agentKeepAliveTimeoutBuffer: ms(knobs.hint_buffer),\n keepAliveMsecs: ms(knobs.keepalive_idle),\n maxSockets: spec.pool.max,\n maxFreeSockets: spec.pool.max,\n scheduling: \"lifo\",\n };\n};\n\n/** This function gives the bytes of the dial: `OPTIONS *` with the Host header, and a close after the answer. */\nexport const optionsRequest = (host: string, port: number): string => `OPTIONS * HTTP/1.1\\r\\nHost: ${authority(host, port)}\\r\\nConnection: close\\r\\n\\r\\n`;\n\n/** This judge reads the status line of the answer. Any status passes, because it tells that an HTTP server answered. */\nexport const statusJudge: Judge = statusLineJudge(() => null);\n\n/** This dial function opens a TCP connection, sends `OPTIONS *`, and waits for the status line. It changes no state on the server. */\nexport const httpDial: DialFn = (host, port, signal) => helloDial(optionsRequest(host, port), statusJudge)(host, port, signal);\n\n/**\n * This function makes an HTTP client, a dependency of a service over an `http.Agent` of Node.\n * - It sets each timer of the agent from the declaration. The agent sends no request again by itself,\n * and the client sends again only an idempotent operation of its table.\n * - Its call is a request until the end of the body of its response. The wrapper has a timer for the\n * connect and one for the call, because the agent has none.\n * - It tells the outcome of a call in three values. A request that did not get a connected socket\n * did not leave the client. A failure after that is not certain.\n * - It destroys the socket of each call that is not `ok`, thus no later request gets that socket.\n * - It records each new socket of the pool (D1). HTTP gives no id of a connection.\n *\n * The core of the clients gives the outcomes, the second try, the calls in flight and the timer of a\n * call. It also gives the bounded close and the checks. This entry gives what the agent does in its own way.\n */\nexport const httpClient = (name: string, spec: HttpClientSpec, options: HttpClientOptions = {}): HttpClient => {\n const problems = specProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { knobs } = spec;\n const clock = options.clock ?? realClock;\n const create = options.create ?? nodeAgent;\n const dial = options.dial ?? httpDial;\n const operations = operationTable(HTTP_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const connectBound = ms(knobs.connect_bound);\n const check = spec.check ?? OPTIONS_STAR;\n\n let agent: HttpAgent | null = null;\n let status = \"none\";\n const joins: ClientJoin[] = [];\n // the calls that left the client: the close waits for them, in its bound\n const flight = inFlight();\n // the calls that did not leave the client: the close ends each one as not sent\n const waiting = new Set<(error: string) => void>();\n\n const emit = clientRecorder(options.record, clock, name);\n // the state of the client is the outcome of the last connect of a socket of its pool\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n /**\n * This function makes one try of a call. The try waits for a socket of the agent: a free one, or a\n * new one in `connect_bound`. A failure before the socket is ready is certain: the request did not\n * leave the client. After that, the try waits for the whole response in the rest of `request_timeout`.\n */\n const attempt = async (call: HttpCall, signal: AbortSignal | undefined): Promise<Attempt<HttpResponse>> => {\n const a = agent;\n if (a === null) return notSent(`${name} has not connected`);\n if (closing()) return notSent(`${name} is ${status}: the request did not leave the client`);\n if (signal?.aborted) return notSent(\"the caller aborted the request before it left the client\");\n const started = clock.now();\n const body = typeof call.body === \"string\" ? Buffer.from(call.body, \"utf8\") : call.body;\n const headers = { ...call.headers, ...(body === undefined ? {} : { \"content-length\": String(body.byteLength) }) };\n\n let socket: HttpSocket | undefined;\n let reused = false;\n let left = false;\n // true when the wrapper ended the try itself: the error of the agent that follows is not a failed connect\n let ending = false;\n let connectTimer: Cancel = () => {};\n let decide: (value: true | Attempt<never>) => void = () => {};\n const leaving = new Promise<true | Attempt<never>>((resolve) => {\n let decided = false;\n decide = (value) => {\n if (decided) return;\n decided = true;\n resolve(value);\n };\n });\n // a result of the agent that arrives before the try records it\n let deliver: ((value: Attempt<HttpResponse>, cause?: Error) => void) | null = null;\n let early: { readonly value: Attempt<HttpResponse>; readonly cause: Error | undefined } | null = null;\n let settled = false;\n const settleWith = (value: Attempt<HttpResponse>, cause?: Error): void => {\n if (deliver === null) early ??= { value, cause };\n else deliver(value, cause);\n };\n\n let exchange: AgentExchange | null = null;\n const stop = (text: string): void => {\n if (left) return;\n ending = true;\n connectTimer();\n exchange?.abort(new Error(text));\n decide(notSent(text));\n };\n const ready = (): void => {\n left = true;\n connectTimer();\n decide(true);\n };\n exchange = a.request(\n { host: spec.host, port: spec.port, method: call.method, path: call.path, headers, body },\n {\n socket(given, isReused) {\n socket = given;\n reused = isReused;\n if (isReused) {\n ready();\n return;\n }\n connectTimer = clock.after(connectBound, () => {\n if (left) return;\n record(\"connect.failed\", closing() ? status : \"failing\", \"no connection in connect_bound\");\n stop(\"no connection in connect_bound: the request did not leave the client\");\n });\n },\n connect() {\n const generation = joins.length + 1;\n joins.push({ generation, at: clock.now(), ...socketEnds(socket) });\n record(\"join\", closing() ? status : \"ready\", `socket ${generation}`);\n ready();\n },\n },\n );\n // the agent can fail a request in its queue or at its connect: it did not leave the client\n exchange.response.then(\n (response) => settleWith({ outcome: \"ok\", value: response }),\n (error: unknown) => {\n const cause = error instanceof Error ? error : new Error(message(error));\n if (!left) {\n connectTimer();\n if (!ending) record(\"connect.failed\", closing() ? status : \"failing\", message(error));\n decide(notSent(message(error)));\n return;\n }\n // the abort of the wrapper after the call settled is not a failure of the socket\n if (settled) return;\n // a reused socket that fails before the response: the server closed it, as in the keep-alive race\n if (reused) record(\"reuse.failed\", status, message(error));\n settleWith({ outcome: \"indeterminate\", error: message(error) }, cause);\n },\n );\n\n const abandoned = (): void => stop(\"the caller abandoned the request before it left the client\");\n signal?.addEventListener(\"abort\", abandoned, { once: true });\n const queued = clock.after(requestTimeout, () => stop(\"no socket in request_timeout: the request did not leave the client\"));\n waiting.add(stop);\n const got = await leaving;\n signal?.removeEventListener(\"abort\", abandoned);\n queued();\n waiting.delete(stop);\n if (got !== true) return got;\n\n const sent = exchange;\n return trackWithTimer<HttpResponse>(\n flight,\n clock,\n Math.max(0, requestTimeout - (clock.now() - started)),\n signal,\n \"the caller abandoned the request after it left the client\",\n \"no whole response in request_timeout: the server can have the request\",\n (settle) => {\n deliver = settle;\n if (early !== null) settle(early.value, early.cause);\n },\n (value, cause) => {\n settled = true;\n // the socket of a call that is not ok can hold a part of a response: it goes, and no later request gets it\n if (value.outcome !== \"ok\") sent.abort(cause ?? new Error(value.error));\n },\n );\n };\n\n const request = (given: HttpCall, sendOptions: SendOptions = {}): Promise<Sent<HttpResponse>> => {\n // the headers of the context of the caller, read now: each try of the call sends the same ones\n const call = options.callContext === undefined ? given : { ...given, headers: { ...options.callContext.headers(), ...given.headers } };\n const method = call.method.toUpperCase();\n const named = call.operation ?? method;\n return sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[named],\n options: sendOptions,\n attempt: (signal) => attempt({ ...call, method }, signal),\n onReissue: () => record(\"command.reissue\", status, named),\n });\n };\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n agent = await create(agentOptions(spec));\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // the check request opens the first socket of the pool. A server that is down does not stop the\n // startup: the checks keep readiness tripped until a connect succeeds (readiness is earned)\n await request(check, { signal, reissue: false });\n },\n async close() {\n const a = agent;\n if (a === null || closing()) return;\n record(\"close.request\", \"closing\");\n for (const stop of [...waiting]) stop(\"the client closed before the request left\");\n // the agent has no close that waits: the client waits for its calls in flight, in its bound\n if (!(await withinBound(clock, ms(knobs.close_bound), flight.idle()))) {\n record(\"close.bound\");\n const open = a.sockets().length;\n flight.settleAll(\"the client closed with the request in flight\");\n a.destroy();\n record(\"close.destroy\", status, `open sockets: ${open}`);\n } else {\n // each free socket closes with a FIN\n a.destroy();\n }\n record(\"status.end\", \"end\");\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n hint_buffer: knobs.hint_buffer,\n keepalive_idle: knobs.keepalive_idle,\n // the agent sends nothing on a free socket, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions) =>\n stepChecks<ClientStep>(name, checkOptions, {\n // the outcome of the last connect of a socket, without a round trip\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // the check request through the pool of the application. A status of 500 or more fails it\n \"round-trip\": roundTripCheck(async (sendOptions) => {\n const sent = await request(check, sendOptions);\n return sent.outcome === \"ok\" && sent.value.status >= 500\n ? { outcome: \"error\", error: `the server answered ${sent.value.status}`, reply: true, attempts: sent.attempts }\n : sent;\n }),\n // a new connection each time, with OPTIONS *\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: httpClientMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n request,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O01: the pool must close an idle socket before the server does\n const idle = idleCloseProblem(name, knobs.pool_idle_expiry, knobs.server_idle_close);\n return [...clientProblems(name, description, clientBounds(knobs)), ...(idle === null ? [] : [idle])];\n },\n };\n};\n"],"mappings":";;;;;;;;;;AAqFA,MAAa,eAA6B;CAAE,QAAQ;CAAW,MAAM;AAAI;;;;;AAkDzE,MAAa,kBAAuD;CAClE,KAAK,EAAE,YAAY,KAAK;CACxB,MAAM,EAAE,YAAY,KAAK;CACzB,SAAS,EAAE,YAAY,KAAK;CAC5B,OAAO,EAAE,YAAY,KAAK;CAC1B,KAAK,EAAE,YAAY,KAAK;CACxB,QAAQ,EAAE,YAAY,KAAK;CAC3B,MAAM,EAAE,YAAY,MAAM;CAC1B,OAAO,EAAE,YAAY,MAAM;AAC7B;;AAGA,MAAa,gBAAgB,MAAc,SAAmC;CAC5E,MAAM,EAAE,UAAU;CAClB,MAAM,WAAW;EACf,GAAG,aAAa,MAAM,KAAK;EAE3B,GAAG,qBAAqB,MAAM,OAAO;GAAE,eAAe;GAAa,iBAAiB;EAAS,CAAC;EAE9F,GAAG,aAAa,MAAM,aAAa,OAAO,EAAE,SAAS,CAAC,kBAAkB,EAAE,CAAC;EAC3E,GAAG,oBAAoB,MAAM,OAAO,WAAW;EAE/C,GAAG,cAAc,MAAM,OAAO;GAAE,QAAQ;IAAC;IAAiB;IAAmB;IAAoB;GAAa;GAAG,SAAS,CAAC,gBAAgB;EAAE,CAAC;EAC9I,GAAG,aAAa,MAAM;GAAE,KAAK,KAAK,KAAK;GAAK,KAAK;EAAE,CAAC;EACpD,GAAG,YAAY,MAAM,OAAO,mDAAmD;CACjF;CACA,IAAI,CAAC,OAAO,SAAS,GAAG,MAAM,WAAW,CAAC,GAAG,SAAS,KAAK,GAAG,KAAK,wFAAwF;CAC3J,OAAO;AACT;;AAGA,MAAa,gBAAgB,SAA2C;CACtE,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,WAAW;EACX,SAAS,GAAG,MAAM,gBAAgB;EAClC,6BAA6B,GAAG,MAAM,WAAW;EACjD,gBAAgB,GA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V,OAAO,iBAAiB,QAAQ,iBAAiB,MAAM;GACzD,OAEE,EAAE,QAAQ;GAEZ,OAAO,cAAc,KAAK;EAC5B;CACF;CAEA,MAAM,cAAwC;EAC5C,QAAQ,KAAK;EACb,OAAO;GACL,eAAe,MAAM;GACrB,iBAAiB,MAAM;GACvB,kBAAkB,MAAM;GACxB,aAAa,MAAM;GACnB,gBAAgB,MAAM;GAEtB,uBAAuB,MAAM;GAC7B,oBAAoB,MAAM;GAC1B,aAAa,MAAM;GACnB,qBAAqB,MAAM;EAC7B;EACA;CACF;CAEA,MAAM,UAAU,iBACd,WAAuB,MAAM,cAAc;EAEzC,eAAe,sBAAsB,WAAW,OAAO;EAEvD,cAAc,eAAe,OAAO,gBAAgB;GAClD,MAAM,OAAO,MAAM,QAAQ,OAAO,WAAW;GAC7C,OAAO,KAAK,YAAY,QAAQ,KAAK,MAAM,UAAU,MACjD;IAAE,SAAS;IAAS,OAAO,uBAAuB,KAAK,MAAM;IAAU,OAAO;IAAM,UAAU,KAAK;GAAS,IAC5G;EACN,CAAC;EAED,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,mBAAmB,MAAM,KAAK;EACrC,IAAI,SAAS;GACX,OAAO;EACT;EACA;EACA;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,SAAS,aAAa;GAEpB,MAAM,OAAO,iBAAiB,MAAM,MAAM,kBAAkB,MAAM,iBAAiB;GACnF,OAAO,CAAC,GAAG,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC,GAAG,GAAI,SAAS,OAAO,CAAC,IAAI,CAAC,IAAI,CAAE;EACrG;CACF;AACF"}
@@ -0,0 +1,78 @@
1
+ import { ClientSocket, Factory } from "../client/core.js";
2
+ /** An HTTP socket is the socket of a client in the core: the join of the prober and the bounded close read it. */
3
+ export type HttpSocket = ClientSocket;
4
+ /** An HTTP response is a whole response: its status, its headers, and its whole body. */
5
+ export interface HttpResponse {
6
+ readonly status: number;
7
+ /** These are the headers of the response, by their names in lower case, as Node gives them. */
8
+ readonly headers: Readonly<Record<string, string | readonly string[] | undefined>>;
9
+ readonly body: Buffer;
10
+ }
11
+ /** An agent request is one request that the wrapper gives the agent. */
12
+ export interface AgentRequest {
13
+ readonly host: string;
14
+ readonly port: number;
15
+ readonly method: string;
16
+ readonly path: string;
17
+ readonly headers: Readonly<Record<string, string>>;
18
+ readonly body?: Uint8Array | undefined;
19
+ }
20
+ /**
21
+ * These are the events of one request that the wrapper reads. The agent gives each one at most one
22
+ * time. `connect` comes only for a new connection. A request on a free socket left the client when it got that socket.
23
+ */
24
+ export interface AgentEvents {
25
+ /** The agent gave the request a socket. `reused` is true for a socket from the free list (`req.reusedSocket`). */
26
+ socket(socket: HttpSocket, reused: boolean): void;
27
+ /** The new socket of the request connected. The request then leaves the client. */
28
+ connect(): void;
29
+ }
30
+ /** An agent exchange is one request in the agent: the promise of its whole response, and the abort that destroys its socket. */
31
+ export interface AgentExchange {
32
+ /** This promise resolves with the whole response, or rejects with the error of the request, the socket or the body. */
33
+ readonly response: Promise<HttpResponse>;
34
+ /** This method destroys the request and its socket. A request that waits for a socket leaves the queue of the agent. */
35
+ abort(error: Error): void;
36
+ }
37
+ /**
38
+ * An agent is the part of an `http.Agent` of Node that the wrapper uses, with `http.request` on it.
39
+ * A fake for tests has each part too. Thus the wrapper does not load node:http until it connects.
40
+ */
41
+ export interface HttpAgent {
42
+ /** This method sends one request on the agent. */
43
+ request(request: AgentRequest, events: AgentEvents): AgentExchange;
44
+ /** This method gives each socket of the agent that is open: the busy ones and the free ones. */
45
+ sockets(): readonly HttpSocket[];
46
+ /** This method destroys each socket of the agent. A request on a socket then fails. */
47
+ destroy(): void;
48
+ }
49
+ /**
50
+ * These are the options that the wrapper gives `new http.Agent`. Each one comes from the declaration.
51
+ * The wrapper sets each option that has an effect on a timer, thus no default of Node decides one.
52
+ */
53
+ export interface HttpAgentOptions {
54
+ readonly keepAlive: true;
55
+ /**
56
+ * This time is the free socket timer (`timeout`). The agent closes a free socket at the smaller of
57
+ * this time and the hint of the server less `agentKeepAliveTimeoutBuffer`. 0 is no timer, and then the hint does not apply.
58
+ */
59
+ readonly timeout: number;
60
+ /** This time is subtracted from the hint of the server (`Keep-Alive: timeout=…`). A hint at or below it gives no reuse. */
61
+ readonly agentKeepAliveTimeoutBuffer: number;
62
+ /** This time is the idle time of TCP keepalive. The agent always turns keepalive on, and Node truncates the time to whole seconds. */
63
+ readonly keepAliveMsecs: number;
64
+ /** This count is the most sockets for one origin. A request waits in the agent for a socket above it. */
65
+ readonly maxSockets: number;
66
+ /** This count is the most free sockets for one origin. */
67
+ readonly maxFreeSockets: number;
68
+ /** The agent gives the socket that was free last, as the global agent does. */
69
+ readonly scheduling: "lifo";
70
+ }
71
+ /** An agent factory makes the agent of the client from its options. */
72
+ export type AgentFactory = Factory<HttpAgentOptions, HttpAgent>;
73
+ /**
74
+ * This factory makes an `http.Agent` of Node. It loads node:http only when a client connects.
75
+ * Each request goes through `http.request` with the agent. The response settles at the end of its body.
76
+ * A body that ends before it is complete rejects the response.
77
+ */
78
+ export declare const nodeAgent: AgentFactory;
@@ -0,0 +1,54 @@
1
+ // src/http-client/connection.ts
2
+ /**
3
+ * This factory makes an `http.Agent` of Node. It loads node:http only when a client connects.
4
+ * Each request goes through `http.request` with the agent. The response settles at the end of its body.
5
+ * A body that ends before it is complete rejects the response.
6
+ */
7
+ const nodeAgent = async (options) => {
8
+ const http = await import("node:http");
9
+ const agent = new http.Agent(options);
10
+ const all = (lists) => Object.values(lists).flatMap((list) => list ?? []);
11
+ return {
12
+ request(request, events) {
13
+ const req = http.request({
14
+ host: request.host,
15
+ port: request.port,
16
+ method: request.method,
17
+ path: request.path,
18
+ headers: request.headers,
19
+ agent
20
+ });
21
+ const response = new Promise((resolve, reject) => {
22
+ req.on("socket", (socket) => {
23
+ events.socket(socket, req.reusedSocket);
24
+ if (socket.connecting) socket.once("connect", () => events.connect());
25
+ else if (!req.reusedSocket) events.connect();
26
+ });
27
+ req.on("response", (incoming) => {
28
+ const chunks = [];
29
+ incoming.on("data", (chunk) => chunks.push(chunk));
30
+ incoming.on("error", reject);
31
+ incoming.on("end", () => resolve({
32
+ status: incoming.statusCode ?? 0,
33
+ headers: incoming.headers,
34
+ body: Buffer.concat(chunks)
35
+ }));
36
+ incoming.on("close", () => {
37
+ if (!incoming.complete) reject(/* @__PURE__ */ new Error("the connection closed before the end of the body"));
38
+ });
39
+ });
40
+ req.on("error", reject);
41
+ });
42
+ req.end(request.body);
43
+ return {
44
+ response,
45
+ abort: (error) => req.destroy(error)
46
+ };
47
+ },
48
+ sockets: () => [...all(agent.sockets), ...all(agent.freeSockets)],
49
+ destroy: () => agent.destroy()
50
+ };
51
+ };
52
+ export { nodeAgent };
53
+
54
+ //# sourceMappingURL=connection.js.map