@mark1russell7/service 0.8.19 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/README.md +6 -2
  2. package/build/backoff.d.ts +44 -2
  3. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  4. package/build/builder.js +499 -0
  5. package/build/builder.js.map +1 -0
  6. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  7. package/build/channel.d.ts +1 -1
  8. package/build/channel.js.map +1 -1
  9. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  10. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  11. package/build/client/core.js.map +1 -0
  12. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  13. package/build/client/dial.js +52 -0
  14. package/build/client/dial.js.map +1 -0
  15. package/build/client/machine.js +29 -0
  16. package/build/client/machine.js.map +1 -0
  17. package/build/client/meets.d.ts +35 -0
  18. package/build/client/meets.js +78 -0
  19. package/build/client/meets.js.map +1 -0
  20. package/build/clock.d.ts +2 -2
  21. package/build/clock.js +1 -1
  22. package/build/conformance.d.ts +122 -0
  23. package/build/conformance.js +469 -0
  24. package/build/conformance.js.map +1 -0
  25. package/build/contract.d.ts +28 -0
  26. package/build/contract.js +184 -0
  27. package/build/contract.js.map +1 -0
  28. package/build/description.d.ts +161 -0
  29. package/build/description.js +11 -0
  30. package/build/description.js.map +1 -0
  31. package/build/drains.js +35 -0
  32. package/build/drains.js.map +1 -0
  33. package/build/events.d.ts +25 -0
  34. package/build/fakes.d.ts +43 -0
  35. package/build/fakes.js +93 -0
  36. package/build/fakes.js.map +1 -0
  37. package/build/grpc/client.d.ts +153 -0
  38. package/build/grpc/client.js +474 -0
  39. package/build/grpc/client.js.map +1 -0
  40. package/build/grpc/connection.d.ts +97 -0
  41. package/build/grpc/connection.js +59 -0
  42. package/build/grpc/connection.js.map +1 -0
  43. package/build/grpc/machine.d.ts +12 -0
  44. package/build/grpc/machine.js +149 -0
  45. package/build/grpc/machine.js.map +1 -0
  46. package/build/grpc/meets.d.ts +14 -0
  47. package/build/grpc/meets.js +105 -0
  48. package/build/grpc/meets.js.map +1 -0
  49. package/build/grpc/starting.d.ts +33 -0
  50. package/build/grpc/starting.js +89 -0
  51. package/build/grpc/starting.js.map +1 -0
  52. package/build/grpc.d.ts +9 -303
  53. package/build/grpc.js +7 -854
  54. package/build/health.d.ts +93 -0
  55. package/build/health.js +225 -0
  56. package/build/health.js.map +1 -0
  57. package/build/heartbeat.d.ts +6 -2
  58. package/build/heartbeat.js.map +1 -1
  59. package/build/host/discovery.d.ts +61 -0
  60. package/build/host/discovery.js +113 -0
  61. package/build/host/discovery.js.map +1 -0
  62. package/build/host/env.d.ts +14 -0
  63. package/build/host/env.js +57 -0
  64. package/build/host/env.js.map +1 -0
  65. package/build/host/fakes.d.ts +82 -0
  66. package/build/host/fakes.js +239 -0
  67. package/build/host/fakes.js.map +1 -0
  68. package/build/host/group.d.ts +142 -0
  69. package/build/host/group.js +524 -0
  70. package/build/host/group.js.map +1 -0
  71. package/build/host/install.d.ts +96 -0
  72. package/build/host/install.js +330 -0
  73. package/build/host/install.js.map +1 -0
  74. package/build/host/lock.d.ts +78 -0
  75. package/build/host/lock.js +190 -0
  76. package/build/host/lock.js.map +1 -0
  77. package/build/host/logs.d.ts +26 -0
  78. package/build/host/logs.js +48 -0
  79. package/build/host/logs.js.map +1 -0
  80. package/build/host/node.d.ts +14 -0
  81. package/build/host/node.js +309 -0
  82. package/build/host/node.js.map +1 -0
  83. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  84. package/build/host/ports.js +17 -0
  85. package/build/host/ports.js.map +1 -0
  86. package/build/host/probes.d.ts +51 -0
  87. package/build/host/probes.js +139 -0
  88. package/build/host/probes.js.map +1 -0
  89. package/build/host/processes.d.ts +32 -0
  90. package/build/host/processes.js +63 -0
  91. package/build/host/processes.js.map +1 -0
  92. package/build/host/render.d.ts +84 -0
  93. package/build/host/render.js +235 -0
  94. package/build/host/render.js.map +1 -0
  95. package/build/host/watch.d.ts +90 -0
  96. package/build/host/watch.js +165 -0
  97. package/build/host/watch.js.map +1 -0
  98. package/build/host.d.ts +13 -671
  99. package/build/host.js +12 -2126
  100. package/build/http/answers.js +29 -0
  101. package/build/http/answers.js.map +1 -0
  102. package/build/http/fake-server.js +61 -0
  103. package/build/http/fake-server.js.map +1 -0
  104. package/build/http/outcome.d.ts +115 -0
  105. package/build/http/outcome.js +325 -0
  106. package/build/http/outcome.js.map +1 -0
  107. package/build/http/probes.d.ts +83 -0
  108. package/build/http/probes.js +232 -0
  109. package/build/http/probes.js.map +1 -0
  110. package/build/http/transport.d.ts +165 -0
  111. package/build/http/transport.js +518 -0
  112. package/build/http/transport.js.map +1 -0
  113. package/build/http-client/client.d.ts +121 -0
  114. package/build/http-client/client.js +330 -0
  115. package/build/http-client/client.js.map +1 -0
  116. package/build/http-client/connection.d.ts +78 -0
  117. package/build/http-client/connection.js +54 -0
  118. package/build/http-client/connection.js.map +1 -0
  119. package/build/http-client/machine.d.ts +14 -0
  120. package/build/http-client/machine.js +109 -0
  121. package/build/http-client/machine.js.map +1 -0
  122. package/build/http-client/meets.d.ts +11 -0
  123. package/build/http-client/meets.js +74 -0
  124. package/build/http-client/meets.js.map +1 -0
  125. package/build/http-client/session.d.ts +87 -0
  126. package/build/http-client/session.js +99 -0
  127. package/build/http-client/session.js.map +1 -0
  128. package/build/http-client/starting.d.ts +25 -0
  129. package/build/http-client/starting.js +65 -0
  130. package/build/http-client/starting.js.map +1 -0
  131. package/build/http-client.d.ts +9 -330
  132. package/build/http-client.js +8 -707
  133. package/build/http.d.ts +5 -353
  134. package/build/http.js +3 -1086
  135. package/build/identity.d.ts +16 -0
  136. package/build/identity.js +44 -0
  137. package/build/identity.js.map +1 -0
  138. package/build/index.d.ts +35 -412
  139. package/build/index.js +25 -3278
  140. package/build/knobs.d.ts +1 -0
  141. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  142. package/build/knobs.js.map +1 -0
  143. package/build/latch.d.ts +29 -0
  144. package/build/latch.js +122 -0
  145. package/build/latch.js.map +1 -0
  146. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  147. package/build/law.js +149 -0
  148. package/build/law.js.map +1 -0
  149. package/build/lifecycle.d.ts +144 -0
  150. package/build/lifecycle.js +411 -0
  151. package/build/lifecycle.js.map +1 -0
  152. package/build/limiter/machine.d.ts +40 -0
  153. package/build/limiter/machine.js +279 -0
  154. package/build/limiter/machine.js.map +1 -0
  155. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  156. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  157. package/build/limiter/policy.js.map +1 -0
  158. package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
  159. package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
  160. package/build/limiter/quota.js.map +1 -0
  161. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  162. package/build/limiter/store.js +145 -0
  163. package/build/limiter/store.js.map +1 -0
  164. package/build/limiter.d.ts +4 -3
  165. package/build/limiter.js +4 -2
  166. package/build/lint.d.ts +152 -0
  167. package/build/lint.js +576 -0
  168. package/build/lint.js.map +1 -0
  169. package/build/logger.d.ts +71 -0
  170. package/build/logger.js +183 -0
  171. package/build/logger.js.map +1 -0
  172. package/build/machines.d.ts +41 -0
  173. package/build/machines.js +451 -0
  174. package/build/machines.js.map +1 -0
  175. package/build/metrics.d.ts +53 -0
  176. package/build/metrics.js +111 -0
  177. package/build/metrics.js.map +1 -0
  178. package/build/mongodb/client.d.ts +131 -0
  179. package/build/mongodb/client.js +388 -0
  180. package/build/mongodb/client.js.map +1 -0
  181. package/build/mongodb/connection.d.ts +112 -0
  182. package/build/mongodb/connection.js +12 -0
  183. package/build/mongodb/connection.js.map +1 -0
  184. package/build/mongodb/machine.d.ts +14 -0
  185. package/build/mongodb/machine.js +122 -0
  186. package/build/mongodb/machine.js.map +1 -0
  187. package/build/mongodb/meets.d.ts +15 -0
  188. package/build/mongodb/meets.js +103 -0
  189. package/build/mongodb/meets.js.map +1 -0
  190. package/build/mongodb/starting.d.ts +29 -0
  191. package/build/mongodb/starting.js +77 -0
  192. package/build/mongodb/starting.js.map +1 -0
  193. package/build/mongodb.d.ts +8 -296
  194. package/build/mongodb.js +7 -682
  195. package/build/operation.d.ts +27 -0
  196. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  197. package/build/operation.js.map +1 -0
  198. package/build/otel.d.ts +2 -2
  199. package/build/pg/client.d.ts +96 -0
  200. package/build/pg/client.js +277 -0
  201. package/build/pg/client.js.map +1 -0
  202. package/build/pg/connection.d.ts +75 -0
  203. package/build/pg/connection.js +11 -0
  204. package/build/pg/connection.js.map +1 -0
  205. package/build/pg/machine.d.ts +13 -0
  206. package/build/pg/machine.js +111 -0
  207. package/build/pg/machine.js.map +1 -0
  208. package/build/pg/meets.d.ts +14 -0
  209. package/build/pg/meets.js +83 -0
  210. package/build/pg/meets.js.map +1 -0
  211. package/build/pg/starting.d.ts +26 -0
  212. package/build/pg/starting.js +62 -0
  213. package/build/pg/starting.js.map +1 -0
  214. package/build/pg.d.ts +8 -219
  215. package/build/pg.js +7 -525
  216. package/build/poller.d.ts +9 -0
  217. package/build/poller.js +154 -0
  218. package/build/poller.js.map +1 -0
  219. package/build/process.d.ts +114 -0
  220. package/build/process.js +170 -0
  221. package/build/process.js.map +1 -0
  222. package/build/profiles.d.ts +68 -0
  223. package/build/profiles.js +120 -0
  224. package/build/profiles.js.map +1 -0
  225. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  226. package/build/queue.js +279 -0
  227. package/build/queue.js.map +1 -0
  228. package/build/rabbitmq/client.d.ts +144 -0
  229. package/build/rabbitmq/client.js +426 -0
  230. package/build/rabbitmq/client.js.map +1 -0
  231. package/build/rabbitmq/connection.d.ts +91 -0
  232. package/build/rabbitmq/connection.js +15 -0
  233. package/build/rabbitmq/connection.js.map +1 -0
  234. package/build/rabbitmq/machine.d.ts +13 -0
  235. package/build/rabbitmq/machine.js +159 -0
  236. package/build/rabbitmq/machine.js.map +1 -0
  237. package/build/rabbitmq/meets.d.ts +12 -0
  238. package/build/rabbitmq/meets.js +96 -0
  239. package/build/rabbitmq/meets.js.map +1 -0
  240. package/build/rabbitmq/starting.d.ts +27 -0
  241. package/build/rabbitmq/starting.js +67 -0
  242. package/build/rabbitmq/starting.js.map +1 -0
  243. package/build/rabbitmq.d.ts +8 -283
  244. package/build/rabbitmq.js +7 -742
  245. package/build/redis/client.d.ts +86 -0
  246. package/build/redis/client.js +285 -0
  247. package/build/redis/client.js.map +1 -0
  248. package/build/redis/connection.d.ts +57 -0
  249. package/build/redis/connection.js +11 -0
  250. package/build/redis/connection.js.map +1 -0
  251. package/build/redis/limiter.d.ts +43 -0
  252. package/build/redis/limiter.js +164 -0
  253. package/build/redis/limiter.js.map +1 -0
  254. package/build/redis/machine.d.ts +12 -0
  255. package/build/redis/machine.js +144 -0
  256. package/build/redis/machine.js.map +1 -0
  257. package/build/redis/meets.d.ts +11 -0
  258. package/build/redis/meets.js +75 -0
  259. package/build/redis/meets.js.map +1 -0
  260. package/build/redis/operations.d.ts +5 -0
  261. package/build/redis/operations.js +114 -0
  262. package/build/redis/operations.js.map +1 -0
  263. package/build/redis.d.ts +10 -207
  264. package/build/redis.js +9 -771
  265. package/build/requests.d.ts +66 -0
  266. package/build/requests.js +279 -0
  267. package/build/requests.js.map +1 -0
  268. package/build/retrier.d.ts +62 -0
  269. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  270. package/build/retrier.js.map +1 -0
  271. package/build/routes.d.ts +35 -0
  272. package/build/routes.js +77 -0
  273. package/build/routes.js.map +1 -0
  274. package/build/rules.d.ts +19 -2
  275. package/build/stops.d.ts +51 -0
  276. package/build/stops.js +86 -0
  277. package/build/stops.js.map +1 -0
  278. package/build/testing.d.ts +8 -270
  279. package/build/testing.js +4 -1027
  280. package/build/testing.js.map +1 -1
  281. package/build/timing.d.ts +63 -0
  282. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  283. package/build/timing.js.map +1 -0
  284. package/build/units.d.ts +17 -0
  285. package/build/units.js +236 -0
  286. package/build/units.js.map +1 -0
  287. package/build/watchdog.d.ts +38 -0
  288. package/build/watchdog.js +57 -0
  289. package/build/watchdog.js.map +1 -0
  290. package/build/websocket/client.d.ts +136 -0
  291. package/build/websocket/client.js +422 -0
  292. package/build/websocket/client.js.map +1 -0
  293. package/build/websocket/connection.d.ts +83 -0
  294. package/build/websocket/connection.js +57 -0
  295. package/build/websocket/connection.js.map +1 -0
  296. package/build/websocket/machine.d.ts +12 -0
  297. package/build/websocket/machine.js +155 -0
  298. package/build/websocket/machine.js.map +1 -0
  299. package/build/websocket/meets.d.ts +14 -0
  300. package/build/websocket/meets.js +92 -0
  301. package/build/websocket/meets.js.map +1 -0
  302. package/build/websocket/starting.d.ts +25 -0
  303. package/build/websocket/starting.js +69 -0
  304. package/build/websocket/starting.js.map +1 -0
  305. package/build/websocket.d.ts +9 -264
  306. package/build/websocket.js +8 -774
  307. package/build/worker.d.ts +92 -0
  308. package/build/worker.js +153 -0
  309. package/build/worker.js.map +1 -0
  310. package/package.json +5 -4
  311. package/build/backoff-QTRGfkEK.d.ts +0 -45
  312. package/build/clock-DpVgpY4h.d.ts +0 -2
  313. package/build/grpc.js.map +0 -1
  314. package/build/host.js.map +0 -1
  315. package/build/http-client.js.map +0 -1
  316. package/build/http.js.map +0 -1
  317. package/build/index.js.map +0 -1
  318. package/build/knobs-BJcz6m01.js.map +0 -1
  319. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  320. package/build/limiter-DrM0PQV9.js.map +0 -1
  321. package/build/logger-B6drv9w0.d.ts +0 -488
  322. package/build/machine-BhVeHr_m.js.map +0 -1
  323. package/build/mongodb.js.map +0 -1
  324. package/build/operation-DF73RZOI.js.map +0 -1
  325. package/build/pg.js.map +0 -1
  326. package/build/policy-UYALkqVq.js.map +0 -1
  327. package/build/process-7R9M29wN.js +0 -437
  328. package/build/process-7R9M29wN.js.map +0 -1
  329. package/build/rabbitmq.js.map +0 -1
  330. package/build/redis.js.map +0 -1
  331. package/build/requests-DD2ALv0_.js +0 -583
  332. package/build/requests-DD2ALv0_.js.map +0 -1
  333. package/build/retrier-Dnjhvxol.js.map +0 -1
  334. package/build/timing-DZl36uXs.js.map +0 -1
  335. package/build/websocket.js.map +0 -1
