@mark1russell7/service 0.8.19 → 0.9.0

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 (335) hide show
  1. package/README.md +6 -2
  2. package/build/backoff.d.ts +44 -2
  3. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  4. package/build/builder.js +499 -0
  5. package/build/builder.js.map +1 -0
  6. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  7. package/build/channel.d.ts +1 -1
  8. package/build/channel.js.map +1 -1
  9. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  10. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  11. package/build/client/core.js.map +1 -0
  12. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  13. package/build/client/dial.js +52 -0
  14. package/build/client/dial.js.map +1 -0
  15. package/build/client/machine.js +29 -0
  16. package/build/client/machine.js.map +1 -0
  17. package/build/client/meets.d.ts +35 -0
  18. package/build/client/meets.js +78 -0
  19. package/build/client/meets.js.map +1 -0
  20. package/build/clock.d.ts +2 -2
  21. package/build/clock.js +1 -1
  22. package/build/conformance.d.ts +122 -0
  23. package/build/conformance.js +469 -0
  24. package/build/conformance.js.map +1 -0
  25. package/build/contract.d.ts +28 -0
  26. package/build/contract.js +184 -0
  27. package/build/contract.js.map +1 -0
  28. package/build/description.d.ts +161 -0
  29. package/build/description.js +11 -0
  30. package/build/description.js.map +1 -0
  31. package/build/drains.js +35 -0
  32. package/build/drains.js.map +1 -0
  33. package/build/events.d.ts +25 -0
  34. package/build/fakes.d.ts +43 -0
  35. package/build/fakes.js +93 -0
  36. package/build/fakes.js.map +1 -0
  37. package/build/grpc/client.d.ts +153 -0
  38. package/build/grpc/client.js +474 -0
  39. package/build/grpc/client.js.map +1 -0
  40. package/build/grpc/connection.d.ts +97 -0
  41. package/build/grpc/connection.js +59 -0
  42. package/build/grpc/connection.js.map +1 -0
  43. package/build/grpc/machine.d.ts +12 -0
  44. package/build/grpc/machine.js +149 -0
  45. package/build/grpc/machine.js.map +1 -0
  46. package/build/grpc/meets.d.ts +14 -0
  47. package/build/grpc/meets.js +105 -0
  48. package/build/grpc/meets.js.map +1 -0
  49. package/build/grpc/starting.d.ts +33 -0
  50. package/build/grpc/starting.js +89 -0
  51. package/build/grpc/starting.js.map +1 -0
  52. package/build/grpc.d.ts +9 -303
  53. package/build/grpc.js +7 -854
  54. package/build/health.d.ts +93 -0
  55. package/build/health.js +225 -0
  56. package/build/health.js.map +1 -0
  57. package/build/heartbeat.d.ts +6 -2
  58. package/build/heartbeat.js.map +1 -1
  59. package/build/host/discovery.d.ts +61 -0
  60. package/build/host/discovery.js +113 -0
  61. package/build/host/discovery.js.map +1 -0
  62. package/build/host/env.d.ts +14 -0
  63. package/build/host/env.js +57 -0
  64. package/build/host/env.js.map +1 -0
  65. package/build/host/fakes.d.ts +82 -0
  66. package/build/host/fakes.js +239 -0
  67. package/build/host/fakes.js.map +1 -0
  68. package/build/host/group.d.ts +142 -0
  69. package/build/host/group.js +524 -0
  70. package/build/host/group.js.map +1 -0
  71. package/build/host/install.d.ts +96 -0
  72. package/build/host/install.js +330 -0
  73. package/build/host/install.js.map +1 -0
  74. package/build/host/lock.d.ts +78 -0
  75. package/build/host/lock.js +190 -0
  76. package/build/host/lock.js.map +1 -0
  77. package/build/host/logs.d.ts +26 -0
  78. package/build/host/logs.js +48 -0
  79. package/build/host/logs.js.map +1 -0
  80. package/build/host/node.d.ts +14 -0
  81. package/build/host/node.js +309 -0
  82. package/build/host/node.js.map +1 -0
  83. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  84. package/build/host/ports.js +17 -0
  85. package/build/host/ports.js.map +1 -0
  86. package/build/host/probes.d.ts +51 -0
  87. package/build/host/probes.js +139 -0
  88. package/build/host/probes.js.map +1 -0
  89. package/build/host/processes.d.ts +32 -0
  90. package/build/host/processes.js +63 -0
  91. package/build/host/processes.js.map +1 -0
  92. package/build/host/render.d.ts +84 -0
  93. package/build/host/render.js +235 -0
  94. package/build/host/render.js.map +1 -0
  95. package/build/host/watch.d.ts +90 -0
  96. package/build/host/watch.js +165 -0
  97. package/build/host/watch.js.map +1 -0
  98. package/build/host.d.ts +13 -671
  99. package/build/host.js +12 -2126
  100. package/build/http/answers.js +29 -0
  101. package/build/http/answers.js.map +1 -0
  102. package/build/http/fake-server.js +61 -0
  103. package/build/http/fake-server.js.map +1 -0
  104. package/build/http/outcome.d.ts +115 -0
  105. package/build/http/outcome.js +325 -0
  106. package/build/http/outcome.js.map +1 -0
  107. package/build/http/probes.d.ts +83 -0
  108. package/build/http/probes.js +232 -0
  109. package/build/http/probes.js.map +1 -0
  110. package/build/http/transport.d.ts +165 -0
  111. package/build/http/transport.js +518 -0
  112. package/build/http/transport.js.map +1 -0
  113. package/build/http-client/client.d.ts +121 -0
  114. package/build/http-client/client.js +330 -0
  115. package/build/http-client/client.js.map +1 -0
  116. package/build/http-client/connection.d.ts +78 -0
  117. package/build/http-client/connection.js +54 -0
  118. package/build/http-client/connection.js.map +1 -0
  119. package/build/http-client/machine.d.ts +14 -0
  120. package/build/http-client/machine.js +109 -0
  121. package/build/http-client/machine.js.map +1 -0
  122. package/build/http-client/meets.d.ts +11 -0
  123. package/build/http-client/meets.js +74 -0
  124. package/build/http-client/meets.js.map +1 -0
  125. package/build/http-client/session.d.ts +87 -0
  126. package/build/http-client/session.js +99 -0
  127. package/build/http-client/session.js.map +1 -0
  128. package/build/http-client/starting.d.ts +25 -0
  129. package/build/http-client/starting.js +65 -0
  130. package/build/http-client/starting.js.map +1 -0
  131. package/build/http-client.d.ts +9 -330
  132. package/build/http-client.js +8 -707
  133. package/build/http.d.ts +5 -353
  134. package/build/http.js +3 -1086
  135. package/build/identity.d.ts +16 -0
  136. package/build/identity.js +44 -0
  137. package/build/identity.js.map +1 -0
  138. package/build/index.d.ts +35 -412
  139. package/build/index.js +25 -3278
  140. package/build/knobs.d.ts +1 -0
  141. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  142. package/build/knobs.js.map +1 -0
  143. package/build/latch.d.ts +29 -0
  144. package/build/latch.js +122 -0
  145. package/build/latch.js.map +1 -0
  146. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  147. package/build/law.js +149 -0
  148. package/build/law.js.map +1 -0
  149. package/build/lifecycle.d.ts +144 -0
  150. package/build/lifecycle.js +411 -0
  151. package/build/lifecycle.js.map +1 -0
  152. package/build/limiter/machine.d.ts +40 -0
  153. package/build/limiter/machine.js +279 -0
  154. package/build/limiter/machine.js.map +1 -0
  155. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  156. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  157. package/build/limiter/policy.js.map +1 -0
  158. package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
  159. package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
  160. package/build/limiter/quota.js.map +1 -0
  161. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  162. package/build/limiter/store.js +145 -0
  163. package/build/limiter/store.js.map +1 -0
  164. package/build/limiter.d.ts +4 -3
  165. package/build/limiter.js +4 -2
  166. package/build/lint.d.ts +152 -0
  167. package/build/lint.js +576 -0
  168. package/build/lint.js.map +1 -0
  169. package/build/logger.d.ts +71 -0
  170. package/build/logger.js +183 -0
  171. package/build/logger.js.map +1 -0
  172. package/build/machines.d.ts +41 -0
  173. package/build/machines.js +451 -0
  174. package/build/machines.js.map +1 -0
  175. package/build/metrics.d.ts +53 -0
  176. package/build/metrics.js +111 -0
  177. package/build/metrics.js.map +1 -0
  178. package/build/mongodb/client.d.ts +131 -0
  179. package/build/mongodb/client.js +388 -0
  180. package/build/mongodb/client.js.map +1 -0
  181. package/build/mongodb/connection.d.ts +112 -0
  182. package/build/mongodb/connection.js +12 -0
  183. package/build/mongodb/connection.js.map +1 -0
  184. package/build/mongodb/machine.d.ts +14 -0
  185. package/build/mongodb/machine.js +122 -0
  186. package/build/mongodb/machine.js.map +1 -0
  187. package/build/mongodb/meets.d.ts +15 -0
  188. package/build/mongodb/meets.js +103 -0
  189. package/build/mongodb/meets.js.map +1 -0
  190. package/build/mongodb/starting.d.ts +29 -0
  191. package/build/mongodb/starting.js +77 -0
  192. package/build/mongodb/starting.js.map +1 -0
  193. package/build/mongodb.d.ts +8 -296
  194. package/build/mongodb.js +7 -682
  195. package/build/operation.d.ts +27 -0
  196. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  197. package/build/operation.js.map +1 -0
  198. package/build/otel.d.ts +2 -2
  199. package/build/pg/client.d.ts +96 -0
  200. package/build/pg/client.js +277 -0
  201. package/build/pg/client.js.map +1 -0
  202. package/build/pg/connection.d.ts +75 -0
  203. package/build/pg/connection.js +11 -0
  204. package/build/pg/connection.js.map +1 -0
  205. package/build/pg/machine.d.ts +13 -0
  206. package/build/pg/machine.js +111 -0
  207. package/build/pg/machine.js.map +1 -0
  208. package/build/pg/meets.d.ts +14 -0
  209. package/build/pg/meets.js +83 -0
  210. package/build/pg/meets.js.map +1 -0
  211. package/build/pg/starting.d.ts +26 -0
  212. package/build/pg/starting.js +62 -0
  213. package/build/pg/starting.js.map +1 -0
  214. package/build/pg.d.ts +8 -219
  215. package/build/pg.js +7 -525
  216. package/build/poller.d.ts +9 -0
  217. package/build/poller.js +154 -0
  218. package/build/poller.js.map +1 -0
  219. package/build/process.d.ts +114 -0
  220. package/build/process.js +170 -0
  221. package/build/process.js.map +1 -0
  222. package/build/profiles.d.ts +68 -0
  223. package/build/profiles.js +120 -0
  224. package/build/profiles.js.map +1 -0
  225. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  226. package/build/queue.js +279 -0
  227. package/build/queue.js.map +1 -0
  228. package/build/rabbitmq/client.d.ts +144 -0
  229. package/build/rabbitmq/client.js +426 -0
  230. package/build/rabbitmq/client.js.map +1 -0
  231. package/build/rabbitmq/connection.d.ts +91 -0
  232. package/build/rabbitmq/connection.js +15 -0
  233. package/build/rabbitmq/connection.js.map +1 -0
  234. package/build/rabbitmq/machine.d.ts +13 -0
  235. package/build/rabbitmq/machine.js +159 -0
  236. package/build/rabbitmq/machine.js.map +1 -0
  237. package/build/rabbitmq/meets.d.ts +12 -0
  238. package/build/rabbitmq/meets.js +96 -0
  239. package/build/rabbitmq/meets.js.map +1 -0
  240. package/build/rabbitmq/starting.d.ts +27 -0
  241. package/build/rabbitmq/starting.js +67 -0
  242. package/build/rabbitmq/starting.js.map +1 -0
  243. package/build/rabbitmq.d.ts +8 -283
  244. package/build/rabbitmq.js +7 -742
  245. package/build/redis/client.d.ts +86 -0
  246. package/build/redis/client.js +285 -0
  247. package/build/redis/client.js.map +1 -0
  248. package/build/redis/connection.d.ts +57 -0
  249. package/build/redis/connection.js +11 -0
  250. package/build/redis/connection.js.map +1 -0
  251. package/build/redis/limiter.d.ts +43 -0
  252. package/build/redis/limiter.js +164 -0
  253. package/build/redis/limiter.js.map +1 -0
  254. package/build/redis/machine.d.ts +12 -0
  255. package/build/redis/machine.js +144 -0
  256. package/build/redis/machine.js.map +1 -0
  257. package/build/redis/meets.d.ts +11 -0
  258. package/build/redis/meets.js +75 -0
  259. package/build/redis/meets.js.map +1 -0
  260. package/build/redis/operations.d.ts +5 -0
  261. package/build/redis/operations.js +114 -0
  262. package/build/redis/operations.js.map +1 -0
  263. package/build/redis.d.ts +10 -207
  264. package/build/redis.js +9 -771
  265. package/build/requests.d.ts +66 -0
  266. package/build/requests.js +279 -0
  267. package/build/requests.js.map +1 -0
  268. package/build/retrier.d.ts +62 -0
  269. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  270. package/build/retrier.js.map +1 -0
  271. package/build/routes.d.ts +35 -0
  272. package/build/routes.js +77 -0
  273. package/build/routes.js.map +1 -0
  274. package/build/rules.d.ts +19 -2
  275. package/build/stops.d.ts +51 -0
  276. package/build/stops.js +86 -0
  277. package/build/stops.js.map +1 -0
  278. package/build/testing.d.ts +8 -270
  279. package/build/testing.js +4 -1027
  280. package/build/testing.js.map +1 -1
  281. package/build/timing.d.ts +63 -0
  282. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  283. package/build/timing.js.map +1 -0
  284. package/build/units.d.ts +17 -0
  285. package/build/units.js +236 -0
  286. package/build/units.js.map +1 -0
  287. package/build/watchdog.d.ts +38 -0
  288. package/build/watchdog.js +57 -0
  289. package/build/watchdog.js.map +1 -0
  290. package/build/websocket/client.d.ts +136 -0
  291. package/build/websocket/client.js +422 -0
  292. package/build/websocket/client.js.map +1 -0
  293. package/build/websocket/connection.d.ts +83 -0
  294. package/build/websocket/connection.js +57 -0
  295. package/build/websocket/connection.js.map +1 -0
  296. package/build/websocket/machine.d.ts +12 -0
  297. package/build/websocket/machine.js +155 -0
  298. package/build/websocket/machine.js.map +1 -0
  299. package/build/websocket/meets.d.ts +14 -0
  300. package/build/websocket/meets.js +92 -0
  301. package/build/websocket/meets.js.map +1 -0
  302. package/build/websocket/starting.d.ts +25 -0
  303. package/build/websocket/starting.js +69 -0
  304. package/build/websocket/starting.js.map +1 -0
  305. package/build/websocket.d.ts +9 -264
  306. package/build/websocket.js +8 -774
  307. package/build/worker.d.ts +92 -0
  308. package/build/worker.js +153 -0
  309. package/build/worker.js.map +1 -0
  310. package/package.json +5 -4
  311. package/build/backoff-QTRGfkEK.d.ts +0 -45
  312. package/build/clock-DpVgpY4h.d.ts +0 -2
  313. package/build/grpc.js.map +0 -1
  314. package/build/host.js.map +0 -1
  315. package/build/http-client.js.map +0 -1
  316. package/build/http.js.map +0 -1
  317. package/build/index.js.map +0 -1
  318. package/build/knobs-BJcz6m01.js.map +0 -1
  319. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  320. package/build/limiter-DrM0PQV9.js.map +0 -1
  321. package/build/logger-B6drv9w0.d.ts +0 -488
  322. package/build/machine-BhVeHr_m.js.map +0 -1
  323. package/build/mongodb.js.map +0 -1
  324. package/build/operation-DF73RZOI.js.map +0 -1
  325. package/build/pg.js.map +0 -1
  326. package/build/policy-UYALkqVq.js.map +0 -1
  327. package/build/process-7R9M29wN.js +0 -437
  328. package/build/process-7R9M29wN.js.map +0 -1
  329. package/build/rabbitmq.js.map +0 -1
  330. package/build/redis.js.map +0 -1
  331. package/build/requests-DD2ALv0_.js +0 -583
  332. package/build/requests-DD2ALv0_.js.map +0 -1
  333. package/build/retrier-Dnjhvxol.js.map +0 -1
  334. package/build/timing-DZl36uXs.js.map +0 -1
  335. package/build/websocket.js.map +0 -1
