@mark1russell7/service 0.8.19 → 0.8.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (331) hide show
  1. package/build/backoff.d.ts +44 -2
  2. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  3. package/build/builder.js +499 -0
  4. package/build/builder.js.map +1 -0
  5. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  6. package/build/channel.d.ts +1 -1
  7. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  8. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  9. package/build/client/core.js.map +1 -0
  10. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  11. package/build/client/dial.js +52 -0
  12. package/build/client/dial.js.map +1 -0
  13. package/build/client/machine.js +29 -0
  14. package/build/client/machine.js.map +1 -0
  15. package/build/client/meets.d.ts +35 -0
  16. package/build/client/meets.js +78 -0
  17. package/build/client/meets.js.map +1 -0
  18. package/build/clock.d.ts +1 -1
  19. package/build/conformance.d.ts +122 -0
  20. package/build/conformance.js +470 -0
  21. package/build/conformance.js.map +1 -0
  22. package/build/contract.d.ts +28 -0
  23. package/build/contract.js +184 -0
  24. package/build/contract.js.map +1 -0
  25. package/build/description.d.ts +161 -0
  26. package/build/description.js +11 -0
  27. package/build/description.js.map +1 -0
  28. package/build/drains.js +35 -0
  29. package/build/drains.js.map +1 -0
  30. package/build/events.d.ts +25 -0
  31. package/build/fakes.d.ts +43 -0
  32. package/build/fakes.js +93 -0
  33. package/build/fakes.js.map +1 -0
  34. package/build/grpc/client.d.ts +153 -0
  35. package/build/grpc/client.js +474 -0
  36. package/build/grpc/client.js.map +1 -0
  37. package/build/grpc/connection.d.ts +97 -0
  38. package/build/grpc/connection.js +59 -0
  39. package/build/grpc/connection.js.map +1 -0
  40. package/build/grpc/machine.d.ts +12 -0
  41. package/build/grpc/machine.js +149 -0
  42. package/build/grpc/machine.js.map +1 -0
  43. package/build/grpc/meets.d.ts +14 -0
  44. package/build/grpc/meets.js +105 -0
  45. package/build/grpc/meets.js.map +1 -0
  46. package/build/grpc/starting.d.ts +33 -0
  47. package/build/grpc/starting.js +89 -0
  48. package/build/grpc/starting.js.map +1 -0
  49. package/build/grpc.d.ts +9 -303
  50. package/build/grpc.js +7 -854
  51. package/build/health.d.ts +93 -0
  52. package/build/health.js +223 -0
  53. package/build/health.js.map +1 -0
  54. package/build/heartbeat.d.ts +1 -1
  55. package/build/host/discovery.d.ts +61 -0
  56. package/build/host/discovery.js +113 -0
  57. package/build/host/discovery.js.map +1 -0
  58. package/build/host/env.d.ts +14 -0
  59. package/build/host/env.js +57 -0
  60. package/build/host/env.js.map +1 -0
  61. package/build/host/fakes.d.ts +82 -0
  62. package/build/host/fakes.js +239 -0
  63. package/build/host/fakes.js.map +1 -0
  64. package/build/host/group.d.ts +142 -0
  65. package/build/host/group.js +517 -0
  66. package/build/host/group.js.map +1 -0
  67. package/build/host/install.d.ts +96 -0
  68. package/build/host/install.js +330 -0
  69. package/build/host/install.js.map +1 -0
  70. package/build/host/lock.d.ts +78 -0
  71. package/build/host/lock.js +190 -0
  72. package/build/host/lock.js.map +1 -0
  73. package/build/host/logs.d.ts +26 -0
  74. package/build/host/logs.js +48 -0
  75. package/build/host/logs.js.map +1 -0
  76. package/build/host/node.d.ts +14 -0
  77. package/build/host/node.js +309 -0
  78. package/build/host/node.js.map +1 -0
  79. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  80. package/build/host/ports.js +17 -0
  81. package/build/host/ports.js.map +1 -0
  82. package/build/host/probes.d.ts +51 -0
  83. package/build/host/probes.js +139 -0
  84. package/build/host/probes.js.map +1 -0
  85. package/build/host/processes.d.ts +32 -0
  86. package/build/host/processes.js +63 -0
  87. package/build/host/processes.js.map +1 -0
  88. package/build/host/render.d.ts +84 -0
  89. package/build/host/render.js +235 -0
  90. package/build/host/render.js.map +1 -0
  91. package/build/host/watch.d.ts +90 -0
  92. package/build/host/watch.js +165 -0
  93. package/build/host/watch.js.map +1 -0
  94. package/build/host.d.ts +13 -671
  95. package/build/host.js +12 -2126
  96. package/build/http/answers.js +29 -0
  97. package/build/http/answers.js.map +1 -0
  98. package/build/http/fake-server.js +61 -0
  99. package/build/http/fake-server.js.map +1 -0
  100. package/build/http/outcome.d.ts +115 -0
  101. package/build/http/outcome.js +325 -0
  102. package/build/http/outcome.js.map +1 -0
  103. package/build/http/probes.d.ts +83 -0
  104. package/build/http/probes.js +232 -0
  105. package/build/http/probes.js.map +1 -0
  106. package/build/http/transport.d.ts +165 -0
  107. package/build/http/transport.js +517 -0
  108. package/build/http/transport.js.map +1 -0
  109. package/build/http-client/client.d.ts +121 -0
  110. package/build/http-client/client.js +330 -0
  111. package/build/http-client/client.js.map +1 -0
  112. package/build/http-client/connection.d.ts +78 -0
  113. package/build/http-client/connection.js +54 -0
  114. package/build/http-client/connection.js.map +1 -0
  115. package/build/http-client/machine.d.ts +14 -0
  116. package/build/http-client/machine.js +109 -0
  117. package/build/http-client/machine.js.map +1 -0
  118. package/build/http-client/meets.d.ts +11 -0
  119. package/build/http-client/meets.js +74 -0
  120. package/build/http-client/meets.js.map +1 -0
  121. package/build/http-client/session.d.ts +87 -0
  122. package/build/http-client/session.js +99 -0
  123. package/build/http-client/session.js.map +1 -0
  124. package/build/http-client/starting.d.ts +25 -0
  125. package/build/http-client/starting.js +65 -0
  126. package/build/http-client/starting.js.map +1 -0
  127. package/build/http-client.d.ts +9 -330
  128. package/build/http-client.js +8 -707
  129. package/build/http.d.ts +5 -353
  130. package/build/http.js +3 -1086
  131. package/build/identity.d.ts +16 -0
  132. package/build/identity.js +44 -0
  133. package/build/identity.js.map +1 -0
  134. package/build/index.d.ts +35 -412
  135. package/build/index.js +24 -3277
  136. package/build/knobs.d.ts +1 -0
  137. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  138. package/build/knobs.js.map +1 -0
  139. package/build/latch.d.ts +29 -0
  140. package/build/latch.js +122 -0
  141. package/build/latch.js.map +1 -0
  142. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  143. package/build/law.js +149 -0
  144. package/build/law.js.map +1 -0
  145. package/build/lifecycle.d.ts +144 -0
  146. package/build/lifecycle.js +411 -0
  147. package/build/lifecycle.js.map +1 -0
  148. package/build/limiter/machine.d.ts +40 -0
  149. package/build/limiter/machine.js +279 -0
  150. package/build/limiter/machine.js.map +1 -0
  151. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  152. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  153. package/build/limiter/policy.js.map +1 -0
  154. package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
  155. package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
  156. package/build/limiter/quota.js.map +1 -0
  157. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  158. package/build/limiter/store.js +145 -0
  159. package/build/limiter/store.js.map +1 -0
  160. package/build/limiter.d.ts +4 -3
  161. package/build/limiter.js +4 -2
  162. package/build/lint.d.ts +152 -0
  163. package/build/lint.js +576 -0
  164. package/build/lint.js.map +1 -0
  165. package/build/logger.d.ts +71 -0
  166. package/build/logger.js +183 -0
  167. package/build/logger.js.map +1 -0
  168. package/build/machines.d.ts +41 -0
  169. package/build/machines.js +451 -0
  170. package/build/machines.js.map +1 -0
  171. package/build/metrics.d.ts +53 -0
  172. package/build/metrics.js +111 -0
  173. package/build/metrics.js.map +1 -0
  174. package/build/mongodb/client.d.ts +131 -0
  175. package/build/mongodb/client.js +388 -0
  176. package/build/mongodb/client.js.map +1 -0
  177. package/build/mongodb/connection.d.ts +112 -0
  178. package/build/mongodb/connection.js +12 -0
  179. package/build/mongodb/connection.js.map +1 -0
  180. package/build/mongodb/machine.d.ts +14 -0
  181. package/build/mongodb/machine.js +122 -0
  182. package/build/mongodb/machine.js.map +1 -0
  183. package/build/mongodb/meets.d.ts +15 -0
  184. package/build/mongodb/meets.js +103 -0
  185. package/build/mongodb/meets.js.map +1 -0
  186. package/build/mongodb/starting.d.ts +29 -0
  187. package/build/mongodb/starting.js +77 -0
  188. package/build/mongodb/starting.js.map +1 -0
  189. package/build/mongodb.d.ts +8 -296
  190. package/build/mongodb.js +7 -682
  191. package/build/operation.d.ts +27 -0
  192. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  193. package/build/operation.js.map +1 -0
  194. package/build/otel.d.ts +2 -2
  195. package/build/pg/client.d.ts +96 -0
  196. package/build/pg/client.js +277 -0
  197. package/build/pg/client.js.map +1 -0
  198. package/build/pg/connection.d.ts +75 -0
  199. package/build/pg/connection.js +11 -0
  200. package/build/pg/connection.js.map +1 -0
  201. package/build/pg/machine.d.ts +13 -0
  202. package/build/pg/machine.js +111 -0
  203. package/build/pg/machine.js.map +1 -0
  204. package/build/pg/meets.d.ts +14 -0
  205. package/build/pg/meets.js +83 -0
  206. package/build/pg/meets.js.map +1 -0
  207. package/build/pg/starting.d.ts +26 -0
  208. package/build/pg/starting.js +62 -0
  209. package/build/pg/starting.js.map +1 -0
  210. package/build/pg.d.ts +8 -219
  211. package/build/pg.js +7 -525
  212. package/build/poller.d.ts +9 -0
  213. package/build/poller.js +152 -0
  214. package/build/poller.js.map +1 -0
  215. package/build/process.d.ts +114 -0
  216. package/build/process.js +170 -0
  217. package/build/process.js.map +1 -0
  218. package/build/profiles.d.ts +68 -0
  219. package/build/profiles.js +120 -0
  220. package/build/profiles.js.map +1 -0
  221. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  222. package/build/queue.js +279 -0
  223. package/build/queue.js.map +1 -0
  224. package/build/rabbitmq/client.d.ts +144 -0
  225. package/build/rabbitmq/client.js +426 -0
  226. package/build/rabbitmq/client.js.map +1 -0
  227. package/build/rabbitmq/connection.d.ts +91 -0
  228. package/build/rabbitmq/connection.js +15 -0
  229. package/build/rabbitmq/connection.js.map +1 -0
  230. package/build/rabbitmq/machine.d.ts +13 -0
  231. package/build/rabbitmq/machine.js +159 -0
  232. package/build/rabbitmq/machine.js.map +1 -0
  233. package/build/rabbitmq/meets.d.ts +12 -0
  234. package/build/rabbitmq/meets.js +96 -0
  235. package/build/rabbitmq/meets.js.map +1 -0
  236. package/build/rabbitmq/starting.d.ts +27 -0
  237. package/build/rabbitmq/starting.js +67 -0
  238. package/build/rabbitmq/starting.js.map +1 -0
  239. package/build/rabbitmq.d.ts +8 -283
  240. package/build/rabbitmq.js +7 -742
  241. package/build/redis/client.d.ts +86 -0
  242. package/build/redis/client.js +285 -0
  243. package/build/redis/client.js.map +1 -0
  244. package/build/redis/connection.d.ts +57 -0
  245. package/build/redis/connection.js +11 -0
  246. package/build/redis/connection.js.map +1 -0
  247. package/build/redis/limiter.d.ts +43 -0
  248. package/build/redis/limiter.js +164 -0
  249. package/build/redis/limiter.js.map +1 -0
  250. package/build/redis/machine.d.ts +12 -0
  251. package/build/redis/machine.js +144 -0
  252. package/build/redis/machine.js.map +1 -0
  253. package/build/redis/meets.d.ts +11 -0
  254. package/build/redis/meets.js +75 -0
  255. package/build/redis/meets.js.map +1 -0
  256. package/build/redis/operations.d.ts +5 -0
  257. package/build/redis/operations.js +114 -0
  258. package/build/redis/operations.js.map +1 -0
  259. package/build/redis.d.ts +10 -207
  260. package/build/redis.js +9 -771
  261. package/build/requests.d.ts +66 -0
  262. package/build/requests.js +279 -0
  263. package/build/requests.js.map +1 -0
  264. package/build/retrier.d.ts +62 -0
  265. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  266. package/build/retrier.js.map +1 -0
  267. package/build/routes.d.ts +35 -0
  268. package/build/routes.js +77 -0
  269. package/build/routes.js.map +1 -0
  270. package/build/rules.d.ts +19 -2
  271. package/build/stops.d.ts +51 -0
  272. package/build/stops.js +86 -0
  273. package/build/stops.js.map +1 -0
  274. package/build/testing.d.ts +8 -270
  275. package/build/testing.js +4 -1027
  276. package/build/testing.js.map +1 -1
  277. package/build/timing.d.ts +63 -0
  278. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  279. package/build/timing.js.map +1 -0
  280. package/build/units.d.ts +17 -0
  281. package/build/units.js +236 -0
  282. package/build/units.js.map +1 -0
  283. package/build/watchdog.d.ts +34 -0
  284. package/build/watchdog.js +53 -0
  285. package/build/watchdog.js.map +1 -0
  286. package/build/websocket/client.d.ts +136 -0
  287. package/build/websocket/client.js +422 -0
  288. package/build/websocket/client.js.map +1 -0
  289. package/build/websocket/connection.d.ts +83 -0
  290. package/build/websocket/connection.js +57 -0
  291. package/build/websocket/connection.js.map +1 -0
  292. package/build/websocket/machine.d.ts +12 -0
  293. package/build/websocket/machine.js +155 -0
  294. package/build/websocket/machine.js.map +1 -0
  295. package/build/websocket/meets.d.ts +14 -0
  296. package/build/websocket/meets.js +92 -0
  297. package/build/websocket/meets.js.map +1 -0
  298. package/build/websocket/starting.d.ts +25 -0
  299. package/build/websocket/starting.js +69 -0
  300. package/build/websocket/starting.js.map +1 -0
  301. package/build/websocket.d.ts +9 -264
  302. package/build/websocket.js +8 -774
  303. package/build/worker.d.ts +92 -0
  304. package/build/worker.js +153 -0
  305. package/build/worker.js.map +1 -0
  306. package/package.json +4 -3
  307. package/build/backoff-QTRGfkEK.d.ts +0 -45
  308. package/build/clock-DpVgpY4h.d.ts +0 -2
  309. package/build/grpc.js.map +0 -1
  310. package/build/host.js.map +0 -1
  311. package/build/http-client.js.map +0 -1
  312. package/build/http.js.map +0 -1
  313. package/build/index.js.map +0 -1
  314. package/build/knobs-BJcz6m01.js.map +0 -1
  315. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  316. package/build/limiter-DrM0PQV9.js.map +0 -1
  317. package/build/logger-B6drv9w0.d.ts +0 -488
  318. package/build/machine-BhVeHr_m.js.map +0 -1
  319. package/build/mongodb.js.map +0 -1
  320. package/build/operation-DF73RZOI.js.map +0 -1
  321. package/build/pg.js.map +0 -1
  322. package/build/policy-UYALkqVq.js.map +0 -1
  323. package/build/process-7R9M29wN.js +0 -437
  324. package/build/process-7R9M29wN.js.map +0 -1
  325. package/build/rabbitmq.js.map +0 -1
  326. package/build/redis.js.map +0 -1
  327. package/build/requests-DD2ALv0_.js +0 -583
  328. package/build/requests-DD2ALv0_.js.map +0 -1
  329. package/build/retrier-Dnjhvxol.js.map +0 -1
  330. package/build/timing-DZl36uXs.js.map +0 -1
  331. package/build/websocket.js.map +0 -1
