@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,144 @@
1
+ import { Clock } from "./clock.js";
2
+ import { CooperativeFloor } from "./description.js";
3
+ import { Health, StartOptions } from "./health.js";
4
+ import { ProcessPort, UncaughtOrigin } from "./process.js";
5
+ import { RequestFn, RequestOptions, RequestStream } from "./requests.js";
6
+ import "./routes.js";
7
+ import { Extent } from "@mark1russell7/quantity";
8
+ /**
9
+ * A transport is a source of work: a server, a consumer or a worker. Each has one contract. It
10
+ * starts, stops its intake, and drains to a deadline without a throw. It counts its work in flight,
11
+ * and it closes. A second close has no effect.
12
+ */
13
+ export interface TransportImpl {
14
+ /**
15
+ * This method starts the transport. The lifecycle is the object that `run()` gives at the end of
16
+ * the startup. Its request tracking operates from the start: a request before the startup ends
17
+ * gets a retryable refusal, and `keepAlive()` is false. Do not wait for `life.started` here,
18
+ * because the startup waits for this method.
19
+ */
20
+ start(signal: AbortSignal, life: Lifecycle): Promise<void> | void;
21
+ stopIntake(): Promise<void> | void;
22
+ /**
23
+ * This method lets the work in flight end until `deadline` (milliseconds on the monotonic
24
+ * clock). The signal is the cooperative abort, which comes before the deadline.
25
+ */
26
+ drain(deadline: number, signal: AbortSignal): Promise<void> | void;
27
+ inFlight(): number;
28
+ close(): Promise<void> | void;
29
+ }
30
+ /** A dependency handle connects to a dependency at the start, and closes the connection at the end. */
31
+ export interface DependencyHandle {
32
+ connect(signal: AbortSignal): Promise<void> | void;
33
+ close(): Promise<void> | void;
34
+ }
35
+ /**
36
+ * A health server answers the probes, on its own port. It starts first, thus the probes answer
37
+ * while the dependencies connect, and it closes last.
38
+ */
39
+ export interface HealthServer {
40
+ listen(health: Health): Promise<void> | void;
41
+ close(): Promise<void> | void;
42
+ }
43
+ /** A phase context is what a phase gives its work: its deadline, its signal and the clock. */
44
+ export interface PhaseContext {
45
+ /** This time is the end of the cap of the phase, in milliseconds on the monotonic clock. */
46
+ readonly deadline: number;
47
+ /** This signal aborts at the end of the cap of the phase. */
48
+ readonly signal: AbortSignal;
49
+ readonly clock: Clock;
50
+ }
51
+ /** A phase work is a step of the shutdown that an owner adds to a phase. */
52
+ export type PhaseWork = (context: PhaseContext) => Promise<void> | void;
53
+ /**
54
+ * These are the stages of the shutdown, in their sequence. A declared phase with one of these
55
+ * names gets the work of the runtime for its stage. A phase with another name gets only the work of
56
+ * its owners.
57
+ * - `fail readiness`: readiness fails at the start of the shutdown. This phase then holds for its
58
+ * cap, while the endpoints of the platform remove the service.
59
+ * - `stop intake`: each transport stops its intake, and new requests get a retryable 503.
60
+ * - `drain`: the transports and the requests in flight end, until the cap. The cooperative abort
61
+ * comes before the end of the cap, by the cooperative window.
62
+ * - `close transports`: each transport closes.
63
+ * - `stop the poller`: each check and watchdog stops. Then the signal of the service aborts.
64
+ * - `tear down dependencies`: each dependency closes, in the reverse sequence of its connection.
65
+ * - `close the health server`: the probes stop.
66
+ * - `flush the output`: the work of the owners of this phase ends, and then the process port
67
+ * writes the buffered output. Without this phase, the process exits without a wait.
68
+ */
69
+ export declare const STAGES: readonly ["fail readiness", "stop intake", "drain", "close transports", "stop the poller", "tear down dependencies", "close the health server", "flush the output"];
70
+ export type Stage = (typeof STAGES)[number];
71
+ /** This function gives the place of a stage in the sequence, or -1 for a phase of another name. */
72
+ export declare const stageRank: (name: string) => number;
73
+ /**
74
+ * This function gives the time of the cooperative abort, in milliseconds after the drain starts. It
75
+ * is the cap less the cooperative window. With the floor `half`, it is not less than half the cap,
76
+ * and a window without a bound gives half the cap. With the floor `none`, it is not less than 0.
77
+ */
78
+ export declare const cooperativeAbortAt: (cap: number, window: Extent, floor?: CooperativeFloor) => number;
79
+ /**
80
+ * These options make each error that no code caught a trigger of the shutdown. They are an uncaught
81
+ * exception and an unhandled rejection.
82
+ */
83
+ export interface UncaughtOptions {
84
+ /** This code is the exit code after an uncaught error, a whole number from 0 to 255. The default is 1. */
85
+ readonly exitCode?: number | undefined;
86
+ /**
87
+ * This function tells if the runtime skips an error, for example an `ECONNRESET` of a peer socket.
88
+ * The logger gets a skipped error at `warn`, and the service continues. A throw of this function skips nothing.
89
+ */
90
+ readonly ignore?: ((error: unknown, origin: UncaughtOrigin) => boolean) | undefined;
91
+ }
92
+ /** These options run the lifecycle. Without them, it uses the real clock and the process of Node. */
93
+ export interface RunOptions extends StartOptions {
94
+ readonly process?: ProcessPort | undefined;
95
+ /**
96
+ * With these options, the lifecycle adds a handler for the errors that no code caught, from its start
97
+ * to its exit. Each error that it does not skip is an error of the lifecycle at `error`. It then
98
+ * starts the shutdown with its exit code, as a signal does. Without them, the runtime adds no handler.
99
+ */
100
+ readonly uncaught?: UncaughtOptions | undefined;
101
+ }
102
+ /** These options go with a request for the shutdown. */
103
+ export interface ShutdownOptions {
104
+ /**
105
+ * This code is the exit code that the work of the process gives, a whole number from 0 to 255. The
106
+ * first exit request with a code sets it. A code of 0 lets an error make the exit code 1.
107
+ */
108
+ readonly code?: number | undefined;
109
+ }
110
+ /** A lifecycle state tells where the service is in its life. */
111
+ export type LifecycleState = "starting" | "running" | "draining" | "exited";
112
+ /** The lifecycle of a running service. */
113
+ export interface Lifecycle {
114
+ readonly health: Health;
115
+ readonly state: LifecycleState;
116
+ /** This code is the exit code, or null before the exit. */
117
+ readonly exitCode: number | null;
118
+ /** These texts are the errors of the lifecycle. An error makes the exit code 1, unless an exit request gives another code. */
119
+ readonly errors: readonly string[];
120
+ /** This promise ends when the startup ends: the service runs, or its startup failed. */
121
+ readonly started: Promise<void>;
122
+ /** This promise gives the exit code when the shutdown ends. */
123
+ readonly done: Promise<number>;
124
+ /** This signal aborts after the poller stops: the background work of the service stops with it. */
125
+ readonly signal: AbortSignal;
126
+ /**
127
+ * This method asks for the shutdown, as an exit signal does. A second request does not start a
128
+ * second shutdown. It can give the exit code, when no request gave one before.
129
+ */
130
+ shutdown(cause?: string, options?: ShutdownOptions): Promise<number>;
131
+ /**
132
+ * This method does one request of a controller, on a route or a route pattern that the controller
133
+ * declares. It gives the stream of the request: each item of the work, then one end. The service
134
+ * refuses the request while it cannot take new work, and the shutdown can cut it. An undeclared
135
+ * route throws, because it has no idempotency.
136
+ */
137
+ request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;
138
+ inFlight(controller?: string): number;
139
+ /**
140
+ * This method tells if a response can keep its connection open. It is false while the service is
141
+ * not ready, thus each response then closes its connection.
142
+ */
143
+ keepAlive(): boolean;
144
+ }
@@ -0,0 +1,411 @@
1
+ import { realClock } from "./clock.js";
2
+ import { lateHolds, ownStream, takeOutside } from "./drains.js";
3
+ import { EXIT_SIGNALS, isExitCode, isExitSignal, matchesMessage, nodeProcess } from "./process.js";
4
+ import { tracker } from "./requests.js";
5
+ import { valueIn } from "@mark1russell7/quantity";
6
+ // src/lifecycle.ts
7
+ /**
8
+ * These are the stages of the shutdown, in their sequence. A declared phase with one of these
9
+ * names gets the work of the runtime for its stage. A phase with another name gets only the work of
10
+ * its owners.
11
+ * - `fail readiness`: readiness fails at the start of the shutdown. This phase then holds for its
12
+ * cap, while the endpoints of the platform remove the service.
13
+ * - `stop intake`: each transport stops its intake, and new requests get a retryable 503.
14
+ * - `drain`: the transports and the requests in flight end, until the cap. The cooperative abort
15
+ * comes before the end of the cap, by the cooperative window.
16
+ * - `close transports`: each transport closes.
17
+ * - `stop the poller`: each check and watchdog stops. Then the signal of the service aborts.
18
+ * - `tear down dependencies`: each dependency closes, in the reverse sequence of its connection.
19
+ * - `close the health server`: the probes stop.
20
+ * - `flush the output`: the work of the owners of this phase ends, and then the process port
21
+ * writes the buffered output. Without this phase, the process exits without a wait.
22
+ */
23
+ const STAGES = [
24
+ "fail readiness",
25
+ "stop intake",
26
+ "drain",
27
+ "close transports",
28
+ "stop the poller",
29
+ "tear down dependencies",
30
+ "close the health server",
31
+ "flush the output"
32
+ ];
33
+ /** This function gives the place of a stage in the sequence, or -1 for a phase of another name. */
34
+ const stageRank = (name) => STAGES.indexOf(name);
35
+ /** The signal of the service aborts after the poller stops, and before the dependencies close. */
36
+ const ABORT_AFTER = stageRank("stop the poller");
37
+ /**
38
+ * This function gives the time of the cooperative abort, in milliseconds after the drain starts. It
39
+ * is the cap less the cooperative window. With the floor `half`, it is not less than half the cap,
40
+ * and a window without a bound gives half the cap. With the floor `none`, it is not less than 0.
41
+ */
42
+ const cooperativeAbortAt = (cap, window, floor = "half") => {
43
+ const before = window.value === "infinite" ? Number.POSITIVE_INFINITY : valueIn(window, "ms");
44
+ return Math.max(cap - before, floor === "none" ? 0 : cap / 2);
45
+ };
46
+ /** This function gives the problems of the option `uncaught`: an exit code that is not from 0 to 255. */
47
+ const uncaughtProblems = (uncaught) => {
48
+ const code = uncaught?.exitCode;
49
+ return code === void 0 || isExitCode(code) ? [] : [`the exit code ${code} of an uncaught error is not a whole number from 0 to 255`];
50
+ };
51
+ const message = (error) => error instanceof Error ? error.message : String(error);
52
+ /** This function gives the text of an error with its stack, when it has one. */
53
+ const withStack = (error) => error instanceof Error && typeof error.stack === "string" && error.stack.length > 0 ? error.stack : message(error);
54
+ const UNCAUGHT_NAMES = {
55
+ uncaughtException: "an uncaught exception",
56
+ unhandledRejection: "an unhandled rejection"
57
+ };
58
+ /**
59
+ * This function gives the problems of a declaration that the lifecycle cannot start: a stage with
60
+ * work and no declared phase. The runtime has no defaults, thus a transport without a drain phase
61
+ * has no time to drain.
62
+ */
63
+ const lifecycleProblems = (description, components) => {
64
+ const declared = new Set(description.shutdown.phases.map((phase) => phase.name));
65
+ const needs = (stage, why) => declared.has(stage) ? [] : [`${description.name} has ${why}, thus it declares the phase "${stage}"`];
66
+ const problems = [];
67
+ for (const transport of description.transports) if (!components.transports.has(transport.name)) problems.push(`transport ${transport.name} has no implementation: the runtime has no defaults`);
68
+ if (components.transports.size > 0 || description.controllers.length > 0) {
69
+ problems.push(...needs("stop intake", "transports or controllers"));
70
+ problems.push(...needs("drain", "transports or controllers"));
71
+ }
72
+ if (components.transports.size > 0) problems.push(...needs("close transports", "transports"));
73
+ if (description.checks.length > 0) problems.push(...needs("stop the poller", "checks"));
74
+ if (components.dependencies.size > 0) problems.push(...needs("tear down dependencies", "dependency handles"));
75
+ if (components.healthServer !== null) problems.push(...needs("close the health server", "a health server"));
76
+ return problems;
77
+ };
78
+ /**
79
+ * This function starts the lifecycle of a service. The startup has a sequence: the health server
80
+ * first, then each dependency, then each transport, and the startup gate last. A trigger during the
81
+ * startup gets its shutdown after the startup ends. The shutdown does the declared phases in their
82
+ * sequence, each one capped. Only the lifecycle ends the process. Its exit code is the code of the
83
+ * exit request, else 1 after an error, else 0.
84
+ */
85
+ const lifecycle = (description, runtime, components, options = {}, bind = () => {}) => {
86
+ const clock = options.clock ?? realClock;
87
+ const port = options.process ?? nodeProcess;
88
+ const record = (machine, from, to, on, detail) => options.record?.({
89
+ at: clock.now(),
90
+ machine,
91
+ instance: description.name,
92
+ from,
93
+ to,
94
+ on,
95
+ ...detail === void 0 ? {} : { detail }
96
+ });
97
+ const service = new AbortController();
98
+ const errors = [];
99
+ const exitCodes = description.shutdown.exitCodes ?? {};
100
+ const repeatPolicy = description.shutdown.onRepeatSignal;
101
+ let state = "starting";
102
+ let exitCode = null;
103
+ let requested;
104
+ let intakeStopped = false;
105
+ let shutdownStarted = false;
106
+ let failedStartup = false;
107
+ let exitState = "running";
108
+ const moveExit = (to, on, detail) => {
109
+ record("exit", exitState, to, on, detail);
110
+ exitState = to;
111
+ };
112
+ const fail = (cause) => {
113
+ errors.push(cause);
114
+ if (exitState !== "exited") record("exit", exitState, exitState, "error", cause);
115
+ };
116
+ const requests = tracker(description.controllers, clock, (controller) => {
117
+ if (state === "starting") return "the service has not started";
118
+ if (state === "exited") return "the service has exited";
119
+ if (state === "draining") return null;
120
+ return runtime.verdict().controllers[controller] === true ? null : `controller ${controller} is not ready`;
121
+ }, components.choices);
122
+ let finish = () => {};
123
+ const done = new Promise((resolve) => {
124
+ finish = resolve;
125
+ });
126
+ let healthListening = false;
127
+ const connected = [];
128
+ const startedTransports = [];
129
+ let startupEnded = () => {};
130
+ const startup = new Promise((resolve) => {
131
+ startupEnded = resolve;
132
+ });
133
+ let offs = [];
134
+ let release = () => {};
135
+ /** This function ends the process with a code, one time, and removes each handler of a trigger and the hold. */
136
+ const end = (code, on) => {
137
+ state = "exited";
138
+ exitCode = code;
139
+ for (const off of offs) off();
140
+ offs = [];
141
+ moveExit("exited", on, `exit ${code}`);
142
+ finish(code);
143
+ release();
144
+ port.exit(code);
145
+ };
146
+ /**
147
+ * This function receives a trigger of the process: the first one starts the shutdown. The cause
148
+ * names the trigger, and a message that stands for a signal tells it.
149
+ */
150
+ const triggered = (trigger, cause = trigger) => {
151
+ if (exitState === "exited") return;
152
+ if (shutdownStarted || exitState === "stopping") {
153
+ if (isExitSignal(trigger) && repeatPolicy === "exit") {
154
+ fail(`${cause} came again while the shutdown ran, and the declaration exits at once`);
155
+ end(1, "exit.repeat");
156
+ return;
157
+ }
158
+ record("exit", exitState, exitState, "exit.repeat", cause);
159
+ return;
160
+ }
161
+ const code = exitCodes[trigger];
162
+ shutdown(cause, code === void 0 ? {} : { code });
163
+ };
164
+ const messages = description.shutdown.messages ?? [];
165
+ /** This function receives a message of the IPC channel. The first declared shape that it matches gives its trigger. */
166
+ const received = (message) => {
167
+ const found = messages.find((each) => matchesMessage(each.match, message));
168
+ if (found === void 0) return;
169
+ if (found.as === void 0) triggered("ipc-message");
170
+ else triggered(found.as, `${found.as} (a message of the IPC channel)`);
171
+ };
172
+ const uncaught = options.uncaught;
173
+ const uncaughtCode = uncaught?.exitCode !== void 0 && isExitCode(uncaught.exitCode) ? uncaught.exitCode : 1;
174
+ /**
175
+ * This function receives an error that no code caught. A skipped error goes to the logger at
176
+ * `warn`. Each other error is an error of the lifecycle, and it starts the shutdown with its code.
177
+ */
178
+ const caught = (error, origin) => {
179
+ if (exitState === "exited") return;
180
+ const name = UNCAUGHT_NAMES[origin];
181
+ let skip = false;
182
+ try {
183
+ skip = uncaught?.ignore?.(error, origin) === true;
184
+ } catch {}
185
+ if (skip) {
186
+ try {
187
+ options.logger?.log("warn", `${name} was skipped: ${message(error)}`, {
188
+ origin,
189
+ error: withStack(error)
190
+ });
191
+ } catch {}
192
+ return;
193
+ }
194
+ fail(`${name}: ${withStack(error)}`);
195
+ shutdown(`${name}: ${message(error)}`, { code: uncaughtCode });
196
+ };
197
+ /**
198
+ * This function does the work of one phase, until its cap. It tells if the work ended in time. When
199
+ * work is left at the cap, `excuse` gives the cause of a cap that is not a failure, or null.
200
+ */
201
+ const runPhase = async (phase, hold, work, excuse = () => null) => {
202
+ const cap = valueIn(phase.cap, "ms");
203
+ const deadline = clock.now() + cap;
204
+ const capped = new AbortController();
205
+ const context = {
206
+ deadline,
207
+ signal: capped.signal,
208
+ clock
209
+ };
210
+ let pending = work.length;
211
+ const all = Promise.all(work.map(async (each) => {
212
+ try {
213
+ await each(context);
214
+ } catch (error) {
215
+ fail(`the phase ${phase.name} failed: ${message(error)}`);
216
+ } finally {
217
+ pending -= 1;
218
+ }
219
+ }));
220
+ let cancelCap = () => {};
221
+ const end = new Promise((resolve) => {
222
+ cancelCap = clock.after(cap, () => resolve("cap"));
223
+ });
224
+ if (await Promise.race([all.then(() => "work"), end]) === "work" && hold) await end;
225
+ const excused = pending > 0 ? excuse(pending) : null;
226
+ cancelCap();
227
+ capped.abort(/* @__PURE__ */ new Error(`the phase ${phase.name} reached its cap`));
228
+ return {
229
+ inTime: pending === 0,
230
+ excused
231
+ };
232
+ };
233
+ async function shutdown(cause = "the service asked for it", request = {}) {
234
+ if (request.code !== void 0 && !isExitCode(request.code)) throw new Error(`${description.name}: the exit code ${request.code} is not a whole number from 0 to 255`);
235
+ if (exitState === "exited") return done;
236
+ if (request.code !== void 0 && requested === void 0) requested = request.code;
237
+ if (shutdownStarted) {
238
+ if (exitState === "stopping") record("exit", exitState, exitState, "exit.repeat", cause);
239
+ return done;
240
+ }
241
+ shutdownStarted = true;
242
+ if (exitState === "running") moveExit("stopping", "exit.request", cause);
243
+ await startup;
244
+ if (exitState === "exited") {
245
+ runtime.stop();
246
+ components.stopPollers();
247
+ return exitCode;
248
+ }
249
+ state = "draining";
250
+ runtime.drain();
251
+ let drainState = "running";
252
+ const moveDrain = (to, on, detail) => {
253
+ record("drain", drainState, to, on, detail);
254
+ drainState = to;
255
+ };
256
+ const abortService = () => {
257
+ if (service.signal.aborted) return;
258
+ service.abort(/* @__PURE__ */ new Error("the service stopped"));
259
+ record("drain", drainState, drainState, "signal.abort");
260
+ };
261
+ const phases = description.shutdown.phases;
262
+ let on = "exit.request";
263
+ let detail;
264
+ for (const phase of phases) {
265
+ if (exitState === "exited") break;
266
+ const rank = stageRank(phase.name);
267
+ moveDrain(phase.name, on, detail);
268
+ if (rank > ABORT_AFTER) abortService();
269
+ const work = [];
270
+ const owned = components.phaseWork.get(phase.name) ?? [];
271
+ if (phase.name === "stop intake") {
272
+ work.push(() => {
273
+ intakeStopped = true;
274
+ requests.stopIntake();
275
+ });
276
+ for (const [, impl] of startedTransports) work.push(() => impl.stopIntake());
277
+ }
278
+ let cancelAbort = () => {};
279
+ let excuse;
280
+ if (phase.name === "drain") {
281
+ const cap = valueIn(phase.cap, "ms");
282
+ const cooperative = new AbortController();
283
+ const fireAt = cooperativeAbortAt(cap, description.shutdown.cooperativeWindow, description.shutdown.cooperativeFloor);
284
+ cancelAbort = clock.after(fireAt, () => {
285
+ cooperative.abort(/* @__PURE__ */ new Error("the cooperative abort of the drain"));
286
+ requests.cooperativeAbort();
287
+ record("drain", drainState, drainState, "drain.cooperative-abort");
288
+ });
289
+ work.push(({ deadline }) => requests.drain(deadline));
290
+ let transportsLeft = 0;
291
+ for (const [, impl] of startedTransports) work.push(async ({ deadline }) => {
292
+ transportsLeft += 1;
293
+ try {
294
+ await impl.drain(deadline, cooperative.signal);
295
+ } finally {
296
+ transportsLeft -= 1;
297
+ }
298
+ });
299
+ excuse = (left) => {
300
+ const holds = lateHolds(life);
301
+ if (left > transportsLeft || transportsLeft > holds.length || holds.some((each) => each.running > 0)) return null;
302
+ return `answers not flushed: ${holds.reduce((sum, each) => sum + each.unflushed, 0)}`;
303
+ };
304
+ }
305
+ if (phase.name === "close transports") for (const [, impl] of startedTransports) work.push(() => impl.close());
306
+ if (phase.name === "stop the poller") work.push(() => {
307
+ runtime.stop();
308
+ components.stopPollers();
309
+ });
310
+ if (phase.name === "tear down dependencies") work.push(async () => {
311
+ for (const [, handle] of [...connected].reverse()) await handle.close();
312
+ });
313
+ if (phase.name === "close the health server" && healthListening && components.healthServer !== null) {
314
+ const server = components.healthServer;
315
+ work.push(() => server.close());
316
+ }
317
+ if (phase.name === "flush the output") work.push(async (context) => {
318
+ await Promise.all(owned.map(async (each) => {
319
+ try {
320
+ await each(context);
321
+ } catch (error) {
322
+ fail(`the phase ${phase.name} failed: ${message(error)}`);
323
+ }
324
+ }));
325
+ await port.flush?.();
326
+ });
327
+ else for (const each of owned) work.push(each);
328
+ const { inTime, excused } = await runPhase(phase, phase.name === "fail readiness", work, excuse);
329
+ cancelAbort();
330
+ if (!inTime && excused === null) fail(`the phase ${phase.name} did not end in its cap of ${valueIn(phase.cap, "s")} s`);
331
+ on = inTime ? "phase.done" : "phase.cap";
332
+ const outsideCount = phase.name === "drain" ? takeOutside(life) : 0;
333
+ const parts = [inTime ? null : excused, outsideCount > 0 ? `streams outside the lifecycle: ${outsideCount}` : null].filter((part) => part !== null);
334
+ detail = parts.length > 0 ? parts.join(", ") : void 0;
335
+ }
336
+ if (exitState !== "exited") moveDrain("done", on, detail);
337
+ abortService();
338
+ runtime.stop();
339
+ components.stopPollers();
340
+ if (!intakeStopped) requests.stopIntake();
341
+ if (exitState === "exited") return exitCode;
342
+ const code = requested !== void 0 && requested !== 0 ? requested : errors.length > 0 ? 1 : 0;
343
+ end(code, "shutdown.done");
344
+ return code;
345
+ }
346
+ const life = {
347
+ health: runtime,
348
+ get state() {
349
+ return state;
350
+ },
351
+ get exitCode() {
352
+ return exitCode;
353
+ },
354
+ get errors() {
355
+ return [...errors];
356
+ },
357
+ started: startup,
358
+ done,
359
+ signal: service.signal,
360
+ shutdown,
361
+ request: (controller, route, work, request) => ownStream(requests.request(controller, route, work, request), life),
362
+ inFlight: (controller) => requests.inFlight(controller),
363
+ keepAlive: () => state === "running" && runtime.verdict().ready
364
+ };
365
+ bind(life);
366
+ release = port.hold?.() ?? (() => {});
367
+ offs = [...EXIT_SIGNALS, ...description.shutdown.triggers ?? []].map((trigger) => port.on(trigger, trigger === "ipc-message" ? received : () => triggered(trigger)));
368
+ if (uncaught !== void 0 && port.onUncaught !== void 0) offs.push(port.onUncaught(caught));
369
+ (async () => {
370
+ const started = (what) => record("gate", "starting", "starting", "component.started", what);
371
+ try {
372
+ runtime.beginStartup();
373
+ if (components.healthServer !== null) {
374
+ await components.healthServer.listen(runtime);
375
+ healthListening = true;
376
+ started("the health server");
377
+ }
378
+ for (const dependency of description.dependencies) {
379
+ const handle = components.dependencies.get(dependency.name);
380
+ if (handle === void 0) continue;
381
+ await handle.connect(service.signal);
382
+ connected.push([dependency.name, handle]);
383
+ started(`dependency ${dependency.name}`);
384
+ }
385
+ for (const transport of description.transports) {
386
+ const impl = components.transports.get(transport.name);
387
+ await impl.start(service.signal, life);
388
+ startedTransports.push([transport.name, impl]);
389
+ started(`${transport.kind} ${transport.name}`);
390
+ }
391
+ await runtime.warmUp();
392
+ if (state === "starting") state = "running";
393
+ } catch (error) {
394
+ const cause = `the startup failed: ${message(error)}`;
395
+ failedStartup = true;
396
+ runtime.failStartup(cause);
397
+ fail(cause);
398
+ if (exitState === "running") moveExit("stopping", "startup.fail", cause);
399
+ else if (exitState === "stopping") record("exit", exitState, exitState, "startup.fail", cause);
400
+ } finally {
401
+ startupEnded();
402
+ }
403
+ })();
404
+ startup.then(() => {
405
+ if (failedStartup && !shutdownStarted && exitState !== "exited") shutdown("the startup failed");
406
+ });
407
+ return life;
408
+ };
409
+ export { STAGES, cooperativeAbortAt, lifecycle, lifecycleProblems, stageRank, uncaughtProblems };
410
+
411
+ //# sourceMappingURL=lifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.js","names":[],"sources":["../src/lifecycle.ts"],"sourcesContent":["import type { Extent } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\nimport type { CooperativeFloor, Phase, ServiceDescription } from \"./description.ts\";\nimport { lateHolds, ownStream, takeOutside } from \"./drains.ts\";\nimport type { MachineName } from \"./events.ts\";\nimport type { Health, Runtime, StartOptions } from \"./health.ts\";\nimport type { ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\nimport { EXIT_SIGNALS, isExitCode, isExitSignal, matchesMessage, nodeProcess } from \"./process.ts\";\nimport type { RequestFn, RequestOptions, RequestStream } from \"./requests.ts\";\nimport { tracker } from \"./requests.ts\";\nimport type { OperationOf } from \"./routes.ts\";\n\n/**\n * A transport is a source of work: a server, a consumer or a worker. Each has one contract. It\n * starts, stops its intake, and drains to a deadline without a throw. It counts its work in flight,\n * and it closes. A second close has no effect.\n */\nexport interface TransportImpl {\n /**\n * This method starts the transport. The lifecycle is the object that `run()` gives at the end of\n * the startup. Its request tracking operates from the start: a request before the startup ends\n * gets a retryable refusal, and `keepAlive()` is false. Do not wait for `life.started` here,\n * because the startup waits for this method.\n */\n start(signal: AbortSignal, life: Lifecycle): Promise<void> | void;\n stopIntake(): Promise<void> | void;\n /**\n * This method lets the work in flight end until `deadline` (milliseconds on the monotonic\n * clock). The signal is the cooperative abort, which comes before the deadline.\n */\n drain(deadline: number, signal: AbortSignal): Promise<void> | void;\n inFlight(): number;\n close(): Promise<void> | void;\n}\n\n/** A dependency handle connects to a dependency at the start, and closes the connection at the end. */\nexport interface DependencyHandle {\n connect(signal: AbortSignal): Promise<void> | void;\n close(): Promise<void> | void;\n}\n\n/**\n * A health server answers the probes, on its own port. It starts first, thus the probes answer\n * while the dependencies connect, and it closes last.\n */\nexport interface HealthServer {\n listen(health: Health): Promise<void> | void;\n close(): Promise<void> | void;\n}\n\n/** A phase context is what a phase gives its work: its deadline, its signal and the clock. */\nexport interface PhaseContext {\n /** This time is the end of the cap of the phase, in milliseconds on the monotonic clock. */\n readonly deadline: number;\n /** This signal aborts at the end of the cap of the phase. */\n readonly signal: AbortSignal;\n readonly clock: Clock;\n}\n\n/** A phase work is a step of the shutdown that an owner adds to a phase. */\nexport type PhaseWork = (context: PhaseContext) => Promise<void> | void;\n\n/**\n * These are the stages of the shutdown, in their sequence. A declared phase with one of these\n * names gets the work of the runtime for its stage. A phase with another name gets only the work of\n * its owners.\n * - `fail readiness`: readiness fails at the start of the shutdown. This phase then holds for its\n * cap, while the endpoints of the platform remove the service.\n * - `stop intake`: each transport stops its intake, and new requests get a retryable 503.\n * - `drain`: the transports and the requests in flight end, until the cap. The cooperative abort\n * comes before the end of the cap, by the cooperative window.\n * - `close transports`: each transport closes.\n * - `stop the poller`: each check and watchdog stops. Then the signal of the service aborts.\n * - `tear down dependencies`: each dependency closes, in the reverse sequence of its connection.\n * - `close the health server`: the probes stop.\n * - `flush the output`: the work of the owners of this phase ends, and then the process port\n * writes the buffered output. Without this phase, the process exits without a wait.\n */\nexport const STAGES = [\n \"fail readiness\",\n \"stop intake\",\n \"drain\",\n \"close transports\",\n \"stop the poller\",\n \"tear down dependencies\",\n \"close the health server\",\n \"flush the output\",\n] as const;\n\nexport type Stage = (typeof STAGES)[number];\n\n/** This function gives the place of a stage in the sequence, or -1 for a phase of another name. */\nexport const stageRank = (name: string): number => (STAGES as readonly string[]).indexOf(name);\n\n/** The signal of the service aborts after the poller stops, and before the dependencies close. */\nconst ABORT_AFTER = stageRank(\"stop the poller\");\n\n/**\n * This function gives the time of the cooperative abort, in milliseconds after the drain starts. It\n * is the cap less the cooperative window. With the floor `half`, it is not less than half the cap,\n * and a window without a bound gives half the cap. With the floor `none`, it is not less than 0.\n */\nexport const cooperativeAbortAt = (cap: number, window: Extent, floor: CooperativeFloor = \"half\"): number => {\n const before = window.value === \"infinite\" ? Number.POSITIVE_INFINITY : valueIn(window, \"ms\");\n return Math.max(cap - before, floor === \"none\" ? 0 : cap / 2);\n};\n\n/**\n * These options make each error that no code caught a trigger of the shutdown. They are an uncaught\n * exception and an unhandled rejection.\n */\nexport interface UncaughtOptions {\n /** This code is the exit code after an uncaught error, a whole number from 0 to 255. The default is 1. */\n readonly exitCode?: number | undefined;\n /**\n * This function tells if the runtime skips an error, for example an `ECONNRESET` of a peer socket.\n * The logger gets a skipped error at `warn`, and the service continues. A throw of this function skips nothing.\n */\n readonly ignore?: ((error: unknown, origin: UncaughtOrigin) => boolean) | undefined;\n}\n\n/** These options run the lifecycle. Without them, it uses the real clock and the process of Node. */\nexport interface RunOptions extends StartOptions {\n readonly process?: ProcessPort | undefined;\n /**\n * With these options, the lifecycle adds a handler for the errors that no code caught, from its start\n * to its exit. Each error that it does not skip is an error of the lifecycle at `error`. It then\n * starts the shutdown with its exit code, as a signal does. Without them, the runtime adds no handler.\n */\n readonly uncaught?: UncaughtOptions | undefined;\n}\n\n/** This function gives the problems of the option `uncaught`: an exit code that is not from 0 to 255. */\nexport const uncaughtProblems = (uncaught: UncaughtOptions | undefined): string[] => {\n const code = uncaught?.exitCode;\n return code === undefined || isExitCode(code) ? [] : [`the exit code ${code} of an uncaught error is not a whole number from 0 to 255`];\n};\n\n/** These options go with a request for the shutdown. */\nexport interface ShutdownOptions {\n /**\n * This code is the exit code that the work of the process gives, a whole number from 0 to 255. The\n * first exit request with a code sets it. A code of 0 lets an error make the exit code 1.\n */\n readonly code?: number | undefined;\n}\n\n/** A lifecycle state tells where the service is in its life. */\nexport type LifecycleState = \"starting\" | \"running\" | \"draining\" | \"exited\";\n\n/** The lifecycle of a running service. */\nexport interface Lifecycle {\n readonly health: Health;\n readonly state: LifecycleState;\n /** This code is the exit code, or null before the exit. */\n readonly exitCode: number | null;\n /** These texts are the errors of the lifecycle. An error makes the exit code 1, unless an exit request gives another code. */\n readonly errors: readonly string[];\n /** This promise ends when the startup ends: the service runs, or its startup failed. */\n readonly started: Promise<void>;\n /** This promise gives the exit code when the shutdown ends. */\n readonly done: Promise<number>;\n /** This signal aborts after the poller stops: the background work of the service stops with it. */\n readonly signal: AbortSignal;\n /**\n * This method asks for the shutdown, as an exit signal does. A second request does not start a\n * second shutdown. It can give the exit code, when no request gave one before.\n */\n shutdown(cause?: string, options?: ShutdownOptions): Promise<number>;\n /**\n * This method does one request of a controller, on a route or a route pattern that the controller\n * declares. It gives the stream of the request: each item of the work, then one end. The service\n * refuses the request while it cannot take new work, and the shutdown can cut it. An undeclared\n * route throws, because it has no idempotency.\n */\n request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;\n inFlight(controller?: string): number;\n /**\n * This method tells if a response can keep its connection open. It is false while the service is\n * not ready, thus each response then closes its connection.\n */\n keepAlive(): boolean;\n}\n\n/** The parts that the builder gives the lifecycle, beside the declaration. */\nexport interface Components {\n readonly transports: ReadonlyMap<string, TransportImpl>;\n readonly dependencies: ReadonlyMap<string, DependencyHandle>;\n readonly healthServer: HealthServer | null;\n readonly phaseWork: ReadonlyMap<string, readonly PhaseWork[]>;\n /** These are the functions of the route patterns, by controller and by pattern. */\n readonly choices?: ReadonlyMap<string, ReadonlyMap<string, OperationOf>> | undefined;\n /** This function stops the parts that the poller stage stops beside the checks: the watchdogs. */\n readonly stopPollers: () => void;\n}\n\nconst message = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** This function gives the text of an error with its stack, when it has one. */\nconst withStack = (error: unknown): string =>\n error instanceof Error && typeof error.stack === \"string\" && error.stack.length > 0 ? error.stack : message(error);\n\nconst UNCAUGHT_NAMES: Readonly<Record<UncaughtOrigin, string>> = {\n uncaughtException: \"an uncaught exception\",\n unhandledRejection: \"an unhandled rejection\",\n};\n\n/**\n * This function gives the problems of a declaration that the lifecycle cannot start: a stage with\n * work and no declared phase. The runtime has no defaults, thus a transport without a drain phase\n * has no time to drain.\n */\nexport const lifecycleProblems = (description: ServiceDescription, components: Components): string[] => {\n const declared = new Set(description.shutdown.phases.map((phase) => phase.name));\n const needs = (stage: Stage, why: string): string[] =>\n declared.has(stage) ? [] : [`${description.name} has ${why}, thus it declares the phase \"${stage}\"`];\n const problems: string[] = [];\n for (const transport of description.transports)\n if (!components.transports.has(transport.name))\n problems.push(`transport ${transport.name} has no implementation: the runtime has no defaults`);\n if (components.transports.size > 0 || description.controllers.length > 0) {\n problems.push(...needs(\"stop intake\", \"transports or controllers\"));\n problems.push(...needs(\"drain\", \"transports or controllers\"));\n }\n if (components.transports.size > 0) problems.push(...needs(\"close transports\", \"transports\"));\n if (description.checks.length > 0) problems.push(...needs(\"stop the poller\", \"checks\"));\n if (components.dependencies.size > 0) problems.push(...needs(\"tear down dependencies\", \"dependency handles\"));\n if (components.healthServer !== null) problems.push(...needs(\"close the health server\", \"a health server\"));\n return problems;\n};\n\n/**\n * This function starts the lifecycle of a service. The startup has a sequence: the health server\n * first, then each dependency, then each transport, and the startup gate last. A trigger during the\n * startup gets its shutdown after the startup ends. The shutdown does the declared phases in their\n * sequence, each one capped. Only the lifecycle ends the process. Its exit code is the code of the\n * exit request, else 1 after an error, else 0.\n */\nexport const lifecycle = (\n description: ServiceDescription,\n runtime: Runtime,\n components: Components,\n options: RunOptions = {},\n /** This function receives the lifecycle before the startup begins. */\n bind: (life: Lifecycle) => void = () => {},\n): Lifecycle => {\n const clock = options.clock ?? realClock;\n const port = options.process ?? nodeProcess;\n const record = (machine: MachineName, from: string, to: string, on: string, detail?: string): void =>\n options.record?.({\n at: clock.now(),\n machine,\n instance: description.name,\n from,\n to,\n on,\n ...(detail === undefined ? {} : { detail }),\n });\n const service = new AbortController();\n const errors: string[] = [];\n const exitCodes = description.shutdown.exitCodes ?? {};\n const repeatPolicy = description.shutdown.onRepeatSignal;\n let state: LifecycleState = \"starting\";\n let exitCode: number | null = null;\n // the code of the first exit request that gives one\n let requested: number | undefined;\n let intakeStopped = false;\n let shutdownStarted = false;\n let failedStartup = false;\n // the exit manager: running, stopping, exited\n let exitState = \"running\";\n const moveExit = (to: string, on: string, detail?: string): void => {\n record(\"exit\", exitState, to, on, detail);\n exitState = to;\n };\n const fail = (cause: string): void => {\n errors.push(cause);\n // after an exit, the process has ended: the exit manager does not move again\n if (exitState !== \"exited\") record(\"exit\", exitState, exitState, \"error\", cause);\n };\n\n const requests = tracker(description.controllers, clock, (controller) => {\n if (state === \"starting\") return \"the service has not started\";\n if (state === \"exited\") return \"the service has exited\";\n // while it drains and before its intake stops, the service still serves: the platform can\n // still route a request to it until its endpoints update\n if (state === \"draining\") return null;\n return runtime.verdict().controllers[controller] === true ? null : `controller ${controller} is not ready`;\n }, components.choices);\n\n let finish: (code: number) => void = () => {};\n const done = new Promise<number>((resolve) => {\n finish = resolve;\n });\n // what started, thus what the shutdown stops\n let healthListening = false;\n const connected: Array<[string, DependencyHandle]> = [];\n const startedTransports: Array<[string, TransportImpl]> = [];\n // the startup exists before any part starts: a transport that asks for the shutdown in its start waits for it\n let startupEnded: () => void = () => {};\n const startup = new Promise<void>((resolve) => {\n startupEnded = resolve;\n });\n let offs: Array<() => void> = [];\n // the hold of the process, from the start of the lifecycle to its exit\n let release: () => void = () => {};\n\n /** This function ends the process with a code, one time, and removes each handler of a trigger and the hold. */\n const end = (code: number, on: string): void => {\n state = \"exited\";\n exitCode = code;\n for (const off of offs) off();\n offs = [];\n moveExit(\"exited\", on, `exit ${code}`);\n finish(code);\n // the hold ends at the exit, not at the stop of the intake: the drain and the teardown still need the process\n release();\n port.exit(code);\n };\n\n /**\n * This function receives a trigger of the process: the first one starts the shutdown. The cause\n * names the trigger, and a message that stands for a signal tells it.\n */\n const triggered = (trigger: ExitTrigger, cause: string = trigger): void => {\n if (exitState === \"exited\") return;\n if (shutdownStarted || exitState === \"stopping\") {\n // a signal while the shutdown runs obeys the declared policy. Another trigger, for example the\n // end of stdin after a SIGTERM, has no effect\n if (isExitSignal(trigger) && repeatPolicy === \"exit\") {\n fail(`${cause} came again while the shutdown ran, and the declaration exits at once`);\n end(1, \"exit.repeat\");\n return;\n }\n record(\"exit\", exitState, exitState, \"exit.repeat\", cause);\n return;\n }\n const code = exitCodes[trigger];\n void shutdown(cause, code === undefined ? {} : { code });\n };\n const messages = description.shutdown.messages ?? [];\n /** This function receives a message of the IPC channel. The first declared shape that it matches gives its trigger. */\n const received = (message: unknown): void => {\n const found = messages.find((each) => matchesMessage(each.match, message));\n if (found === undefined) return;\n if (found.as === undefined) triggered(\"ipc-message\");\n else triggered(found.as, `${found.as} (a message of the IPC channel)`);\n };\n const uncaught = options.uncaught;\n const uncaughtCode = uncaught?.exitCode !== undefined && isExitCode(uncaught.exitCode) ? uncaught.exitCode : 1;\n /**\n * This function receives an error that no code caught. A skipped error goes to the logger at\n * `warn`. Each other error is an error of the lifecycle, and it starts the shutdown with its code.\n */\n const caught = (error: unknown, origin: UncaughtOrigin): void => {\n if (exitState === \"exited\") return;\n const name = UNCAUGHT_NAMES[origin];\n let skip = false;\n try {\n skip = uncaught?.ignore?.(error, origin) === true;\n } catch {\n // a throw of the function skips nothing\n }\n if (skip) {\n try {\n options.logger?.log(\"warn\", `${name} was skipped: ${message(error)}`, { origin, error: withStack(error) });\n } catch {\n // the lifecycle does not depend on its logger\n }\n return;\n }\n // the error event goes to the logger at `error`, with the stack\n fail(`${name}: ${withStack(error)}`);\n void shutdown(`${name}: ${message(error)}`, { code: uncaughtCode });\n };\n\n /**\n * This function does the work of one phase, until its cap. It tells if the work ended in time. When\n * work is left at the cap, `excuse` gives the cause of a cap that is not a failure, or null.\n */\n const runPhase = async (\n phase: Phase,\n hold: boolean,\n work: ReadonlyArray<(context: PhaseContext) => Promise<void> | void>,\n excuse: (left: number) => string | null = () => null,\n ): Promise<{ readonly inTime: boolean; readonly excused: string | null }> => {\n const cap = valueIn(phase.cap, \"ms\");\n const deadline = clock.now() + cap;\n const capped = new AbortController();\n const context: PhaseContext = { deadline, signal: capped.signal, clock };\n let pending = work.length;\n const all = Promise.all(\n work.map(async (each) => {\n try {\n await each(context);\n } catch (error) {\n fail(`the phase ${phase.name} failed: ${message(error)}`);\n } finally {\n pending -= 1;\n }\n }),\n );\n let cancelCap: Cancel = () => {};\n // the timer of the cap starts after the timers of the work: at the same time, the work comes first\n const end = new Promise<\"cap\">((resolve) => {\n // the phase awaits its cap, thus the cap keeps the process alive (SYS-126)\n cancelCap = clock.after(cap, () => resolve(\"cap\"));\n });\n const first = await Promise.race([all.then(() => \"work\" as const), end]);\n if (first === \"work\" && hold) await end;\n // the work that is left is read at the cap, before the next phase changes it\n const excused = pending > 0 ? excuse(pending) : null;\n cancelCap();\n capped.abort(new Error(`the phase ${phase.name} reached its cap`));\n return { inTime: pending === 0, excused };\n };\n\n async function shutdown(cause = \"the service asked for it\", request: ShutdownOptions = {}): Promise<number> {\n if (request.code !== undefined && !isExitCode(request.code))\n throw new Error(`${description.name}: the exit code ${request.code} is not a whole number from 0 to 255`);\n if (exitState === \"exited\") return done;\n if (request.code !== undefined && requested === undefined) requested = request.code;\n if (shutdownStarted) {\n if (exitState === \"stopping\") record(\"exit\", exitState, exitState, \"exit.repeat\", cause);\n return done;\n }\n shutdownStarted = true;\n if (exitState === \"running\") moveExit(\"stopping\", \"exit.request\", cause);\n // a trigger during the startup gets its shutdown after the startup ends\n await startup;\n // a repeat signal can end the process while the startup ends: then only the timers stop\n if (exitState === \"exited\") {\n runtime.stop();\n components.stopPollers();\n return exitCode!;\n }\n state = \"draining\";\n runtime.drain();\n let drainState = \"running\";\n const moveDrain = (to: string, on: string, detail?: string): void => {\n record(\"drain\", drainState, to, on, detail);\n drainState = to;\n };\n const abortService = (): void => {\n if (service.signal.aborted) return;\n service.abort(new Error(\"the service stopped\"));\n record(\"drain\", drainState, drainState, \"signal.abort\");\n };\n const phases = description.shutdown.phases;\n let on = \"exit.request\";\n let detail: string | undefined;\n for (const phase of phases) {\n // after a repeat signal ends the process, no phase starts\n if (exitState === \"exited\") break;\n const rank = stageRank(phase.name);\n moveDrain(phase.name, on, detail);\n if (rank > ABORT_AFTER) abortService();\n const work: Array<(context: PhaseContext) => Promise<void> | void> = [];\n const owned = components.phaseWork.get(phase.name) ?? [];\n if (phase.name === \"stop intake\") {\n work.push(() => {\n intakeStopped = true;\n requests.stopIntake();\n });\n for (const [, impl] of startedTransports) work.push(() => impl.stopIntake());\n }\n // the cooperative abort of the drain: the cap less the window, not before the floor. It ends\n // with the phase, thus a drain that ends before it does not abort anything\n let cancelAbort: Cancel = () => {};\n let excuse: ((left: number) => string | null) | undefined;\n if (phase.name === \"drain\") {\n const cap = valueIn(phase.cap, \"ms\");\n const cooperative = new AbortController();\n const fireAt = cooperativeAbortAt(cap, description.shutdown.cooperativeWindow, description.shutdown.cooperativeFloor);\n // the drain awaits its cooperative abort, thus the timer keeps the process alive (SYS-126)\n cancelAbort = clock.after(fireAt, () => {\n cooperative.abort(new Error(\"the cooperative abort of the drain\"));\n requests.cooperativeAbort();\n record(\"drain\", drainState, drainState, \"drain.cooperative-abort\");\n });\n // the cut of the requests is the first work, thus its timer comes before the timer of the cap. A\n // transport can reach the deadline before the cut: httpTransport then waits for the answers of the cut (SYS-29)\n work.push(({ deadline }) => requests.drain(deadline));\n let transportsLeft = 0;\n for (const [, impl] of startedTransports)\n work.push(async ({ deadline }) => {\n transportsLeft += 1;\n try {\n await impl.drain(deadline, cooperative.signal);\n } finally {\n transportsLeft -= 1;\n }\n });\n // a phase fails only for its own work. At the cap, a drain whose transports wait only for the\n // bytes of their answers did its work: the cap is not a failure, and its event gives the count (SYS-29)\n excuse = (left) => {\n const holds = lateHolds(life);\n if (left > transportsLeft || transportsLeft > holds.length || holds.some((each) => each.running > 0)) return null;\n return `answers not flushed: ${holds.reduce((sum, each) => sum + each.unflushed, 0)}`;\n };\n }\n if (phase.name === \"close transports\")\n for (const [, impl] of startedTransports) work.push(() => impl.close());\n if (phase.name === \"stop the poller\")\n work.push(() => {\n runtime.stop();\n components.stopPollers();\n });\n if (phase.name === \"tear down dependencies\")\n work.push(async () => {\n for (const [, handle] of [...connected].reverse()) await handle.close();\n });\n if (phase.name === \"close the health server\" && healthListening && components.healthServer !== null) {\n const server = components.healthServer;\n work.push(() => server.close());\n }\n if (phase.name === \"flush the output\")\n // the owners write their last output first (a log or a trace exporter), then the port writes it\n work.push(async (context) => {\n await Promise.all(\n owned.map(async (each) => {\n try {\n await each(context);\n } catch (error) {\n fail(`the phase ${phase.name} failed: ${message(error)}`);\n }\n }),\n );\n await port.flush?.();\n });\n else for (const each of owned) work.push(each);\n const { inTime, excused } = await runPhase(phase, phase.name === \"fail readiness\", work, excuse);\n cancelAbort();\n if (!inTime && excused === null) fail(`the phase ${phase.name} did not end in its cap of ${valueIn(phase.cap, \"s\")} s`);\n on = inTime ? \"phase.done\" : \"phase.cap\";\n // the streams outside the lifecycle do not hold the drain, and its record gives their count\n const outsideCount = phase.name === \"drain\" ? takeOutside(life) : 0;\n const parts = [inTime ? null : excused, outsideCount > 0 ? `streams outside the lifecycle: ${outsideCount}` : null].filter(\n (part): part is string => part !== null,\n );\n detail = parts.length > 0 ? parts.join(\", \") : undefined;\n }\n if (exitState !== \"exited\") moveDrain(\"done\", on, detail);\n abortService();\n // a stage that the declaration does not name still stops: the checks, at the end\n runtime.stop();\n components.stopPollers();\n if (!intakeStopped) requests.stopIntake();\n // a repeat signal can end the process during the sequence: then it ended already\n if (exitState === \"exited\") return exitCode!;\n const code = requested !== undefined && requested !== 0 ? requested : errors.length > 0 ? 1 : 0;\n end(code, \"shutdown.done\");\n return code;\n }\n\n const life: Lifecycle = {\n health: runtime,\n get state() {\n return state;\n },\n get exitCode() {\n return exitCode;\n },\n get errors() {\n return [...errors];\n },\n started: startup,\n done,\n signal: service.signal,\n shutdown,\n // the lifecycle owns each stream that it makes: its drain cuts the stream (SYS-29)\n request: (controller, route, work, request) => ownStream(requests.request(controller, route, work, request), life),\n inFlight: (controller) => requests.inFlight(controller),\n keepAlive: () => state === \"running\" && runtime.verdict().ready,\n };\n\n bind(life);\n release = port.hold?.() ?? (() => {});\n offs = [...EXIT_SIGNALS, ...(description.shutdown.triggers ?? [])].map((trigger: ExitTrigger) =>\n port.on(trigger, trigger === \"ipc-message\" ? received : () => triggered(trigger)),\n );\n // the handler of the uncaught errors goes at the exit, with the handlers of the triggers\n if (uncaught !== undefined && port.onUncaught !== undefined) offs.push(port.onUncaught(caught));\n\n void (async (): Promise<void> => {\n const started = (what: string): void => record(\"gate\", \"starting\", \"starting\", \"component.started\", what);\n try {\n runtime.beginStartup();\n if (components.healthServer !== null) {\n await components.healthServer.listen(runtime);\n healthListening = true;\n started(\"the health server\");\n }\n for (const dependency of description.dependencies) {\n const handle = components.dependencies.get(dependency.name);\n if (handle === undefined) continue;\n await handle.connect(service.signal);\n connected.push([dependency.name, handle]);\n started(`dependency ${dependency.name}`);\n }\n for (const transport of description.transports) {\n const impl = components.transports.get(transport.name)!;\n await impl.start(service.signal, life);\n startedTransports.push([transport.name, impl]);\n started(`${transport.kind} ${transport.name}`);\n }\n await runtime.warmUp();\n if (state === \"starting\") state = \"running\";\n } catch (error) {\n const cause = `the startup failed: ${message(error)}`;\n failedStartup = true;\n runtime.failStartup(cause);\n fail(cause);\n if (exitState === \"running\") moveExit(\"stopping\", \"startup.fail\", cause);\n else if (exitState === \"stopping\") record(\"exit\", exitState, exitState, \"startup.fail\", cause);\n } finally {\n startupEnded();\n }\n })();\n // a failed startup shuts down what started. An exit request during the startup waits for it\n void startup.then(() => {\n if (failedStartup && !shutdownStarted && exitState !== \"exited\") void shutdown(\"the startup failed\");\n });\n\n return life;\n};\n"],"mappings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