@@ -0,0 +1,93 @@
1
+ import { Clock } from "./clock.js";
2
+ import { Check, Gate } from "./description.js";
3
+ import { Recorder } from "./events.js";
4
+ import { Result } from "./latch.js";
5
+ import { Logger } from "./logger.js";
6
+ import { HealthMetrics } from "./metrics.js";
7
+ import { CheckFn } from "./poller.js";
8
+ /** These options start the runtime. Without them, it uses the real clock and `Math.random`. */
9
+ export interface StartOptions {
10
+ readonly clock?: Clock | undefined;
11
+ /** This function gives a number in [0, 1) for the jitter of each poll. */
12
+ readonly random?: (() => number) | undefined;
13
+ /** This list names the checks or dependencies whose polls fail at once (a seam for tests). */
14
+ readonly forceFail?: readonly string[] | undefined;
15
+ /** This function receives each transition of each machine of the runtime. */
16
+ readonly record?: Recorder | undefined;
17
+ /**
18
+ * This logger receives each transition too, as a log entry with a level and fields (`logEvents`).
19
+ * Without it, the runtime writes no log, as before. For the console, give `consoleLogger()`.
20
+ */
21
+ readonly logger?: Logger | undefined;
22
+ /**
23
+ * This function can replace the function of a check, for example to add a delay to each call
24
+ * (a seam for tests: a degraded dependency). It gives the function to use.
25
+ */
26
+ readonly wrapCheck?: ((check: Check, run: CheckFn) => CheckFn) | undefined;
27
+ }
28
+ /** A check verdict is the cached state of one check, for the probes and the report. */
29
+ export interface CheckVerdict {
30
+ readonly gates: Gate | null;
31
+ readonly dependency: string | null;
32
+ /** This flag tells if the latch of the check is tripped, or it is null for a check that only reports. */
33
+ readonly tripped: boolean | null;
34
+ readonly streak: number;
35
+ /** This time is when the latch last changed, in milliseconds on the monotonic clock. */
36
+ readonly since: number | null;
37
+ readonly last: Result | null;
38
+ }
39
+ /** A verdict is the state of the service, from its cache. Nothing in it starts a check. */
40
+ export interface HealthVerdict {
41
+ /** This flag becomes true one time, after the warm-up sweep. */
42
+ readonly started: boolean;
43
+ readonly draining: boolean;
44
+ /** This flag tells if the service can take new work: started, not draining, and each readiness latch released. */
45
+ readonly ready: boolean;
46
+ /** This flag tells if each liveness latch is released. */
47
+ readonly alive: boolean;
48
+ /** These flags tell if each controller can take new work, from the dependencies that it needs. */
49
+ readonly controllers: Readonly<Record<string, boolean>>;
50
+ readonly dependencies: Readonly<Record<string, boolean>>;
51
+ readonly checks: Readonly<Record<string, CheckVerdict>>;
52
+ readonly startup: {
53
+ readonly budget: number;
54
+ readonly elapsed: number;
55
+ readonly overBudget: boolean;
56
+ };
57
+ }
58
+ /** A probe kind is the question that a probe asks: the startup, the readiness, the liveness, or the whole report. */
59
+ export type ProbeKind = "startup" | "readiness" | "liveness" | "report";
60
+ /** A probe answer is a status and a body, for any HTTP framework or none. */
61
+ export interface ProbeAnswer {
62
+ readonly status: 200 | 503;
63
+ readonly contentType: "application/health+json";
64
+ readonly body: {
65
+ readonly status: "pass" | "fail";
66
+ readonly service: string;
67
+ readonly probe: ProbeKind;
68
+ readonly controller?: string | undefined;
69
+ readonly verdict?: HealthVerdict | undefined;
70
+ };
71
+ }
72
+ /** The health runtime of a started service. It reads its timing and its checks from the declaration. */
73
+ export interface Health {
74
+ verdict(): HealthVerdict;
75
+ /**
76
+ * This method answers a probe from the cache, in constant time, and it starts no check. A
77
+ * readiness probe with a controller asks about that controller. The report always answers 200.
78
+ */
79
+ probe(kind: ProbeKind, controller?: string): ProbeAnswer;
80
+ /**
81
+ * This method gives the counts of the runtime (B18). They are the outcomes, the durations and the
82
+ * episodes of failure of each check, and the transitions of its machines. It starts no check.
83
+ */
84
+ metrics(): HealthMetrics;
85
+ /** This method gives each change of the verdict to `listener`, and gives the function that stops it. */
86
+ subscribe(listener: (verdict: HealthVerdict) => void): () => void;
87
+ /** This method adds a name to the force-fail list, or removes it. */
88
+ forceFail(name: string, on: boolean): void;
89
+ /** This method fails readiness for good. The drain of the lifecycle starts with it. */
90
+ drain(): void;
91
+ /** This method stops each poller and each timer of the runtime. */
92
+ stop(): void;
93
+ }
@@ -0,0 +1,225 @@
1
+ import { realClock, unrefClock } from "./clock.js";
2
+ import { latch } from "./latch.js";
3
+ import { meter } from "./metrics.js";
4
+ import { poller } from "./poller.js";
5
+ import { valueIn } from "@mark1russell7/quantity";
6
+ // src/health.ts
7
+ /**
8
+ * This function makes the runtime of a declaration. The service has no defaults of its own: each
9
+ * timing, poll and coupling comes from the description.
10
+ */
11
+ const healthRuntime = (description, runs, options = {}) => {
12
+ const clock = options.clock ?? realClock;
13
+ const random = options.random ?? Math.random;
14
+ const forced = new Set(options.forceFail ?? []);
15
+ const startedAt = clock.now();
16
+ const budget = valueIn(description.policies.startup, "ms");
17
+ const entries = /* @__PURE__ */ new Map();
18
+ const dependencies = new Set(description.dependencies.map((dependency) => dependency.name));
19
+ const lateDependencies = /* @__PURE__ */ new Set();
20
+ const listeners = /* @__PURE__ */ new Set();
21
+ let started = false;
22
+ let draining = false;
23
+ let stopped = false;
24
+ let gate = "closed";
25
+ const counts = meter();
26
+ const record = (event) => {
27
+ counts.event(event);
28
+ options.record?.(event);
29
+ };
30
+ const tracer = (machine, instance) => (from, to, on) => record({
31
+ at: clock.now(),
32
+ machine,
33
+ instance,
34
+ from,
35
+ to,
36
+ on
37
+ });
38
+ const gateTrace = tracer("gate", description.name);
39
+ const moveGate = (to, on, detail) => {
40
+ const from = gate;
41
+ gate = to;
42
+ record({
43
+ at: clock.now(),
44
+ machine: "gate",
45
+ instance: description.name,
46
+ from,
47
+ to,
48
+ on,
49
+ ...detail === void 0 ? {} : { detail }
50
+ });
51
+ };
52
+ let budgetTimer = clock.after(budget, () => {
53
+ budgetTimer = null;
54
+ if (gate !== "open" && gate !== "failed") gateTrace(gate, gate, "startup.over-budget");
55
+ });
56
+ budgetTimer.unref?.();
57
+ const changed = () => {
58
+ if (listeners.size === 0) return;
59
+ const now = verdict();
60
+ for (const listener of listeners) listener(now);
61
+ };
62
+ const add = (check, given, late) => {
63
+ const run = options.wrapCheck?.(check, given) ?? given;
64
+ const timing = check.gates === null ? null : description.policies[check.gates];
65
+ const made = timing === null ? null : latch(timing, unrefClock(clock), check.gates === "readiness", changed, tracer(timing.type === "window" ? "window" : "latch", check.name));
66
+ const entry = {
67
+ check,
68
+ latch: made,
69
+ poller: poller({
70
+ name: check.name,
71
+ poll: check.poll,
72
+ run,
73
+ clock,
74
+ random,
75
+ unrefLoop: true,
76
+ forced: () => forced.has(check.name) || check.dependency !== null && forced.has(check.dependency),
77
+ record: (result) => {
78
+ counts.poll(check, result);
79
+ made?.record(result);
80
+ if (result.outcome === "ok" && check.dependency !== null) {
81
+ if (lateDependencies.delete(check.dependency)) changed();
82
+ }
83
+ },
84
+ trace: tracer("poller", check.name)
85
+ })
86
+ };
87
+ entries.set(check.name, entry);
88
+ counts.add(check);
89
+ if (late && !stopped) {
90
+ entry.poller.pollNow();
91
+ entry.poller.start(entry.poller.jittered());
92
+ }
93
+ };
94
+ for (const check of description.checks) {
95
+ const run = runs.get(check.name);
96
+ if (run === void 0) throw new Error(`check ${check.name} has no function: the runtime has no defaults`);
97
+ add(check, run, false);
98
+ }
99
+ const latchesOf = (gateOf, keep = () => true) => [...entries.values()].flatMap((entry) => entry.check.gates === gateOf && entry.latch !== null && keep(entry.check) ? [entry.latch] : []);
100
+ const released = (latches) => latches.every((each) => !each.tripped);
101
+ /** This function tells if a policy fails through a declared coupling from another policy. */
102
+ const coupledOff = (to, base) => description.couplings.some((coupling) => coupling.to === to && !base[coupling.from]);
103
+ const verdict = () => {
104
+ const base = {
105
+ readiness: released(latchesOf("readiness")) && lateDependencies.size === 0,
106
+ liveness: released(latchesOf("liveness"))
107
+ };
108
+ const alive = base.liveness && !coupledOff("liveness", base);
109
+ const open = started && !draining && !coupledOff("readiness", base);
110
+ const ready = open && base.readiness;
111
+ const dependencyReady = (name) => !lateDependencies.has(name) && released(latchesOf("readiness", (check) => check.dependency === name));
112
+ const own = released(latchesOf("readiness", (check) => check.dependency === null));
113
+ const dependenciesOut = {};
114
+ for (const name of dependencies) dependenciesOut[name] = dependencyReady(name);
115
+ const controllers = {};
116
+ for (const controller of description.controllers) controllers[controller.name] = open && own && controller.requires.every(dependencyReady);
117
+ const checks = {};
118
+ for (const [name, entry] of entries) checks[name] = {
119
+ gates: entry.check.gates,
120
+ dependency: entry.check.dependency,
121
+ tripped: entry.latch?.tripped ?? null,
122
+ streak: entry.latch?.streak ?? 0,
123
+ since: entry.latch?.since ?? null,
124
+ last: entry.poller.last
125
+ };
126
+ const elapsed = clock.now() - startedAt;
127
+ return {
128
+ started,
129
+ draining,
130
+ ready,
131
+ alive,
132
+ controllers,
133
+ dependencies: dependenciesOut,
134
+ checks,
135
+ startup: {
136
+ budget,
137
+ elapsed,
138
+ overBudget: !started && elapsed > budget
139
+ }
140
+ };
141
+ };
142
+ const answer = (kind, pass, controller) => ({
143
+ status: pass || kind === "report" ? 200 : 503,
144
+ contentType: "application/health+json",
145
+ body: {
146
+ status: pass ? "pass" : "fail",
147
+ service: description.name,
148
+ probe: kind,
149
+ ...controller === void 0 ? {} : { controller },
150
+ ...kind === "report" ? { verdict: verdict() } : {}
151
+ }
152
+ });
153
+ return {
154
+ verdict,
155
+ metrics: counts.metrics,
156
+ probe(kind, controller) {
157
+ const now = verdict();
158
+ if (kind === "startup") return answer(kind, now.started);
159
+ if (kind === "liveness") return answer(kind, now.alive);
160
+ if (kind === "report") return answer(kind, now.ready && now.alive);
161
+ if (controller === void 0) return answer(kind, now.ready);
162
+ const known = Object.hasOwn(now.controllers, controller) ? now.controllers[controller] : void 0;
163
+ if (known === void 0) throw new Error(`${description.name} has no controller ${controller}`);
164
+ return answer(kind, known, controller);
165
+ },
166
+ subscribe(listener) {
167
+ listeners.add(listener);
168
+ return () => listeners.delete(listener);
169
+ },
170
+ forceFail(name, on) {
171
+ if (on) forced.add(name);
172
+ else forced.delete(name);
173
+ },
174
+ drain() {
175
+ if (draining) return;
176
+ draining = true;
177
+ changed();
178
+ },
179
+ stop() {
180
+ stopped = true;
181
+ budgetTimer?.();
182
+ budgetTimer = null;
183
+ for (const entry of entries.values()) {
184
+ entry.poller.stop();
185
+ entry.latch?.stop();
186
+ }
187
+ },
188
+ beginStartup() {
189
+ if (gate === "closed") moveGate("starting", "startup.begin");
190
+ },
191
+ failStartup(cause) {
192
+ if (gate === "open" || gate === "failed") return;
193
+ moveGate("failed", "startup.fail", cause);
194
+ budgetTimer?.();
195
+ budgetTimer = null;
196
+ },
197
+ async warmUp() {
198
+ if (started || stopped || gate === "failed" || gate === "sweeping") return;
199
+ moveGate("sweeping", "mark-ready");
200
+ const sweep = clock.now();
201
+ await Promise.all([...entries.values()].map((entry) => entry.poller.pollNow()));
202
+ if (stopped || gate !== "sweeping") return;
203
+ for (const entry of entries.values()) entry.poller.start(entry.poller.jittered() - (clock.now() - sweep));
204
+ started = true;
205
+ budgetTimer?.();
206
+ budgetTimer = null;
207
+ moveGate("open", "sweep.done");
208
+ changed();
209
+ },
210
+ addCheck(check, run) {
211
+ if (entries.has(check.name)) throw new Error(`${description.name} already has a check named ${check.name}`);
212
+ add(check, run, true);
213
+ changed();
214
+ },
215
+ addDependency(name) {
216
+ if (dependencies.has(name)) return;
217
+ dependencies.add(name);
218
+ lateDependencies.add(name);
219
+ changed();
220
+ }
221
+ };
222
+ };
223
+ export { healthRuntime };
224
+
225
+ //# sourceMappingURL=health.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.js","names":[],"sources":["../src/health.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock, unrefClock } from \"./clock.ts\";\nimport type { Check, Gate, ServiceDescription } from \"./description.ts\";\nimport type { MachineName, Recorder } from \"./events.ts\";\nimport type { Latch, Result, Trace } from \"./latch.ts\";\nimport type { Logger } from \"./logger.ts\";\nimport { latch } from \"./latch.ts\";\nimport type { HealthMetrics } from \"./metrics.ts\";\nimport { meter } from \"./metrics.ts\";\nimport type { CheckFn, Poller } from \"./poller.ts\";\nimport { poller } from \"./poller.ts\";\n\n/** These options start the runtime. Without them, it uses the real clock and `Math.random`. */\nexport interface StartOptions {\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each poll. */\n readonly random?: (() => number) | undefined;\n /** This list names the checks or dependencies whose polls fail at once (a seam for tests). */\n readonly forceFail?: readonly string[] | undefined;\n /** This function receives each transition of each machine of the runtime. */\n readonly record?: Recorder | undefined;\n /**\n * This logger receives each transition too, as a log entry with a level and fields (`logEvents`).\n * Without it, the runtime writes no log, as before. For the console, give `consoleLogger()`.\n */\n readonly logger?: Logger | undefined;\n /**\n * This function can replace the function of a check, for example to add a delay to each call\n * (a seam for tests: a degraded dependency). It gives the function to use.\n */\n readonly wrapCheck?: ((check: Check, run: CheckFn) => CheckFn) | undefined;\n}\n\n/** A check verdict is the cached state of one check, for the probes and the report. */\nexport interface CheckVerdict {\n readonly gates: Gate | null;\n readonly dependency: string | null;\n /** This flag tells if the latch of the check is tripped, or it is null for a check that only reports. */\n readonly tripped: boolean | null;\n readonly streak: number;\n /** This time is when the latch last changed, in milliseconds on the monotonic clock. */\n readonly since: number | null;\n readonly last: Result | null;\n}\n\n/** A verdict is the state of the service, from its cache. Nothing in it starts a check. */\nexport interface HealthVerdict {\n /** This flag becomes true one time, after the warm-up sweep. */\n readonly started: boolean;\n readonly draining: boolean;\n /** This flag tells if the service can take new work: started, not draining, and each readiness latch released. */\n readonly ready: boolean;\n /** This flag tells if each liveness latch is released. */\n readonly alive: boolean;\n /** These flags tell if each controller can take new work, from the dependencies that it needs. */\n readonly controllers: Readonly<Record<string, boolean>>;\n readonly dependencies: Readonly<Record<string, boolean>>;\n readonly checks: Readonly<Record<string, CheckVerdict>>;\n readonly startup: { readonly budget: number; readonly elapsed: number; readonly overBudget: boolean };\n}\n\n/** A probe kind is the question that a probe asks: the startup, the readiness, the liveness, or the whole report. */\nexport type ProbeKind = \"startup\" | \"readiness\" | \"liveness\" | \"report\";\n\n/** A probe answer is a status and a body, for any HTTP framework or none. */\nexport interface ProbeAnswer {\n readonly status: 200 | 503;\n readonly contentType: \"application/health+json\";\n readonly body: {\n readonly status: \"pass\" | \"fail\";\n readonly service: string;\n readonly probe: ProbeKind;\n readonly controller?: string | undefined;\n readonly verdict?: HealthVerdict | undefined;\n };\n}\n\n/** The health runtime of a started service. It reads its timing and its checks from the declaration. */\nexport interface Health {\n verdict(): HealthVerdict;\n /**\n * This method answers a probe from the cache, in constant time, and it starts no check. A\n * readiness probe with a controller asks about that controller. The report always answers 200.\n */\n probe(kind: ProbeKind, controller?: string): ProbeAnswer;\n /**\n * This method gives the counts of the runtime (B18). They are the outcomes, the durations and the\n * episodes of failure of each check, and the transitions of its machines. It starts no check.\n */\n metrics(): HealthMetrics;\n /** This method gives each change of the verdict to `listener`, and gives the function that stops it. */\n subscribe(listener: (verdict: HealthVerdict) => void): () => void;\n /** This method adds a name to the force-fail list, or removes it. */\n forceFail(name: string, on: boolean): void;\n /** This method fails readiness for good. The drain of the lifecycle starts with it. */\n drain(): void;\n /** This method stops each poller and each timer of the runtime. */\n stop(): void;\n}\n\n/** The runtime parts that the builder and the lifecycle use. */\nexport interface Runtime extends Health {\n /**\n * This method opens the startup gate: one bounded warm-up sweep of each check, then the loops of\n * the pollers. It is idempotent, and it does nothing after `failStartup()` or `stop()`.\n */\n warmUp(): Promise<void>;\n /** This method moves the gate from `closed` to `starting`: the lifecycle starts its components. */\n beginStartup(): void;\n /** This method moves the gate to `failed` for good: a component did not start. */\n failStartup(cause: string): void;\n addCheck(check: Check, run: CheckFn): void;\n addDependency(name: string): void;\n}\n\ninterface Entry {\n readonly check: Check;\n readonly poller: Poller;\n readonly latch: Latch | null;\n}\n\n/**\n * This function makes the runtime of a declaration. The service has no defaults of its own: each\n * timing, poll and coupling comes from the description.\n */\nexport const healthRuntime = (\n description: ServiceDescription,\n runs: ReadonlyMap<string, CheckFn>,\n options: StartOptions = {},\n): Runtime => {\n const clock = options.clock ?? realClock;\n const random = options.random ?? Math.random;\n const forced = new Set(options.forceFail ?? []);\n const startedAt = clock.now();\n const budget = valueIn(description.policies.startup, \"ms\");\n const entries = new Map<string, Entry>();\n const dependencies = new Set(description.dependencies.map((dependency) => dependency.name));\n // a dependency that joined after the start is tripped until a check on it passes one time\n const lateDependencies = new Set<string>();\n const listeners = new Set<(verdict: HealthVerdict) => void>();\n let started = false;\n let draining = false;\n let stopped = false;\n // the startup gate: closed, starting (components start), sweeping (the warm-up), open or failed\n let gate = \"closed\";\n\n const counts = meter();\n // each transition goes to the meter, and then to the recorder of the options\n const record: Recorder = (event) => {\n counts.event(event);\n options.record?.(event);\n };\n const tracer =\n (machine: MachineName, instance: string): Trace =>\n (from, to, on) =>\n record({ at: clock.now(), machine, instance, from, to, on });\n const gateTrace = tracer(\"gate\", description.name);\n const moveGate = (to: string, on: string, detail?: string): void => {\n const from = gate;\n gate = to;\n record({\n at: clock.now(),\n machine: \"gate\",\n instance: description.name,\n from,\n to,\n on,\n ...(detail === undefined ? {} : { detail }),\n });\n };\n // the startup budget: a gate that is not open at its end says so. The platform's startup probe\n // acts on it, and the runtime does not stop itself\n let budgetTimer: Cancel | null = clock.after(budget, () => {\n budgetTimer = null;\n if (gate !== \"open\" && gate !== \"failed\") gateTrace(gate, gate, \"startup.over-budget\");\n });\n // the budget only traces, thus it does not keep the process alive (SYS-126)\n budgetTimer.unref?.();\n\n const changed = (): void => {\n if (listeners.size === 0) return;\n const now = verdict();\n for (const listener of listeners) listener(now);\n };\n\n const add = (check: Check, given: CheckFn, late: boolean): void => {\n const run = options.wrapCheck?.(check, given) ?? given;\n const timing = check.gates === null ? null : description.policies[check.gates];\n // readiness is earned: its latch starts tripped. Liveness passes from the start (and a late\n // liveness check starts released too, or one late registration could restart the process)\n const made =\n timing === null\n ? null\n : latch(\n timing,\n // a check watches the parts of the service: the parts keep the process alive, and the\n // windows of the latch do not (SYS-126)\n unrefClock(clock),\n check.gates === \"readiness\",\n changed,\n tracer(timing.type === \"window\" ? \"window\" : \"latch\", check.name),\n );\n const entry: Entry = {\n check,\n latch: made,\n poller: poller({\n name: check.name,\n poll: check.poll,\n run,\n clock,\n random,\n // a check watches the parts of the service: the parts keep the process alive. The warm-up\n // awaits its sweep of polls, thus the timeout of a poll stays referenced (SYS-126)\n unrefLoop: true,\n forced: () =>\n forced.has(check.name) || (check.dependency !== null && forced.has(check.dependency)),\n record: (result) => {\n counts.poll(check, result);\n made?.record(result);\n // a late dependency is released by the first pass of a check on it\n if (result.outcome === \"ok\" && check.dependency !== null)\n if (lateDependencies.delete(check.dependency)) changed();\n },\n trace: tracer(\"poller\", check.name),\n }),\n };\n entries.set(check.name, entry);\n counts.add(check);\n if (late && !stopped) {\n // a late registration pulls readiness until its first pass: it polls at once, then on its loop\n void entry.poller.pollNow();\n entry.poller.start(entry.poller.jittered());\n }\n };\n\n for (const check of description.checks) {\n const run = runs.get(check.name);\n if (run === undefined) throw new Error(`check ${check.name} has no function: the runtime has no defaults`);\n add(check, run, false);\n }\n\n const latchesOf = (gateOf: Gate, keep: (check: Check) => boolean = () => true): Latch[] =>\n [...entries.values()].flatMap((entry) =>\n entry.check.gates === gateOf && entry.latch !== null && keep(entry.check) ? [entry.latch] : [],\n );\n const released = (latches: readonly Latch[]): boolean => latches.every((each) => !each.tripped);\n /** This function tells if a policy fails through a declared coupling from another policy. */\n const coupledOff = (to: Gate, base: Record<Gate, boolean>): boolean =>\n description.couplings.some((coupling) => coupling.to === to && !base[coupling.from]);\n\n const verdict = (): HealthVerdict => {\n const base: Record<Gate, boolean> = {\n readiness: released(latchesOf(\"readiness\")) && lateDependencies.size === 0,\n liveness: released(latchesOf(\"liveness\")),\n };\n const alive = base.liveness && !coupledOff(\"liveness\", base);\n const open = started && !draining && !coupledOff(\"readiness\", base);\n const ready = open && base.readiness;\n const dependencyReady = (name: string): boolean =>\n !lateDependencies.has(name) &&\n released(latchesOf(\"readiness\", (check) => check.dependency === name));\n const own = released(latchesOf(\"readiness\", (check) => check.dependency === null));\n const dependenciesOut: Record<string, boolean> = {};\n for (const name of dependencies) dependenciesOut[name] = dependencyReady(name);\n const controllers: Record<string, boolean> = {};\n for (const controller of description.controllers)\n controllers[controller.name] = open && own && controller.requires.every(dependencyReady);\n const checks: Record<string, CheckVerdict> = {};\n for (const [name, entry] of entries) {\n checks[name] = {\n gates: entry.check.gates,\n dependency: entry.check.dependency,\n tripped: entry.latch?.tripped ?? null,\n streak: entry.latch?.streak ?? 0,\n since: entry.latch?.since ?? null,\n last: entry.poller.last,\n };\n }\n const elapsed = clock.now() - startedAt;\n return {\n started,\n draining,\n ready,\n alive,\n controllers,\n dependencies: dependenciesOut,\n checks,\n startup: { budget, elapsed, overBudget: !started && elapsed > budget },\n };\n };\n\n const answer = (kind: ProbeKind, pass: boolean, controller?: string): ProbeAnswer => ({\n status: pass || kind === \"report\" ? 200 : 503,\n contentType: \"application/health+json\",\n body: {\n status: pass ? \"pass\" : \"fail\",\n service: description.name,\n probe: kind,\n ...(controller === undefined ? {} : { controller }),\n ...(kind === \"report\" ? { verdict: verdict() } : {}),\n },\n });\n\n return {\n verdict,\n metrics: counts.metrics,\n probe(kind, controller) {\n const now = verdict();\n if (kind === \"startup\") return answer(kind, now.started);\n if (kind === \"liveness\") return answer(kind, now.alive);\n if (kind === \"report\") return answer(kind, now.ready && now.alive);\n if (controller === undefined) return answer(kind, now.ready);\n // only an own key is a controller: a name such as \"constructor\" is not one\n const known = Object.hasOwn(now.controllers, controller) ? now.controllers[controller] : undefined;\n if (known === undefined) throw new Error(`${description.name} has no controller ${controller}`);\n return answer(kind, known, controller);\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n forceFail(name, on) {\n if (on) forced.add(name);\n else forced.delete(name);\n },\n drain() {\n if (draining) return;\n draining = true;\n changed();\n },\n stop() {\n stopped = true;\n budgetTimer?.();\n budgetTimer = null;\n for (const entry of entries.values()) {\n entry.poller.stop();\n entry.latch?.stop();\n }\n },\n beginStartup() {\n if (gate === \"closed\") moveGate(\"starting\", \"startup.begin\");\n },\n failStartup(cause) {\n if (gate === \"open\" || gate === \"failed\") return;\n moveGate(\"failed\", \"startup.fail\", cause);\n budgetTimer?.();\n budgetTimer = null;\n },\n async warmUp() {\n if (started || stopped || gate === \"failed\" || gate === \"sweeping\") return;\n moveGate(\"sweeping\", \"mark-ready\");\n // one bounded sweep of each check: each poll ends at its timeout at the latest\n const sweep = clock.now();\n await Promise.all([...entries.values()].map((entry) => entry.poller.pollNow()));\n if (stopped || gate !== \"sweeping\") return;\n for (const entry of entries.values())\n entry.poller.start(entry.poller.jittered() - (clock.now() - sweep));\n started = true;\n budgetTimer?.();\n budgetTimer = null;\n moveGate(\"open\", \"sweep.done\");\n changed();\n },\n addCheck(check, run) {\n if (entries.has(check.name)) throw new Error(`${description.name} already has a check named ${check.name}`);\n add(check, run, true);\n changed();\n },\n addDependency(name) {\n if (dependencies.has(name)) return;\n dependencies.add(name);\n lateDependencies.add(name);\n changed();\n },\n };\n};\n"],"mappings":";;;;;;;;;;AA8HA,MAAa,iBACX,aACA,MACA,UAAwB,CAAC,MACb;CACZ,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,SAAS,QAAQ,UAAU,KAAK;CACtC,MAAM,SAAS,IAAI,IAAI,QAAQ,aAAa,CAAC,CAAC;CAC9C,MAAM,YAAY,MAAM,IAAI;CAC5B,MAAM,SAAS,QAAQ,YAAY,SAAS,SAAS,IAAI;CACzD,MAAM,0BAAU,IAAI,IAAmB;CACvC,MAAM,eAAe,IAAI,IAAI,YAAY,aAAa,KAAK,eAAe,WAAW,IAAI,CAAC;CAE1F,MAAM,mCAAmB,IAAI,IAAY;CACzC,MA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AAU,MAAM,OAAO,QAAQ,CAAC,CAAC;GAC9E,IAAI,WAAW,SAAS,YAAY;GACpC,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,MAAM,MAAM,OAAO,SAAS,KAAK,MAAM,IAAI,IAAI,MAAM;GACpE,UAAU;GACV,cAAc;GACd,cAAc;GACd,SAAS,QAAQ,YAAY;GAC7B,QAAQ;EACV;EACA,SAAS,OAAO,KAAK;GACnB,IAAI,QAAQ,IAAI,MAAM,IAAI,GAAG,MAAM,IAAI,MAAM,GAAG,YAAY,KAAK,6BAA6B,MAAM,MAAM;GAC1G,IAAI,OAAO,KAAK,IAAI;GACpB,QAAQ;EACV;EACA,cAAc,MAAM;GAClB,IAAI,aAAa,IAAI,IAAI,GAAG;GAC5B,aAAa,IAAI,IAAI;GACrB,iBAAiB,IAAI,IAAI;GACzB,QAAQ;EACV;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { n as Clock } from "./clock-DpVgpY4h.js";
1
+ import { Clock } from "./clock.js";
2
2
  /** These options make a heartbeat. Each time is in milliseconds on the clock. */
