@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,83 @@
1
+ import { Health, ProbeKind } from "../health.js";
2
+ import { HealthServer } from "../lifecycle.js";
3
+ import { RequestHandler } from "./transport.js";
4
+ import { Quantity } from "@mark1russell7/quantity";
5
+ import { ListenOptions } from "node:net";
6
+ import { Server } from "node:http";
7
+ /** A probe response is the status, the headers and the body of one probe, for any HTTP framework or none. */
8
+ export interface ProbeResponse {
9
+ readonly status: number;
10
+ readonly headers: Readonly<Record<string, string>>;
11
+ readonly body: string;
12
+ }
13
+ /** A health source is the health runtime, or a function that gives it when it exists. */
14
+ export type HealthSource = Health | (() => Health | null | undefined);
15
+ /**
16
+ * These are the four probe kinds, in the sequence of their paths. A probe server and a probe handler
17
+ * answer all four, unless their option `kinds` names fewer.
18
+ */
19
+ export declare const PROBE_KINDS: readonly ProbeKind[];
20
+ /**
21
+ * Probe paths are more paths for each probe kind, for example `{ liveness: ["/livez", "/healthz"] }`.
22
+ * Each path is a whole path, and the prefix does not go before it. The paths of `PROBE_KINDS` still answer.
23
+ */
24
+ export type ProbePaths = Partial<Readonly<Record<ProbeKind, readonly string[]>>>;
25
+ /**
26
+ * This function gives the response of a probe path from the cache of the health runtime. For a path
27
+ * that is not a probe, it gives null. The paths are `/startup`, `/readiness`, `/liveness` and
28
+ * `/report` after the prefix. `/readiness/<controller>` gives the readiness of one controller.
29
+ * `kinds` names the probes that answer. The path of a kind that it does not name is not a probe.
30
+ *
31
+ * `aliases` gives the probe kind of each more path. A more path of readiness has no controller.
32
+ */
33
+ export declare const probeResponse: (health: Health | null | undefined, method: string | undefined, path: string, prefix?: string, kinds?: readonly ProbeKind[], aliases?: ReadonlyMap<string, ProbeKind>) => ProbeResponse | null;
34
+ /** These options mount the probes on the port of the application. */
35
+ export interface ProbeHandlerOptions {
36
+ /** This path goes before each probe path, for example `/health`. It starts with `/`, or it is empty. */
37
+ readonly prefix: string;
38
+ /**
39
+ * These are the probes that the handler answers. The default is all four of `PROBE_KINDS`. The
40
+ * path of a kind that the list does not name goes to the next handler.
41
+ */
42
+ readonly kinds?: readonly ProbeKind[] | undefined;
43
+ /**
44
+ * These are more paths for each probe kind, for example `{ liveness: ["/livez", "/healthz"] }`. Each is
45
+ * a whole path, with no prefix. Without them, the handler answers only the paths of `PROBE_KINDS`.
46
+ */
47
+ readonly paths?: ProbePaths | undefined;
48
+ }
49
+ /**
50
+ * This function gives a request handler that answers the probes on the port of the application. It
51
+ * answers until `close transports`, thus its mount keeps the listener open through the drain. A path
52
+ * that is not a probe goes to the next handler. Each 503 gets the `Retry-After` of the context.
53
+ */
54
+ export declare const probeHandler: (health: HealthSource, options: ProbeHandlerOptions) => RequestHandler;
55
+ /** These options make a probe server: the listen options of its port, the prefix of its paths, and the time of a retry. */
56
+ export interface ProbeServerOptions extends ListenOptions {
57
+ /**
58
+ * This time goes in the `Retry-After` of each 503 of a probe, as on the port of the application.
59
+ * The probe server has no defaults, thus the knob is necessary.
60
+ */
61
+ readonly server_retry_after: Quantity;
62
+ /** This path goes before each probe path. The default is no prefix, because the port has only the probes. */
63
+ readonly prefix?: string | undefined;
64
+ /** This server answers the probes. Without it, the probe server makes a server of `node:http`. */
65
+ readonly server?: Server | undefined;
66
+ /**
67
+ * These are the probes that the server answers. The default is all four of `PROBE_KINDS`. The path
68
+ * of a kind that the list does not name gets 404, as each other path.
69
+ */
70
+ readonly kinds?: readonly ProbeKind[] | undefined;
71
+ /** These are more paths for each probe kind, as the option `paths` of `probeHandler`. */
72
+ readonly paths?: ProbePaths | undefined;
73
+ }
74
+ /** A probe server is a health server on its own port. Its server is visible for the address of the port. */
75
+ export interface ProbeServer extends HealthServer {
76
+ readonly server: Server;
77
+ }
78
+ /**
79
+ * This function makes a health server on a port of its own (S6 decision D5). It starts first and
80
+ * closes last, thus the probes answer through the whole drain. Each probe answers from the cache, and
81
+ * each 503 gets the `Retry-After` of `server_retry_after`.
82
+ */
83
+ export declare const probeServer: (options: ProbeServerOptions) => ProbeServer;
@@ -0,0 +1,232 @@
1
+ import { pathOf, retryAfterOf } from "./transport.js";
2
+ import { createServer } from "node:http";
3
+ // src/http/probes.ts
4
+ /**
5
+ * These are the four probe kinds, in the sequence of their paths. A probe server and a probe handler
6
+ * answer all four, unless their option `kinds` names fewer.
7
+ */
8
+ const PROBE_KINDS = Object.freeze([
9
+ "startup",
10
+ "readiness",
11
+ "liveness",
12
+ "report"
13
+ ]);
14
+ const named = PROBE_KINDS.map((kind) => `"${kind}"`).join(", ");
15
+ /**
16
+ * This function gives the probe kinds of an option `kinds`: all four when it is undefined, or else a
17
+ * frozen copy. It refuses a value that is not a list, an empty list, an unknown kind and a kind two times.
18
+ */
19
+ const kindsOf = (kinds) => {
20
+ if (kinds === void 0) return PROBE_KINDS;
21
+ if (!Array.isArray(kinds)) throw new Error(`the probe kinds ${JSON.stringify(kinds)} are not a list of ${named}`);
22
+ if (kinds.length === 0) throw new Error(`the probe kinds are an empty list: name one or more of ${named}`);
23
+ const seen = /* @__PURE__ */ new Set();
24
+ for (const kind of kinds) {
25
+ if (!PROBE_KINDS.includes(kind)) throw new Error(`the probe kind ${JSON.stringify(kind)} is not one of ${named}`);
26
+ if (seen.has(kind)) throw new Error(`the probe kind "${kind}" is two times in the probe kinds`);
27
+ seen.add(kind);
28
+ }
29
+ return Object.freeze([...kinds]);
30
+ };
31
+ const NO_ALIASES = /* @__PURE__ */ new Map();
32
+ /**
33
+ * This function gives the probe kind of each more path of an option `paths`. It refuses a key that is
34
+ * not a probe kind, and a kind that `kinds` does not name. It refuses a path that does not start
35
+ * with `/`, or ends with `/`. It also refuses a path two times, and a path of `PROBE_KINDS` after the prefix.
36
+ */
37
+ const aliasesOf = (paths, kinds, prefix) => {
38
+ if (paths === void 0) return NO_ALIASES;
39
+ if (paths === null || typeof paths !== "object" || Array.isArray(paths)) throw new Error(`the probe paths ${JSON.stringify(paths)} are not an object of probe kinds`);
40
+ const aliases = /* @__PURE__ */ new Map();
41
+ for (const [key, list] of Object.entries(paths)) {
42
+ const kind = key;
43
+ if (!PROBE_KINDS.includes(kind)) throw new Error(`the probe paths name ${JSON.stringify(key)}, which is not one of ${named}`);
44
+ if (!kinds.includes(kind)) throw new Error(`the probe paths name "${kind}", but the probe kinds do not`);
45
+ if (!Array.isArray(list)) throw new Error(`the probe paths of "${kind}" are not a list`);
46
+ for (const path of list) {
47
+ if (typeof path !== "string" || !path.startsWith("/") || path.length < 2 || path.endsWith("/") || /[?#]/.test(path)) throw new Error(`the probe path ${JSON.stringify(path)} of "${kind}" does not start with "/", ends with "/", or has a query`);
48
+ if (aliases.has(path)) throw new Error(`the probe path "${path}" is two times in the probe paths`);
49
+ if (PROBE_KINDS.some((each) => path === `${prefix}/${each}` || path.startsWith(`${prefix}/${each}/`))) throw new Error(`the probe path "${path}" is a path of a probe kind after the prefix "${prefix}"`);
50
+ aliases.set(path, kind);
51
+ }
52
+ }
53
+ return aliases;
54
+ };
55
+ /** This function gives the probe kind and the controller of a path, or null for a path that is not a probe. */
56
+ const probeTarget = (path, prefix, kinds, aliases) => {
57
+ const alias = aliases.get(path);
58
+ if (alias !== void 0) return {
59
+ kind: alias,
60
+ controller: void 0
61
+ };
62
+ if (!path.startsWith(`${prefix}/`)) return null;
63
+ const parts = path.slice(prefix.length + 1).split("/");
64
+ const kind = PROBE_KINDS.find((each) => each === parts[0] && kinds.includes(each));
65
+ if (kind === void 0) return null;
66
+ const controller = parts[1];
67
+ if (parts.length > 2 || controller !== void 0 && (kind !== "readiness" || controller === "")) return null;
68
+ return {
69
+ kind,
70
+ controller
71
+ };
72
+ };
73
+ const prefixProblem = (prefix) => prefix === "" || prefix.startsWith("/") && !prefix.endsWith("/") ? null : `the probe prefix "${prefix}" does not start with "/", or it ends with "/"`;
74
+ /** These escapes replace `<`, `>` and `&` in a JSON body. The JSON stays valid, with the same value, and no part of it is markup. */
75
+ const ESCAPES = {
76
+ "<": "\\u003c",
77
+ ">": "\\u003e",
78
+ "&": "\\u0026"
79
+ };
80
+ /**
81
+ * This function gives a JSON answer, and its body escapes `<`, `>` and `&`. A body can repeat a part
82
+ * of the path. An example is the name of a controller that the service does not have.
83
+ */
84
+ const json = (status, body) => ({
85
+ status,
86
+ headers: {
87
+ "content-type": "application/health+json",
88
+ "cache-control": "no-store"
89
+ },
90
+ body: JSON.stringify(body).replace(/[<>&]/g, (char) => ESCAPES[char])
91
+ });
92
+ /**
93
+ * This function gives the response of a probe path from the cache of the health runtime. For a path
94
+ * that is not a probe, it gives null. The paths are `/startup`, `/readiness`, `/liveness` and
95
+ * `/report` after the prefix. `/readiness/<controller>` gives the readiness of one controller.
96
+ * `kinds` names the probes that answer. The path of a kind that it does not name is not a probe.
97
+ *
98
+ * `aliases` gives the probe kind of each more path. A more path of readiness has no controller.
99
+ */
100
+ const probeResponse = (health, method, path, prefix = "", kinds = PROBE_KINDS, aliases = NO_ALIASES) => {
101
+ const target = probeTarget(path, prefix, kinds, aliases);
102
+ if (target === null) return null;
103
+ const { kind, controller } = target;
104
+ if (method !== "GET" && method !== "HEAD") return {
105
+ status: 405,
106
+ headers: {
107
+ allow: "GET, HEAD",
108
+ "content-length": "0"
109
+ },
110
+ body: ""
111
+ };
112
+ if (health === null || health === void 0) return json(503, {
113
+ status: "fail",
114
+ probe: kind
115
+ });
116
+ try {
117
+ const answer = health.probe(kind, controller === void 0 ? void 0 : decodeURIComponent(controller));
118
+ return {
119
+ ...json(answer.status, answer.body),
120
+ headers: {
121
+ "content-type": answer.contentType,
122
+ "cache-control": "no-store"
123
+ }
124
+ };
125
+ } catch {
126
+ return json(404, {
127
+ status: "fail",
128
+ probe: kind,
129
+ controller
130
+ });
131
+ }
132
+ };
133
+ /**
134
+ * This function writes a probe response. Each response gets `X-Content-Type-Options: nosniff`, thus a
135
+ * browser does not read it as a different type. A 503 gets `Retry-After`, when the writer has the time of a retry.
136
+ */
137
+ const write = (req, res, response, retryAfter) => {
138
+ const retry = response.status === 503 && retryAfter !== void 0 ? { "retry-after": retryAfter } : {};
139
+ const length = String(Buffer.byteLength(response.body));
140
+ res.writeHead(response.status, {
141
+ ...response.headers,
142
+ ...retry,
143
+ "x-content-type-options": "nosniff",
144
+ "content-length": length
145
+ });
146
+ res.end(req.method === "HEAD" ? void 0 : response.body);
147
+ };
148
+ /**
149
+ * This function gives a request handler that answers the probes on the port of the application. It
150
+ * answers until `close transports`, thus its mount keeps the listener open through the drain. A path
151
+ * that is not a probe goes to the next handler. Each 503 gets the `Retry-After` of the context.
152
+ */
153
+ const probeHandler = (health, options) => {
154
+ const problem = prefixProblem(options.prefix);
155
+ if (problem !== null) throw new Error(problem);
156
+ const kinds = kindsOf(options.kinds);
157
+ const aliases = aliasesOf(options.paths, kinds, options.prefix);
158
+ const handler = (req, res, context) => {
159
+ const runtime = typeof health === "function" ? health() : health;
160
+ const response = probeResponse(runtime, req.method, pathOf(req.url), options.prefix, kinds, aliases);
161
+ if (response === null) return false;
162
+ const retryAfter = context?.retryAfter === void 0 ? void 0 : retryAfterOf({ server_retry_after: context.retryAfter }, "probeHandler");
163
+ write(req, res, response, retryAfter);
164
+ return true;
165
+ };
166
+ return Object.assign(handler, { until: "close transports" });
167
+ };
168
+ /**
169
+ * This function makes a health server on a port of its own (S6 decision D5). It starts first and
170
+ * closes last, thus the probes answer through the whole drain. Each probe answers from the cache, and
171
+ * each 503 gets the `Retry-After` of `server_retry_after`.
172
+ */
173
+ const probeServer = (options) => {
174
+ const { prefix = "", server = createServer(), server_retry_after, kinds: chosen, paths, ...listen } = options;
175
+ const retryAfter = retryAfterOf({ server_retry_after }, "probeServer");
176
+ const problem = prefixProblem(prefix);
177
+ if (problem !== null) throw new Error(problem);
178
+ const kinds = kindsOf(chosen);
179
+ const aliases = aliasesOf(paths, kinds, prefix);
180
+ if (server.listenerCount("request") > 0) throw new Error("the probe server has a request listener of its own");
181
+ let health = null;
182
+ let closing = null;
183
+ const sockets = /* @__PURE__ */ new Set();
184
+ server.on("connection", (socket) => {
185
+ sockets.add(socket);
186
+ socket.once("close", () => sockets.delete(socket));
187
+ });
188
+ server.on("request", (req, res) => {
189
+ const response = probeResponse(health, req.method, pathOf(req.url), prefix, kinds, aliases);
190
+ write(req, res, response ?? {
191
+ status: 404,
192
+ headers: { "content-type": "text/plain; charset=utf-8" },
193
+ body: "Not Found"
194
+ }, retryAfter);
195
+ });
196
+ return {
197
+ server,
198
+ listen(runtime) {
199
+ health = runtime;
200
+ if (server.listening) return Promise.resolve();
201
+ return new Promise((resolve, reject) => {
202
+ const failed = (error) => {
203
+ server.off("listening", listened);
204
+ reject(error);
205
+ };
206
+ const listened = () => {
207
+ server.off("error", failed);
208
+ resolve();
209
+ };
210
+ server.once("error", failed);
211
+ server.once("listening", listened);
212
+ server.listen(listen);
213
+ });
214
+ },
215
+ close() {
216
+ if (closing !== null) return closing;
217
+ closing = new Promise((resolve) => {
218
+ if (!server.listening) {
219
+ resolve();
220
+ return;
221
+ }
222
+ server.close(() => resolve());
223
+ server.closeAllConnections();
224
+ for (const socket of [...sockets]) socket.destroy();
225
+ });
226
+ return closing;
227
+ }
228
+ };
229
+ };
230
+ export { PROBE_KINDS, probeHandler, probeResponse, probeServer };
231
+
232
+ //# sourceMappingURL=probes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"probes.js","names":[],"sources":["../../src/http/probes.ts"],"sourcesContent":["import type { IncomingMessage, Server, ServerResponse } from \"node:http\";\nimport { createServer } from \"node:http\";\nimport type { ListenOptions, Socket } from \"node:net\";\nimport type { Health, ProbeKind } from \"../health.ts\";\nimport type { HealthServer } from \"../lifecycle.ts\";\nimport type { Quantity } from \"@mark1russell7/quantity\";\nimport type { MountContext, RequestHandler } from \"./transport.ts\";\nimport { pathOf, retryAfterOf } from \"./transport.ts\";\n\n/** A probe response is the status, the headers and the body of one probe, for any HTTP framework or none. */\nexport interface ProbeResponse {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n}\n\n/** A health source is the health runtime, or a function that gives it when it exists. */\nexport type HealthSource = Health | (() => Health | null | undefined);\n\n/**\n * These are the four probe kinds, in the sequence of their paths. A probe server and a probe handler\n * answer all four, unless their option `kinds` names fewer.\n */\nexport const PROBE_KINDS: readonly ProbeKind[] = Object.freeze([\"startup\", \"readiness\", \"liveness\", \"report\"] as const);\n\nconst named = PROBE_KINDS.map((kind) => `\"${kind}\"`).join(\", \");\n\n/**\n * This function gives the probe kinds of an option `kinds`: all four when it is undefined, or else a\n * frozen copy. It refuses a value that is not a list, an empty list, an unknown kind and a kind two times.\n */\nconst kindsOf = (kinds: readonly ProbeKind[] | undefined): readonly ProbeKind[] => {\n if (kinds === undefined) return PROBE_KINDS;\n if (!Array.isArray(kinds)) throw new Error(`the probe kinds ${JSON.stringify(kinds)} are not a list of ${named}`);\n if (kinds.length === 0) throw new Error(`the probe kinds are an empty list: name one or more of ${named}`);\n const seen = new Set<ProbeKind>();\n for (const kind of kinds) {\n if (!PROBE_KINDS.includes(kind)) throw new Error(`the probe kind ${JSON.stringify(kind)} is not one of ${named}`);\n if (seen.has(kind)) throw new Error(`the probe kind \"${kind}\" is two times in the probe kinds`);\n seen.add(kind);\n }\n return Object.freeze([...kinds]);\n};\n\n/**\n * Probe paths are more paths for each probe kind, for example `{ liveness: [\"/livez\", \"/healthz\"] }`.\n * Each path is a whole path, and the prefix does not go before it. The paths of `PROBE_KINDS` still answer.\n */\nexport type ProbePaths = Partial<Readonly<Record<ProbeKind, readonly string[]>>>;\n\nconst NO_ALIASES: ReadonlyMap<string, ProbeKind> = new Map();\n\n/**\n * This function gives the probe kind of each more path of an option `paths`. It refuses a key that is\n * not a probe kind, and a kind that `kinds` does not name. It refuses a path that does not start\n * with `/`, or ends with `/`. It also refuses a path two times, and a path of `PROBE_KINDS` after the prefix.\n */\nconst aliasesOf = (paths: ProbePaths | undefined, kinds: readonly ProbeKind[], prefix: string): ReadonlyMap<string, ProbeKind> => {\n if (paths === undefined) return NO_ALIASES;\n if (paths === null || typeof paths !== \"object\" || Array.isArray(paths))\n throw new Error(`the probe paths ${JSON.stringify(paths)} are not an object of probe kinds`);\n const aliases = new Map<string, ProbeKind>();\n for (const [key, list] of Object.entries(paths)) {\n const kind = key as ProbeKind;\n if (!PROBE_KINDS.includes(kind)) throw new Error(`the probe paths name ${JSON.stringify(key)}, which is not one of ${named}`);\n if (!kinds.includes(kind)) throw new Error(`the probe paths name \"${kind}\", but the probe kinds do not`);\n if (!Array.isArray(list)) throw new Error(`the probe paths of \"${kind}\" are not a list`);\n for (const path of list as readonly unknown[]) {\n if (typeof path !== \"string\" || !path.startsWith(\"/\") || path.length < 2 || path.endsWith(\"/\") || /[?#]/.test(path))\n throw new Error(`the probe path ${JSON.stringify(path)} of \"${kind}\" does not start with \"/\", ends with \"/\", or has a query`);\n if (aliases.has(path)) throw new Error(`the probe path \"${path}\" is two times in the probe paths`);\n if (PROBE_KINDS.some((each) => path === `${prefix}/${each}` || path.startsWith(`${prefix}/${each}/`)))\n throw new Error(`the probe path \"${path}\" is a path of a probe kind after the prefix \"${prefix}\"`);\n aliases.set(path, kind);\n }\n }\n return aliases;\n};\n\n/** This function gives the probe kind and the controller of a path, or null for a path that is not a probe. */\nconst probeTarget = (\n path: string,\n prefix: string,\n kinds: readonly ProbeKind[],\n aliases: ReadonlyMap<string, ProbeKind>,\n): { readonly kind: ProbeKind; readonly controller: string | undefined } | null => {\n const alias = aliases.get(path);\n if (alias !== undefined) return { kind: alias, controller: undefined };\n if (!path.startsWith(`${prefix}/`)) return null;\n const parts = path.slice(prefix.length + 1).split(\"/\");\n const kind = PROBE_KINDS.find((each) => each === parts[0] && kinds.includes(each));\n if (kind === undefined) return null;\n const controller = parts[1];\n if (parts.length > 2 || (controller !== undefined && (kind !== \"readiness\" || controller === \"\"))) return null;\n return { kind, controller };\n};\n\nconst prefixProblem = (prefix: string): string | null =>\n prefix === \"\" || (prefix.startsWith(\"/\") && !prefix.endsWith(\"/\"))\n ? null\n : `the probe prefix \"${prefix}\" does not start with \"/\", or it ends with \"/\"`;\n\n/** These escapes replace `<`, `>` and `&` in a JSON body. The JSON stays valid, with the same value, and no part of it is markup. */\nconst ESCAPES: Readonly<Record<string, string>> = { \"<\": \"\\\\u003c\", \">\": \"\\\\u003e\", \"&\": \"\\\\u0026\" };\n\n/**\n * This function gives a JSON answer, and its body escapes `<`, `>` and `&`. A body can repeat a part\n * of the path. An example is the name of a controller that the service does not have.\n */\nconst json = (status: number, body: unknown): ProbeResponse => ({\n status,\n headers: { \"content-type\": \"application/health+json\", \"cache-control\": \"no-store\" },\n body: JSON.stringify(body).replace(/[<>&]/g, (char) => ESCAPES[char]!),\n});\n\n/**\n * This function gives the response of a probe path from the cache of the health runtime. For a path\n * that is not a probe, it gives null. The paths are `/startup`, `/readiness`, `/liveness` and\n * `/report` after the prefix. `/readiness/<controller>` gives the readiness of one controller.\n * `kinds` names the probes that answer. The path of a kind that it does not name is not a probe.\n *\n * `aliases` gives the probe kind of each more path. A more path of readiness has no controller.\n */\nexport const probeResponse = (\n health: Health | null | undefined,\n method: string | undefined,\n path: string,\n prefix = \"\",\n kinds: readonly ProbeKind[] = PROBE_KINDS,\n aliases: ReadonlyMap<string, ProbeKind> = NO_ALIASES,\n): ProbeResponse | null => {\n const target = probeTarget(path, prefix, kinds, aliases);\n if (target === null) return null;\n const { kind, controller } = target;\n if (method !== \"GET\" && method !== \"HEAD\")\n return { status: 405, headers: { allow: \"GET, HEAD\", \"content-length\": \"0\" }, body: \"\" };\n // before the runtime exists, each probe fails: the service has not started\n if (health === null || health === undefined) return json(503, { status: \"fail\", probe: kind });\n try {\n const answer = health.probe(kind, controller === undefined ? undefined : decodeURIComponent(controller));\n return { ...json(answer.status, answer.body), headers: { \"content-type\": answer.contentType, \"cache-control\": \"no-store\" } };\n } catch {\n // a controller that the service does not have\n return json(404, { status: \"fail\", probe: kind, controller });\n }\n};\n\n/**\n * This function writes a probe response. Each response gets `X-Content-Type-Options: nosniff`, thus a\n * browser does not read it as a different type. A 503 gets `Retry-After`, when the writer has the time of a retry.\n */\nconst write = (req: IncomingMessage, res: ServerResponse, response: ProbeResponse, retryAfter: string | undefined): void => {\n const retry = response.status === 503 && retryAfter !== undefined ? { \"retry-after\": retryAfter } : {};\n const length = String(Buffer.byteLength(response.body));\n res.writeHead(response.status, { ...response.headers, ...retry, \"x-content-type-options\": \"nosniff\", \"content-length\": length });\n res.end(req.method === \"HEAD\" ? undefined : response.body);\n};\n\n/** These options mount the probes on the port of the application. */\nexport interface ProbeHandlerOptions {\n /** This path goes before each probe path, for example `/health`. It starts with `/`, or it is empty. */\n readonly prefix: string;\n /**\n * These are the probes that the handler answers. The default is all four of `PROBE_KINDS`. The\n * path of a kind that the list does not name goes to the next handler.\n */\n readonly kinds?: readonly ProbeKind[] | undefined;\n /**\n * These are more paths for each probe kind, for example `{ liveness: [\"/livez\", \"/healthz\"] }`. Each is\n * a whole path, with no prefix. Without them, the handler answers only the paths of `PROBE_KINDS`.\n */\n readonly paths?: ProbePaths | undefined;\n}\n\n/**\n * This function gives a request handler that answers the probes on the port of the application. It\n * answers until `close transports`, thus its mount keeps the listener open through the drain. A path\n * that is not a probe goes to the next handler. Each 503 gets the `Retry-After` of the context.\n */\nexport const probeHandler = (health: HealthSource, options: ProbeHandlerOptions): RequestHandler => {\n const problem = prefixProblem(options.prefix);\n if (problem !== null) throw new Error(problem);\n const kinds = kindsOf(options.kinds);\n const aliases = aliasesOf(options.paths, kinds, options.prefix);\n const handler = (req: IncomingMessage, res: ServerResponse, context?: MountContext): boolean => {\n const runtime = typeof health === \"function\" ? health() : health;\n const response = probeResponse(runtime, req.method, pathOf(req.url), options.prefix, kinds, aliases);\n if (response === null) return false;\n // the transport gives server_retry_after through the context, and it adds the header to each 503 too\n const retryAfter = context?.retryAfter === undefined ? undefined : retryAfterOf({ server_retry_after: context.retryAfter }, \"probeHandler\");\n write(req, res, response, retryAfter);\n return true;\n };\n return Object.assign(handler, { until: \"close transports\" as const });\n};\n\n/** These options make a probe server: the listen options of its port, the prefix of its paths, and the time of a retry. */\nexport interface ProbeServerOptions extends ListenOptions {\n /**\n * This time goes in the `Retry-After` of each 503 of a probe, as on the port of the application.\n * The probe server has no defaults, thus the knob is necessary.\n */\n readonly server_retry_after: Quantity;\n /** This path goes before each probe path. The default is no prefix, because the port has only the probes. */\n readonly prefix?: string | undefined;\n /** This server answers the probes. Without it, the probe server makes a server of `node:http`. */\n readonly server?: Server | undefined;\n /**\n * These are the probes that the server answers. The default is all four of `PROBE_KINDS`. The path\n * of a kind that the list does not name gets 404, as each other path.\n */\n readonly kinds?: readonly ProbeKind[] | undefined;\n /** These are more paths for each probe kind, as the option `paths` of `probeHandler`. */\n readonly paths?: ProbePaths | undefined;\n}\n\n/** A probe server is a health server on its own port. Its server is visible for the address of the port. */\nexport interface ProbeServer extends HealthServer {\n readonly server: Server;\n}\n\n/**\n * This function makes a health server on a port of its own (S6 decision D5). It starts first and\n * closes last, thus the probes answer through the whole drain. Each probe answers from the cache, and\n * each 503 gets the `Retry-After` of `server_retry_after`.\n */\nexport const probeServer = (options: ProbeServerOptions): ProbeServer => {\n const { prefix = \"\", server = createServer(), server_retry_after, kinds: chosen, paths, ...listen } = options;\n const retryAfter = retryAfterOf({ server_retry_after }, \"probeServer\");\n const problem = prefixProblem(prefix);\n if (problem !== null) throw new Error(problem);\n const kinds = kindsOf(chosen);\n const aliases = aliasesOf(paths, kinds, prefix);\n if (server.listenerCount(\"request\") > 0) throw new Error(\"the probe server has a request listener of its own\");\n let health: Health | null = null;\n let closing: Promise<void> | null = null;\n const sockets = new Set<Socket>();\n server.on(\"connection\", (socket: Socket) => {\n sockets.add(socket);\n socket.once(\"close\", () => sockets.delete(socket));\n });\n server.on(\"request\", (req: IncomingMessage, res: ServerResponse) => {\n const response = probeResponse(health, req.method, pathOf(req.url), prefix, kinds, aliases);\n write(req, res, response ?? { status: 404, headers: { \"content-type\": \"text/plain; charset=utf-8\" }, body: \"Not Found\" }, retryAfter);\n });\n return {\n server,\n listen(runtime) {\n health = runtime;\n if (server.listening) return Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const failed = (error: Error): void => {\n server.off(\"listening\", listened);\n reject(error);\n };\n const listened = (): void => {\n server.off(\"error\", failed);\n resolve();\n };\n server.once(\"error\", failed);\n server.once(\"listening\", listened);\n server.listen(listen);\n });\n },\n close() {\n if (closing !== null) return closing;\n closing = new Promise<void>((resolve) => {\n if (!server.listening) {\n resolve();\n return;\n }\n server.close(() => resolve());\n server.closeAllConnections();\n for (const socket of [...sockets]) socket.destroy();\n });\n return closing;\n },\n };\n};\n"],"mappings":";;;;;;;AAuBA,MAAa,cAAoC,OAAO,OAAO;CAAC;CAAW;CAAa;CAAY;AAAQ,CAAU;AAEtH,MAAM,QAAQ,YAAY,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI;;;;;AAM9D,MAAM,WAAW,UAAkE;CACjF,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,MAAM,IAAI,MAAM,mBAAmB,KAAK,UAAU,KAAK,EAAE,qBAAqB,OAAO;CAChH,IAAI,MAAM,WAAW,GAAG,MAAM,IAAI,MAAM,0DAA0D,OAAO;CACzG,MAAM,uBAAO,IAAI,IAAe;CAChC,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,CAAC,YAAY,SAAS,IAAI,GAAG,MAAM,IAAI,MAAM,kBAAkB,KAAK,UAAU,IAAI,EAAE,iBAAiB,OAAO;EAChH,IAAI,KAAK,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB,KAAK,kCAAkC;EAC9F,KAAK,IAAI,IAAI;CACf;CACA,OAAO,OAAO,OAAO,CAAC,GA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IACV;IACA,OAAO,KAAK,SAAS,MAAM;IAC3B,OAAO,KAAK,aAAa,QAAQ;IACjC,OAAO,OAAO,MAAM;GACtB,CAAC;EACH;EACA,QAAQ;GACN,IAAI,YAAY,MAAM,OAAO;GAC7B,UAAU,IAAI,SAAe,YAAY;IACvC,IAAI,CAAC,OAAO,WAAW;KACrB,QAAQ;KACR;IACF;IACA,OAAO,YAAY,QAAQ,CAAC;IAC5B,OAAO,oBAAoB;IAC3B,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,QAAQ;GACpD,CAAC;GACD,OAAO;EACT;CACF;AACF"}
@@ -0,0 +1,165 @@
1
+ import { CallContext } from "../call-context.js";
2
+ import { Clock } from "../clock.js";
3
+ import { Lifecycle, TransportImpl } from "../lifecycle.js";
4
+ import { Extent, Quantity } from "@mark1russell7/quantity";
5
+ import { ListenOptions } from "node:net";
6
+ import { IncomingMessage, Server, ServerEventMap, ServerResponse } from "node:http";
7
+ import { Http2Server } from "node:http2";
8
+ /**
9
+ * These are the knobs of an HTTP transport, by the names of the ordering law. The transport has no
10
+ * defaults, thus each knob is necessary. The declaration of the server gets the same record.
11
+ */
12
+ export interface HttpKnobs {
13
+ /**
14
+ * This time is the real idle close of the server, which O01 compares with the idle time of a
15
+ * client. Node closes an idle connection at `keepAliveTimeout` plus `keepAliveTimeoutBuffer`.
16
+ * Thus the transport sets `keepAliveTimeout` to this time less the buffer of the server.
17
+ * A time without a bound stops the timer. On HTTP/2, the time is the timeout of a session with no
18
+ * frame (`server.setTimeout`). Node then sends GOAWAY and closes the session.
19
+ */
20
+ readonly server_idle_close: Extent;
21
+ /**
22
+ * This time is the interval of the sweep of idle connections, from the stop of the intake until the
23
+ * close. A time without a bound gives one sweep, at the stop of the intake.
24
+ */
25
+ readonly server_idle_sweep_interval: Extent;
26
+ /** This time goes in the `Retry-After` of each 503 that the transport gives after its intake stops. */
27
+ readonly server_retry_after: Quantity;
28
+ /**
29
+ * This count is the backlog of listen(2), the limit of the accept queue that the server asks for (SYS-103). The
30
+ * kernel clamps it to `net.core.somaxconn`, and a full queue holds the limit plus one (SYS-63). Without this
31
+ * knob, the transport gives no backlog, and Node asks for 511. The knob needs the listen options of the transport.
32
+ * The knob is 1 or more: Node gives listen(2) 511 for a backlog of 0 (`lib/net.js` of Node 24.21.0, line 2325).
33
+ */
34
+ readonly server_listen_backlog?: Quantity;
35
+ /** The other knobs of the server go to the declaration. The transport does not read them. */
36
+ readonly [knob: string]: Extent;
37
+ }
38
+ /**
39
+ * These are the knobs that the transport gives the declaration: the knobs of the caller, and the two
40
+ * times that the transport found. Thus the declaration shows the three times of the idle close.
41
+ */
42
+ export interface HttpTransportKnobs extends HttpKnobs {
43
+ /** This time is the hint that each response sends (`Keep-Alive: timeout=…`), in whole seconds. A time without a bound tells that no hint goes, as on HTTP/2. */
44
+ readonly server_idle_close_hint: Extent;
45
+ /** This time is the `keepAliveTimeoutBuffer` of the server, which Node adds to the timer and not to the hint. A server of HTTP/2 has none: 0 ms. */
46
+ readonly server_idle_close_buffer: Quantity;
47
+ }
48
+ /** A mount stage is the stage of the shutdown at which a mount stops: the stop of the intake, or the close. */
49
+ export type MountStage = "stop intake" | "close transports";
50
+ /** A mount context gives each handler the signals of the shutdown, the lifecycle and the time of a retry. */
51
+ export interface MountContext {
52
+ /** This signal aborts when the intake stops. A long stream ends in its own protocol at it. */
53
+ readonly intake: AbortSignal;
54
+ /** This signal aborts at the cooperative abort of the drain, or at the close. The work in flight stops at it. */
55
+ readonly signal: AbortSignal;
56
+ /** This lifecycle is the lifecycle that the transport got at its start, or null before the start. */
57
+ readonly life: Lifecycle | null;
58
+ /** This time is the knob `server_retry_after`: the `Retry-After` of each 503 of the handlers. */
59
+ readonly retryAfter: Quantity;
60
+ /**
61
+ * This function tells if a response of a handler can keep its connection open, as the transport
62
+ * decides it. The decision is the option `keepAlive` or `life.keepAlive()`, while the intake is
63
+ * open. Without this function, a handler reads `life.keepAlive()`.
64
+ */
65
+ readonly keepAlive?: (() => boolean) | undefined;
66
+ }
67
+ /**
68
+ * A request handler answers a request and gives true, or it gives false and does not touch the
69
+ * response. Then the next handler gets the request. `until` tells when the handler stops.
70
+ */
71
+ export interface RequestHandler {
72
+ (req: IncomingMessage, res: ServerResponse, context: MountContext): boolean | Promise<boolean>;
73
+ readonly until?: MountStage | undefined;
74
+ }
75
+ type UpgradeArgs = ServerEventMap["upgrade"];
76
+ /** An upgrade socket is the stream of an upgraded connection, as the `upgrade` event of Node gives it. */
77
+ export type UpgradeSocket = UpgradeArgs[1];
78
+ /** An upgrade handler takes an upgraded connection, for example a WebSocket server in its `noServer` mode. */
79
+ export interface UpgradeHandler {
80
+ (req: IncomingMessage, socket: UpgradeSocket, head: UpgradeArgs[2], context: MountContext): void;
81
+ readonly until?: MountStage | undefined;
82
+ }
83
+ /** An upgrade match is a path, without its query, or a function that tells if a handler takes a request. */
84
+ export type UpgradeMatch = string | ((req: IncomingMessage) => boolean);
85
+ /** These options change one mount. */
86
+ export interface MountOptions {
87
+ /**
88
+ * This stage is when the mount stops. Without it, the stage of the handler applies, and then
89
+ * `stop intake`. A mount until `close transports` keeps the listener open through the drain.
90
+ */
91
+ readonly until?: MountStage | undefined;
92
+ }
93
+ /**
94
+ * An edge server is the server of a transport: a server of `node:http`, or a server of `node:http2`
95
+ * without TLS (h2c, from `http2.createServer()`).
96
+ */
97
+ export type EdgeServer = Server | Http2Server;
98
+ /** These options make an HTTP transport. */
99
+ export interface HttpTransportOptions<S extends EdgeServer = Server> {
100
+ /**
101
+ * These are the listen options of `start()`, or a function that makes the server listen. Without
102
+ * them, `start()` takes a server that listens already.
103
+ */
104
+ readonly listen?: ListenOptions | ((server: S) => Promise<void> | void) | undefined;
105
+ /** This clock is the clock of the lifecycle. The deadline of the drain and the sweep use it. */
106
+ readonly clock?: Clock | undefined;
107
+ /**
108
+ * This function tells if a response can keep its connection open. Without it, the transport reads
109
+ * `life.keepAlive()` of the lifecycle of its start. The transport reads it when the headers of
110
+ * each response go. On HTTP/1.1, false gives `Connection: close`. On HTTP/2, false gives a GOAWAY
111
+ * on the session of the response.
112
+ */
113
+ readonly keepAlive?: (() => boolean) | undefined;
114
+ /** This function receives each error of a handler. The transport then answers 500, or it destroys the response. */
115
+ readonly onError?: ((error: unknown, req: IncomingMessage) => void) | undefined;
116
+ /**
117
+ * With this call context, each handler runs in the context of the headers of its request. The context
118
+ * has the trace of `traceparent`, and the baggage of a trusted request. `callContext` of the entry `/otel` gives one.
119
+ */
120
+ readonly callContext?: CallContext | undefined;
121
+ /**
122
+ * This function tells if the baggage of a request is trusted, for example after a token check. The
123
+ * default trusts no request: each request joins the trace of its caller, and its baggage is dropped.
124
+ */
125
+ readonly trustBaggage?: ((req: IncomingMessage) => boolean) | undefined;
126
+ }
127
+ /** An HTTP transport is a server of `node:http` or `node:http2` as a transport of the lifecycle, with a list of mounts on its listener. */
128
+ export interface HttpTransport<S extends EdgeServer = Server> extends TransportImpl {
129
+ readonly server: S;
130
+ /** These knobs go to the declaration of the server: the knobs of the caller, the hint and the buffer. */
131
+ readonly knobs: HttpTransportKnobs;
132
+ /** This method adds a request handler at the end of the list, and gives the function that removes it. */
133
+ mount(handler: RequestHandler, options?: MountOptions): () => void;
134
+ /** This method adds an upgrade handler for a path, and gives the function that removes it. A server of HTTP/2 has no upgrade, thus it refuses the handler. */
135
+ upgrade(match: UpgradeMatch, handler: UpgradeHandler, options?: MountOptions): () => void;
136
+ /** This count is the number of open connections, idle connections and upgraded connections too. On HTTP/2, a connection is the socket of a session. */
137
+ readonly connections: number;
138
+ /** This flag tells if the transport stopped its intake. */
139
+ readonly intakeStopped: boolean;
140
+ }
141
+ /** This function gives the path of a request target, without its query and fragment. */
142
+ export declare const pathOf: (url: string | undefined) => string;
143
+ /**
144
+ * This function makes a server of `node:http` or `node:http2` a transport of the lifecycle (S6 A8 and
145
+ * A13). It is not a framework: it has no routes, no body parser and no middleware.
146
+ * - The count of work in flight comes from events: each response until its `close`, and each upgraded
147
+ * connection until its `close`.
148
+ * - `stopIntake` closes the listener, and new connections get a refusal. It closes the idle connections
149
+ * at once and at each `server_idle_sweep_interval`. Each later response gets `Connection: close`.
150
+ * A connection is not idle while the bytes of its answer go (SYS-33).
151
+ * - `drain` waits until no work is in flight, or until the deadline. It gives the cooperative abort to
152
+ * the handlers through their context. At the deadline, it also waits for each answer that is to come
153
+ * or to go out (SYS-29). The cap of the phase bounds that wait. Answers that did not go out by the
154
+ * cap are not a failure of the phase. A stream outside the lifecycle of the transport does not hold it.
155
+ * - `close` destroys each connection. A second close gives the same promise.
156
+ * - The mounts share one port. The first request handler that gives true answers. After the stop of
157
+ * the intake, only the mounts until `close transports` answer, and each other request gets a 503.
158
+ * - HTTP/2 has no `Connection` header (RFC 9113, section 8.2.2). Thus a close of a connection is a
159
+ * GOAWAY on its session. Each handler gets the request and the response of the compatibility API of
160
+ * `node:http2`. They have the parts of the API that the handlers of this entry use. A handler that
161
+ * gives `Connection: close` gets a GOAWAY. The stop of the intake sends GOAWAY on each session, and
162
+ * the close destroys each session.
163
+ */
164
+ export declare const httpTransport: <S extends EdgeServer = Server>(edge: S, knobs: HttpKnobs, options?: HttpTransportOptions<S>) => HttpTransport<S>;
165
+ export {};