@mark1russell7/service 0.8.18 → 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 (332) hide show
  1. package/README.md +19 -0
  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/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  9. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  10. package/build/client/core.js.map +1 -0
  11. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  12. package/build/client/dial.js +52 -0
  13. package/build/client/dial.js.map +1 -0
  14. package/build/client/machine.js +29 -0
  15. package/build/client/machine.js.map +1 -0
  16. package/build/client/meets.d.ts +35 -0
  17. package/build/client/meets.js +78 -0
  18. package/build/client/meets.js.map +1 -0
  19. package/build/clock.d.ts +1 -1
  20. package/build/conformance.d.ts +122 -0
  21. package/build/conformance.js +470 -0
  22. package/build/conformance.js.map +1 -0
  23. package/build/contract.d.ts +28 -0
  24. package/build/contract.js +184 -0
  25. package/build/contract.js.map +1 -0
  26. package/build/description.d.ts +161 -0
  27. package/build/description.js +11 -0
  28. package/build/description.js.map +1 -0
  29. package/build/drains.js +35 -0
  30. package/build/drains.js.map +1 -0
  31. package/build/events.d.ts +25 -0
  32. package/build/fakes.d.ts +43 -0
  33. package/build/fakes.js +93 -0
  34. package/build/fakes.js.map +1 -0
  35. package/build/grpc/client.d.ts +153 -0
  36. package/build/grpc/client.js +474 -0
  37. package/build/grpc/client.js.map +1 -0
  38. package/build/grpc/connection.d.ts +97 -0
  39. package/build/grpc/connection.js +59 -0
  40. package/build/grpc/connection.js.map +1 -0
  41. package/build/grpc/machine.d.ts +12 -0
  42. package/build/grpc/machine.js +149 -0
  43. package/build/grpc/machine.js.map +1 -0
  44. package/build/grpc/meets.d.ts +14 -0
  45. package/build/grpc/meets.js +105 -0
  46. package/build/grpc/meets.js.map +1 -0
  47. package/build/grpc/starting.d.ts +33 -0
  48. package/build/grpc/starting.js +89 -0
  49. package/build/grpc/starting.js.map +1 -0
  50. package/build/grpc.d.ts +9 -303
  51. package/build/grpc.js +7 -854
  52. package/build/health.d.ts +93 -0
  53. package/build/health.js +223 -0
  54. package/build/health.js.map +1 -0
  55. package/build/heartbeat.d.ts +1 -1
  56. package/build/host/discovery.d.ts +61 -0
  57. package/build/host/discovery.js +113 -0
  58. package/build/host/discovery.js.map +1 -0
  59. package/build/host/env.d.ts +14 -0
  60. package/build/host/env.js +57 -0
  61. package/build/host/env.js.map +1 -0
  62. package/build/host/fakes.d.ts +82 -0
  63. package/build/host/fakes.js +239 -0
  64. package/build/host/fakes.js.map +1 -0
  65. package/build/host/group.d.ts +142 -0
  66. package/build/host/group.js +517 -0
  67. package/build/host/group.js.map +1 -0
  68. package/build/host/install.d.ts +96 -0
  69. package/build/host/install.js +330 -0
  70. package/build/host/install.js.map +1 -0
  71. package/build/host/lock.d.ts +78 -0
  72. package/build/host/lock.js +190 -0
  73. package/build/host/lock.js.map +1 -0
  74. package/build/host/logs.d.ts +26 -0
  75. package/build/host/logs.js +48 -0
  76. package/build/host/logs.js.map +1 -0
  77. package/build/host/node.d.ts +14 -0
  78. package/build/host/node.js +309 -0
  79. package/build/host/node.js.map +1 -0
  80. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  81. package/build/host/ports.js +17 -0
  82. package/build/host/ports.js.map +1 -0
  83. package/build/host/probes.d.ts +51 -0
  84. package/build/host/probes.js +139 -0
  85. package/build/host/probes.js.map +1 -0
  86. package/build/host/processes.d.ts +32 -0
  87. package/build/host/processes.js +63 -0
  88. package/build/host/processes.js.map +1 -0
  89. package/build/host/render.d.ts +84 -0
  90. package/build/host/render.js +235 -0
  91. package/build/host/render.js.map +1 -0
  92. package/build/host/watch.d.ts +90 -0
  93. package/build/host/watch.js +165 -0
  94. package/build/host/watch.js.map +1 -0
  95. package/build/host.d.ts +13 -671
  96. package/build/host.js +12 -2126
  97. package/build/http/answers.js +29 -0
  98. package/build/http/answers.js.map +1 -0
  99. package/build/http/fake-server.js +61 -0
  100. package/build/http/fake-server.js.map +1 -0
  101. package/build/http/outcome.d.ts +115 -0
  102. package/build/http/outcome.js +325 -0
  103. package/build/http/outcome.js.map +1 -0
  104. package/build/http/probes.d.ts +83 -0
  105. package/build/http/probes.js +232 -0
  106. package/build/http/probes.js.map +1 -0
  107. package/build/http/transport.d.ts +165 -0
  108. package/build/http/transport.js +517 -0
  109. package/build/http/transport.js.map +1 -0
  110. package/build/http-client/client.d.ts +121 -0
  111. package/build/http-client/client.js +330 -0
  112. package/build/http-client/client.js.map +1 -0
  113. package/build/http-client/connection.d.ts +78 -0
  114. package/build/http-client/connection.js +54 -0
  115. package/build/http-client/connection.js.map +1 -0
  116. package/build/http-client/machine.d.ts +14 -0
  117. package/build/http-client/machine.js +109 -0
  118. package/build/http-client/machine.js.map +1 -0
  119. package/build/http-client/meets.d.ts +11 -0
  120. package/build/http-client/meets.js +74 -0
  121. package/build/http-client/meets.js.map +1 -0
  122. package/build/http-client/session.d.ts +87 -0
  123. package/build/http-client/session.js +99 -0
  124. package/build/http-client/session.js.map +1 -0
  125. package/build/http-client/starting.d.ts +25 -0
  126. package/build/http-client/starting.js +65 -0
  127. package/build/http-client/starting.js.map +1 -0
  128. package/build/http-client.d.ts +9 -330
  129. package/build/http-client.js +8 -707
  130. package/build/http.d.ts +5 -353
  131. package/build/http.js +3 -1086
  132. package/build/identity.d.ts +16 -0
  133. package/build/identity.js +44 -0
  134. package/build/identity.js.map +1 -0
  135. package/build/index.d.ts +35 -412
  136. package/build/index.js +24 -3277
  137. package/build/knobs.d.ts +1 -0
  138. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  139. package/build/knobs.js.map +1 -0
  140. package/build/latch.d.ts +29 -0
  141. package/build/latch.js +122 -0
  142. package/build/latch.js.map +1 -0
  143. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  144. package/build/law.js +149 -0
  145. package/build/law.js.map +1 -0
  146. package/build/lifecycle.d.ts +144 -0
  147. package/build/lifecycle.js +411 -0
  148. package/build/lifecycle.js.map +1 -0
  149. package/build/limiter/machine.d.ts +40 -0
  150. package/build/limiter/machine.js +279 -0
  151. package/build/limiter/machine.js.map +1 -0
  152. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  153. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  154. package/build/limiter/policy.js.map +1 -0
  155. package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
  156. package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
  157. package/build/limiter/quota.js.map +1 -0
  158. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  159. package/build/limiter/store.js +145 -0
  160. package/build/limiter/store.js.map +1 -0
  161. package/build/limiter.d.ts +4 -3
  162. package/build/limiter.js +4 -2
  163. package/build/lint.d.ts +152 -0
  164. package/build/lint.js +576 -0
  165. package/build/lint.js.map +1 -0
  166. package/build/logger.d.ts +71 -0
  167. package/build/logger.js +183 -0
  168. package/build/logger.js.map +1 -0
  169. package/build/machines.d.ts +41 -0
  170. package/build/machines.js +451 -0
  171. package/build/machines.js.map +1 -0
  172. package/build/metrics.d.ts +53 -0
  173. package/build/metrics.js +111 -0
  174. package/build/metrics.js.map +1 -0
  175. package/build/mongodb/client.d.ts +131 -0
  176. package/build/mongodb/client.js +388 -0
  177. package/build/mongodb/client.js.map +1 -0
  178. package/build/mongodb/connection.d.ts +112 -0
  179. package/build/mongodb/connection.js +12 -0
  180. package/build/mongodb/connection.js.map +1 -0
  181. package/build/mongodb/machine.d.ts +14 -0
  182. package/build/mongodb/machine.js +122 -0
  183. package/build/mongodb/machine.js.map +1 -0
  184. package/build/mongodb/meets.d.ts +15 -0
  185. package/build/mongodb/meets.js +103 -0
  186. package/build/mongodb/meets.js.map +1 -0
  187. package/build/mongodb/starting.d.ts +29 -0
  188. package/build/mongodb/starting.js +77 -0
  189. package/build/mongodb/starting.js.map +1 -0
  190. package/build/mongodb.d.ts +8 -296
  191. package/build/mongodb.js +7 -682
  192. package/build/operation.d.ts +27 -0
  193. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  194. package/build/operation.js.map +1 -0
  195. package/build/otel.d.ts +2 -2
  196. package/build/pg/client.d.ts +96 -0
  197. package/build/pg/client.js +277 -0
  198. package/build/pg/client.js.map +1 -0
  199. package/build/pg/connection.d.ts +75 -0
  200. package/build/pg/connection.js +11 -0
  201. package/build/pg/connection.js.map +1 -0
  202. package/build/pg/machine.d.ts +13 -0
  203. package/build/pg/machine.js +111 -0
  204. package/build/pg/machine.js.map +1 -0
  205. package/build/pg/meets.d.ts +14 -0
  206. package/build/pg/meets.js +83 -0
  207. package/build/pg/meets.js.map +1 -0
  208. package/build/pg/starting.d.ts +26 -0
  209. package/build/pg/starting.js +62 -0
  210. package/build/pg/starting.js.map +1 -0
  211. package/build/pg.d.ts +8 -219
  212. package/build/pg.js +7 -525
  213. package/build/poller.d.ts +9 -0
  214. package/build/poller.js +152 -0
  215. package/build/poller.js.map +1 -0
  216. package/build/process.d.ts +114 -0
  217. package/build/process.js +170 -0
  218. package/build/process.js.map +1 -0
  219. package/build/profiles.d.ts +68 -0
  220. package/build/profiles.js +120 -0
  221. package/build/profiles.js.map +1 -0
  222. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  223. package/build/queue.js +279 -0
  224. package/build/queue.js.map +1 -0
  225. package/build/rabbitmq/client.d.ts +144 -0
  226. package/build/rabbitmq/client.js +426 -0
  227. package/build/rabbitmq/client.js.map +1 -0
  228. package/build/rabbitmq/connection.d.ts +91 -0
  229. package/build/rabbitmq/connection.js +15 -0
  230. package/build/rabbitmq/connection.js.map +1 -0
  231. package/build/rabbitmq/machine.d.ts +13 -0
  232. package/build/rabbitmq/machine.js +159 -0
  233. package/build/rabbitmq/machine.js.map +1 -0
  234. package/build/rabbitmq/meets.d.ts +12 -0
  235. package/build/rabbitmq/meets.js +96 -0
  236. package/build/rabbitmq/meets.js.map +1 -0
  237. package/build/rabbitmq/starting.d.ts +27 -0
  238. package/build/rabbitmq/starting.js +67 -0
  239. package/build/rabbitmq/starting.js.map +1 -0
  240. package/build/rabbitmq.d.ts +8 -283
  241. package/build/rabbitmq.js +7 -742
  242. package/build/redis/client.d.ts +86 -0
  243. package/build/redis/client.js +285 -0
  244. package/build/redis/client.js.map +1 -0
  245. package/build/redis/connection.d.ts +57 -0
  246. package/build/redis/connection.js +11 -0
  247. package/build/redis/connection.js.map +1 -0
  248. package/build/redis/limiter.d.ts +43 -0
  249. package/build/redis/limiter.js +164 -0
  250. package/build/redis/limiter.js.map +1 -0
  251. package/build/redis/machine.d.ts +12 -0
  252. package/build/redis/machine.js +144 -0
  253. package/build/redis/machine.js.map +1 -0
  254. package/build/redis/meets.d.ts +11 -0
  255. package/build/redis/meets.js +75 -0
  256. package/build/redis/meets.js.map +1 -0
  257. package/build/redis/operations.d.ts +5 -0
  258. package/build/redis/operations.js +114 -0
  259. package/build/redis/operations.js.map +1 -0
  260. package/build/redis.d.ts +10 -207
  261. package/build/redis.js +9 -771
  262. package/build/requests.d.ts +66 -0
  263. package/build/requests.js +279 -0
  264. package/build/requests.js.map +1 -0
  265. package/build/retrier.d.ts +62 -0
  266. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  267. package/build/retrier.js.map +1 -0
  268. package/build/routes.d.ts +35 -0
  269. package/build/routes.js +77 -0
  270. package/build/routes.js.map +1 -0
  271. package/build/rules.d.ts +19 -2
  272. package/build/stops.d.ts +51 -0
  273. package/build/stops.js +86 -0
  274. package/build/stops.js.map +1 -0
  275. package/build/testing.d.ts +8 -270
  276. package/build/testing.js +4 -1027
  277. package/build/testing.js.map +1 -1
  278. package/build/timing.d.ts +63 -0
  279. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  280. package/build/timing.js.map +1 -0
  281. package/build/units.d.ts +17 -0
  282. package/build/units.js +236 -0
  283. package/build/units.js.map +1 -0
  284. package/build/watchdog.d.ts +34 -0
  285. package/build/watchdog.js +53 -0
  286. package/build/watchdog.js.map +1 -0
  287. package/build/websocket/client.d.ts +136 -0
  288. package/build/websocket/client.js +422 -0
  289. package/build/websocket/client.js.map +1 -0
  290. package/build/websocket/connection.d.ts +83 -0
  291. package/build/websocket/connection.js +57 -0
  292. package/build/websocket/connection.js.map +1 -0
  293. package/build/websocket/machine.d.ts +12 -0
  294. package/build/websocket/machine.js +155 -0
  295. package/build/websocket/machine.js.map +1 -0
  296. package/build/websocket/meets.d.ts +14 -0
  297. package/build/websocket/meets.js +92 -0
  298. package/build/websocket/meets.js.map +1 -0
  299. package/build/websocket/starting.d.ts +25 -0
  300. package/build/websocket/starting.js +69 -0
  301. package/build/websocket/starting.js.map +1 -0
  302. package/build/websocket.d.ts +9 -264
  303. package/build/websocket.js +8 -774
  304. package/build/worker.d.ts +92 -0
  305. package/build/worker.js +153 -0
  306. package/build/worker.js.map +1 -0
  307. package/package.json +4 -3
  308. package/build/backoff-QTRGfkEK.d.ts +0 -45
  309. package/build/clock-DpVgpY4h.d.ts +0 -2
  310. package/build/grpc.js.map +0 -1
  311. package/build/host.js.map +0 -1
  312. package/build/http-client.js.map +0 -1
  313. package/build/http.js.map +0 -1
  314. package/build/index.js.map +0 -1
  315. package/build/knobs-BJcz6m01.js.map +0 -1
  316. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  317. package/build/limiter-Bgy6Gmvl.js.map +0 -1
  318. package/build/logger-B6drv9w0.d.ts +0 -488
  319. package/build/machine-BhVeHr_m.js.map +0 -1
  320. package/build/mongodb.js.map +0 -1
  321. package/build/operation-DF73RZOI.js.map +0 -1
  322. package/build/pg.js.map +0 -1
  323. package/build/policy-UYALkqVq.js.map +0 -1
  324. package/build/process-7R9M29wN.js +0 -437
  325. package/build/process-7R9M29wN.js.map +0 -1
  326. package/build/rabbitmq.js.map +0 -1
  327. package/build/redis.js.map +0 -1
  328. package/build/requests-DD2ALv0_.js +0 -583
  329. package/build/requests-DD2ALv0_.js.map +0 -1
  330. package/build/retrier-Dnjhvxol.js.map +0 -1
  331. package/build/timing-DZl36uXs.js.map +0 -1
  332. package/build/websocket.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"units.js","names":[],"sources":["../src/units.ts"],"sourcesContent":["// The units of work of a worker loop and of a queue drain: the count of the units in flight, the\n// drain to a deadline with the cooperative abort, the sleeps on the clock, the bound of each unit,\n// and the request tracking of the service for each unit.\n\nimport type { Backoff } from \"./backoff.ts\";\nimport { backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { ServiceDescription } from \"./description.ts\";\nimport type { KnobRecord } from \"./knobs.ts\";\nimport { boundedMillisecondsOf } from \"./knobs.ts\";\nimport type { Lifecycle } from \"./lifecycle.ts\";\nimport type { RequestEnd } from \"./requests.ts\";\n\n/**\n * A unit request names the route of each unit of work in the request tracking of the service. Then\n * the service admits, counts, drains and cuts each unit as it does each request (`life.request`).\n * The controller declares the route, thus its idempotency tells if a cut unit can go again.\n */\nexport interface UnitRequest<U> {\n /** This name is the controller that declares the route. */\n readonly controller: string;\n /** This name is the route of each unit, or a function that gives it from the unit. A route can match a route pattern. */\n readonly route: string | ((unit: U) => string);\n /** This function gives the detail of a unit, for the function of a route pattern. */\n readonly detail?: ((unit: U) => unknown) | undefined;\n}\n\n/**\n * A unit end tells how one unit of work ended:\n * - `done`: the work gave its value.\n * - `failed`: the work threw for a cause of its own, or after its bound aborted it.\n * - `refused`: the service did not admit the unit, thus the work did not start.\n * - `cut`: the shutdown stopped the unit. It is not a failure. `retryable` tells if the unit can go again.\n */\nexport type UnitEnd =\n | { readonly kind: \"done\"; readonly value: unknown }\n | { readonly kind: \"failed\"; readonly error: unknown }\n | { readonly kind: \"refused\"; readonly cause: string }\n | { readonly kind: \"cut\"; readonly cause: string; readonly retryable: boolean };\n\n/** This function gives the cause of an abort as text. */\nexport const causeOf = (signal: AbortSignal): string =>\n signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? \"the unit got an abort\");\n\n/** These are the parts of one unit of work. */\nexport interface UnitRun<U> {\n readonly clock: Clock;\n /** This time is the bound of the unit, in milliseconds, or infinity. At it, the signal of the work aborts. */\n readonly bound: number;\n /** This controller is the abort of the transport for the unit: the cooperative abort and the close. */\n readonly abort: AbortController;\n readonly life: Lifecycle;\n readonly request: UnitRequest<U> | undefined;\n readonly unit: U;\n /** This function starts the work, and gives its value or a promise. */\n readonly work: (signal: AbortSignal) => unknown;\n}\n\n/**\n * This function does one unit of work, and gives its end. With a request, the unit goes through\n * `life.request`, thus the service counts it, drains it and can cut it. A throw after the abort of\n * the transport is a cut, not a failure (S6 A10). A throw after the bound is a failure.\n */\nexport const runUnit = async <U>(run: UnitRun<U>): Promise<UnitEnd> => {\n const { clock, bound, abort, life, request, unit, work } = run;\n const timeout = new AbortController();\n const cancel: Cancel = Number.isFinite(bound)\n ? clock.after(bound, () => timeout.abort(new Error(`the unit did not end in its unit_processing_time of ${bound} ms`)))\n : () => {};\n const call = async (tracker?: AbortSignal): Promise<unknown> =>\n work(AbortSignal.any(tracker === undefined ? [abort.signal, timeout.signal] : [abort.signal, timeout.signal, tracker]));\n // the transport cannot read the idempotency of the route, thus a cut of its own does not go again\n const thrown = (error: unknown): UnitEnd => {\n if (abort.signal.aborted) return { kind: \"cut\", cause: causeOf(abort.signal), retryable: false };\n if (timeout.signal.aborted) return { kind: \"failed\", error: timeout.signal.reason };\n return { kind: \"failed\", error };\n };\n try {\n if (request === undefined) {\n try {\n return { kind: \"done\", value: await call() };\n } catch (error) {\n return thrown(error);\n }\n }\n let collected: Promise<{ readonly items: readonly unknown[]; readonly end: RequestEnd }>;\n try {\n const route = typeof request.route === \"string\" ? request.route : request.route(unit);\n const detail = request.detail?.(unit);\n // the value goes in a box: a work that gives an async iterable is one value here, not a stream\n const stream = life.request(request.controller, route, (signal) => call(signal).then((value) => ({ value })), detail === undefined ? {} : { detail });\n collected = stream.collect();\n } catch (error) {\n // an undeclared route, or a lifecycle with no service\n return { kind: \"failed\", error };\n }\n const { items, end } = await collected;\n if (end.kind === \"done\") return { kind: \"done\", value: (items[0] as { readonly value: unknown } | undefined)?.value };\n if (end.kind === \"failed\") return thrown(end.error);\n if (end.kind === \"refused\") return { kind: \"refused\", cause: end.cause };\n return { kind: \"cut\", cause: end.cause, retryable: end.retryable };\n } finally {\n cancel();\n }\n};\n\n/** A flight set counts the units in flight, from their events, and drains them to a deadline. */\nexport interface Flights {\n /** This count is the number of units in flight. */\n readonly size: number;\n /** This method adds a unit, and gives the function that removes it. A unit after the cooperative abort gets the abort at once. */\n add(unit: AbortController): () => void;\n /** This method aborts each unit in flight and each later unit: the cooperative abort, or the close. */\n abort(reason: unknown): void;\n /** This method removes each unit from the count: the close cuts them. */\n clear(): void;\n /** This method waits until no unit is in flight, or until the deadline. The signal is the cooperative abort. It does not throw. */\n drain(deadline: number, signal: AbortSignal): Promise<void>;\n /** This method gives a promise that ends when the count goes down, or at `release()`. */\n less(): Promise<void>;\n /** This method ends each promise of `less()`. */\n release(): void;\n}\n\n/** This function makes a flight set on a clock. */\nexport const flights = (clock: Clock): Flights => {\n const units = new Set<AbortController>();\n const idle = new Set<() => void>();\n const lower = new Set<() => void>();\n let aborted: { readonly reason: unknown } | null = null;\n const settle = (): void => {\n for (const done of [...lower]) done();\n lower.clear();\n if (units.size === 0) for (const done of [...idle]) done();\n };\n const abort = (reason: unknown): void => {\n aborted ??= { reason };\n for (const unit of [...units]) if (!unit.signal.aborted) unit.abort(aborted.reason);\n };\n return {\n get size() {\n return units.size;\n },\n add(unit) {\n units.add(unit);\n if (aborted !== null && !unit.signal.aborted) unit.abort(aborted.reason);\n return () => {\n if (units.delete(unit)) settle();\n };\n },\n abort,\n clear() {\n units.clear();\n settle();\n },\n drain(deadline, signal) {\n const cooperative = (): void => abort(signal.reason);\n if (signal.aborted) cooperative();\n else signal.addEventListener(\"abort\", cooperative, { once: true });\n // nothing in flight, or a deadline that passed: the drain ends at once, with no timer\n if (units.size === 0 || deadline <= clock.now()) {\n signal.removeEventListener(\"abort\", cooperative);\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n const done = (): void => {\n idle.delete(done);\n cancel();\n signal.removeEventListener(\"abort\", cooperative);\n resolve();\n };\n idle.add(done);\n cancel = clock.after(Math.max(0, deadline - clock.now()), done);\n });\n },\n less() {\n return new Promise<void>((resolve) => lower.add(resolve));\n },\n release() {\n for (const done of [...lower]) done();\n lower.clear();\n },\n };\n};\n\n/**\n * A sleeper gives the waits of a loop on the clock. `wake()` ends each wait that it can end, and\n * `stop()` ends each wait. A wait without a bound uses no timer.\n */\nexport interface Sleeper {\n /** This count goes up at each `wake()`. A loop reads it before a unit, and a wake during the unit then ends the next sleep at once. */\n readonly wakes: number;\n /** This method waits on the clock. A wake after `since` ends it, and with `since` past, it ends at once. */\n sleep(ms: number, since: number): Promise<void>;\n /** This method waits on the clock. A wake does not end it: it is a backoff after a failure. */\n backoff(ms: number): Promise<void>;\n /** This method ends each sleep, and gives the count of sleeps that it ended. */\n wake(): number;\n /** This method ends each wait, the backoffs too. Each later wait then ends at once. */\n stop(): void;\n}\n\n/** This function makes a sleeper on a clock. */\nexport const sleeper = (clock: Clock): Sleeper => {\n let wakes = 0;\n let stopped = false;\n const sleeps = new Set<() => void>();\n const backoffs = new Set<() => void>();\n const wait = (ms: number, into: Set<() => void>): Promise<void> =>\n stopped\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n let cancel: Cancel = () => {};\n const done = (): void => {\n if (!into.delete(done)) return;\n cancel();\n resolve();\n };\n into.add(done);\n if (Number.isFinite(ms)) cancel = clock.after(ms, done);\n });\n return {\n get wakes() {\n return wakes;\n },\n sleep(ms, since) {\n if (since !== wakes) return Promise.resolve();\n return wait(ms, sleeps);\n },\n backoff(ms) {\n return wait(ms, backoffs);\n },\n wake() {\n wakes += 1;\n const ended = sleeps.size;\n for (const done of [...sleeps]) done();\n return ended;\n },\n stop() {\n stopped = true;\n for (const done of [...sleeps, ...backoffs]) done();\n },\n };\n};\n\n/** A settled wait tells how a work ended in its bound: it ended, it threw, or the bound came first. */\nexport type Settled = { readonly kind: \"done\" } | { readonly kind: \"failed\"; readonly error: unknown } | { readonly kind: \"bound\" };\n\n/** This function waits for a work until a bound on the clock, in milliseconds. */\nexport const settleWithin = (clock: Clock, ms: number, work: Promise<unknown>): Promise<Settled> =>\n new Promise<Settled>((resolve) => {\n const cancel: Cancel = Number.isFinite(ms) ? clock.after(ms, () => resolve({ kind: \"bound\" })) : () => {};\n work.then(\n () => {\n cancel();\n resolve({ kind: \"done\" });\n },\n (error: unknown) => {\n cancel();\n resolve({ kind: \"failed\", error });\n },\n );\n });\n\n/**\n * This function gives the value of a promise, or `stop` when the signal aborts first. Each wait adds\n * its own listener, and removes it when the promise settles. A race against one pending promise\n * keeps each settled value until that promise ends.\n */\nexport const untilAbort = <T, S>(promise: Promise<T>, signal: AbortSignal, stop: S): Promise<T | S> => {\n // A promise that settled before the abort still comes first, as in a race.\n if (signal.aborted) return Promise.race([promise, Promise.resolve(stop)]);\n return new Promise<T | S>((resolve, reject) => {\n const onAbort = (): void => resolve(stop);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(value);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n });\n};\n\n/**\n * This function gives the backoff of the knobs of a loop. The first delay is `retry_base`, and each\n * delay is two times longer, up to `retry_cap`. Each delay has a jitter up to the base, as in the Redis client.\n */\nexport const retryOf = (knobs: KnobRecord, owner: string): Backoff => {\n const base = boundedMillisecondsOf(knobs, \"retry_base\", owner);\n const cap = boundedMillisecondsOf(knobs, \"retry_cap\", owner);\n const backoff: Backoff = { base, factor: 2, cap, jitter: { kind: \"add\", amount: base } };\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`${owner}: the retry_base and retry_cap give no backoff: ${problems.join(\", \")}`);\n return backoff;\n};\n\n/**\n * This function gives the problems of a loop in a declaration: each phase that the loop needs and\n * that the declaration does not give. A loop closes in `close transports`, and it ends its units in\n * `drain`. `lint()` compares the bounds with the caps of the phases (`BOUND_RULES`, S6 A10).\n */\nexport const boundProblems = (owner: string, description: ServiceDescription): string[] => {\n const has = (name: string): boolean => description.shutdown.phases.some((each) => each.name === name);\n return [\n ...(has(\"close transports\") ? [] : [`${owner} needs the phase \"close transports\" to close`]),\n ...(has(\"drain\") ? [] : [`${owner} needs the phase \"drain\" to end its units`]),\n ];\n};\n"],"mappings":";;;;AAyCA,MAAa,WAAW,WACtB,OAAO,kBAAkB,QAAQ,OAAO,OAAO,UAAU,OAAO,OAAO,UAAU,uBAAuB;;;;;;AAqB1G,MAAa,UAAU,OAAU,QAAsC;CACrE,MAAM,EAAE,OAAO,OAAO,OAAO,MAAM,SAAS,MAAM,SAAS;CAC3D,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,SAAiB,OAAO,SAAS,KAAK,IACxC,MAAM,MAAM,aAAa,QAAQ,sBAAM,IAAI,MAAM,uDAAuD,MAAM,IAAI,CAAC,CAAC,UAC9G,CAAC;CACX,MAAM,OAAO,OAAO,YAClB,KAAK,YAAY,IAAI,YAAY,KAAA,IAAY,CAAC,MAAM,QAAQ,QAAQ,MAAM,IAAI;EAAC,MAAM;EAAQ,QAAQ;EAAQ;CAAO,CAAC,CAAC;CAExH,MAAM,UAAU,UAA4B;EAC1C,IAAI,MAAM,OAAO,SAAS,OAAO;GAAE,MAAM;GAAO,OAAO,QAAQ,MAAM,MAAM;GAAG,WAAW;EAAM;EAC/F,IAAI,QAAQ,OAAO,SAAS,OAAO;GAAE,MAAM;GA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K,CAAC,SAAS,QAAQ,QAAQ,IAAI,CAAC,CAAC;CACxE,OAAO,IAAI,SAAgB,SAAS,WAAW;EAC7C,MAAM,gBAAsB,QAAQ,IAAI;EACxC,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACxD,QAAQ,MACL,UAAU;GACT,OAAO,oBAAoB,SAAS,OAAO;GAC3C,QAAQ,KAAK;EACf,IACC,UAAmB;GAClB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,OAAO,KAAK;EACd,CACF;CACF,CAAC;AACH;;;;;AAMA,MAAa,WAAW,OAAmB,UAA2B;CACpE,MAAM,OAAO,sBAAsB,OAAO,cAAc,KAAK;CAE7D,MAAM,UAAmB;EAAE;EAAM,QAAQ;EAAG,KADhC,sBAAsB,OAAO,aAAa,KACR;EAAG,QAAQ;GAAE,MAAM;GAAO,QAAQ;EAAK;CAAE;CACvF,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,GAAG,MAAM,kDAAkD,SAAS,KAAK,IAAI,GAAG;CACzH,OAAO;AACT;;;;;;AAOA,MAAa,iBAAiB,OAAe,gBAA8C;CACzF,MAAM,OAAO,SAA0B,YAAY,SAAS,OAAO,MAAM,SAAS,KAAK,SAAS,IAAI;CACpG,OAAO,CACL,GAAI,IAAI,kBAAkB,IAAI,CAAC,IAAI,CAAC,GAAG,MAAM,6CAA6C,GAC1F,GAAI,IAAI,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,MAAM,0CAA0C,CAC9E;AACF"}