@@ -0,0 +1,66 @@
1
+ import "./clock.js";
2
+ import "./description.js";
3
+ import "./routes.js";
4
+ /**
5
+ * A request end is the one final result of the stream of a request. Its count `delivered` is the
6
+ * number of items that the stream gave before it. An end after the first item is in-band. The
7
+ * transport sent its answer, thus it writes the end as the last line of the stream, not as a status.
8
+ * - `done`: the work gave each of its items.
9
+ * - `failed`: the work failed for a cause of its own. Before the first item, the adapter answers it
10
+ * as it answers any error of the route.
11
+ * - `refused`: the service did not admit the request. A refused request did not start, thus its
12
+ * caller can send it again: 503, retryable.
13
+ * - `cut`: the shutdown stopped the request. Before the first item, a route whose callers can send
14
+ * it again answers 503, retryable, and each other route answers 500. After the first item, the
15
+ * status is null, and the end is in-band.
16
+ */
17
+ export type RequestEnd = {
18
+ readonly kind: "done";
19
+ readonly delivered: number;
20
+ } | {
21
+ readonly kind: "failed";
22
+ readonly error: unknown;
23
+ readonly delivered: number;
24
+ } | {
25
+ readonly kind: "refused";
26
+ readonly status: 503;
27
+ readonly retryable: true;
28
+ readonly cause: string;
29
+ readonly delivered: 0;
30
+ } | {
31
+ readonly kind: "cut";
32
+ readonly status: 503 | 500 | null;
33
+ readonly retryable: boolean;
34
+ readonly cause: string;
35
+ readonly delivered: number;
36
+ };
37
+ /** A request event is one event of the stream of a request: an item, or the one end, which comes last. */
38
+ export type RequestEvent<T> = {
39
+ readonly kind: "item";
40
+ readonly value: T;
41
+ } | RequestEnd;
42
+ /**
43
+ * A request stream is what a request comes to: its items, then one end. A unary work gives a stream
44
+ * of one item. The stream gives an item only when its reader asks for the next event. Thus a slow
45
+ * reader slows the work, and the request stays in flight until the work ends. When the reader
46
+ * stops before the end, the work gets its abort and the `return()` of its iterator.
47
+ */
48
+ export interface RequestStream<T> extends AsyncIterable<RequestEvent<T>> {
49
+ /** This method reads the whole stream, and gives its items and its end. */
50
+ collect(): Promise<{
51
+ readonly items: readonly T[];
52
+ readonly end: RequestEnd;
53
+ }>;
54
+ }
55
+ /**
56
+ * A request work is what a request function gives: one value, or a stream of values. A work that
57
+ * gives an async iterable is a stream, also through a promise. Each other value is a stream of one.
58
+ */
59
+ export type RequestWork<T> = T | PromiseLike<T> | AsyncIterable<T> | PromiseLike<AsyncIterable<T>>;
60
+ /** A request function does the work of one request. It receives a signal that the shutdown aborts. */
61
+ export type RequestFn<T> = (signal: AbortSignal) => RequestWork<T>;
62
+ /** These options go with one request. */
63
+ export interface RequestOptions {
64
+ /** This value goes to the function of a route pattern, for example the metadata of a procedure. */
65
+ readonly detail?: unknown;
66
+ }
@@ -0,0 +1,279 @@
1
+ import { mayReissue } from "./operation.js";
2
+ import { compilePattern } from "./routes.js";
3
+ import { untilAbort } from "./units.js";
4
+ import { quantity } from "@mark1russell7/quantity";
5
+ // src/requests.ts
6
+ const isAsyncIterable = (value) => value !== null && (typeof value === "object" || typeof value === "function") && typeof value[Symbol.asyncIterator] === "function";
7
+ const isPromiseLike = (value) => value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
8
+ /** This function gives a stream of events from a function that gives the next event. */
9
+ const streamOf = (next, stop) => {
10
+ let chain = Promise.resolve();
11
+ const iterator = {
12
+ next() {
13
+ const step = chain.then(next).then((event) => event === null ? {
14
+ value: void 0,
15
+ done: true
16
+ } : {
17
+ value: event,
18
+ done: false
19
+ });
20
+ chain = step.catch(() => {});
21
+ return step;
22
+ },
23
+ return() {
24
+ stop();
25
+ return Promise.resolve({
26
+ value: void 0,
27
+ done: true
28
+ });
29
+ }
30
+ };
31
+ return {
32
+ [Symbol.asyncIterator]: () => iterator,
33
+ async collect() {
34
+ const items = [];
35
+ for (;;) {
36
+ const step = await iterator.next();
37
+ if (step.done === true) throw new Error("the stream ended without its end");
38
+ if (step.value.kind === "item") items.push(step.value.value);
39
+ else return {
40
+ items,
41
+ end: step.value
42
+ };
43
+ }
44
+ }
45
+ };
46
+ };
47
+ /**
48
+ * This function makes a tracker. `refuses` gives the reason that the service refuses a new request
49
+ * for a controller at this time, or null when it admits it. `choices` gives the function of each
50
+ * route pattern, by controller and by pattern.
51
+ */
52
+ const tracker = (controllers, clock, refuses, choices = /* @__PURE__ */ new Map()) => {
53
+ const byName = new Map(controllers.map((controller) => [controller.name, {
54
+ controller,
55
+ patterns: (controller.patterns ?? []).map((declared) => ({
56
+ declared,
57
+ compiled: compilePattern(declared.pattern)
58
+ }))
59
+ }]));
60
+ const flights = /* @__PURE__ */ new Set();
61
+ const idle = /* @__PURE__ */ new Set();
62
+ let intake = true;
63
+ /** This function gives the operation of a request: its exact route, else the first pattern that matches it. */
64
+ const operationOf = (controller, route, detail) => {
65
+ const held = byName.get(controller);
66
+ if (held === void 0) throw new Error(`there is no controller ${controller}`);
67
+ const exact = held.controller.routes[route];
68
+ if (exact !== void 0) return exact;
69
+ for (const { declared, compiled } of held.patterns) {
70
+ const found = compiled.match(route);
71
+ if (found === null) continue;
72
+ const names = Object.keys(declared.operations);
73
+ const choose = choices.get(controller)?.get(declared.pattern);
74
+ const name = choose === void 0 ? names[0] : choose({
75
+ controller,
76
+ route,
77
+ ...found,
78
+ detail
79
+ });
80
+ const operation = declared.operations[name];
81
+ if (operation === void 0) throw new Error(`the pattern ${declared.pattern} of ${controller} declares no operation ${String(name)} for ${route}`);
82
+ return operation;
83
+ }
84
+ throw new Error(`controller ${controller} does not declare the route ${route}`);
85
+ };
86
+ const settle = (flight) => {
87
+ if (!flights.delete(flight)) return;
88
+ if (flights.size === 0) for (const done of [...idle]) done();
89
+ };
90
+ /** This function starts the work of an admitted request, and gives its stream. */
91
+ const open = (controller, operation, work) => {
92
+ const started = clock.now();
93
+ const abort = new AbortController();
94
+ let delivered = 0;
95
+ let end = null;
96
+ let ended = false;
97
+ let returned = false;
98
+ let source = null;
99
+ let unary = null;
100
+ const interruption = new AbortController();
101
+ const interrupt = () => interruption.abort();
102
+ const cutEnd = (cause) => {
103
+ const since = quantity(Math.max(0, clock.now() - started) / 1e3, "s");
104
+ const retryable = mayReissue(operation, since);
105
+ return {
106
+ kind: "cut",
107
+ status: delivered > 0 ? null : retryable ? 503 : 500,
108
+ retryable,
109
+ cause,
110
+ delivered
111
+ };
112
+ };
113
+ /** This function ends the work of the request: the end is known, and the request leaves the flights. */
114
+ const finish = (given) => {
115
+ if (end !== null) return;
116
+ end = given;
117
+ settle(flight);
118
+ interrupt();
119
+ };
120
+ /** This function ends the work after a throw: a failure after the shutdown aborted it is a cut. */
121
+ const failed = (error) => finish(abort.signal.aborted ? cutEnd("the shutdown aborted it, and it failed") : {
122
+ kind: "failed",
123
+ error,
124
+ delivered
125
+ });
126
+ const closeSource = () => {
127
+ if (source === null || returned) return;
128
+ returned = true;
129
+ try {
130
+ Promise.resolve(source.return?.()).catch(() => {});
131
+ } catch {}
132
+ };
133
+ const flight = {
134
+ controller,
135
+ cooperative: () => {
136
+ abort.abort(/* @__PURE__ */ new Error("the cooperative abort of the drain"));
137
+ closeSource();
138
+ },
139
+ cut: (cause) => {
140
+ abort.abort(new Error(cause));
141
+ finish(cutEnd(cause));
142
+ closeSource();
143
+ }
144
+ };
145
+ flights.add(flight);
146
+ /** This function takes the result of the work: a stream, or one value. */
147
+ const take = (result) => {
148
+ if (end !== null) return;
149
+ if (isAsyncIterable(result)) {
150
+ source = result[Symbol.asyncIterator]();
151
+ if (abort.signal.aborted) closeSource();
152
+ } else {
153
+ unary = { value: result };
154
+ settle(flight);
155
+ }
156
+ };
157
+ let ready;
158
+ try {
159
+ const result = work(abort.signal);
160
+ if (isAsyncIterable(result) || !isPromiseLike(result)) {
161
+ take(result);
162
+ ready = Promise.resolve();
163
+ } else ready = Promise.resolve(result).then(take, failed);
164
+ } catch (error) {
165
+ failed(error);
166
+ ready = Promise.resolve();
167
+ }
168
+ const next = async () => {
169
+ if (ended) return null;
170
+ if (end === null) await untilAbort(ready, interruption.signal, "interrupted");
171
+ if (end === null && unary !== null) {
172
+ const { value } = unary;
173
+ unary = null;
174
+ delivered = 1;
175
+ end = {
176
+ kind: "done",
177
+ delivered
178
+ };
179
+ return {
180
+ kind: "item",
181
+ value
182
+ };
183
+ }
184
+ if (end === null && source !== null) {
185
+ const pending = source.next();
186
+ let step;
187
+ try {
188
+ step = await untilAbort(Promise.resolve(pending), interruption.signal, "interrupted");
189
+ } catch (error) {
190
+ failed(error);
191
+ step = "interrupted";
192
+ }
193
+ if (step !== "interrupted") {
194
+ if (step.done !== true) {
195
+ delivered += 1;
196
+ return {
197
+ kind: "item",
198
+ value: step.value
199
+ };
200
+ }
201
+ finish(abort.signal.aborted ? cutEnd("the shutdown ended the stream") : {
202
+ kind: "done",
203
+ delivered
204
+ });
205
+ }
206
+ }
207
+ ended = true;
208
+ return end;
209
+ };
210
+ const stop = () => {
211
+ if (end === null) {
212
+ abort.abort(/* @__PURE__ */ new Error("the reader stopped the stream"));
213
+ finish({
214
+ kind: "done",
215
+ delivered
216
+ });
217
+ closeSource();
218
+ }
219
+ ended = true;
220
+ };
221
+ return streamOf(next, stop);
222
+ };
223
+ return {
224
+ request(controller, route, work, options = {}) {
225
+ const operation = operationOf(controller, route, options.detail);
226
+ const refusal = intake ? refuses(controller) : "the service stopped its intake";
227
+ if (refusal !== null) {
228
+ let given = false;
229
+ const refused = {
230
+ kind: "refused",
231
+ status: 503,
232
+ retryable: true,
233
+ cause: refusal,
234
+ delivered: 0
235
+ };
236
+ return streamOf(() => {
237
+ if (given) return Promise.resolve(null);
238
+ given = true;
239
+ return Promise.resolve(refused);
240
+ }, () => {
241
+ given = true;
242
+ });
243
+ }
244
+ return open(controller, operation, work);
245
+ },
246
+ inFlight(controller) {
247
+ let count = 0;
248
+ for (const flight of flights) if (controller === void 0 || flight.controller === controller) count += 1;
249
+ return count;
250
+ },
251
+ stopIntake() {
252
+ intake = false;
253
+ },
254
+ cooperativeAbort() {
255
+ for (const flight of [...flights]) flight.cooperative();
256
+ },
257
+ drain(deadline) {
258
+ if (flights.size === 0) return Promise.resolve();
259
+ return new Promise((resolve) => {
260
+ let finished = false;
261
+ const done = () => {
262
+ if (finished) return;
263
+ finished = true;
264
+ idle.delete(done);
265
+ cancel();
266
+ resolve();
267
+ };
268
+ idle.add(done);
269
+ const cancel = clock.after(Math.max(0, deadline - clock.now()), () => {
270
+ for (const flight of [...flights]) flight.cut("the drain reached its deadline");
271
+ done();
272
+ });
273
+ });
274
+ }
275
+ };
276
+ };
277
+ export { tracker };
278
+
279
+ //# sourceMappingURL=requests.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requests.js","names":[],"sources":["../src/requests.ts"],"sourcesContent":["import { quantity } from \"@mark1russell7/quantity\";\nimport type { Clock } from \"./clock.ts\";\nimport type { Controller } from \"./description.ts\";\nimport type { Operation } from \"./operation.ts\";\nimport { mayReissue } from \"./operation.ts\";\nimport type { CompiledPattern, OperationOf } from \"./routes.ts\";\nimport { compilePattern } from \"./routes.ts\";\nimport { untilAbort } from \"./units.ts\";\n\n/**\n * A request end is the one final result of the stream of a request. Its count `delivered` is the\n * number of items that the stream gave before it. An end after the first item is in-band. The\n * transport sent its answer, thus it writes the end as the last line of the stream, not as a status.\n * - `done`: the work gave each of its items.\n * - `failed`: the work failed for a cause of its own. Before the first item, the adapter answers it\n * as it answers any error of the route.\n * - `refused`: the service did not admit the request. A refused request did not start, thus its\n * caller can send it again: 503, retryable.\n * - `cut`: the shutdown stopped the request. Before the first item, a route whose callers can send\n * it again answers 503, retryable, and each other route answers 500. After the first item, the\n * status is null, and the end is in-band.\n */\nexport type RequestEnd =\n | { readonly kind: \"done\"; readonly delivered: number }\n | { readonly kind: \"failed\"; readonly error: unknown; readonly delivered: number }\n | {\n readonly kind: \"refused\";\n readonly status: 503;\n readonly retryable: true;\n readonly cause: string;\n readonly delivered: 0;\n }\n | {\n readonly kind: \"cut\";\n readonly status: 503 | 500 | null;\n readonly retryable: boolean;\n readonly cause: string;\n readonly delivered: number;\n };\n\n/** A request event is one event of the stream of a request: an item, or the one end, which comes last. */\nexport type RequestEvent<T> = { readonly kind: \"item\"; readonly value: T } | RequestEnd;\n\n/**\n * A request stream is what a request comes to: its items, then one end. A unary work gives a stream\n * of one item. The stream gives an item only when its reader asks for the next event. Thus a slow\n * reader slows the work, and the request stays in flight until the work ends. When the reader\n * stops before the end, the work gets its abort and the `return()` of its iterator.\n */\nexport interface RequestStream<T> extends AsyncIterable<RequestEvent<T>> {\n /** This method reads the whole stream, and gives its items and its end. */\n collect(): Promise<{ readonly items: readonly T[]; readonly end: RequestEnd }>;\n}\n\n/**\n * A request work is what a request function gives: one value, or a stream of values. A work that\n * gives an async iterable is a stream, also through a promise. Each other value is a stream of one.\n */\nexport type RequestWork<T> = T | PromiseLike<T> | AsyncIterable<T> | PromiseLike<AsyncIterable<T>>;\n\n/** A request function does the work of one request. It receives a signal that the shutdown aborts. */\nexport type RequestFn<T> = (signal: AbortSignal) => RequestWork<T>;\n\n/** These options go with one request. */\nexport interface RequestOptions {\n /** This value goes to the function of a route pattern, for example the metadata of a procedure. */\n readonly detail?: unknown;\n}\n\n/** A tracker admits requests, counts the requests in flight, and ends what the shutdown cuts. */\nexport interface Tracker {\n request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;\n inFlight(controller?: string): number;\n /** This method refuses each later request. */\n stopIntake(): void;\n /** This method aborts the signal of each request in flight, and ends each stream through `return()`: the cooperative abort of the drain. */\n cooperativeAbort(): void;\n /** This method waits until no request is in flight, or until `deadline`. Then it cuts each request that is left. */\n drain(deadline: number): Promise<void>;\n}\n\ninterface InFlight {\n readonly controller: string;\n /** This function aborts the work, and ends its iterator through `return()`. */\n readonly cooperative: () => void;\n /** This function ends the request with a cut, one time. */\n readonly cut: (cause: string) => void;\n}\n\nconst isAsyncIterable = (value: unknown): value is AsyncIterable<unknown> =>\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === \"function\";\nconst isPromiseLike = (value: unknown): value is PromiseLike<unknown> =>\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\";\n\n/** This function gives a stream of events from a function that gives the next event. */\nconst streamOf = <T>(next: () => Promise<RequestEvent<T> | null>, stop: () => void): RequestStream<T> => {\n let chain: Promise<unknown> = Promise.resolve();\n const iterator: AsyncIterator<RequestEvent<T>> = {\n next() {\n // a reader that asks again before an answer gets the events in their sequence\n const step = chain.then(next).then((event): IteratorResult<RequestEvent<T>> =>\n event === null ? { value: undefined, done: true } : { value: event, done: false },\n );\n chain = step.catch(() => {});\n return step;\n },\n return() {\n stop();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n return {\n [Symbol.asyncIterator]: () => iterator,\n async collect() {\n const items: T[] = [];\n for (;;) {\n const step = await iterator.next();\n if (step.done === true) throw new Error(\"the stream ended without its end\");\n if (step.value.kind === \"item\") items.push(step.value.value);\n else return { items, end: step.value };\n }\n },\n };\n};\n\n/**\n * This function makes a tracker. `refuses` gives the reason that the service refuses a new request\n * for a controller at this time, or null when it admits it. `choices` gives the function of each\n * route pattern, by controller and by pattern.\n */\nexport const tracker = (\n controllers: readonly Controller[],\n clock: Clock,\n refuses: (controller: string) => string | null,\n choices: ReadonlyMap<string, ReadonlyMap<string, OperationOf>> = new Map(),\n): Tracker => {\n const byName = new Map(\n controllers.map((controller) => [\n controller.name,\n {\n controller,\n patterns: (controller.patterns ?? []).map((declared) => ({ declared, compiled: compilePattern(declared.pattern) as CompiledPattern })),\n },\n ]),\n );\n const flights = new Set<InFlight>();\n const idle = new Set<() => void>();\n let intake = true;\n\n /** This function gives the operation of a request: its exact route, else the first pattern that matches it. */\n const operationOf = (controller: string, route: string, detail: unknown): Operation => {\n const held = byName.get(controller);\n if (held === undefined) throw new Error(`there is no controller ${controller}`);\n const exact = held.controller.routes[route];\n if (exact !== undefined) return exact;\n for (const { declared, compiled } of held.patterns) {\n const found = compiled.match(route);\n if (found === null) continue;\n const names = Object.keys(declared.operations);\n const choose = choices.get(controller)?.get(declared.pattern);\n const name = choose === undefined ? names[0]! : choose({ controller, route, ...found, detail });\n const operation = declared.operations[name];\n if (operation === undefined)\n throw new Error(`the pattern ${declared.pattern} of ${controller} declares no operation ${String(name)} for ${route}`);\n return operation;\n }\n // a route that nobody declared has no idempotency: the runtime has no defaults\n throw new Error(`controller ${controller} does not declare the route ${route}`);\n };\n\n const settle = (flight: InFlight): void => {\n if (!flights.delete(flight)) return;\n if (flights.size === 0) for (const done of [...idle]) done();\n };\n\n /** This function starts the work of an admitted request, and gives its stream. */\n const open = <T>(controller: string, operation: Operation, work: RequestFn<T>): RequestStream<T> => {\n const started = clock.now();\n const abort = new AbortController();\n let delivered = 0;\n let end: RequestEnd | null = null;\n let ended = false;\n let returned = false;\n let source: AsyncIterator<T> | null = null;\n // a unary work keeps its value until the reader asks for it\n let unary: { readonly value: T } | null = null;\n // Each wait of the reader listens for the end with a listener of its own, thus a long stream keeps no item that went.\n const interruption = new AbortController();\n const interrupt = (): void => interruption.abort();\n\n const cutEnd = (cause: string): RequestEnd => {\n const since = quantity(Math.max(0, clock.now() - started) / 1000, \"s\");\n const retryable = mayReissue(operation, since);\n return { kind: \"cut\", status: delivered > 0 ? null : retryable ? 503 : 500, retryable, cause, delivered };\n };\n /** This function ends the work of the request: the end is known, and the request leaves the flights. */\n const finish = (given: RequestEnd): void => {\n if (end !== null) return;\n end = given;\n settle(flight);\n interrupt();\n };\n /** This function ends the work after a throw: a failure after the shutdown aborted it is a cut. */\n const failed = (error: unknown): void =>\n finish(abort.signal.aborted ? cutEnd(\"the shutdown aborted it, and it failed\") : { kind: \"failed\", error, delivered });\n const closeSource = (): void => {\n if (source === null || returned) return;\n returned = true;\n try {\n void Promise.resolve(source.return?.()).catch(() => {});\n } catch {\n // an iterator whose return() throws has ended\n }\n };\n const flight: InFlight = {\n controller,\n cooperative: () => {\n abort.abort(new Error(\"the cooperative abort of the drain\"));\n closeSource();\n },\n cut: (cause) => {\n abort.abort(new Error(cause));\n finish(cutEnd(cause));\n closeSource();\n },\n };\n flights.add(flight);\n\n /** This function takes the result of the work: a stream, or one value. */\n const take = (result: unknown): void => {\n if (end !== null) return;\n if (isAsyncIterable(result)) {\n source = (result as AsyncIterable<T>)[Symbol.asyncIterator]();\n // a stream that comes after the cooperative abort ends at once\n if (abort.signal.aborted) closeSource();\n } else {\n unary = { value: result as T };\n // the unary work has ended: its value waits for the reader\n settle(flight);\n }\n };\n let ready: Promise<void>;\n try {\n const result = work(abort.signal);\n if (isAsyncIterable(result) || !isPromiseLike(result)) {\n take(result);\n ready = Promise.resolve();\n } else ready = Promise.resolve(result).then(take, failed);\n } catch (error) {\n failed(error);\n ready = Promise.resolve();\n }\n\n const next = async (): Promise<RequestEvent<T> | null> => {\n if (ended) return null;\n if (end === null) await untilAbort(ready, interruption.signal, \"interrupted\");\n if (end === null && unary !== null) {\n const { value } = unary;\n unary = null;\n delivered = 1;\n end = { kind: \"done\", delivered };\n return { kind: \"item\", value };\n }\n if (end === null && source !== null) {\n const pending = source.next();\n let step: IteratorResult<T> | \"interrupted\";\n try {\n step = await untilAbort(Promise.resolve(pending), interruption.signal, \"interrupted\" as const);\n } catch (error) {\n failed(error);\n step = \"interrupted\";\n }\n if (step !== \"interrupted\") {\n if (step.done !== true) {\n delivered += 1;\n return { kind: \"item\", value: step.value };\n }\n // a stream that ends after the abort of the shutdown is a cut\n finish(abort.signal.aborted ? cutEnd(\"the shutdown ended the stream\") : { kind: \"done\", delivered });\n }\n }\n ended = true;\n return end!;\n };\n const stop = (): void => {\n // the reader stopped before the end: the work stops too\n if (end === null) {\n abort.abort(new Error(\"the reader stopped the stream\"));\n finish({ kind: \"done\", delivered });\n closeSource();\n }\n ended = true;\n };\n return streamOf(next, stop);\n };\n\n return {\n request<T>(controller: string, route: string, work: RequestFn<T>, options: RequestOptions = {}) {\n const operation = operationOf(controller, route, options.detail);\n const refusal = intake ? refuses(controller) : \"the service stopped its intake\";\n if (refusal !== null) {\n let given = false;\n const refused: RequestEnd = { kind: \"refused\", status: 503, retryable: true, cause: refusal, delivered: 0 };\n return streamOf<T>(\n () => {\n if (given) return Promise.resolve(null);\n given = true;\n return Promise.resolve(refused);\n },\n () => {\n given = true;\n },\n );\n }\n return open(controller, operation, work);\n },\n inFlight(controller) {\n let count = 0;\n for (const flight of flights) if (controller === undefined || flight.controller === controller) count += 1;\n return count;\n },\n stopIntake() {\n intake = false;\n },\n cooperativeAbort() {\n for (const flight of [...flights]) flight.cooperative();\n },\n drain(deadline) {\n if (flights.size === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n let finished = false;\n const done = (): void => {\n if (finished) return;\n finished = true;\n idle.delete(done);\n cancel();\n resolve();\n };\n idle.add(done);\n // the drain awaits its deadline, thus the timer keeps the process alive (SYS-126)\n const cancel = clock.after(Math.max(0, deadline - clock.now()), () => {\n for (const flight of [...flights]) flight.cut(\"the drain reached its deadline\");\n done();\n });\n });\n },\n };\n};\n"],"mappings":";;;;;AAyFA,MAAM,mBAAmB,UACvB,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA+C,OAAO,mBAAmB;AACnF,MAAM,iBAAiB,UACrB,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;;AAGhD,MAAM,YAAe,MAA6C,SAAuC;CACvG,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,MAAM,WAA2C;EAC/C,OAAO;GAEL,MAAM,OAAO,MAAM,KAAK,IAAI,CAAC,CAAC,MAAM,UAClC,UAAU,OAAO;I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K,MAAM,UAAU,SAAS,IAAI,eAAe,KAAA,KAAa,OAAO,eAAe,YAAY,SAAS;GACzG,OAAO;EACT;EACA,aAAa;GACX,SAAS;EACX;EACA,mBAAmB;GACjB,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,YAAY;EACxD;EACA,MAAM,UAAU;GACd,IAAI,QAAQ,SAAS,GAAG,OAAO,QAAQ,QAAQ;GAC/C,OAAO,IAAI,SAAe,YAAY;IACpC,IAAI,WAAW;IACf,MAAM,aAAmB;KACvB,IAAI,UAAU;KACd,WAAW;KACX,KAAK,OAAO,IAAI;KAChB,OAAO;KACP,QAAQ;IACV;IACA,KAAK,IAAI,IAAI;IAEb,MAAM,SAAS,MAAM,MAAM,KAAK,IAAI,GAAG,WAAW,MAAM,IAAI,CAAC,SAAS;KACpE,KAAK,MAAM,UAAU,CAAC,GAAG,OAAO,GAAG,OAAO,IAAI,gCAAgC;KAC9E,KAAK;IACP,CAAC;GACH,CAAC;EACH;CACF;AACF"}
@@ -0,0 +1,62 @@
1
+ import { Backoff } from "./backoff.js";
2
+ import { Clock } from "./clock.js";
3
+ /** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */
4
+ export interface RetrierOptions extends Backoff {
5
+ /** This clock starts each retry. The default is the real clock. A test gives a fake clock. */
6
+ readonly clock?: Clock | undefined;
7
+ /** This function gives a number in [0, 1) for the jitter of each delay. The default is `Math.random`. */
8
+ readonly random?: (() => number) | undefined;
9
+ /**
10
+ * This signal cancels the retrier when it aborts, for example the `signal` of the lifecycle, which
11
+ * aborts in the drain. After the abort, `schedule` starts nothing.
12
+ */
13
+ readonly signal?: AbortSignal | undefined;
14
+ }
15
+ /** A retrier starts a function again after the backoff of each try, on its clock. */
16
+ export interface Retrier {
17
+ /** This count is the number of tries since the last reset. */
18
+ readonly attempts: number;
19
+ /** This flag tells if a retry waits for its timer. */
20
+ readonly pending: boolean;
21
+ /**
22
+ * This method counts one more try, and starts `run` after the backoff delay of that try. It gives
23
+ * the delay in milliseconds. A retry that waits stops, thus one retry at most waits. After the
24
+ * abort of the signal, it starts nothing and gives null. The function catches its own errors.
25
+ */
26
+ schedule(run: () => void): number | null;
27
+ /** This method sets the count of tries to 0, for example after a start that succeeded. A retry that waits stays. */
28
+ reset(): void;
29
+ /** This method stops the retry that waits. The count of tries stays. */
30
+ cancel(): void;
31
+ }
32
+ /**
33
+ * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after
34
+ * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy
35
+ * with a problem of `backoffProblems`.
36
+ */
37
+ export declare const retrier: (options: RetrierOptions) => Retrier;
38
+ /** These options make one call with retries: the most tries, the errors to retry, and the policy of a retrier. */
39
+ export interface RetryOptions extends RetrierOptions {
40
+ /** This number is the most tries of the call, the first try included. It is 1 or more. */
41
+ readonly tries: number;
42
+ /** This function tells if a try starts again after this error. The default retries each error. */
43
+ readonly retryable?: ((error: unknown) => boolean) | undefined;
44
+ /**
45
+ * This function gives the delay in milliseconds before the next try, in place of the backoff. An example
46
+ * is the `Retry-After` header of an HTTP 429. Null, undefined, NaN, an infinite or a negative number keeps
47
+ * the backoff delay. The retry puts no cap on this delay, so the caller caps it, for example at 60 s.
48
+ */
49
+ readonly delayOf?: ((error: unknown, attempt: number) => number | null | undefined) | undefined;
50
+ }
51
+ /**
52
+ * This function gives the wait of a `Retry-After` header (RFC 9110) in milliseconds: a count of seconds,
53
+ * or an HTTP date after `now`. It gives null for a header with no valid value. A date before `now` gives 0.
54
+ */
55
+ export declare const retryAfterDelay: (header: string | null | undefined, now: number) => number | null;
56
+ /**
57
+ * This function starts `run`, and starts it again after an error, to the count of `tries`. The delay
58
+ * before try n + 1 is `delayOf(error, n)`, else the `backoffDelay` of try n, on the clock. The call gives
59
+ * the value of the first try that succeeds. After the last try, an error that is not retryable, or the
60
+ * abort of the signal, it throws the last error. It refuses a policy with a problem of `backoffProblems`.
61
+ */
62
+ export declare const retry: <T>(run: (attempt: number) => Promise<T>, options: RetryOptions) => Promise<T>;
@@ -81,6 +81,6 @@ const retry = async (run, options) => {
81
81
  }
