@mark1russell7/service 0.8.18 → 0.8.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. package/README.md +19 -0
  2. package/build/backoff.d.ts +44 -2
  3. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  4. package/build/builder.js +499 -0
  5. package/build/builder.js.map +1 -0
  6. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  7. package/build/channel.d.ts +1 -1
  8. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  9. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  10. package/build/client/core.js.map +1 -0
  11. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  12. package/build/client/dial.js +52 -0
  13. package/build/client/dial.js.map +1 -0
  14. package/build/client/machine.js +29 -0
  15. package/build/client/machine.js.map +1 -0
  16. package/build/client/meets.d.ts +35 -0
  17. package/build/client/meets.js +78 -0
  18. package/build/client/meets.js.map +1 -0
  19. package/build/clock.d.ts +1 -1
  20. package/build/conformance.d.ts +122 -0
  21. package/build/conformance.js +470 -0
  22. package/build/conformance.js.map +1 -0
  23. package/build/contract.d.ts +28 -0
  24. package/build/contract.js +184 -0
  25. package/build/contract.js.map +1 -0
  26. package/build/description.d.ts +161 -0
  27. package/build/description.js +11 -0
  28. package/build/description.js.map +1 -0
  29. package/build/drains.js +35 -0
  30. package/build/drains.js.map +1 -0
  31. package/build/events.d.ts +25 -0
  32. package/build/fakes.d.ts +43 -0
  33. package/build/fakes.js +93 -0
  34. package/build/fakes.js.map +1 -0
  35. package/build/grpc/client.d.ts +153 -0
  36. package/build/grpc/client.js +474 -0
  37. package/build/grpc/client.js.map +1 -0
  38. package/build/grpc/connection.d.ts +97 -0
  39. package/build/grpc/connection.js +59 -0
  40. package/build/grpc/connection.js.map +1 -0
  41. package/build/grpc/machine.d.ts +12 -0
  42. package/build/grpc/machine.js +149 -0
  43. package/build/grpc/machine.js.map +1 -0
  44. package/build/grpc/meets.d.ts +14 -0
  45. package/build/grpc/meets.js +105 -0
  46. package/build/grpc/meets.js.map +1 -0
  47. package/build/grpc/starting.d.ts +33 -0
  48. package/build/grpc/starting.js +89 -0
  49. package/build/grpc/starting.js.map +1 -0
  50. package/build/grpc.d.ts +9 -303
  51. package/build/grpc.js +7 -854
  52. package/build/health.d.ts +93 -0
  53. package/build/health.js +223 -0
  54. package/build/health.js.map +1 -0
  55. package/build/heartbeat.d.ts +1 -1
  56. package/build/host/discovery.d.ts +61 -0
  57. package/build/host/discovery.js +113 -0
  58. package/build/host/discovery.js.map +1 -0
  59. package/build/host/env.d.ts +14 -0
  60. package/build/host/env.js +57 -0
  61. package/build/host/env.js.map +1 -0
  62. package/build/host/fakes.d.ts +82 -0
  63. package/build/host/fakes.js +239 -0
  64. package/build/host/fakes.js.map +1 -0
  65. package/build/host/group.d.ts +142 -0
  66. package/build/host/group.js +517 -0
  67. package/build/host/group.js.map +1 -0
  68. package/build/host/install.d.ts +96 -0
  69. package/build/host/install.js +330 -0
  70. package/build/host/install.js.map +1 -0
  71. package/build/host/lock.d.ts +78 -0
  72. package/build/host/lock.js +190 -0
  73. package/build/host/lock.js.map +1 -0
  74. package/build/host/logs.d.ts +26 -0
  75. package/build/host/logs.js +48 -0
  76. package/build/host/logs.js.map +1 -0
  77. package/build/host/node.d.ts +14 -0
  78. package/build/host/node.js +309 -0
  79. package/build/host/node.js.map +1 -0
  80. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  81. package/build/host/ports.js +17 -0
  82. package/build/host/ports.js.map +1 -0
  83. package/build/host/probes.d.ts +51 -0
  84. package/build/host/probes.js +139 -0
  85. package/build/host/probes.js.map +1 -0
  86. package/build/host/processes.d.ts +32 -0
  87. package/build/host/processes.js +63 -0
  88. package/build/host/processes.js.map +1 -0
  89. package/build/host/render.d.ts +84 -0
  90. package/build/host/render.js +235 -0
  91. package/build/host/render.js.map +1 -0
  92. package/build/host/watch.d.ts +90 -0
  93. package/build/host/watch.js +165 -0
  94. package/build/host/watch.js.map +1 -0
  95. package/build/host.d.ts +13 -671
  96. package/build/host.js +12 -2126
  97. package/build/http/answers.js +29 -0
  98. package/build/http/answers.js.map +1 -0
  99. package/build/http/fake-server.js +61 -0
  100. package/build/http/fake-server.js.map +1 -0
  101. package/build/http/outcome.d.ts +115 -0
  102. package/build/http/outcome.js +325 -0
  103. package/build/http/outcome.js.map +1 -0
  104. package/build/http/probes.d.ts +83 -0
  105. package/build/http/probes.js +232 -0
  106. package/build/http/probes.js.map +1 -0
  107. package/build/http/transport.d.ts +165 -0
  108. package/build/http/transport.js +517 -0
  109. package/build/http/transport.js.map +1 -0
  110. package/build/http-client/client.d.ts +121 -0
  111. package/build/http-client/client.js +330 -0
  112. package/build/http-client/client.js.map +1 -0
  113. package/build/http-client/connection.d.ts +78 -0
  114. package/build/http-client/connection.js +54 -0
  115. package/build/http-client/connection.js.map +1 -0
  116. package/build/http-client/machine.d.ts +14 -0
  117. package/build/http-client/machine.js +109 -0
  118. package/build/http-client/machine.js.map +1 -0
  119. package/build/http-client/meets.d.ts +11 -0
  120. package/build/http-client/meets.js +74 -0
  121. package/build/http-client/meets.js.map +1 -0
  122. package/build/http-client/session.d.ts +87 -0
  123. package/build/http-client/session.js +99 -0
  124. package/build/http-client/session.js.map +1 -0
  125. package/build/http-client/starting.d.ts +25 -0
  126. package/build/http-client/starting.js +65 -0
  127. package/build/http-client/starting.js.map +1 -0
  128. package/build/http-client.d.ts +9 -330
  129. package/build/http-client.js +8 -707
  130. package/build/http.d.ts +5 -353
  131. package/build/http.js +3 -1086
  132. package/build/identity.d.ts +16 -0
  133. package/build/identity.js +44 -0
  134. package/build/identity.js.map +1 -0
  135. package/build/index.d.ts +35 -412
  136. package/build/index.js +24 -3277
  137. package/build/knobs.d.ts +1 -0
  138. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  139. package/build/knobs.js.map +1 -0
  140. package/build/latch.d.ts +29 -0
  141. package/build/latch.js +122 -0
  142. package/build/latch.js.map +1 -0
  143. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  144. package/build/law.js +149 -0
  145. package/build/law.js.map +1 -0
  146. package/build/lifecycle.d.ts +144 -0
  147. package/build/lifecycle.js +411 -0
  148. package/build/lifecycle.js.map +1 -0
  149. package/build/limiter/machine.d.ts +40 -0
  150. package/build/limiter/machine.js +279 -0
  151. package/build/limiter/machine.js.map +1 -0
  152. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  153. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  154. package/build/limiter/policy.js.map +1 -0
  155. package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
  156. package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
  157. package/build/limiter/quota.js.map +1 -0
  158. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  159. package/build/limiter/store.js +145 -0
  160. package/build/limiter/store.js.map +1 -0
  161. package/build/limiter.d.ts +4 -3
  162. package/build/limiter.js +4 -2
  163. package/build/lint.d.ts +152 -0
  164. package/build/lint.js +576 -0
  165. package/build/lint.js.map +1 -0
  166. package/build/logger.d.ts +71 -0
  167. package/build/logger.js +183 -0
  168. package/build/logger.js.map +1 -0
  169. package/build/machines.d.ts +41 -0
  170. package/build/machines.js +451 -0
  171. package/build/machines.js.map +1 -0
  172. package/build/metrics.d.ts +53 -0
  173. package/build/metrics.js +111 -0
  174. package/build/metrics.js.map +1 -0
  175. package/build/mongodb/client.d.ts +131 -0
  176. package/build/mongodb/client.js +388 -0
  177. package/build/mongodb/client.js.map +1 -0
  178. package/build/mongodb/connection.d.ts +112 -0
  179. package/build/mongodb/connection.js +12 -0
  180. package/build/mongodb/connection.js.map +1 -0
  181. package/build/mongodb/machine.d.ts +14 -0
  182. package/build/mongodb/machine.js +122 -0
  183. package/build/mongodb/machine.js.map +1 -0
  184. package/build/mongodb/meets.d.ts +15 -0
  185. package/build/mongodb/meets.js +103 -0
  186. package/build/mongodb/meets.js.map +1 -0
  187. package/build/mongodb/starting.d.ts +29 -0
  188. package/build/mongodb/starting.js +77 -0
  189. package/build/mongodb/starting.js.map +1 -0
  190. package/build/mongodb.d.ts +8 -296
  191. package/build/mongodb.js +7 -682
  192. package/build/operation.d.ts +27 -0
  193. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  194. package/build/operation.js.map +1 -0
  195. package/build/otel.d.ts +2 -2
  196. package/build/pg/client.d.ts +96 -0
  197. package/build/pg/client.js +277 -0
  198. package/build/pg/client.js.map +1 -0
  199. package/build/pg/connection.d.ts +75 -0
  200. package/build/pg/connection.js +11 -0
  201. package/build/pg/connection.js.map +1 -0
  202. package/build/pg/machine.d.ts +13 -0
  203. package/build/pg/machine.js +111 -0
  204. package/build/pg/machine.js.map +1 -0
  205. package/build/pg/meets.d.ts +14 -0
  206. package/build/pg/meets.js +83 -0
  207. package/build/pg/meets.js.map +1 -0
  208. package/build/pg/starting.d.ts +26 -0
  209. package/build/pg/starting.js +62 -0
  210. package/build/pg/starting.js.map +1 -0
  211. package/build/pg.d.ts +8 -219
  212. package/build/pg.js +7 -525
  213. package/build/poller.d.ts +9 -0
  214. package/build/poller.js +152 -0
  215. package/build/poller.js.map +1 -0
  216. package/build/process.d.ts +114 -0
  217. package/build/process.js +170 -0
  218. package/build/process.js.map +1 -0
  219. package/build/profiles.d.ts +68 -0
  220. package/build/profiles.js +120 -0
  221. package/build/profiles.js.map +1 -0
  222. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  223. package/build/queue.js +279 -0
  224. package/build/queue.js.map +1 -0
  225. package/build/rabbitmq/client.d.ts +144 -0
  226. package/build/rabbitmq/client.js +426 -0
  227. package/build/rabbitmq/client.js.map +1 -0
  228. package/build/rabbitmq/connection.d.ts +91 -0
  229. package/build/rabbitmq/connection.js +15 -0
  230. package/build/rabbitmq/connection.js.map +1 -0
  231. package/build/rabbitmq/machine.d.ts +13 -0
  232. package/build/rabbitmq/machine.js +159 -0
  233. package/build/rabbitmq/machine.js.map +1 -0
  234. package/build/rabbitmq/meets.d.ts +12 -0
  235. package/build/rabbitmq/meets.js +96 -0
  236. package/build/rabbitmq/meets.js.map +1 -0
  237. package/build/rabbitmq/starting.d.ts +27 -0
  238. package/build/rabbitmq/starting.js +67 -0
  239. package/build/rabbitmq/starting.js.map +1 -0
  240. package/build/rabbitmq.d.ts +8 -283
  241. package/build/rabbitmq.js +7 -742
  242. package/build/redis/client.d.ts +86 -0
  243. package/build/redis/client.js +285 -0
  244. package/build/redis/client.js.map +1 -0
  245. package/build/redis/connection.d.ts +57 -0
  246. package/build/redis/connection.js +11 -0
  247. package/build/redis/connection.js.map +1 -0
  248. package/build/redis/limiter.d.ts +43 -0
  249. package/build/redis/limiter.js +164 -0
  250. package/build/redis/limiter.js.map +1 -0
  251. package/build/redis/machine.d.ts +12 -0
  252. package/build/redis/machine.js +144 -0
  253. package/build/redis/machine.js.map +1 -0
  254. package/build/redis/meets.d.ts +11 -0
  255. package/build/redis/meets.js +75 -0
  256. package/build/redis/meets.js.map +1 -0
  257. package/build/redis/operations.d.ts +5 -0
  258. package/build/redis/operations.js +114 -0
  259. package/build/redis/operations.js.map +1 -0
  260. package/build/redis.d.ts +10 -207
  261. package/build/redis.js +9 -771
  262. package/build/requests.d.ts +66 -0
  263. package/build/requests.js +279 -0
  264. package/build/requests.js.map +1 -0
  265. package/build/retrier.d.ts +62 -0
  266. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  267. package/build/retrier.js.map +1 -0
  268. package/build/routes.d.ts +35 -0
  269. package/build/routes.js +77 -0
  270. package/build/routes.js.map +1 -0
  271. package/build/rules.d.ts +19 -2
  272. package/build/stops.d.ts +51 -0
  273. package/build/stops.js +86 -0
  274. package/build/stops.js.map +1 -0
  275. package/build/testing.d.ts +8 -270
  276. package/build/testing.js +4 -1027
  277. package/build/testing.js.map +1 -1
  278. package/build/timing.d.ts +63 -0
  279. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  280. package/build/timing.js.map +1 -0
  281. package/build/units.d.ts +17 -0
  282. package/build/units.js +236 -0
  283. package/build/units.js.map +1 -0
  284. package/build/watchdog.d.ts +34 -0
  285. package/build/watchdog.js +53 -0
  286. package/build/watchdog.js.map +1 -0
  287. package/build/websocket/client.d.ts +136 -0
  288. package/build/websocket/client.js +422 -0
  289. package/build/websocket/client.js.map +1 -0
  290. package/build/websocket/connection.d.ts +83 -0
  291. package/build/websocket/connection.js +57 -0
  292. package/build/websocket/connection.js.map +1 -0
  293. package/build/websocket/machine.d.ts +12 -0
  294. package/build/websocket/machine.js +155 -0
  295. package/build/websocket/machine.js.map +1 -0
  296. package/build/websocket/meets.d.ts +14 -0
  297. package/build/websocket/meets.js +92 -0
  298. package/build/websocket/meets.js.map +1 -0
  299. package/build/websocket/starting.d.ts +25 -0
  300. package/build/websocket/starting.js +69 -0
  301. package/build/websocket/starting.js.map +1 -0
  302. package/build/websocket.d.ts +9 -264
  303. package/build/websocket.js +8 -774
  304. package/build/worker.d.ts +92 -0
  305. package/build/worker.js +153 -0
  306. package/build/worker.js.map +1 -0
  307. package/package.json +4 -3
  308. package/build/backoff-QTRGfkEK.d.ts +0 -45
  309. package/build/clock-DpVgpY4h.d.ts +0 -2
  310. package/build/grpc.js.map +0 -1
  311. package/build/host.js.map +0 -1
  312. package/build/http-client.js.map +0 -1
  313. package/build/http.js.map +0 -1
  314. package/build/index.js.map +0 -1
  315. package/build/knobs-BJcz6m01.js.map +0 -1
  316. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  317. package/build/limiter-Bgy6Gmvl.js.map +0 -1
  318. package/build/logger-B6drv9w0.d.ts +0 -488
  319. package/build/machine-BhVeHr_m.js.map +0 -1
  320. package/build/mongodb.js.map +0 -1
  321. package/build/operation-DF73RZOI.js.map +0 -1
  322. package/build/pg.js.map +0 -1
  323. package/build/policy-UYALkqVq.js.map +0 -1
  324. package/build/process-7R9M29wN.js +0 -437
  325. package/build/process-7R9M29wN.js.map +0 -1
  326. package/build/rabbitmq.js.map +0 -1
  327. package/build/redis.js.map +0 -1
  328. package/build/requests-DD2ALv0_.js +0 -583
  329. package/build/requests-DD2ALv0_.js.map +0 -1
  330. package/build/retrier-Dnjhvxol.js.map +0 -1
  331. package/build/timing-DZl36uXs.js.map +0 -1
  332. package/build/websocket.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { n as Clock } from "./clock-DpVgpY4h.js";
