@mark1russell7/service 0.8.18 → 0.8.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. package/README.md +19 -0
  2. package/build/backoff.d.ts +44 -2
  3. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  4. package/build/builder.js +499 -0
  5. package/build/builder.js.map +1 -0
  6. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  7. package/build/channel.d.ts +1 -1
  8. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  9. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  10. package/build/client/core.js.map +1 -0
  11. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  12. package/build/client/dial.js +52 -0
  13. package/build/client/dial.js.map +1 -0
  14. package/build/client/machine.js +29 -0
  15. package/build/client/machine.js.map +1 -0
  16. package/build/client/meets.d.ts +35 -0
  17. package/build/client/meets.js +78 -0
  18. package/build/client/meets.js.map +1 -0
  19. package/build/clock.d.ts +1 -1
  20. package/build/conformance.d.ts +122 -0
  21. package/build/conformance.js +470 -0
  22. package/build/conformance.js.map +1 -0
  23. package/build/contract.d.ts +28 -0
  24. package/build/contract.js +184 -0
  25. package/build/contract.js.map +1 -0
  26. package/build/description.d.ts +161 -0
  27. package/build/description.js +11 -0
  28. package/build/description.js.map +1 -0
  29. package/build/drains.js +35 -0
  30. package/build/drains.js.map +1 -0
  31. package/build/events.d.ts +25 -0
  32. package/build/fakes.d.ts +43 -0
  33. package/build/fakes.js +93 -0
  34. package/build/fakes.js.map +1 -0
  35. package/build/grpc/client.d.ts +153 -0
  36. package/build/grpc/client.js +474 -0
  37. package/build/grpc/client.js.map +1 -0
  38. package/build/grpc/connection.d.ts +97 -0
  39. package/build/grpc/connection.js +59 -0
  40. package/build/grpc/connection.js.map +1 -0
  41. package/build/grpc/machine.d.ts +12 -0
  42. package/build/grpc/machine.js +149 -0
  43. package/build/grpc/machine.js.map +1 -0
  44. package/build/grpc/meets.d.ts +14 -0
  45. package/build/grpc/meets.js +105 -0
  46. package/build/grpc/meets.js.map +1 -0
  47. package/build/grpc/starting.d.ts +33 -0
  48. package/build/grpc/starting.js +89 -0
  49. package/build/grpc/starting.js.map +1 -0
  50. package/build/grpc.d.ts +9 -303
  51. package/build/grpc.js +7 -854
  52. package/build/health.d.ts +93 -0
  53. package/build/health.js +223 -0
  54. package/build/health.js.map +1 -0
  55. package/build/heartbeat.d.ts +1 -1
  56. package/build/host/discovery.d.ts +61 -0
  57. package/build/host/discovery.js +113 -0
  58. package/build/host/discovery.js.map +1 -0
  59. package/build/host/env.d.ts +14 -0
  60. package/build/host/env.js +57 -0
  61. package/build/host/env.js.map +1 -0
  62. package/build/host/fakes.d.ts +82 -0
  63. package/build/host/fakes.js +239 -0
  64. package/build/host/fakes.js.map +1 -0
  65. package/build/host/group.d.ts +142 -0
  66. package/build/host/group.js +517 -0
  67. package/build/host/group.js.map +1 -0
  68. package/build/host/install.d.ts +96 -0
  69. package/build/host/install.js +330 -0
  70. package/build/host/install.js.map +1 -0
  71. package/build/host/lock.d.ts +78 -0
  72. package/build/host/lock.js +190 -0
  73. package/build/host/lock.js.map +1 -0
  74. package/build/host/logs.d.ts +26 -0
  75. package/build/host/logs.js +48 -0
  76. package/build/host/logs.js.map +1 -0
  77. package/build/host/node.d.ts +14 -0
  78. package/build/host/node.js +309 -0
  79. package/build/host/node.js.map +1 -0
  80. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  81. package/build/host/ports.js +17 -0
  82. package/build/host/ports.js.map +1 -0
  83. package/build/host/probes.d.ts +51 -0
  84. package/build/host/probes.js +139 -0
  85. package/build/host/probes.js.map +1 -0
  86. package/build/host/processes.d.ts +32 -0
  87. package/build/host/processes.js +63 -0
  88. package/build/host/processes.js.map +1 -0
  89. package/build/host/render.d.ts +84 -0
  90. package/build/host/render.js +235 -0
  91. package/build/host/render.js.map +1 -0
  92. package/build/host/watch.d.ts +90 -0
  93. package/build/host/watch.js +165 -0
  94. package/build/host/watch.js.map +1 -0
  95. package/build/host.d.ts +13 -671
  96. package/build/host.js +12 -2126
  97. package/build/http/answers.js +29 -0
  98. package/build/http/answers.js.map +1 -0
  99. package/build/http/fake-server.js +61 -0
  100. package/build/http/fake-server.js.map +1 -0
  101. package/build/http/outcome.d.ts +115 -0
  102. package/build/http/outcome.js +325 -0
  103. package/build/http/outcome.js.map +1 -0
  104. package/build/http/probes.d.ts +83 -0
  105. package/build/http/probes.js +232 -0
  106. package/build/http/probes.js.map +1 -0
  107. package/build/http/transport.d.ts +165 -0
  108. package/build/http/transport.js +517 -0
  109. package/build/http/transport.js.map +1 -0
  110. package/build/http-client/client.d.ts +121 -0
  111. package/build/http-client/client.js +330 -0
  112. package/build/http-client/client.js.map +1 -0
  113. package/build/http-client/connection.d.ts +78 -0
  114. package/build/http-client/connection.js +54 -0
  115. package/build/http-client/connection.js.map +1 -0
  116. package/build/http-client/machine.d.ts +14 -0
  117. package/build/http-client/machine.js +109 -0
  118. package/build/http-client/machine.js.map +1 -0
  119. package/build/http-client/meets.d.ts +11 -0
  120. package/build/http-client/meets.js +74 -0
  121. package/build/http-client/meets.js.map +1 -0
  122. package/build/http-client/session.d.ts +87 -0
  123. package/build/http-client/session.js +99 -0
  124. package/build/http-client/session.js.map +1 -0
  125. package/build/http-client/starting.d.ts +25 -0
  126. package/build/http-client/starting.js +65 -0
  127. package/build/http-client/starting.js.map +1 -0
  128. package/build/http-client.d.ts +9 -330
  129. package/build/http-client.js +8 -707
  130. package/build/http.d.ts +5 -353
  131. package/build/http.js +3 -1086
  132. package/build/identity.d.ts +16 -0
  133. package/build/identity.js +44 -0
  134. package/build/identity.js.map +1 -0
  135. package/build/index.d.ts +35 -412
  136. package/build/index.js +24 -3277
  137. package/build/knobs.d.ts +1 -0
  138. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  139. package/build/knobs.js.map +1 -0
  140. package/build/latch.d.ts +29 -0
  141. package/build/latch.js +122 -0
  142. package/build/latch.js.map +1 -0
  143. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  144. package/build/law.js +149 -0
  145. package/build/law.js.map +1 -0
  146. package/build/lifecycle.d.ts +144 -0
  147. package/build/lifecycle.js +411 -0
  148. package/build/lifecycle.js.map +1 -0
  149. package/build/limiter/machine.d.ts +40 -0
  150. package/build/limiter/machine.js +279 -0
  151. package/build/limiter/machine.js.map +1 -0
  152. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  153. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  154. package/build/limiter/policy.js.map +1 -0
  155. package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
  156. package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
  157. package/build/limiter/quota.js.map +1 -0
  158. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  159. package/build/limiter/store.js +145 -0
  160. package/build/limiter/store.js.map +1 -0
  161. package/build/limiter.d.ts +4 -3
  162. package/build/limiter.js +4 -2
  163. package/build/lint.d.ts +152 -0
  164. package/build/lint.js +576 -0
  165. package/build/lint.js.map +1 -0
  166. package/build/logger.d.ts +71 -0
  167. package/build/logger.js +183 -0
  168. package/build/logger.js.map +1 -0
  169. package/build/machines.d.ts +41 -0
  170. package/build/machines.js +451 -0
  171. package/build/machines.js.map +1 -0
  172. package/build/metrics.d.ts +53 -0
  173. package/build/metrics.js +111 -0
  174. package/build/metrics.js.map +1 -0
  175. package/build/mongodb/client.d.ts +131 -0
  176. package/build/mongodb/client.js +388 -0
  177. package/build/mongodb/client.js.map +1 -0
  178. package/build/mongodb/connection.d.ts +112 -0
  179. package/build/mongodb/connection.js +12 -0
  180. package/build/mongodb/connection.js.map +1 -0
  181. package/build/mongodb/machine.d.ts +14 -0
  182. package/build/mongodb/machine.js +122 -0
  183. package/build/mongodb/machine.js.map +1 -0
  184. package/build/mongodb/meets.d.ts +15 -0
  185. package/build/mongodb/meets.js +103 -0
  186. package/build/mongodb/meets.js.map +1 -0
  187. package/build/mongodb/starting.d.ts +29 -0
  188. package/build/mongodb/starting.js +77 -0
  189. package/build/mongodb/starting.js.map +1 -0
  190. package/build/mongodb.d.ts +8 -296
  191. package/build/mongodb.js +7 -682
  192. package/build/operation.d.ts +27 -0
  193. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  194. package/build/operation.js.map +1 -0
  195. package/build/otel.d.ts +2 -2
  196. package/build/pg/client.d.ts +96 -0
  197. package/build/pg/client.js +277 -0
  198. package/build/pg/client.js.map +1 -0
  199. package/build/pg/connection.d.ts +75 -0
  200. package/build/pg/connection.js +11 -0
  201. package/build/pg/connection.js.map +1 -0
  202. package/build/pg/machine.d.ts +13 -0
  203. package/build/pg/machine.js +111 -0
  204. package/build/pg/machine.js.map +1 -0
  205. package/build/pg/meets.d.ts +14 -0
  206. package/build/pg/meets.js +83 -0
  207. package/build/pg/meets.js.map +1 -0
  208. package/build/pg/starting.d.ts +26 -0
  209. package/build/pg/starting.js +62 -0
  210. package/build/pg/starting.js.map +1 -0
  211. package/build/pg.d.ts +8 -219
  212. package/build/pg.js +7 -525
  213. package/build/poller.d.ts +9 -0
  214. package/build/poller.js +152 -0
  215. package/build/poller.js.map +1 -0
  216. package/build/process.d.ts +114 -0
  217. package/build/process.js +170 -0
  218. package/build/process.js.map +1 -0
  219. package/build/profiles.d.ts +68 -0
  220. package/build/profiles.js +120 -0
  221. package/build/profiles.js.map +1 -0
  222. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  223. package/build/queue.js +279 -0
  224. package/build/queue.js.map +1 -0
  225. package/build/rabbitmq/client.d.ts +144 -0
  226. package/build/rabbitmq/client.js +426 -0
  227. package/build/rabbitmq/client.js.map +1 -0
  228. package/build/rabbitmq/connection.d.ts +91 -0
  229. package/build/rabbitmq/connection.js +15 -0
  230. package/build/rabbitmq/connection.js.map +1 -0
  231. package/build/rabbitmq/machine.d.ts +13 -0
  232. package/build/rabbitmq/machine.js +159 -0
  233. package/build/rabbitmq/machine.js.map +1 -0
  234. package/build/rabbitmq/meets.d.ts +12 -0
  235. package/build/rabbitmq/meets.js +96 -0
  236. package/build/rabbitmq/meets.js.map +1 -0
  237. package/build/rabbitmq/starting.d.ts +27 -0
  238. package/build/rabbitmq/starting.js +67 -0
  239. package/build/rabbitmq/starting.js.map +1 -0
  240. package/build/rabbitmq.d.ts +8 -283
  241. package/build/rabbitmq.js +7 -742
  242. package/build/redis/client.d.ts +86 -0
  243. package/build/redis/client.js +285 -0
  244. package/build/redis/client.js.map +1 -0
  245. package/build/redis/connection.d.ts +57 -0
  246. package/build/redis/connection.js +11 -0
  247. package/build/redis/connection.js.map +1 -0
  248. package/build/redis/limiter.d.ts +43 -0
  249. package/build/redis/limiter.js +164 -0
  250. package/build/redis/limiter.js.map +1 -0
  251. package/build/redis/machine.d.ts +12 -0
  252. package/build/redis/machine.js +144 -0
  253. package/build/redis/machine.js.map +1 -0
  254. package/build/redis/meets.d.ts +11 -0
  255. package/build/redis/meets.js +75 -0
  256. package/build/redis/meets.js.map +1 -0
  257. package/build/redis/operations.d.ts +5 -0
  258. package/build/redis/operations.js +114 -0
  259. package/build/redis/operations.js.map +1 -0
  260. package/build/redis.d.ts +10 -207
  261. package/build/redis.js +9 -771
  262. package/build/requests.d.ts +66 -0
  263. package/build/requests.js +279 -0
  264. package/build/requests.js.map +1 -0
  265. package/build/retrier.d.ts +62 -0
  266. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  267. package/build/retrier.js.map +1 -0
  268. package/build/routes.d.ts +35 -0
  269. package/build/routes.js +77 -0
  270. package/build/routes.js.map +1 -0
  271. package/build/rules.d.ts +19 -2
  272. package/build/stops.d.ts +51 -0
  273. package/build/stops.js +86 -0
  274. package/build/stops.js.map +1 -0
  275. package/build/testing.d.ts +8 -270
  276. package/build/testing.js +4 -1027
  277. package/build/testing.js.map +1 -1
  278. package/build/timing.d.ts +63 -0
  279. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  280. package/build/timing.js.map +1 -0
  281. package/build/units.d.ts +17 -0
  282. package/build/units.js +236 -0
  283. package/build/units.js.map +1 -0
  284. package/build/watchdog.d.ts +34 -0
  285. package/build/watchdog.js +53 -0
  286. package/build/watchdog.js.map +1 -0
  287. package/build/websocket/client.d.ts +136 -0
  288. package/build/websocket/client.js +422 -0
  289. package/build/websocket/client.js.map +1 -0
  290. package/build/websocket/connection.d.ts +83 -0
  291. package/build/websocket/connection.js +57 -0
  292. package/build/websocket/connection.js.map +1 -0
  293. package/build/websocket/machine.d.ts +12 -0
  294. package/build/websocket/machine.js +155 -0
  295. package/build/websocket/machine.js.map +1 -0
  296. package/build/websocket/meets.d.ts +14 -0
  297. package/build/websocket/meets.js +92 -0
  298. package/build/websocket/meets.js.map +1 -0
  299. package/build/websocket/starting.d.ts +25 -0
  300. package/build/websocket/starting.js +69 -0
  301. package/build/websocket/starting.js.map +1 -0
  302. package/build/websocket.d.ts +9 -264
  303. package/build/websocket.js +8 -774
  304. package/build/worker.d.ts +92 -0
  305. package/build/worker.js +153 -0
  306. package/build/worker.js.map +1 -0
  307. package/package.json +4 -3
  308. package/build/backoff-QTRGfkEK.d.ts +0 -45
  309. package/build/clock-DpVgpY4h.d.ts +0 -2
  310. package/build/grpc.js.map +0 -1
  311. package/build/host.js.map +0 -1
  312. package/build/http-client.js.map +0 -1
  313. package/build/http.js.map +0 -1
  314. package/build/index.js.map +0 -1
  315. package/build/knobs-BJcz6m01.js.map +0 -1
  316. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  317. package/build/limiter-Bgy6Gmvl.js.map +0 -1
  318. package/build/logger-B6drv9w0.d.ts +0 -488
  319. package/build/machine-BhVeHr_m.js.map +0 -1
  320. package/build/mongodb.js.map +0 -1
  321. package/build/operation-DF73RZOI.js.map +0 -1
  322. package/build/pg.js.map +0 -1
  323. package/build/policy-UYALkqVq.js.map +0 -1
  324. package/build/process-7R9M29wN.js +0 -437
  325. package/build/process-7R9M29wN.js.map +0 -1
  326. package/build/rabbitmq.js.map +0 -1
  327. package/build/redis.js.map +0 -1
  328. package/build/requests-DD2ALv0_.js +0 -583
  329. package/build/requests-DD2ALv0_.js.map +0 -1
  330. package/build/retrier-Dnjhvxol.js.map +0 -1
  331. package/build/timing-DZl36uXs.js.map +0 -1
  332. package/build/websocket.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.js","names":[],"sources":["../../src/limiter/policy.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, convertible } from \"@mark1russell7/quantity/time\";\nimport { ONE, div, fromNumber, toNumber } from \"@mark1russell7/rational\";\n\n/**\n * A token bucket gives each key a bucket of `burst` tokens. The bucket refills at `rate`, and each\n * take uses one token. Thus a key can make `burst` takes at once after an idle time, and then\n * `rate` takes in each unit of time.\n */\nexport interface TokenBucket {\n readonly type: \"token-bucket\";\n /** This rate is how fast the bucket refills: a count for each unit of time, for example `{ value: 10, unit: \"count/s\" }`. */\n readonly rate: Quantity;\n /** This count is the size of the bucket: the most takes in a sequence after an idle time. */\n readonly burst: Quantity;\n}\n\n/**\n * A sliding window gives each key at most `limit` takes in each `window`. Each take counts for one\n * window from its time, thus the window moves with the clock and has no fixed edges.\n */\nexport interface SlidingWindow {\n readonly type: \"sliding-window\";\n /** This count is the most takes of one key in one window. */\n readonly limit: Quantity;\n /** This time is the length of the window. */\n readonly window: Quantity;\n}\n\n/** A limit policy is the rule that a keyed limiter applies to each key, as data. It has no defaults. */\nexport type LimitPolicy = TokenBucket | SlidingWindow;\n\n/**\n * A store failure policy tells what a take does when a shared store fails. It has no default.\n * - `open`: the limiter lets the take in. The count is not known, thus `remaining` is 0.\n * - `closed`: the limiter refuses the take with the cause `store`. Its `retryAfter` is the longest\n * `retryAfter` of the policy (`longestRetryAfter`). Thus O29 and O30 apply to it too.\n */\nexport type StoreFailure = \"open\" | \"closed\";\n\n/**\n * A store spec tells where the counts of the keys are:\n * - `local`: in the memory of each replica. A limit L over N replicas is then L / N on each\n * replica. That sum holds only on average, when the balancer spreads the takes of each key evenly.\n * A local store does not fail, thus it has no `onStoreFailure`, and the limiter ignores one.\n * - `shared`: in a store that the replicas share, the dependency of that name. The store decides\n * each take in one atomic step, on its own clock. Thus the limit holds across the replicas.\n * `onStoreFailure` tells what a take does when the store fails.\n */\nexport type LimiterStoreSpec =\n | { readonly kind: \"local\" }\n | { readonly kind: \"shared\"; readonly dependency: string; readonly onStoreFailure: StoreFailure };\n\n/**\n * The eviction of a limiter bounds its keys. A store removes a key only when its state is equal to\n * the state of a new key. That is a bucket that is full again, or a window with no take in it.\n * Thus an eviction changes no decision.\n */\nexport interface LimiterEviction {\n /**\n * This count is the most keys that the store holds. At the cap, the store refuses a take of a new\n * key until a held key is idle for its span (`idleSpan`). A held key keeps its count.\n */\n readonly maxKeys: Quantity;\n}\n\n/** A limiter spec is the declaration of one keyed limiter. Each part is necessary, because the limiter has no defaults. */\nexport interface LimiterSpec {\n /** This text tells what the key of each take is, for example `tenant` or `principal`. The caller gives each key. */\n readonly key: string;\n readonly policy: LimitPolicy;\n readonly store: LimiterStoreSpec;\n readonly evict: LimiterEviction;\n}\n\n/** A limiter is a keyed limiter in the description of a service: its name and its spec. */\nexport interface Limiter extends LimiterSpec {\n readonly name: string;\n}\n\n/**\n * A wait cause tells why a take is refused for a time:\n * - `limit`: the key used its limit.\n * - `cap`: the store holds its cap of keys, and the key is new.\n * - `store`: the shared store failed, and its spec declares `onStoreFailure: \"closed\"`.\n */\nexport type WaitCause = \"limit\" | \"cap\" | \"store\";\n\n/**\n * A refusal cause tells why a take is refused: a wait cause, or `capacity`. The cause `capacity` is\n * a take whose units are over the capacity of the policy. No wait lets it in.\n */\nexport type RefusalCause = WaitCause | \"capacity\";\n\n/**\n * A permitted take used its units of its key. `remaining` is the count of units that the key can\n * take at this time.\n */\nexport interface Allowed {\n readonly allowed: true;\n readonly remaining: number;\n /** This text is the failure of a shared store, when `onStoreFailure: \"open\"` lets the take in. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A wait refusal used nothing. `retryAfter` is the time until the limiter lets the same take in, when\n * no other take comes first. It is always above zero.\n */\nexport interface WaitRefused {\n readonly allowed: false;\n readonly cause: WaitCause;\n readonly retryAfter: Quantity;\n /** This text is the failure of a shared store, for the cause `store`. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A capacity refusal used nothing, and the same take is refused at each time. Its `units` are over\n * the `capacity` of the policy: the `burst` of a bucket, or the `limit` of a window. A caller can\n * split the take into parts of at most `capacity` units.\n */\nexport interface CapacityRefused {\n readonly allowed: false;\n readonly cause: \"capacity\";\n readonly units: number;\n readonly capacity: number;\n}\n\n/**\n * A refused take used nothing. The cause tells the type: a `WaitRefused` has a `retryAfter`, and a\n * `CapacityRefused` has none. Thus a caller examines the cause before it reads `retryAfter`.\n */\nexport type Refused = WaitRefused | CapacityRefused;\n\n/** A decision is the answer of a limiter to one take. */\nexport type Decision = Allowed | Refused;\n\n/**\n * A limit rule is a policy in numbers, which a store applies: each time in milliseconds, and each\n * count as a number. A store in another process, for example a script of Redis, gets these numbers.\n */\nexport type LimitRule =\n | {\n readonly type: \"token-bucket\";\n /** This time is the refill of one token, in milliseconds. */\n readonly interval: number;\n readonly burst: number;\n }\n | {\n readonly type: \"sliding-window\";\n readonly limit: number;\n /** This time is the length of the window, in milliseconds. */\n readonly window: number;\n };\n\n/**\n * A key state is what a store keeps for one key:\n * - A token bucket keeps the time at which its bucket is full again (`full`, in milliseconds).\n * - A sliding window keeps the time of each permitted take in the window, the oldest first.\n */\nexport type KeyState =\n | { readonly type: \"token-bucket\"; readonly full: number }\n | { readonly type: \"sliding-window\"; readonly stamps: readonly number[] };\n\n/** 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. */\nexport interface TakeStep {\n readonly decision: Decision;\n readonly state: KeyState;\n}\n\n/**\n * This tolerance is one nanosecond, in milliseconds. A comparison of times permits it, because a\n * rate of 3 for each second gives an interval that floating point cannot hold exactly.\n */\nconst TOLERANCE = 1e-6;\n\n/** These checks of an amount are internal: the quota module uses them, and the entry does not export them. */\nexport const isCount = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count\");\nexport const isTime = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"s\");\nconst isRate = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count/s\");\n/** This function tells if a unit converts, also for a unit that the quantity package does not know. */\nexport const safely = (test: (amount: Quantity | undefined) => boolean, amount: Quantity | undefined): boolean => {\n try {\n return test(amount);\n } catch {\n return false;\n }\n};\nexport const finiteAbove = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value > 0;\nexport const wholeCount = (amount: Quantity): boolean => finiteAbove(amount) && Number.isInteger(toNumber(convertExact(fromNumber(amount.value), amount.unit, \"count\")));\n\n/** A loose policy is a policy from any source, with each part optional, for the check of its parts. */\ninterface LoosePolicy {\n readonly type?: string;\n readonly rate?: Quantity;\n readonly burst?: Quantity;\n readonly limit?: Quantity;\n readonly window?: Quantity;\n}\n\n/**\n * This function gives the problems of a limiter spec. `describe()` and `keyedLimiter` refuse a spec\n * with a problem. A part that is absent is a problem, because the limiter has no defaults.\n */\nexport const limiterProblems = (name: string, spec: Partial<LimiterSpec> | undefined): string[] => {\n const owner = `limiter ${name}`;\n if (spec === undefined || (spec as unknown) === null) return [`${owner} has no spec: a limiter has no defaults`];\n const problems: string[] = [];\n const missing = (part: string): void => {\n problems.push(`${owner} does not declare ${part}: a limiter has no defaults`);\n };\n if (typeof spec.key !== \"string\") missing(\"what its key is (key)\");\n else if (spec.key.trim().length === 0) problems.push(`${owner} names no key`);\n const policy = spec.policy as LoosePolicy | undefined;\n if (policy === undefined) missing(\"its policy (policy)\");\n else if (policy.type === \"token-bucket\") {\n if (policy.rate === undefined) missing(\"the rate of its bucket (policy.rate)\");\n else if (!safely(isRate, policy.rate)) problems.push(`${owner}'s rate is not a count for each unit of time, for example count/s`);\n else if (!finiteAbove(policy.rate)) problems.push(`${owner}'s rate is not a finite rate above zero`);\n if (policy.burst === undefined) missing(\"the size of its bucket (policy.burst)\");\n else if (!safely(isCount, policy.burst)) problems.push(`${owner}'s burst is not a count`);\n else if (!wholeCount(policy.burst)) problems.push(`${owner}'s burst is not a whole count above zero`);\n } else if (policy.type === \"sliding-window\") {\n if (policy.limit === undefined) missing(\"the limit of its window (policy.limit)\");\n else if (!safely(isCount, policy.limit)) problems.push(`${owner}'s limit is not a count`);\n else if (!wholeCount(policy.limit)) problems.push(`${owner}'s limit is not a whole count above zero`);\n if (policy.window === undefined) missing(\"the length of its window (policy.window)\");\n else if (!safely(isTime, policy.window)) problems.push(`${owner}'s window is not a time`);\n else if (!finiteAbove(policy.window)) problems.push(`${owner}'s window is not a finite time above zero`);\n } else problems.push(`${owner}'s policy ${String(policy.type)} is not \"token-bucket\" or \"sliding-window\"`);\n const store = spec.store as { kind?: string; dependency?: unknown; onStoreFailure?: unknown } | undefined;\n if (store === undefined) missing(`its store, { kind: \"local\" } or { kind: \"shared\", dependency, onStoreFailure } (store)`);\n else if (store.kind === \"shared\") {\n if (typeof store.dependency !== \"string\" || store.dependency.trim().length === 0)\n problems.push(`${owner}'s shared store names no dependency`);\n if (store.onStoreFailure === undefined) missing(`what a failure of its shared store does, \"open\" or \"closed\" (store.onStoreFailure)`);\n else if (store.onStoreFailure !== \"open\" && store.onStoreFailure !== \"closed\")\n problems.push(`${owner}'s onStoreFailure ${String(store.onStoreFailure)} is not \"open\" or \"closed\"`);\n } else if (store.kind !== \"local\") problems.push(`${owner}'s store ${String(store.kind)} is not \"local\" or \"shared\"`);\n const evict = spec.evict as Partial<LimiterEviction> | undefined;\n if (evict === undefined || evict.maxKeys === undefined) missing(\"the most keys that it holds (evict.maxKeys)\");\n else if (!safely(isCount, evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a count`);\n else if (!wholeCount(evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a whole count above zero: the count of keys has a bound`);\n return problems;\n};\n\n/** This function gives an amount in milliseconds, exactly where the units permit, as one number. */\nexport const milliseconds = (amount: Quantity): number => toNumber(convertExact(fromNumber(amount.value), amount.unit, \"ms\"));\n/** This function gives a count as one number. */\nexport const countOf = (amount: Quantity): number => toNumber(convertExact(fromNumber(amount.value), amount.unit, \"count\"));\n\n/**\n * This function gives the rule of a policy in numbers. The interval of a bucket is exact as a\n * rational, and it becomes one number only at the end. Thus 10 for each minute gives 6000 ms.\n */\nexport const limitRule = (policy: LimitPolicy): LimitRule => {\n if (policy.type === \"token-bucket\") {\n const perMs = convertExact(fromNumber(policy.rate.value), policy.rate.unit, \"count/ms\");\n return { type: \"token-bucket\", interval: toNumber(div(ONE, perMs)), burst: countOf(policy.burst) };\n }\n return { type: \"sliding-window\", limit: countOf(policy.limit), window: milliseconds(policy.window) };\n};\n\n/** This function gives a time in milliseconds as a quantity. */\nconst ms = (value: number): Quantity => ({ value, unit: \"ms\" });\n\n/**\n * This function gives the span after which an idle key is equal to a new key. That span is\n * `burst / rate` for a token bucket, and one window for a sliding window. A store can remove the key\n * after it, and no decision changes. It is also the longest `retryAfter` of a new key that the store\n * refuses at its cap.\n */\nexport const idleSpan = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval * rule.burst : rule.window);\n};\n\n/**\n * This function gives the longest `retryAfter` of a refusal by the policy: one interval of the\n * bucket (`1 / rate`), or one window. A refusal at the cap of keys can be longer, up to `idleSpan`.\n */\nexport const longestRetryAfter = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval : rule.window);\n};\n\n/**\n * This function gives a `retryAfter` in whole seconds, rounded up, as the header `Retry-After`\n * (RFC 9110) has it. A time over a whole second by less than one nanosecond rounds down to it,\n * because that part is an error of floating point.\n */\nexport const retryAfterSeconds = (retryAfter: Quantity): number => {\n const seconds = toNumber(convertExact(fromNumber(retryAfter.value), retryAfter.unit, \"s\"));\n return Math.max(0, Math.ceil(seconds - TOLERANCE / 1000));\n};\n\n/** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */\nexport const freeAt = (rule: LimitRule, state: KeyState): number => {\n if (state.type === \"token-bucket\") return state.full;\n const last = state.stamps[state.stamps.length - 1];\n return last === undefined ? Number.NEGATIVE_INFINITY : last + (rule.type === \"sliding-window\" ? rule.window : 0);\n};\n\n/** 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. */\nexport const capacityOf = (rule: LimitRule): number => (rule.type === \"token-bucket\" ? rule.burst : rule.limit);\n\n/**\n * This function gives the units of a take: 1 when they are absent. It throws for units that are not\n * a whole number of 1 or more, because such a take has no meaning.\n */\nexport const unitsOf = (units: number | undefined): number => {\n if (units === undefined) return 1;\n if (typeof units !== \"number\" || !Number.isSafeInteger(units) || units < 1)\n throw new RangeError(`the units of a take are a whole number of 1 or more, not ${String(units)}`);\n return units;\n};\n\n/** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */\nexport const overCapacity = (rule: LimitRule, units: number): CapacityRefused | undefined => {\n const capacity = capacityOf(rule);\n return units > capacity ? { allowed: false, cause: \"capacity\", units, capacity } : undefined;\n};\n\n/**\n * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in\n * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each\n * store in this process. A store in another process does the same arithmetic in its own atomic step.\n * - A take over the capacity of the rule (`capacityOf`) is refused with the cause `capacity`, and\n * the state does not change.\n * - A token bucket (GCRA): the store lets the take in when, with the take, the bucket is full\n * again in at most `burst` intervals. A refusal waits until `units` tokens are back.\n * - A sliding window: the store lets the take in when at most `limit - units` takes are in the\n * window. A refusal waits until enough of the oldest takes leave the window.\n * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.\n */\nexport const decide = (rule: LimitRule, state: KeyState | undefined, now: number, units?: number): TakeStep => {\n const n = unitsOf(units);\n const over = overCapacity(rule, n);\n if (rule.type === \"token-bucket\") {\n const span = rule.interval * rule.burst;\n const full = state?.type === \"token-bucket\" ? Math.max(state.full, now) : now;\n if (over !== undefined) return { decision: over, state: { type: \"token-bucket\", full } };\n const next = full + rule.interval * n;\n if (next - now > span + TOLERANCE)\n return { decision: { allowed: false, retryAfter: ms(next - span - now), cause: \"limit\" }, state: { type: \"token-bucket\", full } };\n const remaining = Math.max(0, Math.floor((span - (next - now)) / rule.interval + TOLERANCE));\n return { decision: { allowed: true, remaining }, state: { type: \"token-bucket\", full: next } };\n }\n const held = state?.type === \"sliding-window\" ? state.stamps : [];\n // a take counts for one window from its time: it leaves the window at stamp + window\n const live = held.filter((stamp) => stamp + rule.window > now + TOLERANCE);\n if (over !== undefined) return { decision: over, state: { type: \"sliding-window\", stamps: live } };\n // the take fits when the oldest (live + n - limit) takes have left the window\n const excess = live.length + n - rule.limit;\n if (excess > 0)\n return { decision: { allowed: false, retryAfter: ms(live[excess - 1]! + rule.window - now), cause: \"limit\" }, state: { type: \"sliding-window\", stamps: live } };\n return {\n decision: { allowed: true, remaining: rule.limit - live.length - n },\n state: { type: \"sliding-window\", stamps: [...live, ...Array.from({ length: n }, () => now)] },\n };\n};\n"],"mappings":";;;;;;;AA+KA,MAAM,YAAY;;AAGlB,MAAa,WAAW,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,OAAO;AAC1H,MAAa,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,GAAG;AACrH,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,SAAS;;AAEpH,MAAa,UAAU,MAAiD,WAA0C;CAChH,IAAI;EACF,OAAO,KAAK,MAAM;CACpB,QAAQ;EACN,OAAO;CACT;AACF;AACA,MAAa,eAAe,WAA8B,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,OAAO,KAAK,KAAK,OAAO,QAAQ;AA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GAAE,MAAM;GAAkB,QAAQ;EAAK;CAAE;CAEjG,MAAM,SAAS,KAAK,SAAS,IAAI,KAAK;CACtC,IAAI,SAAS,GACX,OAAO;EAAE,UAAU;GAAE,SAAS;GAAO,YAAY,GAAG,KAAK,SAAS,KAAM,KAAK,SAAS,GAAG;GAAG,OAAO;EAAQ;EAAG,OAAO;GAAE,MAAM;GAAkB,QAAQ;EAAK;CAAE;CAChK,OAAO;EACL,UAAU;GAAE,SAAS;GAAM,WAAW,KAAK,QAAQ,KAAK,SAAS;EAAE;EACnE,OAAO;GAAE,MAAM;GAAkB,QAAQ,CAAC,GAAG,MAAM,GAAG,MAAM,KAAK,EAAE,QAAQ,EAAE,SAAS,GAAG,CAAC;EAAE;CAC9F;AACF"}
