@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,40 @@
1
+ import { KeyState, LimitPolicy, LimitRule } from "./policy.js";
2
+ import { Machine } from "@mark1russell7/algebra";
3
+ /**
4
+ * A limiter state is the state of one key of a keyed limiter, as its machine document names it:
5
+ * - `new`: the store holds no state for the key, or a state that is equal to the state of a new key.
6
+ * - `open`: the key holds a count, and its next take is permitted.
7
+ * - `limited`: the next take of the key is refused with the cause `limit`, until a unit is back.
8
+ */
9
+ export type LimiterState = "new" | "open" | "limited";
10
+ /**
11
+ * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds
12
+ * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time
13
+ * for the key: when its bucket is full again.
14
+ * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.
15
+ * - A refused take waits until one token is back: at most one interval. That interval is the
16
+ * longest `Retry-After` of the policy (`retry_after@limiter` of the law).
17
+ * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That
18
+ * span is the idle span, and the longest wait of a new key at the cap of keys
19
+ * (`retry_after_at_cap@limiter`).
20
+ */
21
+ export declare const TOKEN_BUCKET_MACHINE: Machine;
22
+ /**
23
+ * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of
24
+ * each permitted take of the key in the window, and each take counts for one window from its time.
25
+ * - A take is permitted when fewer than `limit` takes are in the window.
26
+ * - A refused take waits until the oldest take leaves the window: at most one window. That window is
27
+ * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).
28
+ * - One window after the last take, no take is in the window, and the key is equal to a new key.
29
+ * That window is the idle span, and the longest wait of a new key at the cap of keys
30
+ * (`retry_after_at_cap@limiter`).
31
+ */
32
+ export declare const SLIDING_WINDOW_MACHINE: Machine;
33
+ /** This function gives the machine document of the policy of a limiter. */
34
+ export declare const limiterMachine: (policy: LimitPolicy) => Machine;
35
+ /**
36
+ * This function gives the state of a key of a store as its machine document names it, at the time
37
+ * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps
38
+ * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.
39
+ */
40
+ export declare const limiterStateOf: (rule: LimitRule, state: KeyState | undefined, now: number) => LimiterState;
@@ -0,0 +1,279 @@
1
+ import { decide, freeAt } from "./policy.js";
2
+ // src/limiter/machine.ts
3
+ const t = (id, from, on, to, extra = {}) => ({
4
+ id,
5
+ from,
6
+ on,
7
+ to,
8
+ ...extra
9
+ });
10
+ const count = (key) => ({
11
+ key,
12
+ scope: "limiter",
13
+ unit: "count",
14
+ default: null
15
+ });
16
+ /** These are the states of a key that a store can hold. A store fails in each of them. */
17
+ const HELD = [
18
+ "new",
19
+ "open",
20
+ "limited"
21
+ ];
22
+ /** These are the parts of each document of a limiter that do not change with its policy. */
23
+ const COMMON = {
24
+ format: "mark1russell7.machine/1",
25
+ layer: "self",
26
+ version: "0.1.0",
27
+ sources: [
28
+ {
29
+ ref: "packages/service/src/limiter (the runtime implements this document: decide, memoryStore, keyedLimiter)",
30
+ rung: "implemented"
31
+ },
32
+ {
33
+ ref: "RFC 6585 §4: 429 Too Many Requests, which can carry Retry-After",
34
+ rung: "normative"
35
+ },
36
+ {
37
+ ref: "RFC 9110 §10.2.3: Retry-After, as delay-seconds or an HTTP-date",
38
+ rung: "normative"
39
+ }
40
+ ],
41
+ conditions: {
42
+ "store.local": "the counts are in the memory of one replica: a limit L over N replicas is L / N on each replica, and that sum holds only on average",
43
+ "store.shared": "the counts are in a store that the replicas share: one atomic step on the clock of the store decides each take"
44
+ },
45
+ states: {
46
+ new: {
47
+ initial: true,
48
+ note: "the store holds no state for the key, or a state equal to a new key. The store can remove the key"
49
+ },
50
+ open: { note: "the key holds a count, and its next take is permitted" },
51
+ limited: { note: "the next take is refused with the cause limit, until a unit is back" }
52
+ }
53
+ };
54
+ /** These are the events of each document of a limiter. */
55
+ const EVENTS = {
56
+ take: {
57
+ kind: "app",
58
+ note: "one call of take(key): one request of the key. A permitted take uses one unit"
59
+ },
60
+ "unit.back": {
61
+ kind: "timer",
62
+ note: "the next take of a limited key is permitted again"
63
+ },
64
+ idle: {
65
+ kind: "timer",
66
+ note: "the key is equal to a new key. The store can remove it, and no decision changes"
67
+ },
68
+ "store.fail": {
69
+ kind: "local",
70
+ note: "a shared store fails the take. The state of the key does not change"
71
+ }
72
+ };
73
+ /** These are the knobs of each document of a limiter that do not change with its policy. */
74
+ const KNOBS = {
75
+ max_keys: count("limiters.<name>.evict.maxKeys"),
76
+ on_store_failure: {
77
+ key: "limiters.<name>.store.onStoreFailure",
78
+ scope: "limiter",
79
+ unit: null,
80
+ default: null
81
+ }
82
+ };
83
+ /**
84
+ * These are the transitions of each document of a limiter that do not change with its policy. They
85
+ * are the refusal of a limited key, a new key at the cap of keys, and a failure of a shared store.
86
+ */
87
+ const COMMON_TRANSITIONS = [
88
+ t("refuse", "limited", "take", "limited", {
89
+ emits: ["429 limit"],
90
+ note: "Retry-After is the time until the next take is permitted, in whole seconds, rounded up. The count of the key does not change"
91
+ }),
92
+ t("cap", "new", "take", "new", {
93
+ guard: "the store holds max_keys keys for the limiter, and no held key is equal to a new key",
94
+ emits: ["429 cap"],
95
+ note: "Retry-After is the time until the earliest held key is free: at most the idle span. A held key keeps its count"
96
+ }),
97
+ ...HELD.map((state) => t(`store-failed-${state}`, state, "store.fail", state, {
98
+ guard: "the store is shared",
99
+ emits: ["allow, or 429 store"],
100
+ note: "on_store_failure open lets the take in, with remaining 0. closed refuses it with the cause store, and its Retry-After is the longest of the policy"
101
+ }))
102
+ ];
103
+ /**
104
+ * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds
105
+ * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time
106
+ * for the key: when its bucket is full again.
107
+ * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.
108
+ * - A refused take waits until one token is back: at most one interval. That interval is the
109
+ * longest `Retry-After` of the policy (`retry_after@limiter` of the law).
110
+ * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That
111
+ * span is the idle span, and the longest wait of a new key at the cap of keys
112
+ * (`retry_after_at_cap@limiter`).
113
+ */
114
+ const TOKEN_BUCKET_MACHINE = {
115
+ ...COMMON,
116
+ id: "service.machine.limiter.token-bucket",
117
+ title: "A token bucket of one key of the keyed limiter",
118
+ events: EVENTS,
119
+ knobs: {
120
+ rate: {
121
+ key: "limiters.<name>.policy.rate",
122
+ scope: "limiter",
123
+ unit: "count/s",
124
+ default: null
125
+ },
126
+ burst: count("limiters.<name>.policy.burst"),
127
+ ...KNOBS
128
+ },
129
+ timers: {
130
+ token: {
131
+ duration: {
132
+ expr: "1 / rate",
133
+ unit: "s"
134
+ },
135
+ early: {
136
+ expr: "1 / rate",
137
+ unit: "s"
138
+ },
139
+ arms: ["enter:limited"],
140
+ cancels: ["idle"],
141
+ fires: "unit.back",
142
+ note: "one token comes back at most one interval after the take that used the last token. The Retry-After of each refusal is the time to this firing"
143
+ },
144
+ full: {
145
+ duration: {
146
+ expr: "burst / rate",
147
+ unit: "s"
148
+ },
149
+ early: {
150
+ expr: "(burst - 1) / rate",
151
+ unit: "s"
152
+ },
153
+ arms: ["take"],
154
+ fires: "idle",
155
+ note: "the bucket is full again from one to burst intervals after a permitted take. A refused take does not move it"
156
+ }
157
+ },
158
+ transitions: [
159
+ t("first", "new", "take", "open", {
160
+ guard: "burst > 1",
161
+ emits: ["allow"]
162
+ }),
163
+ t("first-last", "new", "take", "limited", {
164
+ guard: "burst = 1",
165
+ emits: ["allow"]
166
+ }),
167
+ t("take", "open", "take", "open", {
168
+ guard: "a token remains after the take",
169
+ emits: ["allow"]
170
+ }),
171
+ t("take-last", "open", "take", "limited", {
172
+ guard: "the take uses the last token",
173
+ emits: ["allow"]
174
+ }),
175
+ ...COMMON_TRANSITIONS,
176
+ t("token-back", "limited", "unit.back", "open", {
177
+ timer: "token",
178
+ guard: "burst > 1"
179
+ }),
180
+ t("full", "open", "idle", "new", { timer: "full" }),
181
+ t("full-at-once", "limited", "idle", "new", {
182
+ timer: "full",
183
+ guard: "burst = 1: the one token is back when the bucket is full"
184
+ })
185
+ ]
186
+ };
187
+ /**
188
+ * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of
189
+ * each permitted take of the key in the window, and each take counts for one window from its time.
190
+ * - A take is permitted when fewer than `limit` takes are in the window.
191
+ * - A refused take waits until the oldest take leaves the window: at most one window. That window is
192
+ * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).
193
+ * - One window after the last take, no take is in the window, and the key is equal to a new key.
194
+ * That window is the idle span, and the longest wait of a new key at the cap of keys
195
+ * (`retry_after_at_cap@limiter`).
196
+ */
197
+ const SLIDING_WINDOW_MACHINE = {
198
+ ...COMMON,
199
+ id: "service.machine.limiter.sliding-window",
200
+ title: "A sliding window of one key of the keyed limiter",
201
+ events: EVENTS,
202
+ knobs: {
203
+ limit: count("limiters.<name>.policy.limit"),
204
+ window: {
205
+ key: "limiters.<name>.policy.window",
206
+ scope: "limiter",
207
+ unit: "s",
208
+ default: null
209
+ },
210
+ ...KNOBS
211
+ },
212
+ timers: {
213
+ oldest: {
214
+ duration: {
215
+ knob: "window",
216
+ unit: "s"
217
+ },
218
+ early: {
219
+ knob: "window",
220
+ unit: "s"
221
+ },
222
+ arms: ["enter:limited"],
223
+ cancels: ["idle"],
224
+ fires: "unit.back",
225
+ note: "the oldest take leaves the window at most one window after the take that filled it. The Retry-After of each refusal is the time to this firing"
226
+ },
227
+ last: {
228
+ duration: {
229
+ knob: "window",
230
+ unit: "s"
231
+ },
232
+ arms: ["take"],
233
+ fires: "idle",
234
+ note: "the last permitted take leaves the window one window after its time. A refused take does not move it"
235
+ }
236
+ },
237
+ transitions: [
238
+ t("first", "new", "take", "open", {
239
+ guard: "limit > 1",
240
+ emits: ["allow"]
241
+ }),
242
+ t("first-last", "new", "take", "limited", {
243
+ guard: "limit = 1",
244
+ emits: ["allow"]
245
+ }),
246
+ t("take", "open", "take", "open", {
247
+ guard: "fewer than limit - 1 takes are in the window before the take",
248
+ emits: ["allow"]
249
+ }),
250
+ t("take-last", "open", "take", "limited", {
251
+ guard: "the take is the limit-th take in the window",
252
+ emits: ["allow"]
253
+ }),
254
+ ...COMMON_TRANSITIONS,
255
+ t("oldest-leaves", "limited", "unit.back", "open", {
256
+ timer: "oldest",
257
+ guard: "a later take stays in the window"
258
+ }),
259
+ t("last-leaves", "open", "idle", "new", { timer: "last" }),
260
+ t("all-leave", "limited", "idle", "new", {
261
+ timer: "last",
262
+ guard: "each take of the window has one time: limit = 1, or each take came at once"
263
+ })
264
+ ]
265
+ };
266
+ /** This function gives the machine document of the policy of a limiter. */
267
+ const limiterMachine = (policy) => policy.type === "token-bucket" ? TOKEN_BUCKET_MACHINE : SLIDING_WINDOW_MACHINE;
268
+ /**
269
+ * This function gives the state of a key of a store as its machine document names it, at the time
270
+ * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps
271
+ * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.
272
+ */
273
+ const limiterStateOf = (rule, state, now) => {
274
+ if (state === void 0 || freeAt(rule, state) <= now) return "new";
275
+ return decide(rule, state, now).decision.allowed ? "open" : "limited";
276
+ };
277
+ export { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, limiterMachine, limiterStateOf };
278
+
279
+ //# sourceMappingURL=machine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine.js","names":[],"sources":["../../src/limiter/machine.ts"],"sourcesContent":["import type { Machine, TransitionDef } from \"@mark1russell7/algebra\";\nimport type { KeyState, LimitPolicy, LimitRule } from \"./policy.ts\";\nimport { decide, freeAt } from \"./policy.ts\";\n\nconst t = (id: string, from: string | readonly string[], on: string | readonly string[], to: string, extra: Partial<TransitionDef> = {}): TransitionDef => ({\n id,\n from,\n on,\n to,\n ...extra,\n});\nconst count = (key: string) => ({ key, scope: \"limiter\", unit: \"count\", default: null }) as const;\n\n/**\n * A limiter state is the state of one key of a keyed limiter, as its machine document names it:\n * - `new`: the store holds no state for the key, or a state that is equal to the state of a new key.\n * - `open`: the key holds a count, and its next take is permitted.\n * - `limited`: the next take of the key is refused with the cause `limit`, until a unit is back.\n */\nexport type LimiterState = \"new\" | \"open\" | \"limited\";\n\n/** These are the states of a key that a store can hold. A store fails in each of them. */\nconst HELD = [\"new\", \"open\", \"limited\"] as const;\n\n/** These are the parts of each document of a limiter that do not change with its policy. */\nconst COMMON = {\n format: \"mark1russell7.machine/1\",\n layer: \"self\",\n version: \"0.1.0\",\n sources: [\n { ref: \"packages/service/src/limiter (the runtime implements this document: decide, memoryStore, keyedLimiter)\", rung: \"implemented\" },\n { ref: \"RFC 6585 §4: 429 Too Many Requests, which can carry Retry-After\", rung: \"normative\" },\n { ref: \"RFC 9110 §10.2.3: Retry-After, as delay-seconds or an HTTP-date\", rung: \"normative\" },\n ],\n conditions: {\n \"store.local\": \"the counts are in the memory of one replica: a limit L over N replicas is L / N on each replica, and that sum holds only on average\",\n \"store.shared\": \"the counts are in a store that the replicas share: one atomic step on the clock of the store decides each take\",\n },\n states: {\n new: { initial: true, note: \"the store holds no state for the key, or a state equal to a new key. The store can remove the key\" },\n open: { note: \"the key holds a count, and its next take is permitted\" },\n limited: { note: \"the next take is refused with the cause limit, until a unit is back\" },\n },\n} as const;\n\n/** These are the events of each document of a limiter. */\nconst EVENTS = {\n take: { kind: \"app\", note: \"one call of take(key): one request of the key. A permitted take uses one unit\" },\n \"unit.back\": { kind: \"timer\", note: \"the next take of a limited key is permitted again\" },\n idle: { kind: \"timer\", note: \"the key is equal to a new key. The store can remove it, and no decision changes\" },\n \"store.fail\": { kind: \"local\", note: \"a shared store fails the take. The state of the key does not change\" },\n} as const;\n\n/** These are the knobs of each document of a limiter that do not change with its policy. */\nconst KNOBS = {\n max_keys: count(\"limiters.<name>.evict.maxKeys\"),\n on_store_failure: { key: \"limiters.<name>.store.onStoreFailure\", scope: \"limiter\", unit: null, default: null },\n} as const;\n\n/**\n * These are the transitions of each document of a limiter that do not change with its policy. They\n * are the refusal of a limited key, a new key at the cap of keys, and a failure of a shared store.\n */\nconst COMMON_TRANSITIONS: readonly TransitionDef[] = [\n t(\"refuse\", \"limited\", \"take\", \"limited\", {\n emits: [\"429 limit\"],\n note: \"Retry-After is the time until the next take is permitted, in whole seconds, rounded up. The count of the key does not change\",\n }),\n t(\"cap\", \"new\", \"take\", \"new\", {\n guard: \"the store holds max_keys keys for the limiter, and no held key is equal to a new key\",\n emits: [\"429 cap\"],\n note: \"Retry-After is the time until the earliest held key is free: at most the idle span. A held key keeps its count\",\n }),\n ...HELD.map((state) =>\n t(`store-failed-${state}`, state, \"store.fail\", state, {\n guard: \"the store is shared\",\n emits: [\"allow, or 429 store\"],\n note: \"on_store_failure open lets the take in, with remaining 0. closed refuses it with the cause store, and its Retry-After is the longest of the policy\",\n }),\n ),\n];\n\n/**\n * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds\n * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time\n * for the key: when its bucket is full again.\n * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.\n * - A refused take waits until one token is back: at most one interval. That interval is the\n * longest `Retry-After` of the policy (`retry_after@limiter` of the law).\n * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That\n * span is the idle span, and the longest wait of a new key at the cap of keys\n * (`retry_after_at_cap@limiter`).\n */\nexport const TOKEN_BUCKET_MACHINE: Machine = {\n ...COMMON,\n id: \"service.machine.limiter.token-bucket\",\n title: \"A token bucket of one key of the keyed limiter\",\n events: EVENTS,\n knobs: {\n rate: { key: \"limiters.<name>.policy.rate\", scope: \"limiter\", unit: \"count/s\", default: null },\n burst: count(\"limiters.<name>.policy.burst\"),\n ...KNOBS,\n },\n timers: {\n token: {\n duration: { expr: \"1 / rate\", unit: \"s\" },\n early: { expr: \"1 / rate\", unit: \"s\" },\n arms: [\"enter:limited\"],\n cancels: [\"idle\"],\n fires: \"unit.back\",\n note: \"one token comes back at most one interval after the take that used the last token. The Retry-After of each refusal is the time to this firing\",\n },\n full: {\n duration: { expr: \"burst / rate\", unit: \"s\" },\n early: { expr: \"(burst - 1) / rate\", unit: \"s\" },\n arms: [\"take\"],\n fires: \"idle\",\n note: \"the bucket is full again from one to burst intervals after a permitted take. A refused take does not move it\",\n },\n },\n transitions: [\n t(\"first\", \"new\", \"take\", \"open\", { guard: \"burst > 1\", emits: [\"allow\"] }),\n t(\"first-last\", \"new\", \"take\", \"limited\", { guard: \"burst = 1\", emits: [\"allow\"] }),\n t(\"take\", \"open\", \"take\", \"open\", { guard: \"a token remains after the take\", emits: [\"allow\"] }),\n t(\"take-last\", \"open\", \"take\", \"limited\", { guard: \"the take uses the last token\", emits: [\"allow\"] }),\n ...COMMON_TRANSITIONS,\n t(\"token-back\", \"limited\", \"unit.back\", \"open\", { timer: \"token\", guard: \"burst > 1\" }),\n t(\"full\", \"open\", \"idle\", \"new\", { timer: \"full\" }),\n t(\"full-at-once\", \"limited\", \"idle\", \"new\", {\n timer: \"full\",\n guard: \"burst = 1: the one token is back when the bucket is full\",\n }),\n ],\n};\n\n/**\n * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of\n * each permitted take of the key in the window, and each take counts for one window from its time.\n * - A take is permitted when fewer than `limit` takes are in the window.\n * - A refused take waits until the oldest take leaves the window: at most one window. That window is\n * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).\n * - One window after the last take, no take is in the window, and the key is equal to a new key.\n * That window is the idle span, and the longest wait of a new key at the cap of keys\n * (`retry_after_at_cap@limiter`).\n */\nexport const SLIDING_WINDOW_MACHINE: Machine = {\n ...COMMON,\n id: \"service.machine.limiter.sliding-window\",\n title: \"A sliding window of one key of the keyed limiter\",\n events: EVENTS,\n knobs: {\n limit: count(\"limiters.<name>.policy.limit\"),\n window: { key: \"limiters.<name>.policy.window\", scope: \"limiter\", unit: \"s\", default: null },\n ...KNOBS,\n },\n timers: {\n oldest: {\n duration: { knob: \"window\", unit: \"s\" },\n early: { knob: \"window\", unit: \"s\" },\n arms: [\"enter:limited\"],\n cancels: [\"idle\"],\n fires: \"unit.back\",\n note: \"the oldest take leaves the window at most one window after the take that filled it. The Retry-After of each refusal is the time to this firing\",\n },\n last: {\n duration: { knob: \"window\", unit: \"s\" },\n arms: [\"take\"],\n fires: \"idle\",\n note: \"the last permitted take leaves the window one window after its time. A refused take does not move it\",\n },\n },\n transitions: [\n t(\"first\", \"new\", \"take\", \"open\", { guard: \"limit > 1\", emits: [\"allow\"] }),\n t(\"first-last\", \"new\", \"take\", \"limited\", { guard: \"limit = 1\", emits: [\"allow\"] }),\n t(\"take\", \"open\", \"take\", \"open\", { guard: \"fewer than limit - 1 takes are in the window before the take\", emits: [\"allow\"] }),\n t(\"take-last\", \"open\", \"take\", \"limited\", { guard: \"the take is the limit-th take in the window\", emits: [\"allow\"] }),\n ...COMMON_TRANSITIONS,\n t(\"oldest-leaves\", \"limited\", \"unit.back\", \"open\", { timer: \"oldest\", guard: \"a later take stays in the window\" }),\n t(\"last-leaves\", \"open\", \"idle\", \"new\", { timer: \"last\" }),\n t(\"all-leave\", \"limited\", \"idle\", \"new\", {\n timer: \"last\",\n guard: \"each take of the window has one time: limit = 1, or each take came at once\",\n }),\n ],\n};\n\n/** This function gives the machine document of the policy of a limiter. */\nexport const limiterMachine = (policy: LimitPolicy): Machine =>\n policy.type === \"token-bucket\" ? TOKEN_BUCKET_MACHINE : SLIDING_WINDOW_MACHINE;\n\n/**\n * This function gives the state of a key of a store as its machine document names it, at the time\n * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps\n * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.\n */\nexport const limiterStateOf = (rule: LimitRule, state: KeyState | undefined, now: number): LimiterState => {\n if (state === undefined || freeAt(rule, state) <= now) return \"new\";\n return decide(rule, state, now).decision.allowed ? \"open\" : \"limited\";\n};\n"],"mappings":"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"}
@@ -4,7 +4,7 @@ import { Quantity } from "@mark1russell7/quantity";
4
4
  * take uses one token. Thus a key can make `burst` takes at once after an idle time, and then