2
- import { l as LimiterSpec, o as LimitRule, r as Decision } from "./policy-CBcK2XGg.js";
1
+ import { Clock } from "../clock.js";
2
+ import { Decision, LimitRule, LimiterSpec } from "./policy.js";
3
3
  /** A take request is one take of one key, with the rule and the cap of its limiter in numbers. */
4
- interface TakeRequest {
4
+ export interface TakeRequest {
5
5
  /** This name is the limiter. A store keeps the keys of each limiter apart. */
6
6
  readonly limiter: string;
7
7
  readonly key: string;
@@ -21,7 +21,7 @@ interface TakeRequest {
21
21
  * process uses `decide`. A store that the replicas share does the same arithmetic in one step of its
22
22
  * own, for example one script of Redis that reads `TIME`.
23
23
  */
24
- interface LimiterStore {
24
+ export interface LimiterStore {
25
25
  /** This kind tells where the counts are: in the memory of this replica, or in a store that the replicas share. */
26
26
  readonly kind: "local" | "shared";
27
27
  /**
@@ -32,7 +32,7 @@ interface LimiterStore {
32
32
  take(request: TakeRequest): Decision | Promise<Decision>;
33
33
  }
34
34
  /** A memory store is the store of one replica, on the injected monotonic clock. */
35
- interface MemoryStore extends LimiterStore {
35
+ export interface MemoryStore extends LimiterStore {
36
36
  readonly kind: "local";
37
37
  /** This method gives the count of keys that the store holds for a limiter. */
38
38
  size(limiter: string): number;
@@ -47,9 +47,9 @@ interface MemoryStore extends LimiterStore {
47
47
  * refuses the new key with the cause `cap`. Its `retryAfter` is at most the time until the
48
48
  * earliest held key is free, and that time is at most `idleSpan` of the policy.
49
49
  */
50
- declare const memoryStore: (clock: Clock) => MemoryStore;
50
+ export declare const memoryStore: (clock: Clock) => MemoryStore;
51
51
  /** A keyed limiter is the runtime of one declared limiter: its spec, its rule in numbers, and its store. */
52
- interface KeyedLimiter {
52
+ export interface KeyedLimiter {
53
53
  readonly name: string;
54
54
  /** This spec is the declaration, the same data that `svc.limiter(name, spec)` takes and `describe()` shows. */
55
55
  readonly spec: LimiterSpec;
@@ -71,7 +71,7 @@ interface KeyedLimiter {
71
71
  tryTakeSync?(key: string, units?: number): Decision;
72
72
  }
73
73
  /** A local limiter is a keyed limiter on a memory store: its take can give the decision at once. */
74
- interface LocalLimiter extends KeyedLimiter {
74
+ export interface LocalLimiter extends KeyedLimiter {
75
75
  tryTakeSync(key: string, units?: number): Decision;
76
76
  }
77
77
  /**
@@ -86,6 +86,5 @@ interface LocalLimiter extends KeyedLimiter {
86
86
  * Thus a store of your own that does not read `units` cannot let it in.
87
87
  * - `tryTakeSync` gives the decision at once. A shared store throws, and so does a local store that gives a promise.
88
88
  */
89
- declare function keyedLimiter(name: string, spec: LimiterSpec, store: MemoryStore): LocalLimiter;
90
- declare function keyedLimiter(name: string, spec: LimiterSpec, store: LimiterStore): KeyedLimiter;
91
- export { TakeRequest as a, MemoryStore as i, LimiterStore as n, keyedLimiter as o, LocalLimiter as r, memoryStore as s, KeyedLimiter as t };
89
+ export declare function keyedLimiter(name: string, spec: LimiterSpec, store: MemoryStore): LocalLimiter;
90
+ export declare function keyedLimiter(name: string, spec: LimiterSpec, store: LimiterStore): KeyedLimiter;
@@ -0,0 +1,145 @@
1
+ import { decide, freeAt, limitRule, limiterProblems, longestRetryAfter, overCapacity, unitsOf } from "./policy.js";
2
+ import { convertExact } from "@mark1russell7/quantity/time";
3
+ import { fromNumber, toNumber } from "@mark1russell7/rational";
4
+ // src/limiter/store.ts
5
+ const ms = (value) => ({
6
+ value,
7
+ unit: "ms"
8
+ });
9
+ /**
10
+ * This function makes the store of one replica. It reads time only through the clock. Thus a step
11
+ * of the wall clock does not move a count, and a fake clock gives exact decisions in a test.
12
+ * - The eviction is exact. A key whose bucket is full again, or whose window has no take, is equal
13
+ * to a new key. The store removes it at its next take, or at a sweep.
14
+ * - The count of keys has a bound. At the cap, a take of a new key sweeps the table, but only when
15
+ * a held key can be free. Each sweep reads each key one time. When no key is free, the store
16
+ * refuses the new key with the cause `cap`. Its `retryAfter` is at most the time until the
17
+ * earliest held key is free, and that time is at most `idleSpan` of the policy.
18
+ */
19
+ const memoryStore = (clock) => {
20
+ const tables = /* @__PURE__ */ new Map();
21
+ const sweep = (table, rule, now) => {
22
+ let next = Number.POSITIVE_INFINITY;
23
+ for (const [key, state] of table.states) {
24
+ const free = freeAt(rule, state);
25
+ if (free <= now) table.states.delete(key);
26
+ else next = Math.min(next, free);
27
+ }
28
+ table.next = next;
29
+ };
30
+ return {
31
+ kind: "local",
32
+ take({ limiter, key, rule, maxKeys, units }) {
33
+ const n = unitsOf(units);
34
+ const over = overCapacity(rule, n);
35
+ if (over !== void 0) return over;
36
+ const now = clock.now();
37
+ let table = tables.get(limiter);
38
+ if (table === void 0) {
39
+ table = {
40
+ states: /* @__PURE__ */ new Map(),
41
+ next: Number.POSITIVE_INFINITY
42
+ };
43
+ tables.set(limiter, table);
44
+ }
45
+ let state = table.states.get(key);
46
+ if (state !== void 0 && freeAt(rule, state) <= now) {
47
+ table.states.delete(key);
48
+ state = void 0;
49
+ }
50
+ if (state === void 0 && table.states.size >= maxKeys) {
51
+ if (table.next <= now) sweep(table, rule, now);
52
+ if (table.states.size >= maxKeys) return {
53
+ allowed: false,
54
+ retryAfter: ms(table.next - now),
55
+ cause: "cap"
56
+ };
57
+ }
58
+ const step = decide(rule, state, now, n);
59
+ if (state === void 0) {
60
+ table.states.set(key, step.state);
61
+ table.next = Math.min(table.next, freeAt(rule, step.state));
62
+ } else table.states.set(key, step.state);
63
+ return step.decision;
64
+ },
65
+ size(limiter) {
66
+ return tables.get(limiter)?.states.size ?? 0;
67
+ }
68
+ };
69
+ };
70
+ /** This function gives the text of a failure. */
71
+ const failureOf = (error) => error instanceof Error ? error.message : String(error);
72
+ function keyedLimiter(name, spec, store) {
73
+ const problems = limiterProblems(name, spec);
74
+ if (problems.length > 0) throw new Error(problems.join("; "));
75
+ if (store.kind !== spec.store.kind) throw new Error(`limiter ${name} declares a ${spec.store.kind} store, but the store that it got is ${store.kind}`);
76
+ const rule = limitRule(spec.policy);
77
+ const maxKeys = toNumber(convertExact(fromNumber(spec.evict.maxKeys.value), spec.evict.maxKeys.unit, "count"));
78
+ const onStoreFailure = spec.store.kind === "shared" ? spec.store.onStoreFailure : void 0;
79
+ const closedAfter = longestRetryAfter(spec.policy);
80
+ const take = async (key, units) => {
81
+ const n = unitsOf(units);
82
+ const over = overCapacity(rule, n);
83
+ if (over !== void 0) return over;
84
+ const request = {
85
+ limiter: name,
86
+ key,
87
+ rule,
88
+ maxKeys,
89
+ units: n
90
+ };
91
+ if (onStoreFailure === void 0) return store.take(request);
92
+ try {
93
+ return await store.take(request);
94
+ } catch (error) {
95
+ const failure = failureOf(error);
96
+ if (onStoreFailure === "open") return {
97
+ allowed: true,
98
+ remaining: 0,
99
+ failure
100
+ };
101
+ return {
102
+ allowed: false,
103
+ retryAfter: { ...closedAfter },
104
+ cause: "store",
105
+ failure
106
+ };
107
+ }
108
+ };
109
+ const tryTakeSync = (key, units) => {
110
+ if (store.kind === "shared") throw new Error(`limiter ${name} has a shared store, which decides in a promise: tryTakeSync needs a memory store, thus use take()`);
111
+ const n = unitsOf(units);
112
+ const over = overCapacity(rule, n);
113
+ if (over !== void 0) return over;
114
+ const decision = store.take({
115
+ limiter: name,
116
+ key,
117
+ rule,
118
+ maxKeys,
119
+ units: n
120
+ });
121
+ if (isPromise(decision)) {
122
+ decision.then(void 0, () => {});
123
+ throw new Error(`limiter ${name} has a store whose take gives a promise: tryTakeSync needs a memory store, thus use take()`);
124
+ }
125
+ return decision;
126
+ };
127
+ return {
128
+ name,
129
+ spec: {
130
+ key: spec.key,
131
+ policy: { ...spec.policy },
132
+ store: { ...spec.store },
133
+ evict: { maxKeys: { ...spec.evict.maxKeys } }
134
+ },
135
+ rule,
136
+ maxKeys,
137
+ take,
138
+ tryTakeSync
139
+ };
140
+ }
141
+ /** This function tells if a decision of a store is a promise. */
142
+ const isPromise = (value) => typeof value.then === "function";
143
+ export { keyedLimiter, memoryStore };
144
+
145
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","names":[],"sources":["../../src/limiter/store.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact } from \"@mark1russell7/quantity/time\";\nimport { fromNumber, toNumber } from \"@mark1russell7/rational\";\nimport type { Clock } from \"../clock.ts\";\nimport type { Decision, KeyState, LimiterSpec, LimitRule } from \"./policy.ts\";\nimport { decide, freeAt, limitRule, limiterProblems, longestRetryAfter, overCapacity, unitsOf } from \"./policy.ts\";\n\n/** A take request is one take of one key, with the rule and the cap of its limiter in numbers. */\nexport interface TakeRequest {\n /** This name is the limiter. A store keeps the keys of each limiter apart. */\n readonly limiter: string;\n readonly key: string;\n readonly rule: LimitRule;\n /** This count is the most keys that the store holds for the limiter. */\n readonly maxKeys: number;\n /**\n * This count is the units of the take: 1 when it is absent. A store takes all of them in its one\n * atomic step, or none. `keyedLimiter` always gives it, and it refuses a take over the capacity\n * before the store. A store also refuses such a take with the cause `capacity`.\n */\n readonly units?: number | undefined;\n}\n\n/**\n * A limiter store keeps the state of each key, and it decides each take in one atomic step, on its\n * own clock. Thus two takes of one key do not read the same state at any time. A store in this\n * process uses `decide`. A store that the replicas share does the same arithmetic in one step of its\n * own, for example one script of Redis that reads `TIME`.\n */\nexport interface LimiterStore {\n /** This kind tells where the counts are: in the memory of this replica, or in a store that the replicas share. */\n readonly kind: \"local\" | \"shared\";\n /**\n * This method decides one take of `units` units. It removes a key only when its state is equal to\n * the state of a new key. It holds at most `maxKeys` keys for each limiter. A failure of a shared\n * store rejects the take, and the limiter then applies the `onStoreFailure` of its spec.\n */\n take(request: TakeRequest): Decision | Promise<Decision>;\n}\n\n/** A memory store is the store of one replica, on the injected monotonic clock. */\nexport interface MemoryStore extends LimiterStore {\n readonly kind: \"local\";\n /** This method gives the count of keys that the store holds for a limiter. */\n size(limiter: string): number;\n}\n\n/** A table is the keys of one limiter in a memory store. */\ninterface Table {\n readonly states: Map<string, KeyState>;\n /**\n * This time is at or before the earliest time at which a held key is equal to a new key. An\n * insert lowers it, and a sweep sets it again. A take of a held key only moves the time of that\n * key later, thus the bound stays true.\n */\n next: number;\n}\n\nconst ms = (value: number): Quantity => ({ value, unit: \"ms\" });\n\n/**\n * This function makes the store of one replica. It reads time only through the clock. Thus a step\n * of the wall clock does not move a count, and a fake clock gives exact decisions in a test.\n * - The eviction is exact. A key whose bucket is full again, or whose window has no take, is equal\n * to a new key. The store removes it at its next take, or at a sweep.\n * - The count of keys has a bound. At the cap, a take of a new key sweeps the table, but only when\n * a held key can be free. Each sweep reads each key one time. When no key is free, the store\n * refuses the new key with the cause `cap`. Its `retryAfter` is at most the time until the\n * earliest held key is free, and that time is at most `idleSpan` of the policy.\n */\nexport const memoryStore = (clock: Clock): MemoryStore => {\n const tables = new Map<string, Table>();\n const sweep = (table: Table, rule: LimitRule, now: number): void => {\n let next = Number.POSITIVE_INFINITY;\n for (const [key, state] of table.states) {\n const free = freeAt(rule, state);\n if (free <= now) table.states.delete(key);\n else next = Math.min(next, free);\n }\n table.next = next;\n };\n return {\n kind: \"local\",\n take({ limiter, key, rule, maxKeys, units }) {\n const n = unitsOf(units);\n // a take over the capacity is refused at each time: it reads no state, and it adds no key\n const over = overCapacity(rule, n);\n if (over !== undefined) return over;\n const now = clock.now();\n let table = tables.get(limiter);\n if (table === undefined) {\n table = { states: new Map(), next: Number.POSITIVE_INFINITY };\n tables.set(limiter, table);\n }\n let state = table.states.get(key);\n // a key that is equal to a new key goes: the decision is the same, and it frees its slot\n if (state !== undefined && freeAt(rule, state) <= now) {\n table.states.delete(key);\n state = undefined;\n }\n if (state === undefined && table.states.size >= maxKeys) {\n if (table.next <= now) sweep(table, rule, now);\n if (table.states.size >= maxKeys) return { allowed: false, retryAfter: ms(table.next - now), cause: \"cap\" };\n }\n const step = decide(rule, state, now, n);\n if (state === undefined) {\n // a new key is never refused by its policy: a full bucket, or an empty window\n table.states.set(key, step.state);\n table.next = Math.min(table.next, freeAt(rule, step.state));\n } else table.states.set(key, step.state);\n return step.decision;\n },\n size(limiter) {\n return tables.get(limiter)?.states.size ?? 0;\n },\n };\n};\n\n/** A keyed limiter is the runtime of one declared limiter: its spec, its rule in numbers, and its store. */\nexport interface KeyedLimiter {\n readonly name: string;\n /** This spec is the declaration, the same data that `svc.limiter(name, spec)` takes and `describe()` shows. */\n readonly spec: LimiterSpec;\n readonly rule: LimitRule;\n /** This count is the most keys that the store holds for the limiter. */\n readonly maxKeys: number;\n /**\n * This method takes `units` units for a key (1 when absent), and gives the decision of the store.\n * When a shared store fails, it gives the decision of `onStoreFailure`, with the failure as text.\n * A take over the capacity of the policy is refused with the cause `capacity`, before the store.\n * It rejects units that are not a whole number of 1 or more.\n */\n take(key: string, units?: number): Promise<Decision>;\n /**\n * This method takes `units` units for a key (1 when absent), and gives the decision at once, with\n * no promise. Only a local store whose take gives its decision at once permits it, for example\n * `memoryStore`. A shared store throws.\n */\n tryTakeSync?(key: string, units?: number): Decision;\n}\n\n/** A local limiter is a keyed limiter on a memory store: its take can give the decision at once. */\nexport interface LocalLimiter extends KeyedLimiter {\n tryTakeSync(key: string, units?: number): Decision;\n}\n\n/** This function gives the text of a failure. */\nconst failureOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * This function makes the runtime of a limiter from its spec and its store. It refuses a spec with a\n * problem, because the limiter has no defaults. It also refuses a store of the wrong kind: a spec\n * with a shared store needs a store that the replicas share.\n * - A failure of a shared store gives the decision of `onStoreFailure`. With `open`, the take is\n * permitted with `remaining` 0. With `closed`, it is refused with the cause `store`.\n * - The `retryAfter` of the cause `store` is the longest `retryAfter` of the policy.\n * - A failure of a local store rejects the take, because a local store has no `onStoreFailure`.\n * - A take over the capacity of the policy is refused with the cause `capacity`, before the store.\n * Thus a store of your own that does not read `units` cannot let it in.\n * - `tryTakeSync` gives the decision at once. A shared store throws, and so does a local store that gives a promise.\n */\nexport function keyedLimiter(name: string, spec: LimiterSpec, store: MemoryStore): LocalLimiter;\nexport function keyedLimiter(name: string, spec: LimiterSpec, store: LimiterStore): KeyedLimiter;\nexport function keyedLimiter(name: string, spec: LimiterSpec, store: LimiterStore): KeyedLimiter {\n const problems = limiterProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n if (store.kind !== spec.store.kind)\n throw new Error(`limiter ${name} declares a ${spec.store.kind} store, but the store that it got is ${store.kind}`);\n const rule = limitRule(spec.policy);\n const maxKeys = toNumber(convertExact(fromNumber(spec.evict.maxKeys.value), spec.evict.maxKeys.unit, \"count\"));\n const onStoreFailure = spec.store.kind === \"shared\" ? spec.store.onStoreFailure : undefined;\n const closedAfter = longestRetryAfter(spec.policy);\n const take = async (key: string, units?: number): Promise<Decision> => {\n const n = unitsOf(units);\n const over = overCapacity(rule, n);\n if (over !== undefined) return over;\n const request: TakeRequest = { limiter: name, key, rule, maxKeys, units: n };\n if (onStoreFailure === undefined) return store.take(request);\n try {\n return await store.take(request);\n } catch (error) {\n const failure = failureOf(error);\n if (onStoreFailure === \"open\") return { allowed: true, remaining: 0, failure };\n return { allowed: false, retryAfter: { ...closedAfter }, cause: \"store\", failure };\n }\n };\n const tryTakeSync = (key: string, units?: number): Decision => {\n if (store.kind === \"shared\")\n throw new Error(`limiter ${name} has a shared store, which decides in a promise: tryTakeSync needs a memory store, thus use take()`);\n const n = unitsOf(units);\n const over = overCapacity(rule, n);\n if (over !== undefined) return over;\n const decision = store.take({ limiter: name, key, rule, maxKeys, units: n });\n if (isPromise(decision)) {\n // the take of the store happened: its promise has the decision, and its rejection is not left unhandled\n decision.then(undefined, () => {});\n throw new Error(`limiter ${name} has a store whose take gives a promise: tryTakeSync needs a memory store, thus use take()`);\n }\n return decision;\n };\n return {\n name,\n spec: {\n key: spec.key,\n policy: { ...spec.policy },\n store: { ...spec.store },\n evict: { maxKeys: { ...spec.evict.maxKeys } },\n },\n rule,\n maxKeys,\n take,\n tryTakeSync,\n };\n}\n\n/** This function tells if a decision of a store is a promise. */\nconst isPromise = (value: Decision | Promise<Decision>): value is Promise<Decision> =>\n typeof (value as { then?: unknown }).then === \"function\";\n"],"mappings":";;;;AA0DA,MAAM,MAAM,WAA6B;CAAE;CAAO,MAAM;AAAK;;;;;;;;;;;AAY7D,MAAa,eAAe,UAA8B;CACxD,MAAM,yBAAS,IAAI,IAAmB;CACtC,MAAM,SAAS,OAAc,MAAiB,QAAsB;EAClE,IAAI,OAAO,OAAO;EAClB,KAAK,MAAM,CAAC,KAAK,UAAU,MAAM,QAAQ;GACvC,MAAM,OAAO,OAAO,MAAM,KAAK;GAC/B,IAAI,QAAQ,KAAK,MAAM,OAAO,OAAO,GAAG;QACnC,OAAO,KAAK,IAAI,MAAM,IAAI;EACjC;EACA,MAAM,OAAO;CACf;CACA,OAAO;EACL,MAAM;EACN,KAAK,EAAE,SAAS,KAAK,MAAM,SAAS,SAAS;GAC3C,MAAM,IAAI,QAAQ,KAAK;GAEvB,MAAM,OAAO,aAAa,MAAM,CAAC;GACjC,IAAI,SAAS,KAAA,GAAW,OAAO;GAC/B,MAAM,MAAM,MAAM,IAAI;GACtB,IAAI,QAAQ,OAAO,IAAI,OAAO;GAC9B,IAAI,UAAU,KAAA,GAAW;IACvB,QAAQ;KAAE,wBAAQ,IAAI,IAAI;KAAG,MAAM,OAAO;IAAkB;IAC5D,OAAO,IAAI,SAAS,KAAK;GAC3B;GACA,IAAI,QAAQ,MAAM,OAAO,IAAI,GAAG;GAEhC,IAAI,UAAU,KAAA,KAAa,OAAO,MAAM,KAAK,KAAK,KAAK;IACrD,MAAM,OAAO,OAAO,GAAG;IACvB,QAAQ,KAAA;GACV;GACA,IAAI,UAAU,KAAA,KAAa,MAAM,OAAO,QAAQ,SAAS;IACvD,IAAI,MAAM,QAAQ,KAAK,MAAM,OAAO,MAAM,GAAG;IAC7C,IAAI,MAAM,OAAO,QAAQ,SAAS,OAAO;KAAE,SAAS;KAAO,YAAY,GAAG,MAAM,OAAO,GAAG;KAAG,OAAO;IAAM;GAC5G;GACA,MAAM,OAAO,OAAO,MAAM,OAAO,KAAK,CAAC;GACvC,IAAI,UAAU,KAAA,GAAW;IAEvB,MAAM,OAAO,IAAI,KAAK,KAAK,KAAK;IAChC,MAAM,OAAO,KAAK,IAAI,MAAM,MAAM,OAAO,MAAM,KAAK,KAAK,CAAC;GAC5D,OAAO,MAAM,OAAO,IAAI,KAAK,KAAK,KAAK;GACvC,OAAO,KAAK;EACd;EACA,KAAK,SAAS;GACZ,OAAO,OAAO,IAAI,OAAO,CAAC,EAAE,OAAO,QAAQ;EAC7C;CACF;AACF;;AA+BA,MAAM,aAAa,UAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAgBpG,SAAgB,aAAa,MAAc,MAAmB,OAAmC;CAC/F,MAAM,WAAW,gBAAgB,MAAM,IAAI;CAC3C,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,MAAM,SAAS,KAAK,IAAI,CAAC;CAC5D,IAAI,MAAM,SAAS,KAAK,MAAM,MAC5B,MAAM,IAAI,MAAM,WAAW,KAAK,cAAc,KAAK,MAAM,KAAK,uCAAuC,MAAM,MAAM;CACnH,MAAM,OAAO,UAAU,KAAK,MAAM;CAClC,MAAM,UAAU,SAAS,aAAa,WAAW,KAAK,MAAM,QAAQ,KAAK,GAAG,KAAK,MAAM,QAAQ,MAAM,OAAO,CAAC;CAC7G,MAAM,iBAAiB,KAAK,MAAM,SAAS,WAAW,KAAK,MAAM,iBAAiB,KAAA;CAClF,MAAM,cAAc,kBAAkB,KAAK,MAAM;CACjD,MAAM,OAAO,OAAO,KAAa,UAAsC;EACrE,MAAM,IAAI,QAAQ,KAAK;EACvB,MAAM,OAAO,aAAa,MAAM,CAAC;EACjC,IAAI,SAAS,KAAA,GAAW,OAAO;EAC/B,MAAM,UAAuB;GAAE,SAAS;GAAM;GAAK;GAAM;GAAS,OAAO;EAAE;EAC3E,IAAI,mBAAmB,KAAA,GAAW,OAAO,MAAM,KAAK,OAAO;EAC3D,IAAI;GACF,OAAO,MAAM,MAAM,KAAK,OAAO;EACjC,SAAS,OAAO;GACd,MAAM,UAAU,UAAU,KAAK;GAC/B,IAAI,mBAAmB,QAAQ,OAAO;IAAE,SAAS;IAAM,WAAW;IAAG;GAAQ;GAC7E,OAAO;IAAE,SAAS;IAAO,YAAY,EAAE,GAAG,YAAY;IAAG,OAAO;IAAS;GAAQ;EACnF;CACF;CACA,MAAM,eAAe,KAAa,UAA6B;EAC7D,IAAI,MAAM,SAAS,UACjB,MAAM,IAAI,MAAM,WAAW,KAAK,mGAAmG;EACrI,MAAM,IAAI,QAAQ,KAAK;EACvB,MAAM,OAAO,aAAa,MAAM,CAAC;EACjC,IAAI,SAAS,KAAA,GAAW,OAAO;EAC/B,MAAM,WAAW,MAAM,KAAK;GAAE,SAAS;GAAM;GAAK;GAAM;GAAS,OAAO;EAAE,CAAC;EAC3E,IAAI,UAAU,QAAQ,GAAG;GAEvB,SAAS,KAAK,KAAA,SAAiB,CAAC,CAAC;GACjC,MAAM,IAAI,MAAM,WAAW,KAAK,2FAA2F;EAC7H;EACA,OAAO;CACT;CACA,OAAO;EACL;EACA,MAAM;GACJ,KAAK,KAAK;GACV,QAAQ,EAAE,GAAG,KAAK,OAAO;GACzB,OAAO,EAAE,GAAG,KAAK,MAAM;GACvB,OAAO,EAAE,SAAS,EAAE,GAAG,KAAK,MAAM,QAAQ,EAAE;EAC9C;EACA;EACA;EACA;EACA;CACF;AACF;;AAGA,MAAM,aAAa,UACjB,OAAQ,MAA6B,SAAS"}
@@ -1,4 +1,5 @@
1
- import { C as limitRule, D as retryAfterSeconds, E as overCapacity, O as unitsOf, S as idleSpan, T as longestRetryAfter, _ as WaitCause, a as LimitPolicy, b as decide, c as LimiterEviction, d as RefusalCause, f as Refused, g as TokenBucket, h as TakeStep, i as KeyState, l as LimiterSpec, m as StoreFailure, n as CapacityRefused, o as LimitRule, p as SlidingWindow, r as Decision, s as Limiter, t as Allowed, u as LimiterStoreSpec, v as WaitRefused, w as limiterProblems, x as freeAt, y as capacityOf } from "./policy-CBcK2XGg.js";
2
- import { a as TakeRequest, i as MemoryStore, n as LimiterStore, o as keyedLimiter, r as LocalLimiter, s as memoryStore, t as KeyedLimiter } from "./store-DFwFKrsB.js";
3
- import { A as takeQuotas, C as RollingWindow, D as quotaProblems, E as memoryQuotaStore, F as limiterStateOf, M as SLIDING_WINDOW_MACHINE, N as TOKEN_BUCKET_MACHINE, O as quotaRule, P as limiterMachine, S as QuotasVerdict, T as keyedQuota, _ as QuotaStore, a as QuotaAnswer, b as QuotaWaitRefused, c as QuotaEvent, d as QuotaRecord, f as QuotaRefused, g as QuotaStep, h as QuotaState, i as QuotaAllowed, j as LimiterState, k as quotaStep, l as QuotaPart, m as QuotaSpec, n as KeyedQuota, o as QuotaCapacityRefused, p as QuotaRule, r as MemoryQuotaStore, s as QuotaChange, t as CalendarWindow, u as QuotaReading, v as QuotaTakeStep, w as TakeQuotasOptions, x as QuotaWindow, y as QuotaVerdict } from "./limiter-Cm8nC-Gd.js";
1
+ import { Allowed, CapacityRefused, Decision, KeyState, LimitPolicy, LimitRule, Limiter, LimiterEviction, LimiterSpec, LimiterStoreSpec, RefusalCause, Refused, SlidingWindow, StoreFailure, TakeStep, TokenBucket, WaitCause, WaitRefused, capacityOf, decide, freeAt, idleSpan, limitRule, limiterProblems, longestRetryAfter, overCapacity, retryAfterSeconds, unitsOf } from "./limiter/policy.js";
2
+ import { KeyedLimiter, LimiterStore, LocalLimiter, MemoryStore, TakeRequest, keyedLimiter, memoryStore } from "./limiter/store.js";
3
+ import { LimiterState, SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, limiterMachine, limiterStateOf } from "./limiter/machine.js";
4
+ import { CalendarWindow, KeyedQuota, MemoryQuotaStore, QuotaAllowed, QuotaAnswer, QuotaCapacityRefused, QuotaChange, QuotaEvent, QuotaPart, QuotaReading, QuotaRecord, QuotaRefused, QuotaRule, QuotaSpec, QuotaState, QuotaStep, QuotaStore, QuotaTakeStep, QuotaVerdict, QuotaWaitRefused, QuotaWindow, QuotasVerdict, RollingWindow, TakeQuotasOptions, keyedQuota, memoryQuotaStore, quotaProblems, quotaRule, quotaStep, takeQuotas } from "./limiter/quota.js";
4
5
  export { type Allowed, type CalendarWindow, type CapacityRefused, type Decision, type KeyState, type KeyedLimiter, type KeyedQuota, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type MemoryQuotaStore, type MemoryStore, type QuotaAllowed, type QuotaAnswer, type QuotaCapacityRefused, type QuotaChange, type QuotaEvent, type QuotaPart, type QuotaReading, type QuotaRecord, type QuotaRefused, type QuotaRule, type QuotaSpec, type QuotaState, type QuotaStep, type QuotaStore, type QuotaTakeStep, type QuotaVerdict, type QuotaWaitRefused, type QuotaWindow, type QuotasVerdict, type RefusalCause, type Refused, type RollingWindow, SLIDING_WINDOW_MACHINE, type SlidingWindow, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeQuotasOptions, type TakeRequest, type TakeStep, type TokenBucket, type WaitCause, type WaitRefused, capacityOf, decide, freeAt, idleSpan, keyedLimiter, keyedQuota, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryQuotaStore, memoryStore, overCapacity, quotaProblems, quotaRule, quotaStep, retryAfterSeconds, takeQuotas, unitsOf };
package/build/limiter.js CHANGED
@@ -1,3 +1,5 @@
1
- import { a as freeAt, d as longestRetryAfter, g as unitsOf, l as limitRule, m as retryAfterSeconds, o as idleSpan, p as overCapacity, r as decide, t as capacityOf, u as limiterProblems } from "./policy-UYALkqVq.js";
2
- import { a as quotaStep, c as TOKEN_BUCKET_MACHINE, d as keyedLimiter, f as memoryStore, i as quotaRule, l as limiterMachine, n as memoryQuotaStore, o as takeQuotas, r as quotaProblems, s as SLIDING_WINDOW_MACHINE, t as keyedQuota, u as limiterStateOf } from "./limiter-Bgy6Gmvl.js";
1
+ import { capacityOf, decide, freeAt, idleSpan, limitRule, limiterProblems, longestRetryAfter, overCapacity, retryAfterSeconds, unitsOf } from "./limiter/policy.js";
2
+ import { keyedLimiter, memoryStore } from "./limiter/store.js";
3
+ import { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, limiterMachine, limiterStateOf } from "./limiter/machine.js";
4
+ import { keyedQuota, memoryQuotaStore, quotaProblems, quotaRule, quotaStep, takeQuotas } from "./limiter/quota.js";
3
5
  export { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, capacityOf, decide, freeAt, idleSpan, keyedLimiter, keyedQuota, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryQuotaStore, memoryStore, overCapacity, quotaProblems, quotaRule, quotaStep, retryAfterSeconds, takeQuotas, unitsOf };
@@ -0,0 +1,152 @@
1
+ import { ServiceDescription } from "./description.js";
2
+ import { Bound, Change, Evaluated, Rule, TimerMarks, Verdict } from "./law.js";
3
+ import { Extent, Quantity } from "@mark1russell7/quantity";
4
+ /**
5
+ * This module applies the ordering law to a declaration. The declaration binds the symbols of the
6
+ * service, from its primitives: the polls of its checks, the windows of its policies, its drain.
7
+ * The scenario binds the symbols of the platform (preStop, grace, the probes of the kubelet,
8
+ * propagation) and of each dependency (its failover time, the idle close of its server). Thus the
9
+ * service gives the inequalities, and the scenario gives the values.
10
+ *
11
+ * A rule about a client applies one time for each dependency. A rule about a server (`@server`)
12
+ * also applies one time for each server transport of the service. A rule about a consumer applies
13
+ * one time for each consumer and each worker. A rule about a limiter applies one time for each limiter.
14
+ */
15
+ /** A statistic of a measured distribution. The law binds p99 (`LAW_STATISTIC`). */
16
+ export type Statistic = "p50" | "p90" | "p99" | "p999" | "max";
17
+ /** The law binds this statistic of a distribution. */
18
+ export declare const LAW_STATISTIC: Statistic;
19
+ /**
20
+ * A claim is a value of the scenario that names its epoch: the component and the version that give
21
+ * it, for example "node@22" (E2). A default is true only for a version: the keep-alive of Node is
22
+ * 5 s, but 65 s on main. A claim gives a set value, or a measured distribution by its statistics.
23
+ */
24
+ export type Claim = {
25
+ readonly epoch: string;
26
+ readonly value: Extent;
27
+ } | {
28
+ readonly epoch: string;
29
+ readonly distribution: Readonly<Partial<Record<Statistic, Quantity>>>;
30
+ };
31
+ /**
32
+ * A value of the scenario is an amount, or a claim. An amount names no epoch, thus the finding of
33
+ * each rule that reads it gives null for its epoch.
34
+ */
35
+ export type ScenarioValue = Extent | Claim;
36
+ /** A scenario gives the values of the platform and of each dependency, by the `symbol@hop` of the law. */
37
+ export interface Scenario {
38
+ /** These are the values of the platform: prestop_sleep@pod, termination_grace@pod, probe_period@pod, propagation_bound@cluster. */
39
+ readonly platform: Readonly<Record<string, ScenarioValue>>;
40
+ /**
41
+ * These are the probe windows of the kubelet, period × failure threshold. They add to the
42
+ * windows of the declaration. A probe reads the cached verdict, thus detection is the latch,
43
+ * then the probe.
44
+ */
45
+ readonly probes: {
46
+ readonly readiness: Quantity;
47
+ readonly liveness: Quantity;
48
+ };
49
+ /** These are the values of each dependency, by its name: failover_time@dependency, server_idle_close@server. */
50
+ readonly dependencies?: Readonly<Record<string, Readonly<Record<string, ScenarioValue>>>> | undefined;
51
+ /**
52
+ * These are the values of each transport, by its name and by the `symbol@hop` of the law. For a
53
+ * consumer or a worker, they are the values of its source: lease_duration@broker. For a server,
54
+ * they are the values of its clients: request_timeout@client.
55
+ */
56
+ readonly transports?: Readonly<Record<string, Readonly<Record<string, ScenarioValue>>>> | undefined;
57
+ /**
58
+ * These are the values of the callers of each limiter, by its name and by the `symbol@hop` of the
59
+ * law: client_retry_window@caller, retry_delay@caller. A symbol without a hop binds at `caller`.
60
+ */
61
+ readonly limiters?: Readonly<Record<string, Readonly<Record<string, ScenarioValue>>>> | undefined;
62
+ }
63
+ /** The epochs of a scope map each symbol that the scenario binds to the epoch of its value, or null when the value names none. */
64
+ export type Epochs = Readonly<Record<string, string | null>>;
65
+ /** A finding is the verdict of one rule for one scope: the service, or the client of a dependency. When a value of the scenario names an epoch, the finding gives the epoch of each value that the rule reads. */
66
+ export interface Finding {
67
+ readonly rule: string;
68
+ readonly scope: string;
69
+ readonly verdict: Verdict;
70
+ readonly statement: string;
71
+ readonly window?: string | undefined;
72
+ readonly evaluated: readonly Evaluated[];
73
+ /** These are the symbols that have no bound. A "depends" verdict waits for them. */
74
+ readonly unbound: readonly string[];
75
+ /** These are the epochs of the symbols of the rule that the scenario binds (E2). Thus a finding is true for these versions. */
76
+ readonly epochs?: Epochs | undefined;
77
+ }
78
+ /** These are the identifiers of the rules that each declaration gets. */
79
+ export declare const SERVICE_RULES: readonly string[];
80
+ /**
81
+ * These are the two rules of the law for a keyed limiter, as data. The caller of `lint()` gives
82
+ * them, as it gives each other rule. Each one applies one time for each limiter.
83
+ * - O29: the longest `Retry-After` of a limiter is at most the retry window of its caller. Its
84
+ * second inequality applies the same bound to a new key at the cap of keys.
85
+ * Otherwise the caller stops before the limit lets its call in, and a refusal becomes a failure.
86
+ * - O30: the least delay of a caller before it sends a refused call again is at least the longest
87
+ * `Retry-After` of the policy. Otherwise a caller that does not read the header sends again too
88
+ * early, and the limiter refuses each early call again.
89
+ *
90
+ * The identifiers O29 and O30 are provisional. The private corpus of the law (R3, track B) has 28
91
+ * rules, O01 to O28. It does not have these two rules yet, thus they take the next two identifiers.
92
+ */
93
+ export declare const LIMITER_RULES: readonly Rule[];
94
+ /** This function gives what the declaration tells about the service, as symbols of the law, and the source of each. */
95
+ export declare const serviceBindings: (svc: ServiceDescription, scenario: Scenario) => {
96
+ readonly bind: Record<string, Bound>;
97
+ readonly from: Record<string, string>;
98
+ readonly epochs: Epochs;
99
+ };
100
+ /** This identifier is the rule of the findings about a field that the declaration does not give. */
101
+ export declare const DECLARATION_RULE = "declaration";
102
+ /** This identifier is the rule of the findings for two parts that have one name in the scopes of a rule. */
103
+ export declare const NAME_RULE = "unique-names";
104
+ /** This identifier is the rule of the findings about the stall time of a progress check (`Check.marks`). */
105
+ export declare const PROGRESS_RULE = "progress";
106
+ /** This identifier is the rule of the findings about the bound of a unit against the cap of the `drain` phase. */
107
+ export declare const UNIT_BOUND_RULE = "unit-bound";
108
+ /** This identifier is the rule of the findings about the close bound against the cap of the `close transports` phase. */
109
+ export declare const CLOSE_BOUND_RULE = "close-bound";
110
+ /**
111
+ * These are the rules of the bounds of a loop. Each one applies one time for each consumer and
112
+ * each worker (S6 A10, A11). `lint()` gives them, as it gives `PROGRESS_RULE`.
113
+ * - unit-bound: `unit_processing_time` is less than the cap of the `drain` phase. Otherwise the
114
+ * drain can cut a unit that ends in its bound. A unit without a bound violates the rule.
115
+ * - close-bound: `close_bound` is less than the cap of the `close transports` phase. Otherwise the
116
+ * phase can end before the loop closes.
117
+ *
118
+ * The corpus of the law (R3) does not have these rules, thus they have identifiers of the service,
119
+ * not O-numbers. The symbols `drain_phase_cap@process` and `close_phase_cap@process` are the caps of
120
+ * one phase. `process_drain_time@process` is the sum of the caps of all the phases. A phase that the
121
+ * declaration does not give binds no symbol, thus its finding is `depends`.
122
+ */
123
+ export declare const BOUND_RULES: readonly Rule[];
124
+ /**
125
+ * These are the marks of the timers of the platform (E10). Kubernetes takes the probe period, the
126
+ * preStop sleep and the termination grace in whole seconds, thus each is stepped by 1 s. The
127
+ * cluster sets the propagation of the endpoints, thus a compression of the service cannot scale it.
128
+ */
129
+ export declare const PLATFORM_MARKS: TimerMarks;
130
+ /** A change of a compression of a service: a rule and a scope whose verdict the compression changes. */
131
+ export interface ScopedChange extends Change {
132
+ readonly scope: string;
133
+ }
134
+ /**
135
+ * This function tells which findings of `lint` a compression by k changes (E10). It scales the
136
+ * bindings of each scope by the marks. Thus a harness that runs the service k times faster learns
137
+ * the orderings that its run breaks. The unmarked symbols are the symbols of the rules with no mark.
138
+ * It reads the rules that `lint` applies with their bindings: the service rules and `BOUND_RULES`.
139
+ */
140
+ export declare const compressionOf: (svc: ServiceDescription, scenario: Scenario, rules: readonly Rule[], k: number, marks: TimerMarks) => {
141
+ readonly changed: readonly ScopedChange[];
142
+ readonly unmarked: readonly string[];
143
+ };
144
+ /**
145
+ * This function applies each service rule to a declaration and a scenario. A rule applies one time
146
+ * for the service, for each client, for each consumer and worker, or for each limiter. It also
147
+ * gives a finding for each necessary field that the description does not give (`DECLARATION_RULE`).
148
+ * It gives a finding for each name that two parts share in the scopes of a rule (`NAME_RULE`). Each progress check
149
+ * that names its loops also gets its findings (`PROGRESS_RULE`). The findings of the bounds of each
150
+ * consumer and each worker come last (`BOUND_RULES`).
151
+ */
152
+ export declare const lint: (svc: ServiceDescription, scenario: Scenario, rules: readonly Rule[]) => Finding[];