@@ -1,52 +1,11 @@
1
- import { a as LimitPolicy, i as KeyState, o as LimitRule } from "./policy-CBcK2XGg.js";
2
- import "./store-DFwFKrsB.js";
3
1
  import { Quantity } from "@mark1russell7/quantity";
4
2
  import { WallClock } from "@mark1russell7/algebra/clock";
5
- import { Machine } from "@mark1russell7/algebra";
6
- /**
7
- * A limiter state is the state of one key of a keyed limiter, as its machine document names it:
8
- * - `new`: the store holds no state for the key, or a state that is equal to the state of a new key.
9
- * - `open`: the key holds a count, and its next take is permitted.
10
- * - `limited`: the next take of the key is refused with the cause `limit`, until a unit is back.
11
- */
12
- type LimiterState = "new" | "open" | "limited";
13
- /**
14
- * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds
15
- * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time
16
- * for the key: when its bucket is full again.
17
- * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.
18
- * - A refused take waits until one token is back: at most one interval. That interval is the
19
- * longest `Retry-After` of the policy (`retry_after@limiter` of the law).
20
- * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That
21
- * span is the idle span, and the longest wait of a new key at the cap of keys
22
- * (`retry_after_at_cap@limiter`).
23
- */
24
- declare const TOKEN_BUCKET_MACHINE: Machine;
25
- /**
26
- * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of
27
- * each permitted take of the key in the window, and each take counts for one window from its time.
28
- * - A take is permitted when fewer than `limit` takes are in the window.
29
- * - A refused take waits until the oldest take leaves the window: at most one window. That window is
30
- * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).
31
- * - One window after the last take, no take is in the window, and the key is equal to a new key.
32
- * That window is the idle span, and the longest wait of a new key at the cap of keys
33
- * (`retry_after_at_cap@limiter`).
34
- */
35
- declare const SLIDING_WINDOW_MACHINE: Machine;
36
- /** This function gives the machine document of the policy of a limiter. */
37
- declare const limiterMachine: (policy: LimitPolicy) => Machine;
38
- /**
39
- * This function gives the state of a key of a store as its machine document names it, at the time
40
- * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps
41
- * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.
42
- */
43
- declare const limiterStateOf: (rule: LimitRule, state: KeyState | undefined, now: number) => LimiterState;
44
3
  /**
45
4
  * A rolling window counts the units of the last `span`. Use it when the provider does not tell when
46
5
  * its count starts again. The window puts each take in a time bucket. A unit counts until all of
47
6
  * its bucket is out of the window. Thus the count is not lower than the count of a fixed window.
48
7
  */