5
5
  * `rate` takes in each unit of time.
6
6
  */
7
- interface TokenBucket {
7
+ export interface TokenBucket {
8
8
  readonly type: "token-bucket";
9
9
  /** This rate is how fast the bucket refills: a count for each unit of time, for example `{ value: 10, unit: "count/s" }`. */
10
10
  readonly rate: Quantity;
@@ -15,7 +15,7 @@ interface TokenBucket {
15
15
  * A sliding window gives each key at most `limit` takes in each `window`. Each take counts for one
16
16
  * window from its time, thus the window moves with the clock and has no fixed edges.
17
17
  */
18
- interface SlidingWindow {
18
+ export interface SlidingWindow {
19
19
  readonly type: "sliding-window";
20
20
  /** This count is the most takes of one key in one window. */
21
21
  readonly limit: Quantity;
@@ -23,14 +23,14 @@ interface SlidingWindow {
23
23
  readonly window: Quantity;
24
24
  }
25
25
  /** A limit policy is the rule that a keyed limiter applies to each key, as data. It has no defaults. */
26
- type LimitPolicy = TokenBucket | SlidingWindow;
26
+ export type LimitPolicy = TokenBucket | SlidingWindow;
27
27
  /**
28
28
  * A store failure policy tells what a take does when a shared store fails. It has no default.
29
29
  * - `open`: the limiter lets the take in. The count is not known, thus `remaining` is 0.
30
30
  * - `closed`: the limiter refuses the take with the cause `store`. Its `retryAfter` is the longest
31
31
  * `retryAfter` of the policy (`longestRetryAfter`). Thus O29 and O30 apply to it too.
32
32
  */
33
- type StoreFailure = "open" | "closed";
33
+ export type StoreFailure = "open" | "closed";
34
34
  /**
35
35
  * A store spec tells where the counts of the keys are:
36
36
  * - `local`: in the memory of each replica. A limit L over N replicas is then L / N on each
@@ -40,7 +40,7 @@ type StoreFailure = "open" | "closed";
40
40
  * each take in one atomic step, on its own clock. Thus the limit holds across the replicas.
41
41
  * `onStoreFailure` tells what a take does when the store fails.
42
42
  */
43
- type LimiterStoreSpec = {
43
+ export type LimiterStoreSpec = {
44
44
  readonly kind: "local";
45
45
  } | {
46
46
  readonly kind: "shared";
@@ -52,7 +52,7 @@ type LimiterStoreSpec = {
52
52
  * the state of a new key. That is a bucket that is full again, or a window with no take in it.
53
53
  * Thus an eviction changes no decision.
54
54
  */
55
- interface LimiterEviction {
55
+ export interface LimiterEviction {
56
56
  /**
57
57
  * This count is the most keys that the store holds. At the cap, the store refuses a take of a new
58
58
  * key until a held key is idle for its span (`idleSpan`). A held key keeps its count.
@@ -60,7 +60,7 @@ interface LimiterEviction {
60
60
  readonly maxKeys: Quantity;
61
61
  }
62
62
  /** A limiter spec is the declaration of one keyed limiter. Each part is necessary, because the limiter has no defaults. */
63
- interface LimiterSpec {
63
+ export interface LimiterSpec {
64
64
  /** This text tells what the key of each take is, for example `tenant` or `principal`. The caller gives each key. */
65
65
  readonly key: string;
66
66
  readonly policy: LimitPolicy;
@@ -68,7 +68,7 @@ interface LimiterSpec {
68
68
  readonly evict: LimiterEviction;
69
69
  }
70
70
  /** A limiter is a keyed limiter in the description of a service: its name and its spec. */
71
- interface Limiter extends LimiterSpec {
71
+ export interface Limiter extends LimiterSpec {
72
72
  readonly name: string;
73
73
  }
74
74
  /**
@@ -77,17 +77,17 @@ interface Limiter extends LimiterSpec {
77
77
  * - `cap`: the store holds its cap of keys, and the key is new.
78
78
  * - `store`: the shared store failed, and its spec declares `onStoreFailure: "closed"`.
79
79
  */
80
- type WaitCause = "limit" | "cap" | "store";
80
+ export type WaitCause = "limit" | "cap" | "store";
81
81
  /**
82
82
  * A refusal cause tells why a take is refused: a wait cause, or `capacity`. The cause `capacity` is
83
83
  * a take whose units are over the capacity of the policy. No wait lets it in.
84
84
  */
85
- type RefusalCause = WaitCause | "capacity";
85
+ export type RefusalCause = WaitCause | "capacity";
86
86
  /**
87
87
  * A permitted take used its units of its key. `remaining` is the count of units that the key can
88
88
  * take at this time.
89
89
  */
90
- interface Allowed {
90
+ export interface Allowed {
91
91
  readonly allowed: true;
92
92
  readonly remaining: number;
93
93
  /** This text is the failure of a shared store, when `onStoreFailure: "open"` lets the take in. */
@@ -97,7 +97,7 @@ interface Allowed {
97
97
  * A wait refusal used nothing. `retryAfter` is the time until the limiter lets the same take in, when
98
98
  * no other take comes first. It is always above zero.
99
99
  */
100
- interface WaitRefused {
100
+ export interface WaitRefused {
101
101
  readonly allowed: false;
102
102
  readonly cause: WaitCause;
103
103
  readonly retryAfter: Quantity;
@@ -109,7 +109,7 @@ interface WaitRefused {
109
109
  * the `capacity` of the policy: the `burst` of a bucket, or the `limit` of a window. A caller can
110
110
  * split the take into parts of at most `capacity` units.
111
111
  */
112
- interface CapacityRefused {
112
+ export interface CapacityRefused {
113
113
  readonly allowed: false;
114
114
  readonly cause: "capacity";
115
115
  readonly units: number;
@@ -119,14 +119,14 @@ interface CapacityRefused {
119
119
  * A refused take used nothing. The cause tells the type: a `WaitRefused` has a `retryAfter`, and a
120
120
  * `CapacityRefused` has none. Thus a caller examines the cause before it reads `retryAfter`.
121
121
  */
122
- type Refused = WaitRefused | CapacityRefused;
122
+ export type Refused = WaitRefused | CapacityRefused;
123
123
  /** A decision is the answer of a limiter to one take. */
124
- type Decision = Allowed | Refused;
124
+ export type Decision = Allowed | Refused;
125
125
  /**
126
126
  * A limit rule is a policy in numbers, which a store applies: each time in milliseconds, and each
127
127
  * count as a number. A store in another process, for example a script of Redis, gets these numbers.
128
128
  */
129
- type LimitRule = {
129
+ export type LimitRule = {
130
130
  readonly type: "token-bucket";
131
131
  /** This time is the refill of one token, in milliseconds. */
132
132
  readonly interval: number;
@@ -142,7 +142,7 @@ type LimitRule = {
142
142
  * - A token bucket keeps the time at which its bucket is full again (`full`, in milliseconds).
143
143
  * - A sliding window keeps the time of each permitted take in the window, the oldest first.
144
144
  */
145
- type KeyState = {
145
+ export type KeyState = {
146
146
  readonly type: "token-bucket";
147
147
  readonly full: number;
148
148
  } | {
@@ -150,7 +150,7 @@ type KeyState = {
150
150
  readonly stamps: readonly number[];
151
151
  };
152
152
  /** A step is the decision of one take, and the state of its key after the take. A refusal keeps the count of the key. */
153
- interface TakeStep {
153
+ export interface TakeStep {
154
154
  readonly decision: Decision;
155
155
  readonly state: KeyState;
156
156
  }
@@ -158,41 +158,41 @@ interface TakeStep {
158
158
  * This function gives the problems of a limiter spec. `describe()` and `keyedLimiter` refuse a spec
159
159
  * with a problem. A part that is absent is a problem, because the limiter has no defaults.
160
160
  */
161
- declare const limiterProblems: (name: string, spec: Partial<LimiterSpec> | undefined) => string[];
161
+ export declare const limiterProblems: (name: string, spec: Partial<LimiterSpec> | undefined) => string[];
162
162
  /**
163
163
  * This function gives the rule of a policy in numbers. The interval of a bucket is exact as a
164
164
  * rational, and it becomes one number only at the end. Thus 10 for each minute gives 6000 ms.
165
165
  */
166
- declare const limitRule: (policy: LimitPolicy) => LimitRule;
166
+ export declare const limitRule: (policy: LimitPolicy) => LimitRule;
167
167
  /**
168
168
  * This function gives the span after which an idle key is equal to a new key. That span is
169
169
  * `burst / rate` for a token bucket, and one window for a sliding window. A store can remove the key
170
170
  * after it, and no decision changes. It is also the longest `retryAfter` of a new key that the store
171
171
  * refuses at its cap.
172
172
  */
173
- declare const idleSpan: (policy: LimitPolicy) => Quantity;
173
+ export declare const idleSpan: (policy: LimitPolicy) => Quantity;
174
174
  /**
175
175
  * This function gives the longest `retryAfter` of a refusal by the policy: one interval of the
176
176
  * bucket (`1 / rate`), or one window. A refusal at the cap of keys can be longer, up to `idleSpan`.
177
177
  */
178
- declare const longestRetryAfter: (policy: LimitPolicy) => Quantity;
178
+ export declare const longestRetryAfter: (policy: LimitPolicy) => Quantity;
179
179
  /**
180
180
  * This function gives a `retryAfter` in whole seconds, rounded up, as the header `Retry-After`
181
181
  * (RFC 9110) has it. A time over a whole second by less than one nanosecond rounds down to it,
182
182
  * because that part is an error of floating point.
183
183
  */
184
- declare const retryAfterSeconds: (retryAfter: Quantity) => number;
184
+ export declare const retryAfterSeconds: (retryAfter: Quantity) => number;
185
185
  /** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */
186
- declare const freeAt: (rule: LimitRule, state: KeyState) => number;
186
+ export declare const freeAt: (rule: LimitRule, state: KeyState) => number;
187
187
  /** This function gives the capacity of a rule: the most units of one take. That is the `burst` of a bucket, or the `limit` of a window. */
188
- declare const capacityOf: (rule: LimitRule) => number;
188
+ export declare const capacityOf: (rule: LimitRule) => number;
189
189
  /**
190
190
  * This function gives the units of a take: 1 when they are absent. It throws for units that are not
191
191
  * a whole number of 1 or more, because such a take has no meaning.
192
192
  */
193
- declare const unitsOf: (units: number | undefined) => number;
193
+ export declare const unitsOf: (units: number | undefined) => number;
194
194
  /** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */
195
- declare const overCapacity: (rule: LimitRule, units: number) => CapacityRefused | undefined;
195
+ export declare const overCapacity: (rule: LimitRule, units: number) => CapacityRefused | undefined;
196
196
  /**
197
197
  * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in
198
198
  * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each
@@ -205,5 +205,4 @@ declare const overCapacity: (rule: LimitRule, units: number) => CapacityRefused
205
205
  * window. A refusal waits until enough of the oldest takes leave the window.
206
206
  * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.
207
207
  */
208
- declare const decide: (rule: LimitRule, state: KeyState | undefined, now: number, units?: number) => TakeStep;
209
- export { limitRule as C, retryAfterSeconds as D, overCapacity as E, unitsOf as O, idleSpan as S, longestRetryAfter as T, WaitCause as _, LimitPolicy as a, decide as b, LimiterEviction as c, RefusalCause as d, Refused as f, TokenBucket as g, TakeStep as h, KeyState as i, LimiterSpec as l, StoreFailure as m, CapacityRefused as n, LimitRule as o, SlidingWindow as p, Decision as r, Limiter as s, Allowed as t, LimiterStoreSpec as u, WaitRefused as v, limiterProblems as w, freeAt as x, capacityOf as y };
208
+ export declare const decide: (rule: LimitRule, state: KeyState | undefined, now: number, units?: number) => TakeStep;
@@ -1,4 +1,5 @@
1
- import { convertExact, convertible, rationals } from "@mark1russell7/quantity";
1
+ import { convertExact, convertible } from "@mark1russell7/quantity/time";
2
+ import { ONE, div, fromNumber, toNumber } from "@mark1russell7/rational";
2
3
  // src/limiter/policy.ts
3
4
  /**
4
5
  * This tolerance is one nanosecond, in milliseconds. A comparison of times permits it, because a
@@ -18,7 +19,7 @@ const safely = (test, amount) => {
18
19
  }
19
20
  };
20
21
  const finiteAbove = (amount) => typeof amount.value === "number" && Number.isFinite(amount.value) && amount.value > 0;
21
- const wholeCount = (amount) => finiteAbove(amount) && Number.isInteger(rationals.toNumber(convertExact(rationals.fromNumber(amount.value), amount.unit, "count")));
22
+ const wholeCount = (amount) => finiteAbove(amount) && Number.isInteger(toNumber(convertExact(fromNumber(amount.value), amount.unit, "count")));
22
23
  /**
23
24
  * This function gives the problems of a limiter spec. `describe()` and `keyedLimiter` refuse a spec
24
25
  * with a problem. A part that is absent is a problem, because the limiter has no defaults.
@@ -63,19 +64,19 @@ const limiterProblems = (name, spec) => {
63
64
  return problems;
64
65
  };
65
66
  /** This function gives an amount in milliseconds, exactly where the units permit, as one number. */
66
- const milliseconds = (amount) => rationals.toNumber(convertExact(rationals.fromNumber(amount.value), amount.unit, "ms"));
67
+ const milliseconds = (amount) => toNumber(convertExact(fromNumber(amount.value), amount.unit, "ms"));
67
68
  /** This function gives a count as one number. */
68
- const countOf = (amount) => rationals.toNumber(convertExact(rationals.fromNumber(amount.value), amount.unit, "count"));
69
+ const countOf = (amount) => toNumber(convertExact(fromNumber(amount.value), amount.unit, "count"));
69
70
  /**
70
71
  * This function gives the rule of a policy in numbers. The interval of a bucket is exact as a
71
72
  * rational, and it becomes one number only at the end. Thus 10 for each minute gives 6000 ms.
72
73
  */
73
74
  const limitRule = (policy) => {
74
75
  if (policy.type === "token-bucket") {
75
- const perMs = convertExact(rationals.fromNumber(policy.rate.value), policy.rate.unit, "count/ms");
76
+ const perMs = convertExact(fromNumber(policy.rate.value), policy.rate.unit, "count/ms");
76
77
  return {
77
78
  type: "token-bucket",
78
- interval: rationals.toNumber(rationals.div(rationals.ONE, perMs)),
79
+ interval: toNumber(div(ONE, perMs)),
79
80
  burst: countOf(policy.burst)
80
81
  };
81
82
  }
@@ -114,7 +115,7 @@ const longestRetryAfter = (policy) => {
114
115
  * because that part is an error of floating point.
115
116
  */
116
117
  const retryAfterSeconds = (retryAfter) => {
117
- const seconds = rationals.toNumber(convertExact(rationals.fromNumber(retryAfter.value), retryAfter.unit, "s"));
118
+ const seconds = toNumber(convertExact(fromNumber(retryAfter.value), retryAfter.unit, "s"));
118
119
  return Math.max(0, Math.ceil(seconds - TOLERANCE / 1e3));
119
120
  };
120
121
  /** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */
@@ -223,6 +224,6 @@ const decide = (rule, state, now, units) => {
223
224
  }
224
225
  };
225
226
  };
226
- export { wholeCount as _, freeAt as a, isTime as c, longestRetryAfter as d, milliseconds as f, unitsOf as g, safely as h, finiteAbove as i, limitRule as l, retryAfterSeconds as m, countOf as n, idleSpan as o, overCapacity as p, decide as r, isCount as s, capacityOf as t, limiterProblems as u };
227
+ export { capacityOf, countOf, decide, finiteAbove, freeAt, idleSpan, isCount, isTime, limitRule, limiterProblems, longestRetryAfter, milliseconds, overCapacity, retryAfterSeconds, safely, unitsOf, wholeCount };
227
228
 
228
- //# sourceMappingURL=policy-UYALkqVq.js.map
229
+ //# sourceMappingURL=policy.js.map