82
82
  }
83
83
  };
84
- export { retryAfterDelay as i, retrierOn as n, retry as r, retrier as t };
84
+ export { retrier, retrierOn, retry, retryAfterDelay };
85
85
 
86
- //# sourceMappingURL=retrier-Dnjhvxol.js.map
86
+ //# sourceMappingURL=retrier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retrier.js","names":[],"sources":["../src/retrier.ts"],"sourcesContent":["import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { Backoff } from \"./backoff.ts\";\nimport { backoffDelay, backoffProblems } from \"./backoff.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport { realClock } from \"./clock.ts\";\n\n/** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */\nexport interface RetrierOptions extends Backoff {\n /** This clock starts each retry. The default is the real clock. A test gives a fake clock. */\n readonly clock?: Clock | undefined;\n /** This function gives a number in [0, 1) for the jitter of each delay. The default is `Math.random`. */\n readonly random?: (() => number) | undefined;\n /**\n * This signal cancels the retrier when it aborts, for example the `signal` of the lifecycle, which\n * aborts in the drain. After the abort, `schedule` starts nothing.\n */\n readonly signal?: AbortSignal | undefined;\n}\n\n/** A retrier starts a function again after the backoff of each try, on its clock. */\nexport interface Retrier {\n /** This count is the number of tries since the last reset. */\n readonly attempts: number;\n /** This flag tells if a retry waits for its timer. */\n readonly pending: boolean;\n /**\n * This method counts one more try, and starts `run` after the backoff delay of that try. It gives\n * the delay in milliseconds. A retry that waits stops, thus one retry at most waits. After the\n * abort of the signal, it starts nothing and gives null. The function catches its own errors.\n */\n schedule(run: () => void): number | null;\n /** This method sets the count of tries to 0, for example after a start that succeeded. A retry that waits stays. */\n reset(): void;\n /** This method stops the retry that waits. The count of tries stays. */\n cancel(): void;\n}\n\n/** This function makes a retrier with no check of its policy. A client of the package uses it with its own knobs. */\nexport const retrierOn = (clock: Clock, backoff: Backoff, random: () => number, signal?: AbortSignal): Retrier => {\n let tries = 0;\n let timer: Cancel | null = null;\n const cancel = (): void => {\n timer?.();\n timer = null;\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n return {\n get attempts() {\n return tries;\n },\n get pending() {\n return timer !== null;\n },\n schedule(run) {\n if (signal?.aborted === true) return null;\n tries += 1;\n const delay = Math.round(backoffDelay(backoff, tries, random));\n timer?.();\n // the next try is work, thus the timer keeps the process alive. The owner stops the retrier (SYS-126)\n timer = clock.after(delay, () => {\n timer = null;\n run();\n });\n return delay;\n },\n cancel,\n reset() {\n tries = 0;\n },\n };\n};\n\n/**\n * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after\n * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy\n * with a problem of `backoffProblems`.\n */\nexport const retrier = (options: RetrierOptions): Retrier => {\n const { clock = realClock, random = Math.random, signal, ...backoff } = options;\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retrier has a bad backoff: ${problems.join(\"; \")}`);\n return retrierOn(clock, backoff, random, signal);\n};\n\n/** These options make one call with retries: the most tries, the errors to retry, and the policy of a retrier. */\nexport interface RetryOptions extends RetrierOptions {\n /** This number is the most tries of the call, the first try included. It is 1 or more. */\n readonly tries: number;\n /** This function tells if a try starts again after this error. The default retries each error. */\n readonly retryable?: ((error: unknown) => boolean) | undefined;\n /**\n * This function gives the delay in milliseconds before the next try, in place of the backoff. An example\n * is the `Retry-After` header of an HTTP 429. Null, undefined, NaN, an infinite or a negative number keeps\n * the backoff delay. The retry puts no cap on this delay, so the caller caps it, for example at 60 s.\n */\n readonly delayOf?: ((error: unknown, attempt: number) => number | null | undefined) | undefined;\n}\n\n/**\n * This function gives the wait of a `Retry-After` header (RFC 9110) in milliseconds: a count of seconds,\n * or an HTTP date after `now`. It gives null for a header with no valid value. A date before `now` gives 0.\n */\nexport const retryAfterDelay = (header: string | null | undefined, now: number): number | null => {\n const text = header?.trim() ?? \"\";\n if (text === \"\") return null;\n if (/^\\d+$/.test(text)) return Number(text) * 1000;\n // An HTTP date has the name of its day and month. Without a letter, Date.parse reads \"-3\" as a year.\n const at = /[A-Za-z]/.test(text) ? Date.parse(text) : Number.NaN;\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n};\n\n/**\n * This function starts `run`, and starts it again after an error, to the count of `tries`. The delay\n * before try n + 1 is `delayOf(error, n)`, else the `backoffDelay` of try n, on the clock. The call gives\n * the value of the first try that succeeds. After the last try, an error that is not retryable, or the\n * abort of the signal, it throws the last error. It refuses a policy with a problem of `backoffProblems`.\n */\nexport const retry = async <T>(run: (attempt: number) => Promise<T>, options: RetryOptions): Promise<T> => {\n const { tries, retryable = () => true, delayOf, clock = realClock, random = Math.random, signal, ...backoff } = options;\n if (!Number.isInteger(tries) || tries < 1) throw new Error(`retry needs a whole number of tries of 1 or more, not ${tries}`);\n const problems = backoffProblems(backoff);\n if (problems.length > 0) throw new Error(`the retry has a bad backoff: ${problems.join(\"; \")}`);\n for (let attempt = 1; ; attempt += 1) {\n try {\n return await run(attempt);\n } catch (error) {\n if (attempt >= tries || signal?.aborted === true || !retryable(error)) throw error;\n const own = delayOf?.(error, attempt);\n // A bad delay (NaN, an infinite or a negative number) gets the backoff, so that it cannot start the tries at once.\n const valid = typeof own === \"number\" && Number.isFinite(own) && own >= 0;\n const wait = Math.round(valid ? own : backoffDelay(backoff, attempt, random));\n // An abort in the wait ends the call with the last error of the run, not with the reason of the signal.\n try {\n await delay(clock, wait, signal);\n } catch {\n throw error;\n }\n }\n }\n};\n"],"mappings":";;;;;AAsCA,MAAa,aAAa,OAAc,SAAkB,QAAsB,WAAkC;CAChH,IAAI,QAAQ;CACZ,IAAI,QAAuB;CAC3B,MAAM,eAAqB;EACzB,QAAQ;EACR,QAAQ;CACV;CACA,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;CACxD,OAAO;EACL,IAAI,WAAW;GACb,OAAO;EACT;EACA,IAAI,UAAU;GACZ,OAAO,UAAU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AAW,GACjC,IAAI;EACF,OAAO,MAAM,IAAI,OAAO;CAC1B,SAAS,OAAO;EACd,IAAI,WAAW,SAAS,QAAQ,YAAY,QAAQ,CAAC,UAAU,KAAK,GAAG,MAAM;EAC7E,MAAM,MAAM,UAAU,OAAO,OAAO;EAGpC,MAAM,OAAO,KAAK,MADJ,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,OAAO,IACxC,MAAM,aAAa,SAAS,SAAS,MAAM,CAAC;EAE5E,IAAI;GACF,MAAM,MAAM,OAAO,MAAM,MAAM;EACjC,QAAQ;GACN,MAAM;EACR;CACF;AAEJ"}
@@ -0,0 +1,35 @@
1
+ import { Operation } from "./operation.js";
2
+ /**
3
+ * A route pattern matches the routes of a controller that its exact routes do not name. A
4
+ * registry that changes while the service operates, for example a registry of procedures, thus
5
+ * needs no list of routes before the start. The syntax of a pattern:
6
+ * - `*` matches each text, also an empty text and a text with `/`. The pattern `*` alone matches
7
+ * each route.
8
+ * - `:name` matches a text of one character or more without `/`, and gives it in `params.name`.
9
+ * - Each other character matches itself.
10
+ *
11
+ * The declaration names the operations that a request of the pattern can be. Each operation
12
+ * declares its idempotency, as a route does. A function picks the operation of each request.
13
+ */
14
+ export interface RoutePattern {
15
+ readonly pattern: string;
16
+ /** These are the operations that a request of the pattern can be, by name. */
17
+ readonly operations: Readonly<Record<string, Operation>>;
18
+ }
19
+ /** A route request is what the function of a pattern gets for one request. */
20
+ export interface RouteRequest {
21
+ readonly controller: string;
22
+ readonly route: string;
23
+ /** These are the texts of the `:name` parts of the pattern, by name. */
24
+ readonly params: Readonly<Record<string, string>>;
25
+ /** These are the texts of the `*` parts of the pattern, in their sequence. */
26
+ readonly wildcards: readonly string[];
27
+ /** This value is the detail that the transport gives with the request, or undefined. */
28
+ readonly detail: unknown;
29
+ }
30
+ /**
31
+ * An operation choice gives the name of the operation of one request: one of the operations that
32
+ * the pattern declares. Thus the function decides the idempotency of each request, and the
33
+ * declaration keeps each window of a keyed operation as data.
34
+ */
35
+ export type OperationOf = (request: RouteRequest) => string;
@@ -0,0 +1,77 @@
1
+ import { operationProblems } from "./operation.js";
2
+ // src/routes.ts
3
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*/;
4
+ /** This function gives the problems of the syntax of a pattern: an empty pattern, a part without a name, or a name two times. */
5
+ const patternProblems = (owner, pattern) => {
6
+ const problems = [];
7
+ if (pattern.length === 0) problems.push(`${owner} has an empty route pattern`);
8
+ const names = /* @__PURE__ */ new Set();
9
+ for (let at = 0; at < pattern.length; at += 1) {
10
+ if (pattern[at] !== ":") continue;
11
+ const name = NAME.exec(pattern.slice(at + 1))?.[0];
12
+ if (name === void 0) {
13
+ problems.push(`${owner}'s pattern ${pattern} has a ":" without a name at ${at}`);
14
+ continue;
15
+ }
16
+ if (names.has(name)) problems.push(`${owner}'s pattern ${pattern} names :${name} two times`);
17
+ names.add(name);
18
+ at += name.length;
19
+ }
20
+ return problems;
21
+ };
22
+ /** This function gives the problems of a pattern and of each of its operations, which `describe()` refuses. */
23
+ const routePatternProblems = (owner, declared) => {
24
+ const problems = patternProblems(owner, declared.pattern);
25
+ const names = Object.keys(declared.operations);
26
+ if (names.length === 0) problems.push(`${owner}'s pattern ${declared.pattern} declares no operation`);
27
+ for (const name of names) problems.push(...operationProblems(owner, `${declared.pattern} (${name})`, declared.operations[name]));
28
+ return problems;
29
+ };
30
+ /** This function compiles a pattern to a matcher. The match must cover the whole route. */
31
+ const compilePattern = (pattern) => {
32
+ const kinds = [];
33
+ let source = "^";
34
+ for (let at = 0; at < pattern.length; at += 1) {
35
+ const char = pattern[at];
36
+ if (char === "*") {
37
+ source += "([\\s\\S]*)";
38
+ kinds.push({ kind: "wildcard" });
39
+ continue;
40
+ }
41
+ if (char === ":") {
42
+ const name = NAME.exec(pattern.slice(at + 1))?.[0];
43
+ if (name !== void 0) {
44
+ source += "([^/]+)";
45
+ kinds.push({
46
+ kind: "param",
47
+ name
48
+ });
49
+ at += name.length;
50
+ continue;
51
+ }
52
+ }
53
+ source += char.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
54
+ }
55
+ const matcher = new RegExp(`${source}$`);
56
+ return {
57
+ pattern,
58
+ match(route) {
59
+ const found = matcher.exec(route);
60
+ if (found === null) return null;
61
+ const params = {};
62
+ const wildcards = [];
63
+ kinds.forEach((part, index) => {
64
+ const text = found[index + 1] ?? "";
65
+ if (part.kind === "param") params[part.name] = text;
66
+ else wildcards.push(text);
67
+ });
68
+ return {
69
+ params,
70
+ wildcards
71
+ };
72
+ }
73
+ };
74
+ };
75
+ export { compilePattern, patternProblems, routePatternProblems };
76
+
77
+ //# sourceMappingURL=routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../src/routes.ts"],"sourcesContent":["import type { Operation } from \"./operation.ts\";\nimport { operationProblems } from \"./operation.ts\";\n\n/**\n * A route pattern matches the routes of a controller that its exact routes do not name. A\n * registry that changes while the service operates, for example a registry of procedures, thus\n * needs no list of routes before the start. The syntax of a pattern:\n * - `*` matches each text, also an empty text and a text with `/`. The pattern `*` alone matches\n * each route.\n * - `:name` matches a text of one character or more without `/`, and gives it in `params.name`.\n * - Each other character matches itself.\n *\n * The declaration names the operations that a request of the pattern can be. Each operation\n * declares its idempotency, as a route does. A function picks the operation of each request.\n */\nexport interface RoutePattern {\n readonly pattern: string;\n /** These are the operations that a request of the pattern can be, by name. */\n readonly operations: Readonly<Record<string, Operation>>;\n}\n\n/** A route request is what the function of a pattern gets for one request. */\nexport interface RouteRequest {\n readonly controller: string;\n readonly route: string;\n /** These are the texts of the `:name` parts of the pattern, by name. */\n readonly params: Readonly<Record<string, string>>;\n /** These are the texts of the `*` parts of the pattern, in their sequence. */\n readonly wildcards: readonly string[];\n /** This value is the detail that the transport gives with the request, or undefined. */\n readonly detail: unknown;\n}\n\n/**\n * An operation choice gives the name of the operation of one request: one of the operations that\n * the pattern declares. Thus the function decides the idempotency of each request, and the\n * declaration keeps each window of a keyed operation as data.\n */\nexport type OperationOf = (request: RouteRequest) => string;\n\n/** A compiled pattern matches a route, and gives the parts of the route that it matched. */\nexport interface CompiledPattern {\n readonly pattern: string;\n match(route: string): { readonly params: Record<string, string>; readonly wildcards: string[] } | null;\n}\n\nconst NAME = /^[A-Za-z_][A-Za-z0-9_]*/;\n\n/** This function gives the problems of the syntax of a pattern: an empty pattern, a part without a name, or a name two times. */\nexport const patternProblems = (owner: string, pattern: string): string[] => {\n const problems: string[] = [];\n if (pattern.length === 0) problems.push(`${owner} has an empty route pattern`);\n const names = new Set<string>();\n for (let at = 0; at < pattern.length; at += 1) {\n if (pattern[at] !== \":\") continue;\n const name = NAME.exec(pattern.slice(at + 1))?.[0];\n if (name === undefined) {\n problems.push(`${owner}'s pattern ${pattern} has a \":\" without a name at ${at}`);\n continue;\n }\n if (names.has(name)) problems.push(`${owner}'s pattern ${pattern} names :${name} two times`);\n names.add(name);\n at += name.length;\n }\n return problems;\n};\n\n/** This function gives the problems of a pattern and of each of its operations, which `describe()` refuses. */\nexport const routePatternProblems = (owner: string, declared: RoutePattern): string[] => {\n const problems = patternProblems(owner, declared.pattern);\n const names = Object.keys(declared.operations);\n if (names.length === 0) problems.push(`${owner}'s pattern ${declared.pattern} declares no operation`);\n for (const name of names)\n problems.push(...operationProblems(owner, `${declared.pattern} (${name})`, declared.operations[name]!));\n return problems;\n};\n\n/** This function compiles a pattern to a matcher. The match must cover the whole route. */\nexport const compilePattern = (pattern: string): CompiledPattern => {\n const kinds: Array<{ kind: \"param\"; name: string } | { kind: \"wildcard\" }> = [];\n let source = \"^\";\n for (let at = 0; at < pattern.length; at += 1) {\n const char = pattern[at]!;\n if (char === \"*\") {\n source += \"([\\\\s\\\\S]*)\";\n kinds.push({ kind: \"wildcard\" });\n continue;\n }\n if (char === \":\") {\n const name = NAME.exec(pattern.slice(at + 1))?.[0];\n if (name !== undefined) {\n source += \"([^/]+)\";\n kinds.push({ kind: \"param\", name });\n at += name.length;\n continue;\n }\n }\n source += char.replace(/[.*+?^${}()|[\\]\\\\/]/g, \"\\\\$&\");\n }\n const matcher = new RegExp(`${source}$`);\n return {\n pattern,\n match(route) {\n const found = matcher.exec(route);\n if (found === null) return null;\n const params: Record<string, string> = {};\n const wildcards: string[] = [];\n kinds.forEach((part, index) => {\n const text = found[index + 1] ?? \"\";\n if (part.kind === \"param\") params[part.name] = text;\n else wildcards.push(text);\n });\n return { params, wildcards };\n },\n };\n};\n"],"mappings":";;AA8CA,MAAM,OAAO;;AAGb,MAAa,mBAAmB,OAAe,YAA8B;CAC3E,MAAM,WAAqB,CAAC;CAC5B,IAAI,QAAQ,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,4BAA4B;CAC7E,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,IAAI,KAAK,GAAG,KAAK,QAAQ,QAAQ,MAAM,GAAG;EAC7C,IAAI,QAAQ,QAAQ,KAAK;EACzB,MAAM,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,GAAG;EAChD,IAAI,SAAS,KAAA,GAAW;GACtB,SAAS,KAAK,GAAG,MAAM,aAAa,QAAQ,+BAA+B,IAAI;GAC/E;EACF;EACA,IAAI,MAAM,IAAI,IAAI,GAAG,SAAS,KAAK,GAAG,MAAM,aAAa,QAAQ,UAAU,KAAK,WAAW;EAC3F,MAAM,IAAI,IAAI;EACd,MAAM,KAAK;CACb;CACA,OAAO;AACT;;AAGA,MAAa,wBAAwB,OAAe,aAAqC;CACvF,MAAM,WAAW,gBAAgB,OAAO,SAAS,OAAO;CACxD,MAAM,QAAQ,OAAO,KAAK,SAAS,UAAU;CAC7C,IAAI,MAAM,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,aAAa,SAAS,QAAQ,uBAAuB;CACpG,KAAK,MAAM,QAAQ,OACjB,SAAS,KAAK,GAAG,kBAAkB,OAAO,GAAG,SAAS,QAAQ,IAAI,KAAK,IAAI,SAAS,WAAW,KAAM,CAAC;CACxG,OAAO;AACT;;AAGA,MAAa,kBAAkB,YAAqC;CAClE,MAAM,QAAuE,CAAC;CAC9E,IAAI,SAAS;CACb,KAAK,IAAI,KAAK,GAAG,KAAK,QAAQ,QAAQ,MAAM,GAAG;EAC7C,MAAM,OAAO,QAAQ;EACrB,IAAI,SAAS,KAAK;GAChB,UAAU;GACV,MAAM,KAAK,EAAE,MAAM,WAAW,CAAC;GAC/B;EACF;EACA,IAAI,SAAS,KAAK;GAChB,MAAM,OAAO,KAAK,KAAK,QAAQ,MAAM,KAAK,CAAC,CAAC,CAAC,GAAG;GAChD,IAAI,SAAS,KAAA,GAAW;IACtB,UAAU;IACV,MAAM,KAAK;KAAE,MAAM;KAAS;IAAK,CAAC;IAClC,MAAM,KAAK;IACX;GACF;EACF;EACA,UAAU,KAAK,QAAQ,wBAAwB,MAAM;CACvD;CACA,MAAM,UAAU,IAAI,OAAO,GAAG,OAAO,EAAE;CACvC,OAAO;EACL;EACA,MAAM,OAAO;GACX,MAAM,QAAQ,QAAQ,KAAK,KAAK;GAChC,IAAI,UAAU,MAAM,OAAO;GAC3B,MAAM,SAAiC,CAAC;GACxC,MAAM,YAAsB,CAAC;GAC7B,MAAM,SAAS,MAAM,UAAU;IAC7B,MAAM,OAAO,MAAM,QAAQ,MAAM;IACjC,IAAI,KAAK,SAAS,SAAS,OAAO,KAAK,QAAQ;SAC1C,UAAU,KAAK,IAAI;GAC1B,CAAC;GACD,OAAO;IAAE;IAAQ;GAAU;EAC7B;CACF;AACF"}
package/build/rules.d.ts CHANGED
@@ -1,2 +1,19 @@
1
- import { a as O16, i as O10, n as O04, p as Rule, r as O09, t as DRAIN_RULES } from "./rules-HyFCBStQ.js";
2
- export { DRAIN_RULES, O04, O09, O10, O16, type Rule };
1
+ import { Rule } from "./law.js";
2
+ /**
3
+ * O04 with the hold of the service. The listener of a pod stays open through the preStop sleep and
4
+ * then through the hold of `fail readiness`. Thus the sum of the two must cover the propagation of
5
+ * the endpoints. The rule of the research is the case without a hold.
6
+ */
7
+ export declare const O04: Rule;
8
+ /** O09 is W8: readiness detection plus propagation is no longer than liveness detection plus the preStop sleep. */
9
+ export declare const O09: Rule;
10
+ /** O10: the preStop sleep plus the drain of the process fits in the grace period. */
11
+ export declare const O10: Rule;
12
+ /** O16: the cooperative window is shorter than the drain, which is shorter than the grace less the preStop sleep. */
13
+ export declare const O16: Rule;
14
+ /**
15
+ * These are the rules of the drain. For each way that a pod stops, `lintStop()` applies only the
16
+ * rules of this set that guard that way. `DRAIN_RULE_IDS` gives their identifiers.
17
+ */
18
+ export declare const DRAIN_RULES: readonly Rule[];
19
+ export type { Rule };