@@ -0,0 +1,34 @@
1
+ import { Clock } from "./clock.js";
2
+ import { Gate } from "./description.js";
3
+ import { Outcome, Trace } from "./latch.js";
4
+ import { Poll } from "./timing.js";
5
+ import { Quantity } from "@mark1russell7/quantity";
6
+ /**
7
+ * A watchdog spec declares a watchdog of the event loop. The service declares it as a check whose
8
+ * function the watchdog gives: the process's own wedge, which a liveness window reads.
9
+ */
10
+ export interface WatchdogSpec {
11
+ readonly name: string;
12
+ /** This time is the interval of the tick of the watchdog. */
13
+ readonly tick: Quantity;
14
+ /** This time is the most that a tick can be late before the loop counts as blocked. */
15
+ readonly threshold: Quantity;
16
+ /** This gate is the policy that the check controls, or null for a check that only reports. */
17
+ readonly gates: Gate | null;
18
+ readonly poll: Poll;
19
+ }
20
+ /**
21
+ * A watchdog measures how late its own tick comes. A blocked event loop delays each timer, thus a
22
+ * tick that comes later than the threshold shows the block. Its states are `watching`, `blocked`
23
+ * and `stopped`.
24
+ */
25
+ export interface Watchdog {
26
+ /** This function is the check: it fails when a tick since the last poll came late, or the loop is still blocked. */
27
+ readonly check: () => Outcome;
28
+ /** This time is the most that a tick was late, in milliseconds, since the start. */
29
+ readonly worst: number;
30
+ readonly blocked: boolean;
31
+ stop(): void;
32
+ }
33
+ /** This function starts a watchdog on a clock. */
34
+ export declare const watchdog: (clock: Clock, spec: WatchdogSpec, trace?: Trace) => Watchdog;
@@ -0,0 +1,53 @@
1
+ import { valueIn } from "@mark1russell7/quantity";
2
+ // src/watchdog.ts
3
+ /** This function starts a watchdog on a clock. */
4
+ const watchdog = (clock, spec, trace) => {
5
+ const tick = valueIn(spec.tick, "ms");
6
+ const threshold = valueIn(spec.threshold, "ms");
7
+ if (!(tick > 0)) throw new RangeError(`watchdog ${spec.name} ticks every ${tick} ms, not above zero`);
8
+ let blocked = false;
9
+ let stopped = false;
10
+ let worst = 0;
11
+ let sincePoll = 0;
12
+ let next = null;
13
+ const named = () => stopped ? "stopped" : blocked ? "blocked" : "watching";
14
+ const arm = () => {
15
+ const due = clock.now() + tick;
16
+ next = clock.after(tick, () => {
17
+ next = null;
18
+ if (stopped) return;
19
+ const late = Math.max(0, clock.now() - due);
20
+ worst = Math.max(worst, late);
21
+ sincePoll = Math.max(sincePoll, late);
22
+ const from = named();
23
+ blocked = late > threshold;
24
+ trace?.(from, named(), "tick");
25
+ arm();
26
+ });
27
+ };
28
+ arm();
29
+ return {
30
+ check: () => {
31
+ const failed = blocked || sincePoll > threshold;
32
+ sincePoll = 0;
33
+ return failed ? "error" : "ok";
34
+ },
35
+ get worst() {
36
+ return worst;
37
+ },
38
+ get blocked() {
39
+ return blocked;
40
+ },
41
+ stop() {
42
+ if (stopped) return;
43
+ const from = named();
44
+ stopped = true;
45
+ next?.();
46
+ next = null;
47
+ trace?.(from, "stopped", "stop");
48
+ }
49
+ };
50
+ };
51
+ export { watchdog };
52
+
53
+ //# sourceMappingURL=watchdog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watchdog.js","names":[],"sources":["../src/watchdog.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Gate } from \"./description.ts\";\nimport type { Outcome, Trace } from \"./latch.ts\";\nimport type { Poll } from \"./timing.ts\";\n\n/**\n * A watchdog spec declares a watchdog of the event loop. The service declares it as a check whose\n * function the watchdog gives: the process's own wedge, which a liveness window reads.\n */\nexport interface WatchdogSpec {\n readonly name: string;\n /** This time is the interval of the tick of the watchdog. */\n readonly tick: Quantity;\n /** This time is the most that a tick can be late before the loop counts as blocked. */\n readonly threshold: Quantity;\n /** This gate is the policy that the check controls, or null for a check that only reports. */\n readonly gates: Gate | null;\n readonly poll: Poll;\n}\n\n/**\n * A watchdog measures how late its own tick comes. A blocked event loop delays each timer, thus a\n * tick that comes later than the threshold shows the block. Its states are `watching`, `blocked`\n * and `stopped`.\n */\nexport interface Watchdog {\n /** This function is the check: it fails when a tick since the last poll came late, or the loop is still blocked. */\n readonly check: () => Outcome;\n /** This time is the most that a tick was late, in milliseconds, since the start. */\n readonly worst: number;\n readonly blocked: boolean;\n stop(): void;\n}\n\n/** This function starts a watchdog on a clock. */\nexport const watchdog = (clock: Clock, spec: WatchdogSpec, trace?: Trace): Watchdog => {\n const tick = valueIn(spec.tick, \"ms\");\n const threshold = valueIn(spec.threshold, \"ms\");\n if (!(tick > 0)) throw new RangeError(`watchdog ${spec.name} ticks every ${tick} ms, not above zero`);\n let blocked = false;\n let stopped = false;\n let worst = 0;\n // the worst lateness since the last poll of the check\n let sincePoll = 0;\n let next: Cancel | null = null;\n\n const named = (): string => (stopped ? \"stopped\" : blocked ? \"blocked\" : \"watching\");\n const arm = (): void => {\n const due = clock.now() + tick;\n next = clock.after(tick, () => {\n next = null;\n if (stopped) return;\n const late = Math.max(0, clock.now() - due);\n worst = Math.max(worst, late);\n sincePoll = Math.max(sincePoll, late);\n const from = named();\n blocked = late > threshold;\n trace?.(from, named(), \"tick\");\n arm();\n });\n };\n arm();\n\n return {\n check: () => {\n const failed = blocked || sincePoll > threshold;\n sincePoll = 0;\n return failed ? \"error\" : \"ok\";\n },\n get worst() {\n return worst;\n },\n get blocked() {\n return blocked;\n },\n stop() {\n if (stopped) return;\n const from = named();\n stopped = true;\n next?.();\n next = null;\n trace?.(from, \"stopped\", \"stop\");\n },\n };\n};\n"],"mappings":";;;AAqCA,MAAa,YAAY,OAAc,MAAoB,UAA4B;CACrF,MAAM,OAAO,QAAQ,KAAK,MAAM,IAAI;CACpC,MAAM,YAAY,QAAQ,KAAK,WAAW,IAAI;CAC9C,IAAI,EAAE,OAAO,IAAI,MAAM,IAAI,WAAW,YAAY,KAAK,KAAK,eAAe,KAAK,oBAAoB;CACpG,IAAI,UAAU;CACd,IAAI,UAAU;CACd,IAAI,QAAQ;CAEZ,IAAI,YAAY;CAChB,IAAI,OAAsB;CAE1B,MAAM,cAAuB,UAAU,YAAY,UAAU,YAAY;CACzE,MAAM,YAAkB;EACtB,MAAM,MAAM,MAAM,IAAI,IAAI;EAC1B,OAAO,MAAM,MAAM,YAAY;GAC7B,OAAO;GACP,IAAI,SAAS;GACb,MAAM,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,IAAI,GAAG;GAC1C,QAAQ,KAAK,IAAI,OAAO,IAAI;GAC5B,YAAY,KAAK,IAAI,WAAW,IAAI;GACpC,MAAM,OAAO,MAAM;GACnB,UAAU,OAAO;GACjB,QAAQ,MAAM,MAAM,GAAG,MAAM;GAC7B,IAAI;EACN,CAAC;CACH;CACA,IAAI;CAEJ,OAAO;EACL,aAAa;GACX,MAAM,SAAS,WAAW,YAAY;GACtC,YAAY;GACZ,OAAO,SAAS,UAAU;EAC5B;EACA,IAAI,QAAQ;GACV,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO;EACT;EACA,OAAO;GACL,IAAI,SAAS;GACb,MAAM,OAAO,MAAM;GACnB,UAAU;GACV,OAAO;GACP,OAAO;GACP,QAAQ,MAAM,WAAW,MAAM;EACjC;CACF;AACF"}
@@ -0,0 +1,136 @@
1
+ import { Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, RetryKnobs, SendOptions, Sent } from "../client/core.js";
2
+ import { Judge } from "../client/dial.js";
3
+ import { Operation } from "../operation.js";
4
+ import { WsConnectOptions, WsFactory } from "./connection.js";
5
+ import { Extent, Quantity } from "@mark1russell7/quantity";
6
+ /**
7
+ * These are the knobs of the client, each a time, by the names of the ordering law. The runtime has
8
+ * no defaults, thus each knob is necessary. A bound that nobody gives is "infinite", not zero. The
9
+ * constant `WS_CLIENT_STARTING_KNOBS` gives a declaration from the WS cells. The knobs that each client has come from the core.
10
+ */
11
+ export interface WsKnobs extends ClientKnobs, RetryKnobs {
12
+ /** This time bounds the TCP connect and the upgrade (`handshakeTimeout` of ws). The wrapper also bounds the open with it. */
13
+ readonly connect_bound: Quantity;
14
+ /** This time bounds each call: a request until its reply, and a ping until its pong. The wrapper has this timer, because ws has none. */
15
+ readonly request_timeout: Quantity;
16
+ /** This time is the interval of the ping frames of the heartbeat, from the start of one to the start of the next. "infinite" sends no ping. */
17
+ readonly heartbeat_interval: Extent;
18
+ /** This time bounds each ping of the heartbeat. A ping with no pong in this time is a miss. */
19
+ readonly heartbeat_timeout: Quantity;
20
+ /** This time is the first delay before a new try to connect. The delay doubles after each try. */
21
+ readonly retry_base: Quantity;
22
+ /** This time is the most that one delay can be, before its jitter. */
23
+ readonly retry_cap: Quantity;
24
+ /** This time is the idle time of TCP keepalive (`keepAliveInitialDelay`), in whole seconds. "infinite" keeps keepalive off, as ws does. */
25
+ readonly keepalive_idle: Extent;
26
+ /** The client does not replace its connection at an age, thus this knob must be "infinite". */
27
+ readonly max_connection_age: Extent;
28
+ /** This time bounds the close at the shutdown: the calls in flight, then the close handshake. At the bound, `terminate()` destroys the socket. */
29
+ readonly close_bound: Quantity;
30
+ }
31
+ /** A reply is the id of the request that a message answers, and the error of the server when the reply tells one. */
32
+ export interface WsReply {
33
+ readonly id: string;
34
+ readonly error?: string | undefined;
35
+ }
36
+ /**
37
+ * The replies of a protocol tell which message of the server answers which request. WebSocket has no
38
+ * reply of its own: each application protocol puts an id in its messages, for example JSON-RPC 2.0.
39
+ */
40
+ export interface WsReplies {
41
+ /** This function reads one message of the server. It gives its reply, or null for a message that answers no request. */
42
+ reply(data: Buffer, binary: boolean): WsReply | null;
43
+ }
44
+ /** A WebSocket client spec is the declaration of one WebSocket client: where it connects, and its knobs. */
45
+ export interface WsClientSpec extends ClientSpec<WsKnobs> {
46
+ /** This path is the path of the upgrade request. The default is "/". */
47
+ readonly path?: string | undefined;
48
+ /** These names are the subprotocols that the client offers (`Sec-WebSocket-Protocol`). */
49
+ readonly protocols?: readonly string[] | undefined;
50
+ /** These headers go with the upgrade request and with the dial, for example `authorization`. */
51
+ readonly headers?: Readonly<Record<string, string>> | undefined;
52
+ /** This count is the number of heartbeat misses in sequence that end the connection. The cells used 1. */
53
+ readonly heartbeatMisses: number;
54
+ /** These replies match a message of the server to its request. Without them, the client sends no request. */
55
+ readonly replies?: WsReplies | undefined;
56
+ /**
57
+ * These operations are the calls of the service, by name, with their idempotency. A message does
58
+ * not tell if the server removes its duplicates. Thus the client sends again only a call that this table names, and a ping.
59
+ */
60
+ readonly operations?: ClientSpec<WsKnobs>["operations"];
61
+ }
62
+ /** These options make a client. Without them, it uses ws, the real clock, `Math.random`, and a dial with the upgrade request. */
63
+ export interface WsClientOptions extends ClientOptions<WsFactory> {
64
+ readonly random?: (() => number) | undefined;
65
+ /**
66
+ * This function waits one turn of the event loop. The heartbeat waits it before it counts a miss,
67
+ * thus a pong that is in the socket counts first. The default is `setImmediate`.
68
+ */
69
+ readonly turn?: (() => Promise<void>) | undefined;
70
+ }
71
+ /** A join is one generation of the client: one connection, when its upgrade ended with 101 (D1, D2). WebSocket gives no id of a connection. */
72
+ export interface WsJoin extends ClientJoin {
73
+ /** This URL is the URL of the connection. */
74
+ readonly url: string;
75
+ /** This text is the subprotocol that the server chose, or "" when it chose none. */
76
+ readonly protocol: string;
77
+ }
78
+ /** A request is one message to the server, with the id that its reply gives back. */
79
+ export interface WsRequest {
80
+ readonly id: string;
81
+ /** This data goes as one message. A string goes as a text message, and a buffer as a binary message. */
82
+ readonly data: string | Buffer;
83
+ }
84
+ /** A response is the message of the server that answered a request. */
85
+ export interface WsResponse {
86
+ readonly data: Buffer;
87
+ readonly binary: boolean;
88
+ }
89
+ /** A message listener receives each message of the server that answers no request. */
90
+ export type WsMessageListener = (data: Buffer, binary: boolean) => void;
91
+ /** A WebSocket client is a dependency of a service: its declaration, its handle, its checks and its calls. */
92
+ export interface WsClient extends Client<ClientStep, WsJoin> {
93
+ /** This text is the state of the client, as `WS_CLIENT_MACHINE` names it. */
94
+ readonly status: string;
95
+ /**
96
+ * This method sends a request, and waits for its reply. A reply is `ok`, or a certain error when it
97
+ * tells one. The client sends again only an idempotent operation, one time at most, after an outcome that is not certain.
98
+ */
99
+ request(operation: string, call: WsRequest, options?: SendOptions): Promise<Sent<WsResponse>>;
100
+ /** This method sends a ping frame, and waits for a pong. A pong is `ok`. A ping is idempotent, thus the client can send it again. */
101
+ ping(options?: SendOptions): Promise<Sent<void>>;
102
+ /** This method sends one message with no reply. It gives true when ws took the message, and false when the client is not ready. */
103
+ send(data: string | Buffer): boolean;
104
+ /** This method adds a listener of the messages that answer no request. It gives the function that removes it. */
105
+ onMessage(listener: WsMessageListener): () => void;
106
+ }
107
+ /** These operations are in each table: a ping frame is idempotent (RFC 6455 §5.5.2). */
108
+ export declare const WS_OPERATIONS: Readonly<Record<string, Operation>>;
109
+ /** This function gives the problems of a spec: the knobs that the client cannot use. */
110
+ export declare const specProblems: (name: string, spec: WsClientSpec) => string[];
111
+ /** This function gives the URL of a spec. The client speaks ws:// only. */
112
+ export declare const wsUrl: (spec: WsClientSpec) => string;
113
+ /** This function gives the arguments of `new WebSocket` from a spec. Each timer of ws comes from the declaration. */
114
+ export declare const wsOptions: (spec: WsClientSpec) => WsConnectOptions;
115
+ /** This function gives the bytes of the dial: the upgrade request of RFC 6455 §4.1, with the subprotocols and the headers of the spec. */
116
+ export declare const upgradeRequest: (spec: Pick<WsClientSpec, "host" | "port" | "path" | "protocols" | "headers">) => string;
117
+ /** This judge reads the status line of the answer to the upgrade. Only 101 passes: a WebSocket server takes the upgrade. */
118
+ export declare const upgradeJudge: Judge;
119
+ /** This function makes the dial of a spec: a new TCP connection, the upgrade request, and a wait for 101. The dial then destroys its socket. */
120
+ export declare const wsDial: (spec: Pick<WsClientSpec, "path" | "protocols" | "headers">) => DialFn;
121
+ /**
122
+ * This function makes a WebSocket client, a dependency of a service over ws 8.
123
+ * - It has one connection as one generation. The end of the connection ends the generation. The
124
+ * client then connects again by itself, after a backoff.
125
+ * - Its calls are a request until its reply, and a ping until its pong. Each call has a timer of
126
+ * the wrapper, because ws has none.
127
+ * - Its heartbeat sends a ping frame each interval, one at a time. A ping with no pong in its timeout
128
+ * is a miss. At the last miss, `terminate()` destroys the socket at once, and the client connects again.
129
+ * - It tells the outcome of a call in three values, and it settles each call in flight at the end of its generation (C8, C10).
130
+ * - It records the URL and the ends of the socket of each connection at its open (D1).
131
+ *
132
+ * These parts come from the core of the clients: the outcomes, the second try and the wait for a ready
133
+ * client. The backoff and its schedule, the calls in flight, the bounded close and the checks come from
134
+ * the core too. The heartbeat is the heartbeat of the package. This entry gives what ws does in its own way.
135
+ */
136
+ export declare const wsClient: (name: string, spec: WsClientSpec, options?: WsClientOptions) => WsClient;