49
- interface RollingWindow {
8
+ export interface RollingWindow {
50
9
  readonly kind: "rolling";
51
10
  /** This time is the length of the window, for example `{ value: 24, unit: "h" }`. */
52
11
  readonly span: Quantity;
@@ -59,7 +18,7 @@ interface RollingWindow {
59
18
  * zone skips that time, the window starts at the end of the gap. When the clock shows that time
60
19
  * two times, the window starts at the first of the two.
61
20
  */
62
- interface CalendarWindow {
21
+ export interface CalendarWindow {
63
22
  readonly kind: "calendar";
64
23
  readonly unit: "day" | "month";
65
24
  /** The IANA name of the time zone, for example `America/Chicago` or `UTC`. */
@@ -68,17 +27,25 @@ interface CalendarWindow {
68
27
  readonly start: Quantity;
69
28
  }
70
29
  /** A quota window is a rolling window or a calendar window. */
71
- type QuotaWindow = RollingWindow | CalendarWindow;
30
+ export type QuotaWindow = RollingWindow | CalendarWindow;
72
31
  /** A quota spec is the declaration of a quota. It has no defaults. */
73
- interface QuotaSpec {
32
+ export interface QuotaSpec {
74
33
  /** This count is the count of units that the provider gives in one window. */
75
34
  readonly limit: Quantity;
76
35
  /** The gate keeps this count of units unused: from 0 to less than the limit. */
77
36
  readonly reserve: Quantity;
78
37
  readonly window: QuotaWindow;
38
+ /**
39
+ * This value is the longest block that a reading of the provider can set: a time above zero, or
40
+ * `window`. A reading at the instant `t` blocks the key until `t` plus the time at the latest. With
41
+ * `window`, the block ends at the latest when the bucket of `t` stops counting. Thus a reset of the
42
+ * provider in a wrong form does not stop a key for much longer than one window. The step also
43
+ * applies this bound to a block that the stored record keeps. When it is absent, no block has a bound.
44
+ */
45
+ readonly maxBlock?: Quantity | "window" | undefined;
79
46
  }
80
47
  /** A quota rule is a spec in numbers: each count as a number, and each time in milliseconds. */
81
- interface QuotaRule {
48
+ export interface QuotaRule {
82
49
  readonly limit: number;
83
50
  readonly reserve: number;
84
51
  readonly window: {
@@ -91,12 +58,14 @@ interface QuotaRule {
91
58
  readonly zone: string;
92
59
  readonly start: number;
93
60
  };
61
+ /** This value is the longest block in milliseconds, or `window`. When it is absent, no block has a bound. */
62
+ readonly maxBlock?: number | "window" | undefined;
94
63
  }
95
64
  /**
96
65
  * A quota record is what a store keeps for one key. A store can keep it as JSON. Each instant is in
97
66
  * milliseconds from 1970-01-01T00:00:00Z.
98
67
  */
99
- interface QuotaRecord {
68
+ export interface QuotaRecord {
100
69
  /** Each item is a time bucket: its start, and its count of units. The oldest bucket is first. */
101
70
  readonly spent: readonly (readonly [start: number, units: number])[];
102
71
  /** The provider refused the key until this instant. */
@@ -105,7 +74,7 @@ interface QuotaRecord {
105
74
  readonly readAt?: number | undefined;
106
75
  }
107
76
  /** A quota reading is what an answer of the provider tells of its count. */
108
- interface QuotaReading {
77
+ export interface QuotaReading {
109
78
  /** This count is the count of units that the provider gives before its next reset. */
110
79
  readonly remaining?: number | undefined;
111
80
  /**
@@ -115,7 +84,7 @@ interface QuotaReading {
115
84
  readonly resetAt?: number | undefined;
116
85
  }
117
86
  /** A quota state is the state of one key at the instant `at`. */
118
- interface QuotaState {
87
+ export interface QuotaState {
119
88
  /** This instant is the instant of the step. */
120
89
  readonly at: number;
121
90
  /** This count is the count of units in the window. */
@@ -128,7 +97,7 @@ interface QuotaState {
128
97
  readonly blockedUntil?: number | undefined;
129
98
  }
130
99
  /** A permitted take counted its units at the instant `state.at`. */
131
- interface QuotaAllowed {
100
+ export interface QuotaAllowed {
132
101
  readonly allowed: true;
133
102
  readonly state: QuotaState;
134
103
  }
@@ -137,7 +106,7 @@ interface QuotaAllowed {
137
106
  * and `provider` when the provider refused the key. At `resetAt`, the gate gives the same take,
138
107
  * when no other take comes first.
139
108
  */
140
- interface QuotaWaitRefused {
109
+ export interface QuotaWaitRefused {
141
110
  readonly allowed: false;
142
111
  readonly cause: "limit" | "provider";
143
112
  readonly resetAt: number;
@@ -149,7 +118,7 @@ interface QuotaWaitRefused {
149
118
  * A capacity refusal counted nothing, and the gate refuses the same take at each time. Its units
150
119
  * are more than the `capacity` of one window: the limit less the reserve.
151
120
  */
152
- interface QuotaCapacityRefused {
121
+ export interface QuotaCapacityRefused {
153
122
  readonly allowed: false;
154
123
  readonly cause: "capacity";
155
124
  readonly units: number;
@@ -157,9 +126,9 @@ interface QuotaCapacityRefused {
157
126
  readonly state: QuotaState;
158
127
  }
159
128
  /** A quota refusal is a wait refusal or a capacity refusal. */
160
- type QuotaRefused = QuotaWaitRefused | QuotaCapacityRefused;
129
+ export type QuotaRefused = QuotaWaitRefused | QuotaCapacityRefused;
161
130
  /** A quota verdict is the answer of a quota to one take. */
162
- type QuotaVerdict = QuotaAllowed | QuotaRefused;
131
+ export type QuotaVerdict = QuotaAllowed | QuotaRefused;
163
132
  /**
164
133
  * A quota event is one change of a key:
165
134
  * - `take`: count `units` for a call that starts at the instant of the step, or refuse it.
@@ -169,7 +138,7 @@ type QuotaVerdict = QuotaAllowed | QuotaRefused;
169
138
  * provider came at or after `at`.
170
139
  * - `read`: change nothing, and give the state.
171
140
  */
172
- type QuotaEvent = {
141
+ export type QuotaEvent = {
173
142
  readonly type: "take";
174
143
  readonly units: number;
175
144
  } | {
@@ -183,22 +152,22 @@ type QuotaEvent = {
183
152
  readonly type: "read";
184
153
  };
185
154
  /** A quota step is the next record of a key and its state. Only a take gives a verdict. */
186
- interface QuotaStep {
155
+ export interface QuotaStep {
187
156
  readonly record: QuotaRecord;
188
157
  readonly state: QuotaState;
189
158
  readonly verdict?: QuotaVerdict | undefined;
190
159
  }
191
160
  /** A take step is the step of a take: it always has a verdict. */
192
- interface QuotaTakeStep extends QuotaStep {
161
+ export interface QuotaTakeStep extends QuotaStep {
193
162
  readonly verdict: QuotaVerdict;
194
163
  }
195
164
  /**
196
165
  * This function gives the problems of a quota spec. `keyedQuota` and `quotaRule` refuse a spec with
197
166
  * a problem. A part that is absent is a problem, because a quota has no defaults.
198
167
  */
199
- declare const quotaProblems: (name: string, spec: Partial<QuotaSpec> | undefined) => string[];
168
+ export declare const quotaProblems: (name: string, spec: Partial<QuotaSpec> | undefined) => string[];
200
169
  /** This function gives the rule of a quota spec. It throws an error with the problems of a spec that has a problem. */
201
- declare const quotaRule: (name: string, spec: QuotaSpec) => QuotaRule;
170
+ export declare const quotaRule: (name: string, spec: QuotaSpec) => QuotaRule;
202
171
  /**
203
172
  * This function is the pure step of a quota. It reads the stored record of one key at the instant
204
173
  * `instant`, applies the event, and gives the next record and the state. It removes what does not
@@ -209,18 +178,20 @@ declare const quotaRule: (name: string, spec: QuotaSpec) => QuotaRule;
209
178
  * is the end of that refusal, or a later instant when the window has room for the units.
210
179
  * - A take over the room of the window is refused with the cause `limit`, until enough of the
211
180
  * oldest units stop counting.
181
+ * - With `maxBlock` in the rule, a block ends at the latest at the bound of the instant. The step
182
+ * applies the bound to the stored block before the event, and to the block of a note after it.
212
183
  *
213
184
  * It throws a `RangeError` for an instant that is not a date, and for units that are not a finite
214
185
  * count of 0 or more.
215
186
  */
216
- declare function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: Extract<QuotaEvent, {
187
+ export declare function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: Extract<QuotaEvent, {
217
188
  type: "take";
218
189
  }>): QuotaTakeStep;
219
- declare function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep;
190
+ export declare function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep;
220
191
  /** A quota answer is a value at once for a store that answers at once, else a promise. */
221
- type QuotaAnswer<Sync extends boolean, T> = Sync extends true ? T : Promise<T>;
192
+ export type QuotaAnswer<Sync extends boolean, T> = Sync extends true ? T : Promise<T>;
222
193
  /** A quota change is what a step gives a store: the record to keep, and the result for the caller. */
223
- interface QuotaChange<T> {
194
+ export interface QuotaChange<T> {
224
195
  readonly record: QuotaRecord;
225
196
  readonly result: T;
226
197
  }
@@ -230,7 +201,7 @@ interface QuotaChange<T> {
230
201
  * at once (`sync: true`), for example a store in memory or in SQLite. A store that the replicas
231
202
  * share answers with a promise (`sync: false`).
232
203
  */
233
- interface QuotaStore<Sync extends boolean = boolean> {
204
+ export interface QuotaStore<Sync extends boolean = boolean> {
234
205
  readonly sync: Sync;
235
206
  /**
236
207
  * This method gives `step` the stored record of the quota and the key, or undefined for a new key.
@@ -241,7 +212,7 @@ interface QuotaStore<Sync extends boolean = boolean> {
241
212
  change<T>(quota: string, key: string, step: (stored: unknown) => QuotaChange<T>): QuotaAnswer<Sync, T>;
242
213
  }
243
214
  /** A memory quota store is the store of one process. Its records are in memory. */
244
- interface MemoryQuotaStore extends QuotaStore<true> {
215
+ export interface MemoryQuotaStore extends QuotaStore<true> {
245
216
  /** This method gives the count of keys that the store holds for a quota. */
246
217
  size(quota: string): number;
247
218
  }
@@ -251,9 +222,9 @@ interface MemoryQuotaStore extends QuotaStore<true> {
251
222
  * of a new key. It does not sweep the other keys: use it for a set of keys with a bound, for
252
223
  * example the accounts of an API.
253
224
  */
254
- declare const memoryQuotaStore: () => MemoryQuotaStore;
225
+ export declare const memoryQuotaStore: () => MemoryQuotaStore;
255
226
  /** A keyed quota is the runtime of one quota: its spec, its rule in numbers, its store and its wall clock. */
256
- interface KeyedQuota<Sync extends boolean = boolean> {
227
+ export interface KeyedQuota<Sync extends boolean = boolean> {
257
228
  /** This name is the quota. A store keeps the keys of each quota apart. */
258
229
  readonly name: string;
259
230
  readonly spec: QuotaSpec;
@@ -277,10 +248,14 @@ interface KeyedQuota<Sync extends boolean = boolean> {
277
248
  * store that gives a promise throws an error.
278
249
  * - With a store that answers with a promise, each method gives a promise. A `RangeError` rejects.
279
250
  */
280
- declare function keyedQuota<Sync extends boolean>(name: string, spec: QuotaSpec, store: QuotaStore<Sync>, clock: Pick<WallClock, "time" | "now">): KeyedQuota<Sync>;
281
- /** A quota part is one take of a multi-quota take: a quota, a key, and the units of the take. */
282
- interface QuotaPart<Sync extends boolean = boolean> {
283
- readonly quota: KeyedQuota<Sync>;
251
+ export declare function keyedQuota<Sync extends boolean>(name: string, spec: QuotaSpec, store: QuotaStore<Sync>, clock: Pick<WallClock, "time" | "now">): KeyedQuota<Sync>;
252
+ /**
253
+ * A quota part is one take of a multi-quota take: a quota, a key, and the units of the take. The
254
+ * quota needs only `sync`, `take` and `giveBack`. Thus a gate of your own with these members can be
255
+ * a part, and a `KeyedQuota` is one.
256
+ */
257
+ export interface QuotaPart<Sync extends boolean = boolean> {
258
+ readonly quota: Pick<KeyedQuota<Sync>, "sync" | "take" | "giveBack">;
284
259
  readonly key: string;
285
260
  readonly units: number;
286
261
  }
@@ -291,7 +266,7 @@ interface QuotaPart<Sync extends boolean = boolean> {
291
266
  * - A refused take counted nothing. `refusal` is the refusal of the part `index`: the first
292
267
  * capacity refusal, else the wait refusal with the latest `resetAt`.
293
268
  */
294
- type QuotasVerdict = {
269
+ export type QuotasVerdict = {
295
270
  readonly allowed: true;
296
271
  readonly states: readonly QuotaState[];
297
272
  } | {
@@ -301,7 +276,7 @@ type QuotasVerdict = {
301
276
  readonly states: readonly QuotaState[];
302
277
  };
303
278
  /** The options of `takeQuotas`. */
304
- interface TakeQuotasOptions {
279
+ export interface TakeQuotasOptions {
305
280
  /**
306
281
  * This function gets each error of a give-back, with the index of its part. The units of that
307
282
  * part stay counted, thus its quota refuses sooner, not later. It gets the errors after the last
@@ -320,6 +295,5 @@ interface TakeQuotasOptions {
320
295
  *
321
296
  * With quotas that answer at once, it answers at once. Else it gives a promise.
322
297
  */
323
- declare function takeQuotas(parts: readonly QuotaPart<true>[], options?: TakeQuotasOptions): QuotasVerdict;
324
- declare function takeQuotas(parts: readonly QuotaPart[], options?: TakeQuotasOptions): QuotasVerdict | Promise<QuotasVerdict>;
325
- export { takeQuotas as A, RollingWindow as C, quotaProblems as D, memoryQuotaStore as E, limiterStateOf as F, SLIDING_WINDOW_MACHINE as M, TOKEN_BUCKET_MACHINE as N, quotaRule as O, limiterMachine as P, QuotasVerdict as S, keyedQuota as T, QuotaStore as _, QuotaAnswer as a, QuotaWaitRefused as b, QuotaEvent as c, QuotaRecord as d, QuotaRefused as f, QuotaStep as g, QuotaState as h, QuotaAllowed as i, LimiterState as j, quotaStep as k, QuotaPart as l, QuotaSpec as m, KeyedQuota as n, QuotaCapacityRefused as o, QuotaRule as p, MemoryQuotaStore as r, QuotaChange as s, CalendarWindow as t, QuotaReading as u, QuotaTakeStep as v, TakeQuotasOptions as w, QuotaWindow as x, QuotaVerdict as y };
298
+ export declare function takeQuotas(parts: readonly QuotaPart<true>[], options?: TakeQuotasOptions): QuotasVerdict;
299
+ export declare function takeQuotas(parts: readonly QuotaPart[], options?: TakeQuotasOptions): QuotasVerdict | Promise<QuotasVerdict>;