3
3
  export interface HeartbeatOptions {
4
4
  /**
@@ -35,7 +35,11 @@ export interface HeartbeatOptions {
35
35
  * answer or a miss, thus it reads a reply that is in the socket first. Without it, the heartbeat counts at once.
36
36
  */
37
37
  readonly turn?: (() => Promise<void>) | undefined;
38
- /** This clock gives the ticks and the timeouts. The default is `realClock`. */
38
+ /**
39
+ * This clock gives the ticks and the timeouts. The default is `realClock`, and its timers keep a
40
+ * Node process alive until `stop()`. A heartbeat only watches a connection, and the connection
41
+ * decides if the process stays alive. Thus the owner of a connection gives `unrefClock(clock)`.
42
+ */
39
43
  readonly clock?: Clock | undefined;
40
44
  }
41
45
  /** A heartbeat is a loop of pings that runs until `stop()`. */
@@ -1 +1 @@
1
- {"version":3,"file":"heartbeat.js","names":[],"sources":["../src/heartbeat.ts"],"sourcesContent":["// @mark1russell7/service/heartbeat: a heartbeat on a clock, with no other part of the package. A\n// ping starts each interval, each ping has a timeout, and a count of misses in sequence finds a\n// dead peer. The entry imports no `node:` module and no zod. Thus a client in a browser can use it.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a heartbeat. Each time is in milliseconds on the clock. */\nexport interface HeartbeatOptions {\n /**\n * This time is the interval of the ticks, from the start of one tick to the start of the next.\n * A time that is not finite starts no tick.\n */\n readonly interval: number;\n /** This time bounds each ping. A time that is not finite gives a ping without a timeout. */\n readonly timeout: number;\n /** This count is the number of misses in sequence that make the peer dead. It is a whole number above zero. */\n readonly misses: number;\n /**\n * This function sends one ping. The signal aborts at the timeout of the ping and at `stop()`.\n * - A promise gives the answer: true when the peer answered, and false when it did not.\n * - No value tells that the answer comes later through `answer()`, for example as a pong message.\n * - A throw or a rejection is a miss.\n */\n readonly ping: (signal: AbortSignal) => Promise<boolean> | void;\n /** This function receives the death of the peer: the last of `misses` misses in sequence. The count of misses is then zero again. */\n readonly onDead: () => void;\n /** This function receives each miss, with the count of misses in sequence. */\n readonly onMiss?: ((misses: number) => void) | undefined;\n /**\n * This function operates at each tick, before the ping. The tick sends a ping only when it gives\n * true. A client can also act at the tick, for example to connect again. Without it, each tick sends a ping.\n */\n readonly due?: (() => boolean) | undefined;\n /** This function tells if a miss counts. A miss does not count while it gives false. Without it, each miss counts. */\n readonly live?: (() => boolean) | undefined;\n /** True lets a tick send a ping while an earlier ping waits for its answer. The default is false: one ping at a time. */\n readonly overlap?: boolean | undefined;\n /**\n * This function waits one turn of the event loop. The heartbeat waits it before it counts an\n * answer or a miss, thus it reads a reply that is in the socket first. Without it, the heartbeat counts at once.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n /** This clock gives the ticks and the timeouts. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n}\n\n/** A heartbeat is a loop of pings that runs until `stop()`. */\nexport interface Heartbeat {\n /** This method tells the heartbeat that the peer answered. Each ping that waits gets its answer, and the count of misses is zero. */\n answer(): void;\n /** This method stops the ticks and the timeouts, and it aborts each ping that waits. A second use does nothing. */\n stop(): void;\n /** This count is the number of misses in the current sequence. */\n readonly misses: number;\n /** This count is the number of pings that wait for their answer. */\n readonly waiting: number;\n readonly stopped: boolean;\n}\n\ninterface Waiting {\n readonly settle: (answered: boolean) => void;\n readonly controller: AbortController;\n timer: Cancel | null;\n}\n\n/**\n * This function starts a heartbeat. The first tick comes one interval after the start. Each tick\n * starts the next one first, thus the ticks keep their interval while a ping waits. A ping that has\n * no answer at its timeout is a miss. The last miss of `misses` in sequence starts `onDead`.\n */\nexport const heartbeat = (options: HeartbeatOptions): Heartbeat => {\n const { interval, timeout, misses: limit, clock = realClock } = options;\n if (!Number.isInteger(limit) || limit < 1)\n throw new RangeError(`a heartbeat needs a count of misses that is a whole number above zero, not ${limit}`);\n let misses = 0;\n let stopped = false;\n let next: Cancel | null = null;\n const pings = new Set<Waiting>();\n\n const count = (answered: boolean): void => {\n if (stopped) return;\n if (answered) {\n misses = 0;\n return;\n }\n if (options.live !== undefined && !options.live()) return;\n misses += 1;\n options.onMiss?.(misses);\n if (misses >= limit) {\n misses = 0;\n options.onDead();\n }\n };\n\n const send = (): void => {\n const controller = new AbortController();\n const entry: Waiting = {\n controller,\n timer: null,\n settle: (answered) => {\n if (!pings.delete(entry)) return;\n entry.timer?.();\n const done = (): void => count(answered);\n if (options.turn === undefined) done();\n else void options.turn().then(done, done);\n },\n };\n pings.add(entry);\n if (Number.isFinite(timeout))\n entry.timer = clock.after(timeout, () => {\n entry.settle(false);\n controller.abort();\n });\n let result: Promise<boolean> | void;\n try {\n result = options.ping(controller.signal);\n } catch {\n entry.settle(false);\n return;\n }\n if (result !== undefined)\n result.then(\n (answered) => entry.settle(answered === true),\n () => entry.settle(false),\n );\n };\n\n const tick = (): void => {\n next = clock.after(interval, tick);\n if (options.due !== undefined && !options.due()) return;\n if (stopped || (options.overlap !== true && pings.size > 0)) return;\n send();\n };\n if (Number.isFinite(interval)) next = clock.after(interval, tick);\n\n return {\n answer() {\n if (stopped) return;\n misses = 0;\n for (const entry of [...pings]) entry.settle(true);\n },\n stop() {\n if (stopped) return;\n stopped = true;\n next?.();\n next = null;\n for (const entry of [...pings]) {\n pings.delete(entry);\n entry.timer?.();\n entry.controller.abort();\n }\n },\n get misses() {\n return misses;\n },\n get waiting() {\n return pings.size;\n },\n get stopped() {\n return stopped;\n },\n };\n};\n\n/**\n * This function gives the most time that a heartbeat takes to find a silent peer, in milliseconds.\n * The first ping without an answer starts one interval after the silence at the latest. The last\n * of `misses` pings then fails at its timeout: `misses` intervals plus a timeout. An interval that\n * is not finite gives infinity.\n *\n * The time holds when each tick sends a ping: with `overlap`, or with a timeout below the interval.\n */\nexport const detectionTime = (interval: number, timeout: number, misses: number): number =>\n Number.isFinite(interval) ? misses * interval + timeout : Number.POSITIVE_INFINITY;\n"],"mappings":";;;;;;;AAuEA,MAAa,aAAa,YAAyC;CACjE,MAAM,EAAE,UAAU,SAAS,QAAQ,OAAO,QAAQ,cAAc;CAChE,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WAAW,8EAA8E,OAAO;CAC5G,IAAI,SAAS;CACb,IAAI,UAAU;CACd,IAAI,OAAsB;CAC1B,MAAM,wBAAQ,IAAI,IAAa;CAE/B,MAAM,SAAS,aAA4B;EACzC,IAAI,SAAS;EACb,IAAI,UAAU;GACZ,SAAS;GACT;EACF;EACA,IAAI,QAAQ,SAAS,KAAA,KAAa,CAAC,QAAQ,KAAK,GAAG;EACnD,UAAU;EACV,QAAQ,SAAS,MAAM;EACvB,IAAI,UAAU,OAAO;GACnB,SAAS;GACT,QAAQ,OAAO;EACjB;CACF;CAEA,MAAM,aAAmB;EACvB,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,QAAiB;GACrB;GACA,OAAO;GACP,SAAS,aAAa;IACpB,IAAI,CAAC,MAAM,OAAO,KAAK,GAAG;IAC1B,MAAM,QAAQ;IACd,MAAM,aAAmB,MAAM,QA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AAW,UAAU,OAAO"}
1
+ {"version":3,"file":"heartbeat.js","names":[],"sources":["../src/heartbeat.ts"],"sourcesContent":["// @mark1russell7/service/heartbeat: a heartbeat on a clock, with no other part of the package. A\n// ping starts each interval, each ping has a timeout, and a count of misses in sequence finds a\n// dead peer. The entry imports no `node:` module and no zod. Thus a client in a browser can use it.\n\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a heartbeat. Each time is in milliseconds on the clock. */\nexport interface HeartbeatOptions {\n /**\n * This time is the interval of the ticks, from the start of one tick to the start of the next.\n * A time that is not finite starts no tick.\n */\n readonly interval: number;\n /** This time bounds each ping. A time that is not finite gives a ping without a timeout. */\n readonly timeout: number;\n /** This count is the number of misses in sequence that make the peer dead. It is a whole number above zero. */\n readonly misses: number;\n /**\n * This function sends one ping. The signal aborts at the timeout of the ping and at `stop()`.\n * - A promise gives the answer: true when the peer answered, and false when it did not.\n * - No value tells that the answer comes later through `answer()`, for example as a pong message.\n * - A throw or a rejection is a miss.\n */\n readonly ping: (signal: AbortSignal) => Promise<boolean> | void;\n /** This function receives the death of the peer: the last of `misses` misses in sequence. The count of misses is then zero again. */\n readonly onDead: () => void;\n /** This function receives each miss, with the count of misses in sequence. */\n readonly onMiss?: ((misses: number) => void) | undefined;\n /**\n * This function operates at each tick, before the ping. The tick sends a ping only when it gives\n * true. A client can also act at the tick, for example to connect again. Without it, each tick sends a ping.\n */\n readonly due?: (() => boolean) | undefined;\n /** This function tells if a miss counts. A miss does not count while it gives false. Without it, each miss counts. */\n readonly live?: (() => boolean) | undefined;\n /** True lets a tick send a ping while an earlier ping waits for its answer. The default is false: one ping at a time. */\n readonly overlap?: boolean | undefined;\n /**\n * This function waits one turn of the event loop. The heartbeat waits it before it counts an\n * answer or a miss, thus it reads a reply that is in the socket first. Without it, the heartbeat counts at once.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n /**\n * This clock gives the ticks and the timeouts. The default is `realClock`, and its timers keep a\n * Node process alive until `stop()`. A heartbeat only watches a connection, and the connection\n * decides if the process stays alive. Thus the owner of a connection gives `unrefClock(clock)`.\n */\n readonly clock?: Clock | undefined;\n}\n\n/** A heartbeat is a loop of pings that runs until `stop()`. */\nexport interface Heartbeat {\n /** This method tells the heartbeat that the peer answered. Each ping that waits gets its answer, and the count of misses is zero. */\n answer(): void;\n /** This method stops the ticks and the timeouts, and it aborts each ping that waits. A second use does nothing. */\n stop(): void;\n /** This count is the number of misses in the current sequence. */\n readonly misses: number;\n /** This count is the number of pings that wait for their answer. */\n readonly waiting: number;\n readonly stopped: boolean;\n}\n\ninterface Waiting {\n readonly settle: (answered: boolean) => void;\n readonly controller: AbortController;\n timer: Cancel | null;\n}\n\n/**\n * This function starts a heartbeat. The first tick comes one interval after the start. Each tick\n * starts the next one first, thus the ticks keep their interval while a ping waits. A ping that has\n * no answer at its timeout is a miss. The last miss of `misses` in sequence starts `onDead`.\n */\nexport const heartbeat = (options: HeartbeatOptions): Heartbeat => {\n const { interval, timeout, misses: limit, clock = realClock } = options;\n if (!Number.isInteger(limit) || limit < 1)\n throw new RangeError(`a heartbeat needs a count of misses that is a whole number above zero, not ${limit}`);\n let misses = 0;\n let stopped = false;\n let next: Cancel | null = null;\n const pings = new Set<Waiting>();\n\n const count = (answered: boolean): void => {\n if (stopped) return;\n if (answered) {\n misses = 0;\n return;\n }\n if (options.live !== undefined && !options.live()) return;\n misses += 1;\n options.onMiss?.(misses);\n if (misses >= limit) {\n misses = 0;\n options.onDead();\n }\n };\n\n const send = (): void => {\n const controller = new AbortController();\n const entry: Waiting = {\n controller,\n timer: null,\n settle: (answered) => {\n if (!pings.delete(entry)) return;\n entry.timer?.();\n const done = (): void => count(answered);\n if (options.turn === undefined) done();\n else void options.turn().then(done, done);\n },\n };\n pings.add(entry);\n if (Number.isFinite(timeout))\n entry.timer = clock.after(timeout, () => {\n entry.settle(false);\n controller.abort();\n });\n let result: Promise<boolean> | void;\n try {\n result = options.ping(controller.signal);\n } catch {\n entry.settle(false);\n return;\n }\n if (result !== undefined)\n result.then(\n (answered) => entry.settle(answered === true),\n () => entry.settle(false),\n );\n };\n\n const tick = (): void => {\n next = clock.after(interval, tick);\n if (options.due !== undefined && !options.due()) return;\n if (stopped || (options.overlap !== true && pings.size > 0)) return;\n send();\n };\n if (Number.isFinite(interval)) next = clock.after(interval, tick);\n\n return {\n answer() {\n if (stopped) return;\n misses = 0;\n for (const entry of [...pings]) entry.settle(true);\n },\n stop() {\n if (stopped) return;\n stopped = true;\n next?.();\n next = null;\n for (const entry of [...pings]) {\n pings.delete(entry);\n entry.timer?.();\n entry.controller.abort();\n }\n },\n get misses() {\n return misses;\n },\n get waiting() {\n return pings.size;\n },\n get stopped() {\n return stopped;\n },\n };\n};\n\n/**\n * This function gives the most time that a heartbeat takes to find a silent peer, in milliseconds.\n * The first ping without an answer starts one interval after the silence at the latest. The last\n * of `misses` pings then fails at its timeout: `misses` intervals plus a timeout. An interval that\n * is not finite gives infinity.\n *\n * The time holds when each tick sends a ping: with `overlap`, or with a timeout below the interval.\n */\nexport const detectionTime = (interval: number, timeout: number, misses: number): number =>\n Number.isFinite(interval) ? misses * interval + timeout : Number.POSITIVE_INFINITY;\n"],"mappings":";;;;;;;AA2EA,MAAa,aAAa,YAAyC;CACjE,MAAM,EAAE,UAAU,SAAS,QAAQ,OAAO,QAAQ,cAAc;CAChE,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WAAW,8EAA8E,OAAO;CAC5G,IAAI,SAAS;CACb,IAAI,UAAU;CACd,IAAI,OAAsB;CAC1B,MAAM,wBAAQ,IAAI,IAAa;CAE/B,MAAM,SAAS,aAA4B;EACzC,IAAI,SAAS;EACb,IAAI,UAAU;GACZ,SAAS;GACT;EACF;EACA,IAAI,QAAQ,SAAS,KAAA,KAAa,CAAC,QAAQ,KAAK,GAAG;EACnD,UAAU;EACV,QAAQ,SAAS,MAAM;EACvB,IAAI,UAAU,OAAO;GACnB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,MAAM,WAAW,MAAM;GACzB;EACF;EACA,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO,MAAM;EACf;EACA,IAAI,UAAU;GACZ,OAAO;EACT;CACF;AACF;;;;;;;;;AAUA,MAAa,iBAAiB,UAAkB,SAAiB,WAC/D,OAAO,SAAS,QAAQ,IAAI,SAAS,WAAW,UAAU,OAAO"}
@@ -0,0 +1,61 @@
1
+ import { HostPorts } from "./ports.js";
2
+ /**
3
+ * A discovery record tells where a running instance listens. The instance writes it after its start,
4
+ * and a client reads it to find the instance. The file is JSON, one record.
5
+ */
6
+ export interface Discovery {
7
+ /** This number is the process ID of the instance. */
8
+ readonly pid: number;
9
+ /** This text is the start time of the process, as an ISO 8601 time. */
10
+ readonly startedAt: string;
11
+ /** This number is the port that the instance listens on, or null. */
12
+ readonly port: number | null;
13
+ /** This text is the address of the instance, for example `http://127.0.0.1:8080/`, or null. */
14
+ readonly url: string | null;
15
+ /** These fields are more data of the instance, for example its version. */
16
+ readonly extra?: Readonly<Record<string, unknown>> | undefined;
17
+ }
18
+ /**
19
+ * A discovery read is what a read of the discovery file found. A read does not throw.
20
+ * - `running`: the file names a live process, and its start time does not prove that it is a different process.
21
+ * - `absent`: no file.
22
+ * - `stale`: the file names a process that stopped, or a new process with the same ID.
23
+ * - `malformed`: the file is not a discovery record, or the read failed. The problem tells why.
24
+ */
25
+ export type DiscoveryRead = {
26
+ readonly kind: "running";
27
+ readonly record: Discovery;
28
+ } | {
29
+ readonly kind: "absent";
30
+ } | {
31
+ readonly kind: "stale";
32
+ readonly record: Discovery;
33
+ readonly why: string;
34
+ } | {
35
+ readonly kind: "malformed";
36
+ readonly problem: string;
37
+ };
38
+ /** These options go with a read of the discovery file. */
39
+ export interface ReadDiscoveryOptions {
40
+ /** True removes a stale or malformed file. The default is false. */
41
+ readonly clean?: boolean | undefined;
42
+ }
43
+ /** This function reads a discovery record from a text. It gives the record, or the problem as a text. */
44
+ export declare const parseDiscovery: (text: string) => Discovery | string;
45
+ /** These fields describe where this process listens. */
46
+ export interface DiscoveryFields {
47
+ readonly port?: number | null | undefined;
48
+ readonly url?: string | null | undefined;
49
+ readonly extra?: Readonly<Record<string, unknown>> | undefined;
50
+ }
51
+ /** This function gives the discovery record of the process of the host, with its start time. */
52
+ export declare const discoveryOf: (fields: DiscoveryFields, ports: HostPorts) => Discovery;
53
+ /** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */
54
+ export declare const writeDiscovery: (path: string, record: Discovery, ports: HostPorts) => Promise<void>;
55
+ /**
56
+ * This function reads a discovery file and examines its process. It does not throw: a file that is not
57
+ * a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.
58
+ */
59
+ export declare const readDiscovery: (path: string, ports: HostPorts, options?: ReadDiscoveryOptions) => Promise<DiscoveryRead>;
60
+ /** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */
61
+ export declare const removeDiscovery: (path: string, ports: HostPorts, pid?: number) => Promise<boolean>;
@@ -0,0 +1,113 @@
1
+ import { removeIfSame } from "./lock.js";
2
+ import { sameProcess } from "./processes.js";
3
+ // src/host/discovery.ts
4
+ const isPort = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535;
5
+ /** This function reads a discovery record from a text. It gives the record, or the problem as a text. */
6
+ const parseDiscovery = (text) => {
7
+ let value;
8
+ try {
9
+ value = JSON.parse(text);
10
+ } catch (error) {
11
+ return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;
12
+ }
13
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return "the file is not a JSON object";
14
+ const { pid, startedAt, port, url, extra } = value;
15
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return "the field pid is not a process ID";
16
+ if (typeof startedAt !== "string" || !Number.isFinite(Date.parse(startedAt))) return "the field startedAt is not an ISO time";
17
+ if (port !== null && port !== void 0 && !isPort(port)) return "the field port is not a port from 1 to 65535";
18
+ if (url !== null && url !== void 0 && typeof url !== "string") return "the field url is not a text";
19
+ if (extra !== void 0 && (typeof extra !== "object" || extra === null || Array.isArray(extra))) return "the field extra is not an object";
20
+ return {
21
+ pid,
22
+ startedAt,
23
+ port: isPort(port) ? port : null,
24
+ url: typeof url === "string" ? url : null,
25
+ ...extra === void 0 ? {} : { extra }
26
+ };
27
+ };
28
+ /** This function gives the discovery record of the process of the host, with its start time. */
29
+ const discoveryOf = (fields, ports) => ({
30
+ pid: ports.self.pid,
31
+ startedAt: new Date(ports.self.startedAt).toISOString(),
32
+ port: fields.port ?? null,
33
+ url: fields.url ?? null,
34
+ ...fields.extra === void 0 ? {} : { extra: fields.extra }
35
+ });
36
+ /** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */
37
+ const writeDiscovery = async (path, record, ports) => {
38
+ await ports.files.write(path, `${JSON.stringify(record, null, 2)}\n`);
39
+ };
40
+ /**
41
+ * This function reads a discovery file and examines its process. It does not throw: a file that is not
42
+ * a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.
43
+ */
44
+ const readDiscovery = async (path, ports, options = {}) => {
45
+ const { found, text } = await examine(path, ports);
46
+ if (options.clean === true && text !== null && (found.kind === "stale" || found.kind === "malformed")) try {
47
+ if (await removeIfSame(path, text, ports)) ports.logger?.log("info", `the host removed the ${found.kind} discovery file ${path}`, {
48
+ path,
49
+ kind: found.kind
50
+ });
51
+ } catch {}
52
+ return found;
53
+ };
54
+ const examine = async (path, ports) => {
55
+ let text;
56
+ try {
57
+ text = await ports.files.read(path);
58
+ } catch (error) {
59
+ return {
60
+ found: {
61
+ kind: "malformed",
62
+ problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
63
+ },
64
+ text: null
65
+ };
66
+ }
67
+ if (text === null) return {
68
+ found: { kind: "absent" },
69
+ text
70
+ };
71
+ const record = parseDiscovery(text);
72
+ if (typeof record === "string") return {
73
+ found: {
74
+ kind: "malformed",
75
+ problem: record
76
+ },
77
+ text
78
+ };
79
+ const mark = {
80
+ pid: record.pid,
81
+ startedAt: Date.parse(record.startedAt)
82
+ };
83
+ if (await sameProcess(mark, ports)) return {
84
+ found: {
85
+ kind: "running",
86
+ record
87
+ },
88
+ text
89
+ };
90
+ return {
91
+ found: {
92
+ kind: "stale",
93
+ record,
94
+ why: ports.processes.alive(record.pid) ? `the process ${record.pid} started after the record, thus it is a different process` : `the process ${record.pid} stopped`
95
+ },
96
+ text
97
+ };
98
+ };
99
+ /** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */
100
+ const removeDiscovery = async (path, ports, pid = ports.self.pid) => {
101
+ try {
102
+ const text = await ports.files.read(path);
103
+ if (text === null) return false;
104
+ const record = parseDiscovery(text);
105
+ if (typeof record === "string" || record.pid !== pid) return false;
106
+ return await removeIfSame(path, text, ports);
107
+ } catch {
108
+ return false;
109
+ }
110
+ };
111
+ export { discoveryOf, parseDiscovery, readDiscovery, removeDiscovery, writeDiscovery };
112
+
113
+ //# sourceMappingURL=discovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery.js","names":["record"],"sources":["../../src/host/discovery.ts"],"sourcesContent":["import type { HostPorts } from \"./ports.ts\";\nimport { removeIfSame } from \"./lock.ts\";\nimport { sameProcess } from \"./processes.ts\";\n\n/**\n * A discovery record tells where a running instance listens. The instance writes it after its start,\n * and a client reads it to find the instance. The file is JSON, one record.\n */\nexport interface Discovery {\n /** This number is the process ID of the instance. */\n readonly pid: number;\n /** This text is the start time of the process, as an ISO 8601 time. */\n readonly startedAt: string;\n /** This number is the port that the instance listens on, or null. */\n readonly port: number | null;\n /** This text is the address of the instance, for example `http://127.0.0.1:8080/`, or null. */\n readonly url: string | null;\n /** These fields are more data of the instance, for example its version. */\n readonly extra?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/**\n * A discovery read is what a read of the discovery file found. A read does not throw.\n * - `running`: the file names a live process, and its start time does not prove that it is a different process.\n * - `absent`: no file.\n * - `stale`: the file names a process that stopped, or a new process with the same ID.\n * - `malformed`: the file is not a discovery record, or the read failed. The problem tells why.\n */\nexport type DiscoveryRead =\n | { readonly kind: \"running\"; readonly record: Discovery }\n | { readonly kind: \"absent\" }\n | { readonly kind: \"stale\"; readonly record: Discovery; readonly why: string }\n | { readonly kind: \"malformed\"; readonly problem: string };\n\n/** These options go with a read of the discovery file. */\nexport interface ReadDiscoveryOptions {\n /** True removes a stale or malformed file. The default is false. */\n readonly clean?: boolean | undefined;\n}\n\nconst isPort = (value: unknown): value is number => typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 65_535;\n\n/** This function reads a discovery record from a text. It gives the record, or the problem as a text. */\nexport const parseDiscovery = (text: string): Discovery | string => {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (error) {\n return `the file is not JSON: ${error instanceof Error ? error.message : String(error)}`;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return \"the file is not a JSON object\";\n const record = value as Readonly<Record<string, unknown>>;\n const { pid, startedAt, port, url, extra } = record;\n if (typeof pid !== \"number\" || !Number.isInteger(pid) || pid <= 0) return \"the field pid is not a process ID\";\n if (typeof startedAt !== \"string\" || !Number.isFinite(Date.parse(startedAt))) return \"the field startedAt is not an ISO time\";\n if (port !== null && port !== undefined && !isPort(port)) return \"the field port is not a port from 1 to 65535\";\n if (url !== null && url !== undefined && typeof url !== \"string\") return \"the field url is not a text\";\n if (extra !== undefined && (typeof extra !== \"object\" || extra === null || Array.isArray(extra))) return \"the field extra is not an object\";\n return {\n pid,\n startedAt,\n port: isPort(port) ? port : null,\n url: typeof url === \"string\" ? url : null,\n ...(extra === undefined ? {} : { extra: extra as Readonly<Record<string, unknown>> }),\n };\n};\n\n/** These fields describe where this process listens. */\nexport interface DiscoveryFields {\n readonly port?: number | null | undefined;\n readonly url?: string | null | undefined;\n readonly extra?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** This function gives the discovery record of the process of the host, with its start time. */\nexport const discoveryOf = (fields: DiscoveryFields, ports: HostPorts): Discovery => ({\n pid: ports.self.pid,\n startedAt: new Date(ports.self.startedAt).toISOString(),\n port: fields.port ?? null,\n url: fields.url ?? null,\n ...(fields.extra === undefined ? {} : { extra: fields.extra }),\n});\n\n/** This function writes a discovery file. The write replaces the file in one step, thus a reader sees the old record or the new one. */\nexport const writeDiscovery = async (path: string, record: Discovery, ports: HostPorts): Promise<void> => {\n await ports.files.write(path, `${JSON.stringify(record, null, 2)}\\n`);\n};\n\n/**\n * This function reads a discovery file and examines its process. It does not throw: a file that is not\n * a record, or a failed read, gives `malformed`. With `clean`, it removes a stale or malformed file.\n */\nexport const readDiscovery = async (path: string, ports: HostPorts, options: ReadDiscoveryOptions = {}): Promise<DiscoveryRead> => {\n const { found, text } = await examine(path, ports);\n // The clean removes only the text that it examined: a new instance can write its file after the read.\n if (options.clean === true && text !== null && (found.kind === \"stale\" || found.kind === \"malformed\")) {\n try {\n if (await removeIfSame(path, text, ports)) ports.logger?.log(\"info\", `the host removed the ${found.kind} discovery file ${path}`, { path, kind: found.kind });\n } catch {\n // the next read examines the file again\n }\n }\n return found;\n};\n\nconst examine = async (path: string, ports: HostPorts): Promise<{ readonly found: DiscoveryRead; readonly text: string | null }> => {\n let text: string | null;\n try {\n text = await ports.files.read(path);\n } catch (error) {\n return { found: { kind: \"malformed\", problem: `the read failed: ${error instanceof Error ? error.message : String(error)}` }, text: null };\n }\n if (text === null) return { found: { kind: \"absent\" }, text };\n const record = parseDiscovery(text);\n if (typeof record === \"string\") return { found: { kind: \"malformed\", problem: record }, text };\n const mark = { pid: record.pid, startedAt: Date.parse(record.startedAt) };\n if (await sameProcess(mark, ports)) return { found: { kind: \"running\", record }, text };\n const why = ports.processes.alive(record.pid)\n ? `the process ${record.pid} started after the record, thus it is a different process`\n : `the process ${record.pid} stopped`;\n return { found: { kind: \"stale\", record, why }, text };\n};\n\n/** This function removes a discovery file when it names the process `pid`, by default the process of the host. It tells if it removed the file. */\nexport const removeDiscovery = async (path: string, ports: HostPorts, pid: number = ports.self.pid): Promise<boolean> => {\n try {\n const text = await ports.files.read(path);\n if (text === null) return false;\n const record = parseDiscovery(text);\n if (typeof record === \"string\" || record.pid !== pid) return false;\n return await removeIfSame(path, text, ports);\n } catch {\n return false;\n }\n};\n"],"mappings":";;;AAwCA,MAAM,UAAU,UAAoC,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,SAAS,KAAK,SAAS;;AAGnI,MAAa,kBAAkB,SAAqC;CAClE,IAAI;CACJ,IAAI;EACF,QAAQ,KAAK,MAAM,IAAI;CACzB,SAAS,OAAO;EACd,OAAO,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CACvF;CACA,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAEhF,MAAM,EAAE,KAAK,WAAW,MAAM,KAAK,UAAUA;CAC7C,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,UAAU,GAAG,KAAK,OAAO,GAAG,OAAO;CAC1E,IAAI,OAAO,cAAc,YAAY,CAAC,OAAO,SAAS,KAAK,MAAM,SAAS,CAAC,GAAG,OAAO;CACrF,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,CAAC,OAAO,IAAI,GAAG,OAAO;CACjE,IAAI,QAAQ,QAAQ,QAAQ,KAAA,KAAa,OAAO,QAAQ,UAAU,OAAO;CACzE,IAAI,UAAU,KAAA,MAAc,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,IAAI,OAAO;CACzG,OAAO;EACL;EACA;EACA,MAAM,OAAO,IAAI,IAAI,OAAO;EAC5B,KAAK,OAAO,QAAQ,WAAW,MAAM;EACrC,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAS,MAA2C;CACrF;AACF;;AAUA,MAAa,eAAe,QAAyB,WAAiC;CACpF,KAAK,MAAM,KAAK;CAChB,WAAW,IAAI,KAAK,MAAM,KAAK,SAAS,CAAC,CAAC,YAAY;CACtD,MAAM,O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AM;GAAW;EAAO;EAAG;CAAK;CAItF,OAAO;EAAE,OAAO;GAAE,MAAM;GAAS;GAAQ,KAH7B,MAAM,UAAU,MAAM,OAAO,GAAG,IACxC,eAAe,OAAO,IAAI,6DAC1B,eAAe,OAAO,IAAI;EACe;EAAG;CAAK;AACvD;;AAGA,MAAa,kBAAkB,OAAO,MAAc,OAAkB,MAAc,MAAM,KAAK,QAA0B;CACvH,IAAI;EACF,MAAM,OAAO,MAAM,MAAM,MAAM,KAAK,IAAI;EACxC,IAAI,SAAS,MAAM,OAAO;EAC1B,MAAM,SAAS,eAAe,IAAI;EAClC,IAAI,OAAO,WAAW,YAAY,OAAO,QAAQ,KAAK,OAAO;EAC7D,OAAO,MAAM,aAAa,MAAM,MAAM,KAAK;CAC7C,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -0,0 +1,14 @@
1
+ /** An env file is the variables of a file of environment variables, and the problem of each line that it skipped. */
2
+ export interface EnvFile {
3
+ readonly env: Readonly<Record<string, string>>;
4
+ readonly problems: readonly string[];
5
+ }
6
+ /**
7
+ * This function reads a file of environment variables, one `KEY=value` on each line. It is a pure
8
+ * function. It does not throw: it skips a bad line and gives its problem.
9
+ * - A blank line and a line that starts with `#` are skipped. A line can start with `export `.
10
+ * - A value in single quotes is literal. A value in double quotes has the escapes `\n`, `\t`, `\"` and `\\`.
11
+ * - A value without quotes ends at ` #`, and its spaces at the two ends go.
12
+ * - A key that comes again replaces its value.
13
+ */
14
+ export declare const parseEnvFile: (text: string) => EnvFile;