@@ -0,0 +1,184 @@
1
+ import { fakeClock, seeded } from "./fakes.js";
2
+ import { failSpan, recoverSpan } from "./timing.js";
3
+ import { valueIn } from "@mark1russell7/quantity";
4
+ // src/contract.ts
5
+ const ms = (amount) => valueIn(amount, "ms");
6
+ /** The part of a verdict that the contract compares: what a caller and the platform see. */
7
+ const visible = (verdict) => ({
8
+ ready: verdict.ready,
9
+ alive: verdict.alive,
10
+ controllers: verdict.controllers,
11
+ dependencies: verdict.dependencies
12
+ });
13
+ const same = (expected, actual) => JSON.stringify(expected) === JSON.stringify(actual);
14
+ const failure = (what, expected, actual) => /* @__PURE__ */ new Error(`${what}: expected ${JSON.stringify(expected)}, but the verdict was ${JSON.stringify(actual)}`);
15
+ /**
16
+ * This function generates the contract test of a declaration. `declare` gives a new builder with
17
+ * the declaration and the function of each check, each time. The checks must pass at rest. The
18
+ * cases are:
19
+ * - The service at rest: each controller and each dependency is ready, and the service is alive.
20
+ * - Each dependency unavailable: its polls fail at once (the force-fail list). The dependency and
21
+ * each controller that needs it become not ready, and the other controllers stay ready. Liveness
22
+ * stays, unless a liveness check exercises the dependency.
23
+ * - Each dependency degraded: each call of its checks takes the latency longer. Nothing can fail.
24
+ * - Each dependency recovers: after it is unavailable, the service is again at rest.
25
+ * - A negative control: a client that the declaration does not name fails, and nothing changes.
26
+ *
27
+ * A dependency that no check exercises is a finding: the service cannot see it fail.
28
+ */
29
+ const contractCases = (declare, options = {}) => {
30
+ const degradeBy = options.degradeBy ?? 100;
31
+ const seed = options.seed ?? 1;
32
+ const description = declare().describe();
33
+ const service = description.name;
34
+ const gating = description.checks.filter((check) => check.gates !== null);
35
+ const timingOf = (check) => description.policies[check.gates];
36
+ const failMax = (check) => ms(failSpan(timingOf(check), check.poll, "error").max);
37
+ const recoverMax = (check) => ms(recoverSpan(timingOf(check), check.poll).max);
38
+ const most = (values) => values.reduce((a, b) => Math.max(a, b), 0);
39
+ const settleTime = most(gating.filter((check) => check.gates === "readiness").map(recoverMax)) + 1;
40
+ const quietTime = most(gating.map(failMax)) + 1;
41
+ /** This function starts the declaration on a fake clock, and moves it to rest. */
42
+ const boot = async (extra = () => ({})) => {
43
+ const clock = fakeClock();
44
+ const starting = declare().start({
45
+ clock,
46
+ random: seeded(seed),
47
+ ...extra(clock)
48
+ });
49
+ let started = false;
50
+ starting.then(() => started = true, () => started = true);
51
+ for (let step = 0; step < 1e3 && !started; step += 1) await clock.advance(10);
52
+ const health = await starting;
53
+ await clock.advance(settleTime);
54
+ return {
55
+ health,
56
+ clock,
57
+ rest: visible(health.verdict())
58
+ };
59
+ };
60
+ const stop = (health) => health.stop();
61
+ const cases = [{
62
+ name: `${service}: at rest, each controller and each dependency is ready, and the service is alive`,
63
+ async run() {
64
+ const { health, rest } = await boot();
65
+ try {
66
+ const expected = {
67
+ ready: true,
68
+ alive: true,
69
+ controllers: Object.fromEntries(description.controllers.map((each) => [each.name, true])),
70
+ dependencies: Object.fromEntries(description.dependencies.map((each) => [each.name, true]))
71
+ };
72
+ if (!same(expected, rest)) throw failure("at rest", expected, rest);
73
+ } finally {
74
+ stop(health);
75
+ }
76
+ }
77
+ }];
78
+ for (const dependency of description.dependencies) {
79
+ const on = gating.filter((check) => check.dependency === dependency.name);
80
+ const readiness = on.filter((check) => check.gates === "readiness");
81
+ const liveness = on.filter((check) => check.gates === "liveness");
82
+ const unavailable = (rest) => ({
83
+ ready: readiness.length === 0 ? rest.ready : false,
84
+ alive: liveness.length === 0 ? rest.alive : false,
85
+ controllers: Object.fromEntries(description.controllers.map((each) => [each.name, each.requires.includes(dependency.name) && readiness.length > 0 ? false : rest.controllers[each.name]])),
86
+ dependencies: {
87
+ ...rest.dependencies,
88
+ [dependency.name]: readiness.length === 0
89
+ }
90
+ });
91
+ cases.push({
92
+ name: `${service}: ${dependency.name} unavailable`,
93
+ async run() {
94
+ if (on.length === 0) throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it fail`);
95
+ const { health, clock, rest } = await boot();
96
+ try {
97
+ health.forceFail(dependency.name, true);
98
+ await clock.advance(most(on.map(failMax)) + 1);
99
+ const now = visible(health.verdict());
100
+ const expected = unavailable(rest);
101
+ if (!same(expected, now)) throw failure(`${dependency.name} unavailable`, expected, now);
102
+ } finally {
103
+ stop(health);
104
+ }
105
+ }
106
+ });
107
+ cases.push({
108
+ name: `${service}: ${dependency.name} degraded by ${degradeBy} ms, and nothing fails`,
109
+ async run() {
110
+ const tight = on.filter((check) => ms(check.poll.timeout) <= degradeBy);
111
+ if (tight.length > 0) throw new Error(`${tight.map((check) => `${check.name} times out in ${ms(check.poll.timeout)} ms`).join(", ")}: a latency of ${degradeBy} ms fails it`);
112
+ const { health, clock, rest } = await boot((at) => ({ wrapCheck: (check, run) => check.dependency !== dependency.name ? run : (signal) => new Promise((resolve) => at.after(degradeBy, () => resolve(run(signal)))) }));
113
+ try {
114
+ await clock.advance(quietTime + most(on.map((check) => ms(check.poll.interval))));
115
+ const now = visible(health.verdict());
116
+ if (!same(rest, now)) throw failure(`${dependency.name} degraded`, rest, now);
117
+ } finally {
118
+ stop(health);
119
+ }
120
+ }
121
+ });
122
+ cases.push({
123
+ name: `${service}: ${dependency.name} recovers`,
124
+ async run() {
125
+ if (on.length === 0) throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it recover`);
126
+ const { health, clock, rest } = await boot();
127
+ try {
128
+ health.forceFail(dependency.name, true);
129
+ await clock.advance(most(on.map(failMax)) + 1);
130
+ health.forceFail(dependency.name, false);
131
+ await clock.advance(most(on.map(recoverMax)) + 1);
132
+ const now = visible(health.verdict());
133
+ if (!same(rest, now)) throw failure(`${dependency.name} recovered`, rest, now);
134
+ } finally {
135
+ stop(health);
136
+ }
137
+ }
138
+ });
139
+ }
140
+ const never = `${service}.client-never-registered`;
141
+ cases.push({
142
+ name: `${service}: a client never registered fails, and nothing changes (the negative control)`,
143
+ async run() {
144
+ if (description.dependencies.some((each) => each.name === never)) throw new Error(`the declaration has a dependency named ${never}`);
145
+ const { health, clock, rest } = await boot();
146
+ try {
147
+ health.forceFail(never, true);
148
+ await clock.advance(quietTime);
149
+ const now = visible(health.verdict());
150
+ if (!same(rest, now)) throw failure("the negative control", rest, now);
151
+ } finally {
152
+ stop(health);
153
+ }
154
+ let refused = false;
155
+ try {
156
+ declare().check({
157
+ name: `${never}.check`,
158
+ dependency: never,
159
+ step: "round-trip",
160
+ ownConnection: true,
161
+ gates: null,
162
+ poll: gating[0]?.poll ?? {
163
+ interval: {
164
+ value: 1,
165
+ unit: "s"
166
+ },
167
+ jitter: 0,
168
+ timeout: {
169
+ value: .5,
170
+ unit: "s"
171
+ }
172
+ }
173
+ }).describe();
174
+ } catch {
175
+ refused = true;
176
+ }
177
+ if (!refused) throw new Error(`the declaration accepted a check on ${never}, which is not a dependency`);
178
+ }
179
+ });
180
+ return cases;
181
+ };
182
+ export { contractCases };
183
+
184
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.js","names":[],"sources":["../src/contract.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport type { ServiceBuilder } from \"./builder.ts\";\nimport type { Check, ServiceDescription } from \"./description.ts\";\nimport type { FakeClock } from \"./fakes.ts\";\nimport { fakeClock, seeded } from \"./fakes.ts\";\nimport type { Health, HealthVerdict, StartOptions } from \"./health.ts\";\nimport { failSpan, recoverSpan } from \"./timing.ts\";\n\n/** A contract case is one generated case of the contract test of a declaration. It throws on a failure. */\nexport interface ContractCase {\n readonly name: string;\n run(): Promise<void>;\n}\n\n/** These options tune the contract test. */\nexport interface ContractOptions {\n /** This number is the latency that a degraded dependency adds to each check, in milliseconds. The default of the contract is 100. */\n readonly degradeBy?: number | undefined;\n /** This number is the seed of the jitter. */\n readonly seed?: number | undefined;\n}\n\nconst ms = (amount: { readonly value: number; readonly unit: string }): number => valueIn(amount, \"ms\");\n\n/** The part of a verdict that the contract compares: what a caller and the platform see. */\nconst visible = (verdict: HealthVerdict) => ({\n ready: verdict.ready,\n alive: verdict.alive,\n controllers: verdict.controllers,\n dependencies: verdict.dependencies,\n});\n\nconst same = (expected: unknown, actual: unknown): boolean => JSON.stringify(expected) === JSON.stringify(actual);\n\nconst failure = (what: string, expected: unknown, actual: unknown): Error =>\n new Error(`${what}: expected ${JSON.stringify(expected)}, but the verdict was ${JSON.stringify(actual)}`);\n\n/**\n * This function generates the contract test of a declaration. `declare` gives a new builder with\n * the declaration and the function of each check, each time. The checks must pass at rest. The\n * cases are:\n * - The service at rest: each controller and each dependency is ready, and the service is alive.\n * - Each dependency unavailable: its polls fail at once (the force-fail list). The dependency and\n * each controller that needs it become not ready, and the other controllers stay ready. Liveness\n * stays, unless a liveness check exercises the dependency.\n * - Each dependency degraded: each call of its checks takes the latency longer. Nothing can fail.\n * - Each dependency recovers: after it is unavailable, the service is again at rest.\n * - A negative control: a client that the declaration does not name fails, and nothing changes.\n *\n * A dependency that no check exercises is a finding: the service cannot see it fail.\n */\nexport const contractCases = (declare: () => ServiceBuilder, options: ContractOptions = {}): ContractCase[] => {\n const degradeBy = options.degradeBy ?? 100;\n const seed = options.seed ?? 1;\n const description: ServiceDescription = declare().describe();\n const service = description.name;\n const gating = description.checks.filter((check) => check.gates !== null);\n const timingOf = (check: Check) => description.policies[check.gates!];\n const failMax = (check: Check): number => ms(failSpan(timingOf(check), check.poll, \"error\").max);\n const recoverMax = (check: Check): number => ms(recoverSpan(timingOf(check), check.poll).max);\n const most = (values: readonly number[]): number => values.reduce((a, b) => Math.max(a, b), 0);\n const settleTime = most(gating.filter((check) => check.gates === \"readiness\").map(recoverMax)) + 1;\n const quietTime = most(gating.map(failMax)) + 1;\n\n /** This function starts the declaration on a fake clock, and moves it to rest. */\n const boot = async (\n extra: (clock: FakeClock) => Partial<StartOptions> = () => ({}),\n ): Promise<{ health: Health; clock: FakeClock; rest: ReturnType<typeof visible> }> => {\n const clock = fakeClock();\n // the warm-up sweep can wait on the clock (a degraded check), thus the clock moves while it starts\n const starting = declare().start({ clock, random: seeded(seed), ...extra(clock) });\n let started = false;\n void starting.then(\n () => (started = true),\n () => (started = true),\n );\n for (let step = 0; step < 1000 && !started; step += 1) await clock.advance(10);\n const health = await starting;\n await clock.advance(settleTime);\n return { health, clock, rest: visible(health.verdict()) };\n };\n const stop = (health: Health): void => health.stop();\n\n const cases: ContractCase[] = [\n {\n name: `${service}: at rest, each controller and each dependency is ready, and the service is alive`,\n async run() {\n const { health, rest } = await boot();\n try {\n const expected = {\n ready: true,\n alive: true,\n controllers: Object.fromEntries(description.controllers.map((each) => [each.name, true])),\n dependencies: Object.fromEntries(description.dependencies.map((each) => [each.name, true])),\n };\n if (!same(expected, rest)) throw failure(\"at rest\", expected, rest);\n } finally {\n stop(health);\n }\n },\n },\n ];\n\n for (const dependency of description.dependencies) {\n const on = gating.filter((check) => check.dependency === dependency.name);\n const readiness = on.filter((check) => check.gates === \"readiness\");\n const liveness = on.filter((check) => check.gates === \"liveness\");\n const unavailable = (rest: ReturnType<typeof visible>) => ({\n ready: readiness.length === 0 ? rest.ready : false,\n alive: liveness.length === 0 ? rest.alive : false,\n controllers: Object.fromEntries(\n description.controllers.map((each) => [\n each.name,\n each.requires.includes(dependency.name) && readiness.length > 0 ? false : rest.controllers[each.name],\n ]),\n ),\n dependencies: { ...rest.dependencies, [dependency.name]: readiness.length === 0 },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} unavailable`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it fail`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n const now = visible(health.verdict());\n const expected = unavailable(rest);\n if (!same(expected, now)) throw failure(`${dependency.name} unavailable`, expected, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} degraded by ${degradeBy} ms, and nothing fails`,\n async run() {\n const tight = on.filter((check) => ms(check.poll.timeout) <= degradeBy);\n if (tight.length > 0)\n throw new Error(\n `${tight.map((check) => `${check.name} times out in ${ms(check.poll.timeout)} ms`).join(\", \")}: a latency of ${degradeBy} ms fails it`,\n );\n const { health, clock, rest } = await boot((at) => ({\n wrapCheck: (check, run) =>\n check.dependency !== dependency.name\n ? run\n : (signal) => new Promise((resolve) => at.after(degradeBy, () => resolve(run(signal)))),\n }));\n try {\n await clock.advance(quietTime + most(on.map((check) => ms(check.poll.interval))));\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} degraded`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n\n cases.push({\n name: `${service}: ${dependency.name} recovers`,\n async run() {\n if (on.length === 0)\n throw new Error(`no check that gates a policy exercises ${dependency.name}: the service cannot see it recover`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(dependency.name, true);\n await clock.advance(most(on.map(failMax)) + 1);\n health.forceFail(dependency.name, false);\n await clock.advance(most(on.map(recoverMax)) + 1);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(`${dependency.name} recovered`, rest, now);\n } finally {\n stop(health);\n }\n },\n });\n }\n\n const never = `${service}.client-never-registered`;\n cases.push({\n name: `${service}: a client never registered fails, and nothing changes (the negative control)`,\n async run() {\n if (description.dependencies.some((each) => each.name === never))\n throw new Error(`the declaration has a dependency named ${never}`);\n const { health, clock, rest } = await boot();\n try {\n health.forceFail(never, true);\n await clock.advance(quietTime);\n const now = visible(health.verdict());\n if (!same(rest, now)) throw failure(\"the negative control\", rest, now);\n } finally {\n stop(health);\n }\n // and a check on a client never registered is refused before the start\n let refused = false;\n try {\n declare()\n .check({\n name: `${never}.check`,\n dependency: never,\n step: \"round-trip\",\n ownConnection: true,\n gates: null,\n poll: gating[0]?.poll ?? { interval: { value: 1, unit: \"s\" }, jitter: 0, timeout: { value: 0.5, unit: \"s\" } },\n })\n .describe();\n } catch {\n refused = true;\n }\n if (!refused) throw new Error(`the declaration accepted a check on ${never}, which is not a dependency`);\n },\n });\n\n return cases;\n};\n"],"mappings":";;;;AAsBA,MAAM,MAAM,WAAsE,QAAQ,QAAQ,IAAI;;AAGtG,MAAM,WAAW,aAA4B;CAC3C,OAAO,QAAQ;CACf,OAAO,QAAQ;CACf,aAAa,QAAQ;CACrB,cAAc,QAAQ;AACxB;AAEA,MAAM,QAAQ,UAAmB,WAA6B,KAAK,UAAU,QAAQ,MAAM,KAAK,UAAU,MAAM;AAEhH,MAAM,WAAW,MAAc,UAAmB,2BAChD,IAAI,MAAM,GAAG,KAAK,aAAa,KAAK,UAAU,QAAQ,EAAE,wBAAwB,KAAK,UAAU,MAAM,GAAG;;;;;;;;;;;;;;;AAgB1G,MAAa,iBAAiB,SAA+B,UAA2B,CAAC,MAAsB;CAC7G,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,cAAkC,QAAQ,CAAC,CAAC,SAAS;CAC3D,MAAM,UAAU,YAAY;CAC5B,MAAM,SAAS,YAAY,OAAO,QAAQ,UAAU,MAAM,UAAU,IAAI;CACxE,MAAM,YAAY,UAAiB,YAAY,SAAS,MAAM;CAC9D,MAAM,WAAW,UAAyB,GAAG,SAAS,SAAS,KAAK,GAAG,MAAM,MAAM,OAAO,CAAC,CAAC,GAAG;CAC/F,MAAM,cAAc,UAAyB,GAAG,YAAY,SAAS,KAAK,GAAG,MAAM,IAAI,CAAC,CAAC,GAAG;CAC5F,MAAM,QAAQ,WAAsC,OAAO,QAAQ,GAAG,MAAM,KAAK,IAAI,GAAG,CAAC,GAAG,CAAC;CAC7F,MAAM,aAAa,KAAK,OAAO,QAAQ,UAAU,M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jB,MAAM,MAAM;GACV,IAAI,YAAY,aAAa,MAAM,SAAS,KAAK,SAAS,KAAK,GAC7D,MAAM,IAAI,MAAM,0CAA0C,OAAO;GACnE,MAAM,EAAE,QAAQ,OAAO,SAAS,MAAM,KAAK;GAC3C,IAAI;IACF,OAAO,UAAU,OAAO,IAAI;IAC5B,MAAM,MAAM,QAAQ,SAAS;IAC7B,MAAM,MAAM,QAAQ,OAAO,QAAQ,CAAC;IACpC,IAAI,CAAC,KAAK,MAAM,GAAG,GAAG,MAAM,QAAQ,wBAAwB,MAAM,GAAG;GACvE,UAAU;IACR,KAAK,MAAM;GACb;GAEA,IAAI,UAAU;GACd,IAAI;IACF,QAAQ,CAAC,CACN,MAAM;KACL,MAAM,GAAG,MAAM;KACf,YAAY;KACZ,MAAM;KACN,eAAe;KACf,OAAO;KACP,MAAM,OAAO,EAAE,EAAE,QAAQ;MAAE,UAAU;OAAE,OAAO;OAAG,MAAM;MAAI;MAAG,QAAQ;MAAG,SAAS;OAAE,OAAO;OAAK,MAAM;MAAI;KAAE;IAC9G,CAAC,CAAC,CACD,SAAS;GACd,QAAQ;IACN,UAAU;GACZ;GACA,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,uCAAuC,MAAM,4BAA4B;EACzG;CACF,CAAC;CAED,OAAO;AACT"}
@@ -0,0 +1,161 @@
1
+ import { Limiter } from "./limiter/policy.js";
2
+ import { Operation } from "./operation.js";
3
+ import { ExitSignal, ExitTrigger, MessageShape, ProcessTrigger } from "./process.js";
4
+ import { RoutePattern } from "./routes.js";
5
+ import { Poll, Timing } from "./timing.js";
6
+ import { Extent, Quantity } from "@mark1russell7/quantity";
7
+ /**
8
+ * This is the format of a service as data: what `describe()` exports, and nothing starts. The
9
+ * timer algebra and the ordering law read it. Each timer has a unit. Each knob comes from the
10
+ * declaration, because the runtime has no defaults. A bound that nobody gives is "no bound", not
11
+ * zero.
12
+ */
13
+ export declare const FORMAT = "mark1russell7.service/1";
14
+ /** A step is a step of a connection that a check examines. A check that skips a step cannot see a failure in it. */
15
+ export type Step = "dial" | "local-state" | "round-trip" | "checkout" | "progress" | "topology" | "latency";
16
+ /** A gate is the policy that the failures of a check count toward. */
17
+ export type Gate = "readiness" | "liveness";
18
+ /** A check is an active check: one signal, for one step of a connection. */
19
+ export interface Check {
20
+ readonly name: string;
21
+ /** This name is the dependency that it examines, or null when it reads the state of the process. */
22
+ readonly dependency: string | null;
23
+ readonly step: Step;
24
+ /** This flag tells if it uses the connection of the application. A check on its own connection cannot see a failure of that connection. */
25
+ readonly ownConnection: boolean;
26
+ /** This gate is the policy that it controls, or null for a check that only reports. It has no default. */
27
+ readonly gates: Gate | null;
28
+ readonly poll: Poll;
29
+ /**
30
+ * These are the loops that mark the progress of a check of the step `progress`, and its stall
31
+ * time. Without a declaration, the check names no loops, and `lint()` does not compare its stall time.
32
+ */
33
+ readonly marks?: ProgressMarks | undefined;
34
+ }
35
+ /**
36
+ * A progress mark declaration tells which loops mark the progress of a check, and how long the
37
+ * check waits for a mark. The check function fails when no loop marked in the stall time.
38
+ */
39
+ export interface ProgressMarks {
40
+ /** These are the names of the loops: a check (its poller) or a worker of the service. */
41
+ readonly loops: readonly string[];
42
+ /** This time is the most time from one mark to the next before the check fails. */
43
+ readonly stall: Quantity;
44
+ }
45
+ /**
46
+ * A dependency is something that the service uses, with its client. Its knobs have the names that
47
+ * the ordering law uses: `request_timeout`, `connect_bound`, `driver_writeoff_time`,
48
+ * `heartbeat_interval`, `client_retry_window`. Thus the law reads them without a translation.
49
+ */
50
+ export interface Dependency {
51
+ readonly name: string;
52
+ /** This identifier is the component in the corpus (`systems.component.postgresql`), or null when the corpus does not have it. */
53
+ readonly system: string | null;
54
+ readonly knobs: Readonly<Record<string, Extent>>;
55
+ /**
56
+ * These are the operations that the service does with it, by name (`GET /v1/forecast`, `INCR`).
57
+ * Each operation declares if it can go again. A dependency usually has the two kinds, thus a
58
+ * dependency has no idempotency of its own. An operation without a declaration does not go again.
59
+ */
60
+ readonly operations: Readonly<Record<string, Operation>>;
61
+ }
62
+ /**
63
+ * A transport is something that takes work in: a server, a consumer or a worker. Each is a
64
+ * component with a state machine. The service is ready only while each transport takes work.
65
+ */
66
+ export interface Transport {
67
+ readonly name: string;
68
+ readonly kind: "server" | "consumer" | "worker";
69
+ /** These are its knobs, with the names of the law where the law has them: the `server_idle_close` of a server. */
70
+ readonly knobs: Readonly<Record<string, Extent>>;
71
+ }
72
+ /**
73
+ * A controller is a group of routes. It is ready only while the dependencies that it needs are
74
+ * ready. Each route declares if its callers can send it again. When the shutdown stops a request,
75
+ * an idempotent route answers 503, which a caller can retry. Other routes answer 500.
76
+ */
77
+ export interface Controller {
78
+ readonly name: string;
79
+ readonly requires: readonly string[];
80
+ readonly routes: Readonly<Record<string, Operation>>;
81
+ /**
82
+ * These patterns match the routes that `routes` does not name, in their sequence: the first
83
+ * pattern that matches a route gives its operations. Without a declaration, the controller has
84
+ * no patterns.
85
+ */
86
+ readonly patterns?: readonly RoutePattern[] | undefined;
87
+ }
88
+ /** A coupling is a declared edge between two policies. The algebra checks its margin. */
89
+ export interface Coupling {
90
+ readonly from: Gate;
91
+ readonly to: Gate;
92
+ readonly effect: "fails";
93
+ }
94
+ /** A phase is one step of the shutdown sequence, with a cap. Its owner adds it. */
95
+ export interface Phase {
96
+ readonly name: string;
97
+ readonly cap: Quantity;
98
+ }
99
+ /**
100
+ * A repeat signal policy tells what an exit signal does while the shutdown runs:
101
+ * - `ignore`: the signal has no effect, and the shutdown continues.
102
+ * - `exit`: the process exits with the code 1 at once, as a second Ctrl-C does in a terminal.
103
+ */
104
+ export type RepeatSignal = "ignore" | "exit";
105
+ /**
106
+ * A cooperative floor is the earliest time of the cooperative abort in the drain:
107
+ * - `half`: half the cap of the drain. The work in flight gets half the drain at the least.
108
+ * - `none`: no floor. A window of the whole cap or more aborts the work at the start of the drain.
109
+ */
110
+ export type CooperativeFloor = "half" | "none";
111
+ /** These exit codes replace the code 0 of a clean shutdown, by the trigger of the shutdown. */
112
+ export type ExitCodes = Readonly<Partial<Record<ExitTrigger, number>>>;
113
+ /**
114
+ * A message trigger is a message of the IPC channel that starts the shutdown, for the trigger
115
+ * `ipc-message`. With `as`, the message is that exit signal: it has its exit code and the policy of a
116
+ * repeat signal. Without `as`, the message is the trigger `ipc-message`.
117
+ */
118
+ export interface MessageTrigger {
119
+ /** This shape is the message that starts the shutdown, for example `"shutdown"`. */
120
+ readonly match: MessageShape;
121
+ /** This signal is the exit signal that the message replaces, for example `SIGTERM` on Windows. */
122
+ readonly as?: ExitSignal | undefined;
123
+ }
124
+ /** A service description is the whole graph of a service, as data. */
125
+ export interface ServiceDescription {
126
+ readonly format: typeof FORMAT;
127
+ readonly name: string;
128
+ /** This flag tells if a part joined after the start. That part starts tripped, and the export is partial. */
129
+ readonly partial: boolean;
130
+ readonly transports: readonly Transport[];
131
+ readonly dependencies: readonly Dependency[];
132
+ readonly controllers: readonly Controller[];
133
+ readonly checks: readonly Check[];
134
+ /**
135
+ * These are the keyed limiters of the service, each with its key, its policy, its store and the
136
+ * bound on its keys. Without a declaration, the service has no limiters.
137
+ */
138
+ readonly limiters?: readonly Limiter[] | undefined;
139
+ readonly policies: {
140
+ readonly readiness: Timing;
141
+ readonly liveness: Timing;
142
+ /** This duration is how long the service can take to start. The startup probe must agree with it. */
143
+ readonly startup: Quantity;
144
+ };
145
+ readonly couplings: readonly Coupling[];
146
+ readonly shutdown: {
147
+ readonly phases: readonly Phase[];
148
+ /** This window is how long before the end of the drain the cooperative abort occurs, or no bound. */
149
+ readonly cooperativeWindow: Extent;
150
+ /** This floor is the earliest time of the cooperative abort. Without a declaration, the floor is `half`. */
151
+ readonly cooperativeFloor?: CooperativeFloor | undefined;
152
+ /** This policy tells what a signal does while the shutdown runs. Each declaration gives it, because the runtime has no defaults. */
153
+ readonly onRepeatSignal: RepeatSignal;
154
+ /** These triggers start the shutdown, in addition to the exit signals. Each one is opt-in. */
155
+ readonly triggers?: readonly ProcessTrigger[] | undefined;
156
+ /** These messages of the IPC channel start the shutdown. The trigger `ipc-message` needs one at the least. */
157
+ readonly messages?: readonly MessageTrigger[] | undefined;
158
+ /** These codes replace the exit code 0 by the trigger. Without a code, a clean shutdown exits 0. */
159
+ readonly exitCodes?: ExitCodes | undefined;
160
+ };
161
+ }
@@ -0,0 +1,11 @@
1
+ // src/description.ts
2
+ /**
3
+ * This is the format of a service as data: what `describe()` exports, and nothing starts. The
4
+ * timer algebra and the ordering law read it. Each timer has a unit. Each knob comes from the
5
+ * declaration, because the runtime has no defaults. A bound that nobody gives is "no bound", not
6
+ * zero.
7
+ */
8
+ const FORMAT = "mark1russell7.service/1";
9
+ export { FORMAT };
10
+
11
+ //# sourceMappingURL=description.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"description.js","names":[],"sources":["../src/description.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport type { Limiter } from \"./limiter/policy.ts\";\nimport type { Operation } from \"./operation.ts\";\nimport type { ExitSignal, ExitTrigger, MessageShape, ProcessTrigger } from \"./process.ts\";\nimport type { RoutePattern } from \"./routes.ts\";\nimport type { Poll, Timing } from \"./timing.ts\";\n\n/**\n * This is the format of a service as data: what `describe()` exports, and nothing starts. The\n * timer algebra and the ordering law read it. Each timer has a unit. Each knob comes from the\n * declaration, because the runtime has no defaults. A bound that nobody gives is \"no bound\", not\n * zero.\n */\nexport const FORMAT = \"mark1russell7.service/1\";\n\n/** A step is a step of a connection that a check examines. A check that skips a step cannot see a failure in it. */\nexport type Step =\n \"dial\" | \"local-state\" | \"round-trip\" | \"checkout\" | \"progress\" | \"topology\" | \"latency\";\n\n/** A gate is the policy that the failures of a check count toward. */\nexport type Gate = \"readiness\" | \"liveness\";\n\n/** A check is an active check: one signal, for one step of a connection. */\nexport interface Check {\n readonly name: string;\n /** This name is the dependency that it examines, or null when it reads the state of the process. */\n readonly dependency: string | null;\n readonly step: Step;\n /** This flag tells if it uses the connection of the application. A check on its own connection cannot see a failure of that connection. */\n readonly ownConnection: boolean;\n /** This gate is the policy that it controls, or null for a check that only reports. It has no default. */\n readonly gates: Gate | null;\n readonly poll: Poll;\n /**\n * These are the loops that mark the progress of a check of the step `progress`, and its stall\n * time. Without a declaration, the check names no loops, and `lint()` does not compare its stall time.\n */\n readonly marks?: ProgressMarks | undefined;\n}\n\n/**\n * A progress mark declaration tells which loops mark the progress of a check, and how long the\n * check waits for a mark. The check function fails when no loop marked in the stall time.\n */\nexport interface ProgressMarks {\n /** These are the names of the loops: a check (its poller) or a worker of the service. */\n readonly loops: readonly string[];\n /** This time is the most time from one mark to the next before the check fails. */\n readonly stall: Quantity;\n}\n\n/**\n * A dependency is something that the service uses, with its client. Its knobs have the names that\n * the ordering law uses: `request_timeout`, `connect_bound`, `driver_writeoff_time`,\n * `heartbeat_interval`, `client_retry_window`. Thus the law reads them without a translation.\n */\nexport interface Dependency {\n readonly name: string;\n /** This identifier is the component in the corpus (`systems.component.postgresql`), or null when the corpus does not have it. */\n readonly system: string | null;\n readonly knobs: Readonly<Record<string, Extent>>;\n /**\n * These are the operations that the service does with it, by name (`GET /v1/forecast`, `INCR`).\n * Each operation declares if it can go again. A dependency usually has the two kinds, thus a\n * dependency has no idempotency of its own. An operation without a declaration does not go again.\n */\n readonly operations: Readonly<Record<string, Operation>>;\n}\n\n/**\n * A transport is something that takes work in: a server, a consumer or a worker. Each is a\n * component with a state machine. The service is ready only while each transport takes work.\n */\nexport interface Transport {\n readonly name: string;\n readonly kind: \"server\" | \"consumer\" | \"worker\";\n /** These are its knobs, with the names of the law where the law has them: the `server_idle_close` of a server. */\n readonly knobs: Readonly<Record<string, Extent>>;\n}\n\n/**\n * A controller is a group of routes. It is ready only while the dependencies that it needs are\n * ready. Each route declares if its callers can send it again. When the shutdown stops a request,\n * an idempotent route answers 503, which a caller can retry. Other routes answer 500.\n */\nexport interface Controller {\n readonly name: string;\n readonly requires: readonly string[];\n readonly routes: Readonly<Record<string, Operation>>;\n /**\n * These patterns match the routes that `routes` does not name, in their sequence: the first\n * pattern that matches a route gives its operations. Without a declaration, the controller has\n * no patterns.\n */\n readonly patterns?: readonly RoutePattern[] | undefined;\n}\n\n/** A coupling is a declared edge between two policies. The algebra checks its margin. */\nexport interface Coupling {\n readonly from: Gate;\n readonly to: Gate;\n readonly effect: \"fails\";\n}\n\n/** A phase is one step of the shutdown sequence, with a cap. Its owner adds it. */\nexport interface Phase {\n readonly name: string;\n readonly cap: Quantity;\n}\n\n/**\n * A repeat signal policy tells what an exit signal does while the shutdown runs:\n * - `ignore`: the signal has no effect, and the shutdown continues.\n * - `exit`: the process exits with the code 1 at once, as a second Ctrl-C does in a terminal.\n */\nexport type RepeatSignal = \"ignore\" | \"exit\";\n\n/**\n * A cooperative floor is the earliest time of the cooperative abort in the drain:\n * - `half`: half the cap of the drain. The work in flight gets half the drain at the least.\n * - `none`: no floor. A window of the whole cap or more aborts the work at the start of the drain.\n */\nexport type CooperativeFloor = \"half\" | \"none\";\n\n/** These exit codes replace the code 0 of a clean shutdown, by the trigger of the shutdown. */\nexport type ExitCodes = Readonly<Partial<Record<ExitTrigger, number>>>;\n\n/**\n * A message trigger is a message of the IPC channel that starts the shutdown, for the trigger\n * `ipc-message`. With `as`, the message is that exit signal: it has its exit code and the policy of a\n * repeat signal. Without `as`, the message is the trigger `ipc-message`.\n */\nexport interface MessageTrigger {\n /** This shape is the message that starts the shutdown, for example `\"shutdown\"`. */\n readonly match: MessageShape;\n /** This signal is the exit signal that the message replaces, for example `SIGTERM` on Windows. */\n readonly as?: ExitSignal | undefined;\n}\n\n/** A service description is the whole graph of a service, as data. */\nexport interface ServiceDescription {\n readonly format: typeof FORMAT;\n readonly name: string;\n /** This flag tells if a part joined after the start. That part starts tripped, and the export is partial. */\n readonly partial: boolean;\n readonly transports: readonly Transport[];\n readonly dependencies: readonly Dependency[];\n readonly controllers: readonly Controller[];\n readonly checks: readonly Check[];\n /**\n * These are the keyed limiters of the service, each with its key, its policy, its store and the\n * bound on its keys. Without a declaration, the service has no limiters.\n */\n readonly limiters?: readonly Limiter[] | undefined;\n readonly policies: {\n readonly readiness: Timing;\n readonly liveness: Timing;\n /** This duration is how long the service can take to start. The startup probe must agree with it. */\n readonly startup: Quantity;\n };\n readonly couplings: readonly Coupling[];\n readonly shutdown: {\n readonly phases: readonly Phase[];\n /** This window is how long before the end of the drain the cooperative abort occurs, or no bound. */\n readonly cooperativeWindow: Extent;\n /** This floor is the earliest time of the cooperative abort. Without a declaration, the floor is `half`. */\n readonly cooperativeFloor?: CooperativeFloor | undefined;\n /** This policy tells what a signal does while the shutdown runs. Each declaration gives it, because the runtime has no defaults. */\n readonly onRepeatSignal: RepeatSignal;\n /** These triggers start the shutdown, in addition to the exit signals. Each one is opt-in. */\n readonly triggers?: readonly ProcessTrigger[] | undefined;\n /** These messages of the IPC channel start the shutdown. The trigger `ipc-message` needs one at the least. */\n readonly messages?: readonly MessageTrigger[] | undefined;\n /** These codes replace the exit code 0 by the trigger. Without a code, a clean shutdown exits 0. */\n readonly exitCodes?: ExitCodes | undefined;\n };\n}\n"],"mappings":";;;;;;;AAaA,MAAa,SAAS"}
@@ -0,0 +1,35 @@
1
+ // src/drains.ts
2
+ const holds = /* @__PURE__ */ new WeakMap();
3
+ /** This function adds the hold of a drain under its lifecycle. It gives the function that removes the hold. */
4
+ const holdLate = (life, hold) => {
5
+ const set = holds.get(life) ?? /* @__PURE__ */ new Set();
6
+ holds.set(life, set);
7
+ set.add(hold);
8
+ return () => {
9
+ set.delete(hold);
10
+ };
11
+ };
12
+ /** This function gives the hold of each drain under a lifecycle, as it is at this time. */
13
+ const lateHolds = (life) => [...holds.get(life) ?? []].map((hold) => hold());
14
+ const owners = /* @__PURE__ */ new WeakMap();
15
+ const outside = /* @__PURE__ */ new WeakMap();
16
+ /** This function records the lifecycle that made a stream, and gives the stream. A stream keeps its first owner. */
17
+ const ownStream = (stream, life) => {
18
+ if (!owners.has(stream)) owners.set(stream, life);
19
+ return stream;
20
+ };
21
+ /** This function gives the lifecycle that made a stream, or null for a stream outside each lifecycle. */
22
+ const ownerOf = (stream) => owners.get(stream) ?? null;
23
+ /** This function adds the count of streams outside a lifecycle that a drain found open at its deadline. */
24
+ const noteOutside = (life, count) => {
25
+ if (count > 0) outside.set(life, (outside.get(life) ?? 0) + count);
26
+ };
27
+ /** This function gives the count of streams outside a lifecycle that its drains found, and sets the count to zero. */
28
+ const takeOutside = (life) => {
29
+ const count = outside.get(life) ?? 0;
30
+ outside.delete(life);
31
+ return count;
32
+ };
33
+ export { holdLate, lateHolds, noteOutside, ownStream, ownerOf, takeOutside };
34
+
35
+ //# sourceMappingURL=drains.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drains.js","names":[],"sources":["../src/drains.ts"],"sourcesContent":["// The holds of the drains after their deadline (SYS-29). A transport that waits after the deadline of\n// its drain gives its hold under its lifecycle. At the cap of the drain, the lifecycle reads each hold.\n// A drain that waits only for the bytes of its answers did its work, thus the phase does not fail.\n\n/** A late hold tells what holds the drain of a transport after its deadline. */\nexport interface LateHold {\n /** This count is the number of calls whose end did not come: their handler still runs. */\n readonly running: number;\n /** This count is the number of answers whose bytes did not go to the client, for example to a client that does not read. */\n readonly unflushed: number;\n}\n\nconst holds = new WeakMap<object, Set<() => LateHold>>();\n\n/** This function adds the hold of a drain under its lifecycle. It gives the function that removes the hold. */\nexport const holdLate = (life: object, hold: () => LateHold): (() => void) => {\n const set = holds.get(life) ?? new Set<() => LateHold>();\n holds.set(life, set);\n set.add(hold);\n return () => {\n set.delete(hold);\n };\n};\n\n/** This function gives the hold of each drain under a lifecycle, as it is at this time. */\nexport const lateHolds = (life: object): LateHold[] => [...(holds.get(life) ?? [])].map((hold) => hold());\n\n// The owner of each stream of a request: the lifecycle whose `life.request` made it. A drain waits only\n// for the streams of its own lifecycle, because only its cut ends them. A stream outside the lifecycle\n// does not hold a drain, as in 0.5.4. The drain only counts it, for the record of the phase.\nconst owners = new WeakMap<object, object>();\nconst outside = new WeakMap<object, number>();\n\n/** This function records the lifecycle that made a stream, and gives the stream. A stream keeps its first owner. */\nexport const ownStream = <T extends object>(stream: T, life: object): T => {\n if (!owners.has(stream)) owners.set(stream, life);\n return stream;\n};\n\n/** This function gives the lifecycle that made a stream, or null for a stream outside each lifecycle. */\nexport const ownerOf = (stream: object): object | null => owners.get(stream) ?? null;\n\n/** This function adds the count of streams outside a lifecycle that a drain found open at its deadline. */\nexport const noteOutside = (life: object, count: number): void => {\n if (count > 0) outside.set(life, (outside.get(life) ?? 0) + count);\n};\n\n/** This function gives the count of streams outside a lifecycle that its drains found, and sets the count to zero. */\nexport const takeOutside = (life: object): number => {\n const count = outside.get(life) ?? 0;\n outside.delete(life);\n return count;\n};\n"],"mappings":";AAYA,MAAM,wBAAQ,IAAI,QAAqC;;AAGvD,MAAa,YAAY,MAAc,SAAuC;CAC5E,MAAM,MAAM,MAAM,IAAI,IAAI,qBAAK,IAAI,IAAoB;CACvD,MAAM,IAAI,MAAM,GAAG;CACnB,IAAI,IAAI,IAAI;CACZ,aAAa;EACX,IAAI,OAAO,IAAI;CACjB;AACF;;AAGA,MAAa,aAAa,SAA6B,CAAC,GAAI,MAAM,IAAI,IAAI,KAAK,CAAC,CAAE,CAAC,CAAC,KAAK,SAAS,KAAK,CAAC;AAKxG,MAAM,yBAAS,IAAI,QAAwB;AAC3C,MAAM,0BAAU,IAAI,QAAwB;;AAG5C,MAAa,aAA+B,QAAW,SAAoB;CACzE,IAAI,CAAC,OAAO,IAAI,MAAM,GAAG,OAAO,IAAI,QAAQ,IAAI;CAChD,OAAO;AACT;;AAGA,MAAa,WAAW,WAAkC,OAAO,IAAI,MAAM,KAAK;;AAGhF,MAAa,eAAe,MAAc,UAAwB;CAChE,IAAI,QAAQ,GAAG,QAAQ,IAAI,OAAO,QAAQ,IAAI,IAAI,KAAK,KAAK,KAAK;AACnE;;AAGA,MAAa,eAAe,SAAyB;CACnD,MAAM,QAAQ,QAAQ,IAAI,IAAI,KAAK;CACnC,QAAQ,OAAO,IAAI;CACnB,OAAO;AACT"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A machine name names one machine of the runtime. Each machine has a document in `machines.ts`,
3
+ * which names the same states and events. The document of a client is with its client, for example
4
+ * `REDIS_CLIENT_MACHINE`.
5
+ */
6
+ export type MachineName = "gate" | "latch" | "window" | "poller" | "drain" | "exit" | "watchdog" | "client";
7
+ /**
8
+ * A lifecycle event is one transition of one machine of the runtime, on the monotonic clock. The
9
+ * runtime stamps each planned event: the gate, each phase of the drain, and the exit. Thus a
10
+ * window that a measurement times starts at the event.
11
+ */
12
+ export interface LifecycleEvent {
13
+ /** This time is when the transition occurred, in milliseconds on the monotonic clock. */
14
+ readonly at: number;
15
+ readonly machine: MachineName;
16
+ /** This name identifies one machine among others of its kind: a check, or the service. */
17
+ readonly instance: string;
18
+ readonly from: string;
19
+ readonly to: string;
20
+ readonly on: string;
21
+ /** This text gives more about the event, for example the cause of a failure. */
22
+ readonly detail?: string | undefined;
23
+ }
24
+ /** A recorder receives each lifecycle event. */
25
+ export type Recorder = (event: LifecycleEvent) => void;
@@ -0,0 +1,43 @@
1
+ import { Clock } from "./clock.js";
2
+ import { ExitSignal, ExitTrigger, ProcessPort, UncaughtOrigin } from "./process.js";
3
+ import { FakeClock, fakeClock } from "@mark1russell7/algebra/clock";
4
+ /** A fake process receives triggers from a test, and keeps each exit code in place of an exit. */
5
+ export interface FakeProcess extends ProcessPort {
6
+ /** This method sends a signal to each handler of it. */
7
+ signal(name: ExitSignal): void;
8
+ /** This method sends a trigger to each handler of it: a signal, or a process trigger, for example `stdin-close`. */
9
+ trigger(name: ExitTrigger): void;
10
+ /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */
11
+ message(value: unknown): void;
12
+ /** This method sends an error that no code caught to each handler of `onUncaught`. The default origin is `uncaughtException`. */
13
+ uncaught(error: unknown, origin?: UncaughtOrigin): void;
14
+ /** These are the exit codes, in sequence. A correct runtime exits one time. */
15
+ readonly exits: readonly number[];
16
+ /** This count is the number of handlers that are registered. */
17
+ readonly handlers: number;
18
+ /** These are the triggers that have a handler, in the sequence of their first handler. */
19
+ readonly triggers: readonly ExitTrigger[];
20
+ /** These are the times of the clock of the options at each flush and each exit, when the options give a clock. */
21
+ readonly log: readonly string[];
22
+ /** This count is the number of flushes of the output. */
23
+ readonly flushes: number;
24
+ /** This count is the number of holds of the process that are not released. */
25
+ readonly holds: number;
26
+ /** These counts are the holds that were not released at each exit, in sequence. */
27
+ readonly heldAtExit: readonly number[];
28
+ }
29
+ /** These options shape a fake process. */
30
+ export interface FakeProcessOptions {
31
+ /** This function is the flush of the output, for example a wait on a fake clock. Without it, a flush ends at once. */
32
+ readonly flush?: (() => Promise<void> | void) | undefined;
33
+ /** This clock stamps each line of the log. */
34
+ readonly clock?: Clock | undefined;
35
+ }
36
+ /** This function makes a fake process. */
37
+ export declare const fakeProcess: (options?: FakeProcessOptions) => FakeProcess;
38
+ /**
39
+ * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is
40
+ * `mulberry32` of @mark1russell7/rigor-generators.
41
+ */
42
+ export declare const seeded: (seed: number) => (() => number);
43
+ export { type FakeClock, fakeClock };
package/build/fakes.js ADDED
@@ -0,0 +1,93 @@
1
+ import { fakeClock } from "@mark1russell7/algebra/clock";
2
+ import { mulberry32 } from "@mark1russell7/rigor-generators";
3
+ // src/fakes.ts
4
+ /** This function makes a fake process. */
5
+ const fakeProcess = (options = {}) => {
6
+ const handlers = /* @__PURE__ */ new Map();
7
+ const uncaughtHandlers = /* @__PURE__ */ new Set();
8
+ const exits = [];
9
+ const log = [];
10
+ let flushes = 0;
11
+ let holds = 0;
12
+ const heldAtExit = [];
13
+ const stamp = (what) => {
14
+ log.push(options.clock === void 0 ? what : `${options.clock.now()} ${what}`);
15
+ };
16
+ const send = (name, message) => {
17
+ for (const handler of [...handlers.get(name) ?? []]) handler(message);
18
+ };
19
+ return {
20
+ on(trigger, handler) {
21
+ const set = handlers.get(trigger) ?? /* @__PURE__ */ new Set();
22
+ set.add(handler);
23
+ handlers.set(trigger, set);
24
+ return () => {
25
+ set.delete(handler);
26
+ };
27
+ },
28
+ onUncaught(handler) {
29
+ const own = (error, origin) => handler(error, origin);
30
+ uncaughtHandlers.add(own);
31
+ return () => {
32
+ uncaughtHandlers.delete(own);
33
+ };
34
+ },
35
+ async flush() {
36
+ stamp("flush");
37
+ await options.flush?.();
38
+ flushes += 1;
39
+ stamp("flushed");
40
+ },
41
+ hold() {
42
+ holds += 1;
43
+ let held = true;
44
+ return () => {
45
+ if (!held) return;
46
+ held = false;
47
+ holds -= 1;
48
+ };
49
+ },
50
+ exit(code) {
51
+ stamp(`exit ${code}`);
52
+ heldAtExit.push(holds);
53
+ exits.push(code);
54
+ },
55
+ signal: (name) => send(name),
56
+ trigger: (name) => send(name),
57
+ message: (value) => send("ipc-message", value),
58
+ uncaught: (error, origin = "uncaughtException") => {
59
+ for (const handler of [...uncaughtHandlers]) handler(error, origin);
60
+ },
61
+ get exits() {
62
+ return [...exits];
63
+ },
64
+ get handlers() {
65
+ let count = uncaughtHandlers.size;
66
+ for (const set of handlers.values()) count += set.size;
67
+ return count;
68
+ },
69
+ get triggers() {
70
+ return [...handlers.keys()];
71
+ },
72
+ get log() {
73
+ return [...log];
74
+ },
75
+ get flushes() {
76
+ return flushes;
77
+ },
78
+ get holds() {
79
+ return holds;
80
+ },
81
+ get heldAtExit() {
82
+ return [...heldAtExit];
83
+ }
84
+ };
85
+ };
86
+ /**
87
+ * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is
88
+ * `mulberry32` of @mark1russell7/rigor-generators.
89
+ */
90
+ const seeded = (seed) => mulberry32(seed);
91
+ export { fakeClock, fakeProcess, seeded };
92
+
93
+ //# sourceMappingURL=fakes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fakes.js","names":[],"sources":["../src/fakes.ts"],"sourcesContent":["// The fakes of the runtime for tests: a fake clock gives exact, repeatable timing, a seeded random\n// gives the same jitter on each run, and a fake process takes signals and keeps the exit codes.\n\nimport { mulberry32 } from \"@mark1russell7/rigor-generators\";\nimport type { Clock } from \"./clock.ts\";\nimport type { ExitSignal, ExitTrigger, ProcessPort, UncaughtOrigin } from \"./process.ts\";\n\n// the fake clock lives beside the clock, in @mark1russell7/algebra/clock\nexport type { FakeClock } from \"@mark1russell7/algebra/clock\";\nexport { fakeClock } from \"@mark1russell7/algebra/clock\";\n\n/** A fake process receives triggers from a test, and keeps each exit code in place of an exit. */\nexport interface FakeProcess extends ProcessPort {\n /** This method sends a signal to each handler of it. */\n signal(name: ExitSignal): void;\n /** This method sends a trigger to each handler of it: a signal, or a process trigger, for example `stdin-close`. */\n trigger(name: ExitTrigger): void;\n /** This method sends a message of the IPC channel to each handler of the trigger `ipc-message`. */\n message(value: unknown): void;\n /** This method sends an error that no code caught to each handler of `onUncaught`. The default origin is `uncaughtException`. */\n uncaught(error: unknown, origin?: UncaughtOrigin): void;\n /** These are the exit codes, in sequence. A correct runtime exits one time. */\n readonly exits: readonly number[];\n /** This count is the number of handlers that are registered. */\n readonly handlers: number;\n /** These are the triggers that have a handler, in the sequence of their first handler. */\n readonly triggers: readonly ExitTrigger[];\n /** These are the times of the clock of the options at each flush and each exit, when the options give a clock. */\n readonly log: readonly string[];\n /** This count is the number of flushes of the output. */\n readonly flushes: number;\n /** This count is the number of holds of the process that are not released. */\n readonly holds: number;\n /** These counts are the holds that were not released at each exit, in sequence. */\n readonly heldAtExit: readonly number[];\n}\n\n/** These options shape a fake process. */\nexport interface FakeProcessOptions {\n /** This function is the flush of the output, for example a wait on a fake clock. Without it, a flush ends at once. */\n readonly flush?: (() => Promise<void> | void) | undefined;\n /** This clock stamps each line of the log. */\n readonly clock?: Clock | undefined;\n}\n\n/** This function makes a fake process. */\nexport const fakeProcess = (options: FakeProcessOptions = {}): FakeProcess => {\n const handlers = new Map<ExitTrigger, Set<(message?: unknown) => void>>();\n const uncaughtHandlers = new Set<(error: unknown, origin: UncaughtOrigin) => void>();\n const exits: number[] = [];\n const log: string[] = [];\n let flushes = 0;\n let holds = 0;\n const heldAtExit: number[] = [];\n const stamp = (what: string): void => {\n log.push(options.clock === undefined ? what : `${options.clock.now()} ${what}`);\n };\n const send = (name: ExitTrigger, message?: unknown): void => {\n for (const handler of [...(handlers.get(name) ?? [])]) handler(message);\n };\n return {\n on(trigger, handler) {\n const set = handlers.get(trigger) ?? new Set();\n set.add(handler);\n handlers.set(trigger, set);\n return () => {\n set.delete(handler);\n };\n },\n onUncaught(handler) {\n // each registration is a handler of its own, as with `on`\n const own = (error: unknown, origin: UncaughtOrigin): void => handler(error, origin);\n uncaughtHandlers.add(own);\n return () => {\n uncaughtHandlers.delete(own);\n };\n },\n async flush() {\n stamp(\"flush\");\n await options.flush?.();\n flushes += 1;\n stamp(\"flushed\");\n },\n hold() {\n holds += 1;\n let held = true;\n return () => {\n if (!held) return;\n held = false;\n holds -= 1;\n };\n },\n exit(code) {\n stamp(`exit ${code}`);\n heldAtExit.push(holds);\n exits.push(code);\n },\n signal: (name) => send(name),\n trigger: (name) => send(name),\n message: (value) => send(\"ipc-message\", value),\n uncaught: (error, origin = \"uncaughtException\") => {\n for (const handler of [...uncaughtHandlers]) handler(error, origin);\n },\n get exits() {\n return [...exits];\n },\n get handlers() {\n let count = uncaughtHandlers.size;\n for (const set of handlers.values()) count += set.size;\n return count;\n },\n get triggers() {\n return [...handlers.keys()];\n },\n get log() {\n return [...log];\n },\n get flushes() {\n return flushes;\n },\n get holds() {\n return holds;\n },\n get heldAtExit() {\n return [...heldAtExit];\n },\n };\n};\n\n/**\n * This function gives a seeded random number generator (mulberry32), with numbers in [0, 1). It is\n * `mulberry32` of @mark1russell7/rigor-generators.\n */\nexport const seeded = (seed: number): (() => number) => mulberry32(seed);\n"],"mappings":";;;;AA8CA,MAAa,eAAe,UAA8B,CAAC,MAAmB;CAC5E,MAAM,2BAAW,IAAI,IAAmD;CACxE,MAAM,mCAAmB,IAAI,IAAsD;CACnF,MAAM,QAAkB,CAAC;CACzB,MAAM,MAAgB,CAAC;CACvB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