@mark1russell7/service 0.6.7 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +10 -6
  2. package/build/{builder-bXJqMe2p.d.ts → builder-DPsy9XVN.d.ts} +4 -4
  3. package/build/{core-B1zbS4WY.d.ts → core-BkdE4pz1.d.ts} +4 -4
  4. package/build/{dial-CSGKVlZe.d.ts → dial-CyVazFF-.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/host.d.ts +5 -3
  7. package/build/host.js +13 -3
  8. package/build/host.js.map +1 -1
  9. package/build/http-client.d.ts +3 -3
  10. package/build/http.d.ts +8 -6
  11. package/build/http.js +19 -5
  12. package/build/http.js.map +1 -1
  13. package/build/index.d.ts +8 -8
  14. package/build/index.js +3 -3
  15. package/build/{lifecycle-Ks9Yd5CM.d.ts → lifecycle-BuFfbY3s.d.ts} +2 -2
  16. package/build/{limiter-CmC4vCjk.js → limiter-BTgM4aXZ.js} +19 -8
  17. package/build/limiter-BTgM4aXZ.js.map +1 -0
  18. package/build/{limiter-BoZkXIxk.d.ts → limiter-CkJ_QVFj.d.ts} +3 -3
  19. package/build/limiter.d.ts +4 -4
  20. package/build/limiter.js +3 -3
  21. package/build/{logger-DhFgh48y.d.ts → logger-BY1RFLzq.d.ts} +2 -2
  22. package/build/mongodb.d.ts +3 -3
  23. package/build/pg.d.ts +2 -2
  24. package/build/{policy-G4QJ1ZZq.d.ts → policy-CwYR95Sz.d.ts} +51 -15
  25. package/build/{policy-CgS4y94U.js → policy-G-Y3Meku.js} +55 -14
  26. package/build/policy-G-Y3Meku.js.map +1 -0
  27. package/build/{ports-CZLzYK5d.d.ts → ports-D1U2EHmR.d.ts} +2 -2
  28. package/build/{queue-BjiGodqh.d.ts → queue-CDYBywuU.d.ts} +3 -3
  29. package/build/rabbitmq.d.ts +4 -4
  30. package/build/redis.d.ts +9 -6
  31. package/build/redis.js +17 -8
  32. package/build/redis.js.map +1 -1
  33. package/build/{store-Cwuepb-z.d.ts → store-KWQVA3mp.d.ts} +23 -12
  34. package/build/testing.d.ts +4 -4
  35. package/build/websocket.d.ts +3 -3
  36. package/package.json +1 -1
  37. package/build/limiter-CmC4vCjk.js.map +0 -1
  38. package/build/policy-CgS4y94U.js.map +0 -1
package/build/index.js CHANGED
@@ -2,14 +2,14 @@ import { platformClock, realClock } from "./clock.js";
2
2
  import { detectionTime, heartbeat } from "./heartbeat.js";
3
3
  import { a as recoverSpan, i as heartbeatDetection, n as asWindow, r as failSpan, t as asDebounce } from "./timing-DGRi3XCI.js";
4
4
  import { n as operationProblems, t as mayReissue } from "./operation-DL5RxFds.js";
5
- import { a as limiterProblems, i as limitRule, n as freeAt, o as longestRetryAfter, r as idleSpan, s as retryAfterSeconds, t as decide } from "./policy-CgS4y94U.js";
5
+ import { a as limitRule, c as overCapacity, i as idleSpan, l as retryAfterSeconds, n as decide, o as limiterProblems, r as freeAt, s as longestRetryAfter, t as capacityOf, u as unitsOf } from "./policy-G-Y3Meku.js";
6
6
  import { a as lateHolds, l as takeOutside, n as countOf, r as millisecondsOf, s as ownStream, t as boundedMillisecondsOf } from "./knobs-D2ClI68I.js";
7
7
  import { a as isExitCode, c as matchesMessage, i as embeddedProcess, l as nodeProcess, n as PROCESS_TRIGGERS, o as isExitSignal, r as UNCAUGHT_ORIGINS, s as isMessageShape, t as EXIT_SIGNALS, u as processPortOf } from "./process-DG_im2zc.js";
8
8
  import { a as runUnit, c as untilAbort, i as retryOf, l as routePatternProblems, n as boundProblems, o as settleWithin, r as flights, s as sleeper, t as tracker } from "./requests-BIq9Tr4P.js";
9
9
  import { backoffBand, backoffDelay, backoffProblems } from "./backoff.js";
10
10
  import { DRAIN_RULES, O04, O09, O10, O16 } from "./rules.js";
11
11
  import { i as retryAfterDelay, r as retry, t as retrier } from "./retrier-Nt6r4r6R.js";
12
- import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-CmC4vCjk.js";
12
+ import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-BTgM4aXZ.js";
13
13
  import { convertExact, convertible, rationals, valueIn } from "@mark1russell7/quantity";
14
14
  import { replay } from "@mark1russell7/algebra/replay";
15
15
  //#region src/description.ts
@@ -3547,6 +3547,6 @@ const MACHINES = {
3547
3547
  watchdog: WATCHDOG_MACHINE
3548
3548
  };
3549
3549
  //#endregion
3550
- export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
3550
+ export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, unitsOf, verdictOf, watchdog, workerLoop };
3551
3551
 
3552
3552
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { $ as UncaughtOrigin, S as Gate, X as ProcessPort, _ as CooperativeFloor, c as Logger, h as Check, m as Recorder } from "./logger-DhFgh48y.js";
2
+ import { $ as UncaughtOrigin, S as Gate, X as ProcessPort, _ as CooperativeFloor, c as Logger, h as Check, m as Recorder } from "./logger-BY1RFLzq.js";
3
3
  import { Extent } from "@mark1russell7/quantity";
4
4
  //#region src/latch.d.ts
5
5
  /**
@@ -384,4 +384,4 @@ interface Lifecycle {
384
384
  }
385
385
  //#endregion
386
386
  export { DurationHistogram as A, HealthVerdict as C, CheckFn as D, StartOptions as E, Outcome as F, Result as I, Trace as L, Episode as M, HealthMetrics as N, CheckMetrics as O, redact as P, Health as S, ProbeKind as T, RequestFn as _, PhaseContext as a, RequestWork as b, STAGES as c, TransportImpl as d, UncaughtOptions as f, RequestEvent as g, RequestEnd as h, LifecycleState as i, EPISODES_KEPT as j, DURATION_FRACTIONS as k, ShutdownOptions as l, stageRank as m, HealthServer as n, PhaseWork as o, cooperativeAbortAt as p, Lifecycle as r, RunOptions as s, DependencyHandle as t, Stage as u, RequestOptions as v, ProbeAnswer as w, CheckVerdict as x, RequestStream as y };
387
- //# sourceMappingURL=lifecycle-Ks9Yd5CM.d.ts.map
387
+ //# sourceMappingURL=lifecycle-BuFfbY3s.d.ts.map
@@ -1,4 +1,4 @@
1
- import { a as limiterProblems, i as limitRule, n as freeAt, o as longestRetryAfter, t as decide } from "./policy-CgS4y94U.js";
1
+ import { a as limitRule, c as overCapacity, n as decide, o as limiterProblems, r as freeAt, s as longestRetryAfter, u as unitsOf } from "./policy-G-Y3Meku.js";
2
2
  import { convertExact, rationals } from "@mark1russell7/quantity";
3
3
  //#region src/limiter/store.ts
4
4
  const ms = (value) => ({
@@ -28,7 +28,10 @@ const memoryStore = (clock) => {
28
28
  };
29
29
  return {
30
30
  kind: "local",
31
- take({ limiter, key, rule, maxKeys }) {
31
+ take({ limiter, key, rule, maxKeys, units }) {
32
+ const n = unitsOf(units);
33
+ const over = overCapacity(rule, n);
34
+ if (over !== void 0) return over;
32
35
  const now = clock.now();
33
36
  let table = tables.get(limiter);
34
37
  if (table === void 0) {
@@ -51,7 +54,7 @@ const memoryStore = (clock) => {
51
54
  cause: "cap"
52
55
  };
53
56
  }
54
- const step = decide(rule, state, now);
57
+ const step = decide(rule, state, now, n);
55
58
  if (state === void 0) {
56
59
  table.states.set(key, step.state);
57
60
  table.next = Math.min(table.next, freeAt(rule, step.state));
@@ -73,12 +76,16 @@ function keyedLimiter(name, spec, store) {
73
76
  const maxKeys = rationals.toNumber(convertExact(rationals.fromNumber(spec.evict.maxKeys.value), spec.evict.maxKeys.unit, "count"));
74
77
  const onStoreFailure = spec.store.kind === "shared" ? spec.store.onStoreFailure : void 0;
75
78
  const closedAfter = longestRetryAfter(spec.policy);
76
- const take = async (key) => {
79
+ const take = async (key, units) => {
80
+ const n = unitsOf(units);
81
+ const over = overCapacity(rule, n);
82
+ if (over !== void 0) return over;
77
83
  const request = {
78
84
  limiter: name,
79
85
  key,
80
86
  rule,
81
- maxKeys
87
+ maxKeys,
88
+ units: n
82
89
  };
83
90
  if (onStoreFailure === void 0) return store.take(request);
84
91
  try {
@@ -98,13 +105,17 @@ function keyedLimiter(name, spec, store) {
98
105
  };
99
106
  }
100
107
  };
101
- const tryTakeSync = (key) => {
108
+ const tryTakeSync = (key, units) => {
102
109
  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()`);
110
+ const n = unitsOf(units);
111
+ const over = overCapacity(rule, n);
112
+ if (over !== void 0) return over;
103
113
  const decision = store.take({
104
114
  limiter: name,
105
115
  key,
106
116
  rule,
107
- maxKeys
117
+ maxKeys,
118
+ units: n
108
119
  });
109
120
  if (isPromise(decision)) {
110
121
  decision.then(void 0, () => {});
@@ -407,4 +418,4 @@ const limiterStateOf = (rule, state, now) => {
407
418
  //#endregion
408
419
  export { keyedLimiter as a, limiterStateOf as i, TOKEN_BUCKET_MACHINE as n, memoryStore as o, limiterMachine as r, SLIDING_WINDOW_MACHINE as t };
409
420
 
410
- //# sourceMappingURL=limiter-CmC4vCjk.js.map
421
+ //# sourceMappingURL=limiter-BTgM4aXZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limiter-BTgM4aXZ.js","names":["r"],"sources":["../src/limiter/store.ts","../src/limiter/machine.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, rationals as r } from \"@mark1russell7/quantity\";\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 = r.toNumber(convertExact(r.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","import type { Machine, TransitionDef } from \"@mark1russell7/algebra\";\nimport type { KeyState, LimitPolicy, LimitRule } from \"./policy.ts\";\nimport { decide, freeAt } from \"./policy.ts\";\n\nconst t = (id: string, from: string | readonly string[], on: string | readonly string[], to: string, extra: Partial<TransitionDef> = {}): TransitionDef => ({\n id,\n from,\n on,\n to,\n ...extra,\n});\nconst count = (key: string) => ({ key, scope: \"limiter\", unit: \"count\", default: null }) as const;\n\n/**\n * A limiter state is the state of one key of a keyed limiter, as its machine document names it:\n * - `new`: the store holds no state for the key, or a state that is equal to the state of a new key.\n * - `open`: the key holds a count, and its next take is permitted.\n * - `limited`: the next take of the key is refused with the cause `limit`, until a unit is back.\n */\nexport type LimiterState = \"new\" | \"open\" | \"limited\";\n\n/** These are the states of a key that a store can hold. A store fails in each of them. */\nconst HELD = [\"new\", \"open\", \"limited\"] as const;\n\n/** These are the parts of each document of a limiter that do not change with its policy. */\nconst COMMON = {\n format: \"mark1russell7.machine/1\",\n layer: \"self\",\n version: \"0.1.0\",\n sources: [\n { ref: \"packages/service/src/limiter (the runtime implements this document: decide, memoryStore, keyedLimiter)\", rung: \"implemented\" },\n { ref: \"RFC 6585 §4: 429 Too Many Requests, which can carry Retry-After\", rung: \"normative\" },\n { ref: \"RFC 9110 §10.2.3: Retry-After, as delay-seconds or an HTTP-date\", rung: \"normative\" },\n ],\n conditions: {\n \"store.local\": \"the counts are in the memory of one replica: a limit L over N replicas is L / N on each replica, and that sum holds only on average\",\n \"store.shared\": \"the counts are in a store that the replicas share: one atomic step on the clock of the store decides each take\",\n },\n states: {\n new: { initial: true, note: \"the store holds no state for the key, or a state equal to a new key. The store can remove the key\" },\n open: { note: \"the key holds a count, and its next take is permitted\" },\n limited: { note: \"the next take is refused with the cause limit, until a unit is back\" },\n },\n} as const;\n\n/** These are the events of each document of a limiter. */\nconst EVENTS = {\n take: { kind: \"app\", note: \"one call of take(key): one request of the key. A permitted take uses one unit\" },\n \"unit.back\": { kind: \"timer\", note: \"the next take of a limited key is permitted again\" },\n idle: { kind: \"timer\", note: \"the key is equal to a new key. The store can remove it, and no decision changes\" },\n \"store.fail\": { kind: \"local\", note: \"a shared store fails the take. The state of the key does not change\" },\n} as const;\n\n/** These are the knobs of each document of a limiter that do not change with its policy. */\nconst KNOBS = {\n max_keys: count(\"limiters.<name>.evict.maxKeys\"),\n on_store_failure: { key: \"limiters.<name>.store.onStoreFailure\", scope: \"limiter\", unit: null, default: null },\n} as const;\n\n/**\n * These are the transitions of each document of a limiter that do not change with its policy. They\n * are the refusal of a limited key, a new key at the cap of keys, and a failure of a shared store.\n */\nconst COMMON_TRANSITIONS: readonly TransitionDef[] = [\n t(\"refuse\", \"limited\", \"take\", \"limited\", {\n emits: [\"429 limit\"],\n note: \"Retry-After is the time until the next take is permitted, in whole seconds, rounded up. The count of the key does not change\",\n }),\n t(\"cap\", \"new\", \"take\", \"new\", {\n guard: \"the store holds max_keys keys for the limiter, and no held key is equal to a new key\",\n emits: [\"429 cap\"],\n note: \"Retry-After is the time until the earliest held key is free: at most the idle span. A held key keeps its count\",\n }),\n ...HELD.map((state) =>\n t(`store-failed-${state}`, state, \"store.fail\", state, {\n guard: \"the store is shared\",\n emits: [\"allow, or 429 store\"],\n note: \"on_store_failure open lets the take in, with remaining 0. closed refuses it with the cause store, and its Retry-After is the longest of the policy\",\n }),\n ),\n];\n\n/**\n * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds\n * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time\n * for the key: when its bucket is full again.\n * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.\n * - A refused take waits until one token is back: at most one interval. That interval is the\n * longest `Retry-After` of the policy (`retry_after@limiter` of the law).\n * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That\n * span is the idle span, and the longest wait of a new key at the cap of keys\n * (`retry_after_at_cap@limiter`).\n */\nexport const TOKEN_BUCKET_MACHINE: Machine = {\n ...COMMON,\n id: \"service.machine.limiter.token-bucket\",\n title: \"A token bucket of one key of the keyed limiter\",\n events: EVENTS,\n knobs: {\n rate: { key: \"limiters.<name>.policy.rate\", scope: \"limiter\", unit: \"count/s\", default: null },\n burst: count(\"limiters.<name>.policy.burst\"),\n ...KNOBS,\n },\n timers: {\n token: {\n duration: { expr: \"1 / rate\", unit: \"s\" },\n early: { expr: \"1 / rate\", unit: \"s\" },\n arms: [\"enter:limited\"],\n cancels: [\"idle\"],\n fires: \"unit.back\",\n note: \"one token comes back at most one interval after the take that used the last token. The Retry-After of each refusal is the time to this firing\",\n },\n full: {\n duration: { expr: \"burst / rate\", unit: \"s\" },\n early: { expr: \"(burst - 1) / rate\", unit: \"s\" },\n arms: [\"take\"],\n fires: \"idle\",\n note: \"the bucket is full again from one to burst intervals after a permitted take. A refused take does not move it\",\n },\n },\n transitions: [\n t(\"first\", \"new\", \"take\", \"open\", { guard: \"burst > 1\", emits: [\"allow\"] }),\n t(\"first-last\", \"new\", \"take\", \"limited\", { guard: \"burst = 1\", emits: [\"allow\"] }),\n t(\"take\", \"open\", \"take\", \"open\", { guard: \"a token remains after the take\", emits: [\"allow\"] }),\n t(\"take-last\", \"open\", \"take\", \"limited\", { guard: \"the take uses the last token\", emits: [\"allow\"] }),\n ...COMMON_TRANSITIONS,\n t(\"token-back\", \"limited\", \"unit.back\", \"open\", { timer: \"token\", guard: \"burst > 1\" }),\n t(\"full\", \"open\", \"idle\", \"new\", { timer: \"full\" }),\n t(\"full-at-once\", \"limited\", \"idle\", \"new\", {\n timer: \"full\",\n guard: \"burst = 1: the one token is back when the bucket is full\",\n }),\n ],\n};\n\n/**\n * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of\n * each permitted take of the key in the window, and each take counts for one window from its time.\n * - A take is permitted when fewer than `limit` takes are in the window.\n * - A refused take waits until the oldest take leaves the window: at most one window. That window is\n * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).\n * - One window after the last take, no take is in the window, and the key is equal to a new key.\n * That window is the idle span, and the longest wait of a new key at the cap of keys\n * (`retry_after_at_cap@limiter`).\n */\nexport const SLIDING_WINDOW_MACHINE: Machine = {\n ...COMMON,\n id: \"service.machine.limiter.sliding-window\",\n title: \"A sliding window of one key of the keyed limiter\",\n events: EVENTS,\n knobs: {\n limit: count(\"limiters.<name>.policy.limit\"),\n window: { key: \"limiters.<name>.policy.window\", scope: \"limiter\", unit: \"s\", default: null },\n ...KNOBS,\n },\n timers: {\n oldest: {\n duration: { knob: \"window\", unit: \"s\" },\n early: { knob: \"window\", unit: \"s\" },\n arms: [\"enter:limited\"],\n cancels: [\"idle\"],\n fires: \"unit.back\",\n note: \"the oldest take leaves the window at most one window after the take that filled it. The Retry-After of each refusal is the time to this firing\",\n },\n last: {\n duration: { knob: \"window\", unit: \"s\" },\n arms: [\"take\"],\n fires: \"idle\",\n note: \"the last permitted take leaves the window one window after its time. A refused take does not move it\",\n },\n },\n transitions: [\n t(\"first\", \"new\", \"take\", \"open\", { guard: \"limit > 1\", emits: [\"allow\"] }),\n t(\"first-last\", \"new\", \"take\", \"limited\", { guard: \"limit = 1\", emits: [\"allow\"] }),\n t(\"take\", \"open\", \"take\", \"open\", { guard: \"fewer than limit - 1 takes are in the window before the take\", emits: [\"allow\"] }),\n t(\"take-last\", \"open\", \"take\", \"limited\", { guard: \"the take is the limit-th take in the window\", emits: [\"allow\"] }),\n ...COMMON_TRANSITIONS,\n t(\"oldest-leaves\", \"limited\", \"unit.back\", \"open\", { timer: \"oldest\", guard: \"a later take stays in the window\" }),\n t(\"last-leaves\", \"open\", \"idle\", \"new\", { timer: \"last\" }),\n t(\"all-leave\", \"limited\", \"idle\", \"new\", {\n timer: \"last\",\n guard: \"each take of the window has one time: limit = 1, or each take came at once\",\n }),\n ],\n};\n\n/** This function gives the machine document of the policy of a limiter. */\nexport const limiterMachine = (policy: LimitPolicy): Machine =>\n policy.type === \"token-bucket\" ? TOKEN_BUCKET_MACHINE : SLIDING_WINDOW_MACHINE;\n\n/**\n * This function gives the state of a key of a store as its machine document names it, at the time\n * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps\n * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.\n */\nexport const limiterStateOf = (rule: LimitRule, state: KeyState | undefined, now: number): LimiterState => {\n if (state === undefined || freeAt(rule, state) <= now) return \"new\";\n return decide(rule, state, now).decision.allowed ? \"open\" : \"limited\";\n};\n"],"mappings":";;;AAyDA,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,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wuepb-z.js";
1
+ import { a as LimitPolicy, i as KeyState, o as LimitRule } from "./policy-CwYR95Sz.js";
2
+ import "./store-KWQVA3mp.js";
3
3
  import { Machine } from "@mark1russell7/algebra";
4
4
  //#region src/limiter/machine.d.ts
5
5
  /**
@@ -42,4 +42,4 @@ declare const limiterMachine: (policy: LimitPolicy) => Machine;
42
42
  declare const limiterStateOf: (rule: LimitRule, state: KeyState | undefined, now: number) => LimiterState;
43
43
  //#endregion
44
44
  export { limiterStateOf as a, limiterMachine as i, SLIDING_WINDOW_MACHINE as n, TOKEN_BUCKET_MACHINE as r, LimiterState as t };
45
- //# sourceMappingURL=limiter-BoZkXIxk.d.ts.map
45
+ //# sourceMappingURL=limiter-CkJ_QVFj.d.ts.map
@@ -1,4 +1,4 @@
1
- import { S as retryAfterSeconds, _ as freeAt, a as LimitRule, b as limiterProblems, c as LimiterSpec, d as Refused, f as SlidingWindow, g as decide, h as TokenBucket, i as LimitPolicy, l as LimiterStoreSpec, m as TakeStep, n as Decision, o as Limiter, p as StoreFailure, r as KeyState, s as LimiterEviction, t as Allowed, u as RefusalCause, v as idleSpan, x as longestRetryAfter, y as limitRule } from "./policy-G4QJ1ZZq.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-Cwuepb-z.js";
3
- import { a as limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-BoZkXIxk.js";
4
- export { type Allowed, type Decision, type KeyState, type KeyedLimiter, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type MemoryStore, type RefusalCause, type Refused, SLIDING_WINDOW_MACHINE, type SlidingWindow, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type TokenBucket, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, retryAfterSeconds };
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-CwYR95Sz.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-KWQVA3mp.js";
3
+ import { a as limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-CkJ_QVFj.js";
4
+ export { type Allowed, type CapacityRefused, type Decision, type KeyState, type KeyedLimiter, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type MemoryStore, type RefusalCause, type Refused, SLIDING_WINDOW_MACHINE, type SlidingWindow, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type TokenBucket, type WaitCause, type WaitRefused, capacityOf, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, overCapacity, retryAfterSeconds, unitsOf };
package/build/limiter.js CHANGED
@@ -1,3 +1,3 @@
1
- import { a as limiterProblems, i as limitRule, n as freeAt, o as longestRetryAfter, r as idleSpan, s as retryAfterSeconds, t as decide } from "./policy-CgS4y94U.js";
2
- import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-CmC4vCjk.js";
3
- export { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, retryAfterSeconds };
1
+ import { a as limitRule, c as overCapacity, i as idleSpan, l as retryAfterSeconds, n as decide, o as limiterProblems, r as freeAt, s as longestRetryAfter, t as capacityOf, u as unitsOf } from "./policy-G-Y3Meku.js";
2
+ import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-BTgM4aXZ.js";
3
+ export { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, capacityOf, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, overCapacity, retryAfterSeconds, unitsOf };
@@ -1,4 +1,4 @@
1
- import { o as Limiter } from "./policy-G4QJ1ZZq.js";
1
+ import { s as Limiter } from "./policy-CwYR95Sz.js";
2
2
  import { Extent, Quantity } from "@mark1russell7/quantity";
3
3
  //#region src/operation.d.ts
4
4
  /**
@@ -484,4 +484,4 @@ declare const consoleLogger: (options?: ConsoleLoggerOptions) => Logger;
484
484
  declare const logEvents: (logger: Logger, description?: ServiceDescription) => Recorder;
485
485
  //#endregion
486
486
  export { UncaughtOrigin as $, FailsBy as A, RoutePattern as B, MessageTrigger as C, ServiceDescription as D, RepeatSignal as E, asWindow as F, ExitTrigger as G, EXIT_SIGNALS as H, failSpan as I, PROCESS_TRIGGERS as J, HostStream as K, heartbeatDetection as L, Span as M, Timing as N, Step as O, asDebounce as P, UNCAUGHT_ORIGINS as Q, recoverSpan as R, Gate as S, ProgressMarks as T, EmbeddedProcess as U, RouteRequest as V, ExitSignal as W, ProcessPort as X, ProcessHost as Y, ProcessTrigger as Z, CooperativeFloor as _, LogFields as a, nodeProcess as at, ExitCodes as b, Logger as c, Operation as ct, logEvents as d, embeddedProcess as et, LifecycleEvent as f, Controller as g, Check as h, LogEntry as i, matchesMessage as it, Poll as j, Transport as k, atLeast as l, mayReissue as lt, Recorder as m, ConsoleTarget as n, isExitSignal as nt, LogFormat as o, processPortOf as ot, MachineName as p, MessageShape as q, LOG_LEVELS as r, isMessageShape as rt, LogLevel as s, Idempotency as st, ConsoleLoggerOptions as t, isExitCode as tt, consoleLogger as u, Coupling as v, Phase as w, FORMAT as x, Dependency as y, OperationOf as z };
487
- //# sourceMappingURL=logger-DhFgh48y.d.ts.map
487
+ //# sourceMappingURL=logger-BY1RFLzq.d.ts.map
@@ -1,6 +1,6 @@
1
- import { ct as Operation, j as Poll } from "./logger-DhFgh48y.js";
2
- import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, c as ClientSpec, d as Factory, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation } from "./core-B1zbS4WY.js";
3
- import { t as Judge } from "./dial-CSGKVlZe.js";
1
+ import { ct as Operation, j as Poll } from "./logger-BY1RFLzq.js";
2
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, c as ClientSpec, d as Factory, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation } from "./core-BkdE4pz1.js";
3
+ import { t as Judge } from "./dial-CyVazFF-.js";
4
4
  import { Extent, Quantity } from "@mark1russell7/quantity";
5
5
  import { Machine } from "@mark1russell7/algebra";
6
6
  //#region src/mongodb/connection.d.ts
package/build/pg.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { ct as Operation, j as Poll } from "./logger-DhFgh48y.js";
2
- import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, c as ClientSpec, d as Factory, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation } from "./core-B1zbS4WY.js";
1
+ import { ct as Operation, j as Poll } from "./logger-BY1RFLzq.js";
2
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, c as ClientSpec, d as Factory, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, r as Client, s as ClientSocket, t as Attempt, u as DialFn, w as Manifestation } from "./core-BkdE4pz1.js";
3
3
  import { Extent, Quantity } from "@mark1russell7/quantity";
4
4
  import { Machine } from "@mark1russell7/algebra";
5
5
  //#region src/pg/connection.d.ts
@@ -73,13 +73,21 @@ interface Limiter extends LimiterSpec {
73
73
  readonly name: string;
74
74
  }
75
75
  /**
76
- * A refusal cause tells why a take is refused:
76
+ * A wait cause tells why a take is refused for a time:
77
77
  * - `limit`: the key used its limit.
78
78
  * - `cap`: the store holds its cap of keys, and the key is new.
79
79
  * - `store`: the shared store failed, and its spec declares `onStoreFailure: "closed"`.
80
80
  */
81
- type RefusalCause = "limit" | "cap" | "store";
82
- /** A permitted take used one unit of its key. `remaining` is the count of takes that the key can make at this time. */
81
+ type WaitCause = "limit" | "cap" | "store";
82
+ /**
83
+ * A refusal cause tells why a take is refused: a wait cause, or `capacity`. The cause `capacity` is
84
+ * a take whose units are over the capacity of the policy. No wait lets it in.
85
+ */
86
+ type RefusalCause = WaitCause | "capacity";
87
+ /**
88
+ * A permitted take used its units of its key. `remaining` is the count of units that the key can
89
+ * take at this time.
90
+ */
83
91
  interface Allowed {
84
92
  readonly allowed: true;
85
93
  readonly remaining: number;
@@ -87,16 +95,32 @@ interface Allowed {
87
95
  readonly failure?: string | undefined;
88
96
  }
89
97
  /**
90
- * A refused take used nothing. `retryAfter` is the time until the limiter lets the same take in, when
98
+ * A wait refusal used nothing. `retryAfter` is the time until the limiter lets the same take in, when
91
99
  * no other take comes first. It is always above zero.
92
100
  */
93
- interface Refused {
101
+ interface WaitRefused {
94
102
  readonly allowed: false;
103
+ readonly cause: WaitCause;
95
104
  readonly retryAfter: Quantity;
96
- readonly cause: RefusalCause;
97
105
  /** This text is the failure of a shared store, for the cause `store`. */
98
106
  readonly failure?: string | undefined;
99
107
  }
108
+ /**
109
+ * A capacity refusal used nothing, and the same take is refused at each time. Its `units` are over
110
+ * the `capacity` of the policy: the `burst` of a bucket, or the `limit` of a window. A caller can
111
+ * split the take into parts of at most `capacity` units.
112
+ */
113
+ interface CapacityRefused {
114
+ readonly allowed: false;
115
+ readonly cause: "capacity";
116
+ readonly units: number;
117
+ readonly capacity: number;
118
+ }
119
+ /**
120
+ * A refused take used nothing. The cause tells the type: a `WaitRefused` has a `retryAfter`, and a
121
+ * `CapacityRefused` has none. Thus a caller examines the cause before it reads `retryAfter`.
122
+ */
123
+ type Refused = WaitRefused | CapacityRefused;
100
124
  /** A decision is the answer of a limiter to one take. */
101
125
  type Decision = Allowed | Refused;
102
126
  /**
@@ -161,16 +185,28 @@ declare const longestRetryAfter: (policy: LimitPolicy) => Quantity;
161
185
  declare const retryAfterSeconds: (retryAfter: Quantity) => number;
162
186
  /** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */
163
187
  declare const freeAt: (rule: LimitRule, state: KeyState) => number;
188
+ /** 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. */
189
+ declare const capacityOf: (rule: LimitRule) => number;
190
+ /**
191
+ * This function gives the units of a take: 1 when they are absent. It throws for units that are not
192
+ * a whole number of 1 or more, because such a take has no meaning.
193
+ */
194
+ declare const unitsOf: (units: number | undefined) => number;
195
+ /** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */
196
+ declare const overCapacity: (rule: LimitRule, units: number) => CapacityRefused | undefined;
164
197
  /**
165
- * This function decides one take of a key at the time `now`, in milliseconds, from the state of the
166
- * key (`undefined` for a new key). It is the one decision of each store in this process. A store in
167
- * another process does the same arithmetic in its own atomic step.
198
+ * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in
199
+ * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each
200
+ * store in this process. A store in another process does the same arithmetic in its own atomic step.
201
+ * - A take over the capacity of the rule (`capacityOf`) is refused with the cause `capacity`, and
202
+ * the state does not change.
168
203
  * - A token bucket (GCRA): the store lets the take in when, with the take, the bucket is full
169
- * again in at most `burst` intervals. A refusal waits until one token is back.
170
- * - A sliding window: the store lets the take in when fewer than `limit` takes are in the window.
171
- * A refusal waits until the oldest take leaves the window.
204
+ * again in at most `burst` intervals. A refusal waits until `units` tokens are back.
205
+ * - A sliding window: the store lets the take in when at most `limit - units` takes are in the
206
+ * window. A refusal waits until enough of the oldest takes leave the window.
207
+ * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.
172
208
  */
173
- declare const decide: (rule: LimitRule, state: KeyState | undefined, now: number) => TakeStep;
209
+ declare const decide: (rule: LimitRule, state: KeyState | undefined, now: number, units?: number) => TakeStep;
174
210
  //#endregion
175
- export { retryAfterSeconds as S, freeAt as _, LimitRule as a, limiterProblems as b, LimiterSpec as c, Refused as d, SlidingWindow as f, decide as g, TokenBucket as h, LimitPolicy as i, LimiterStoreSpec as l, TakeStep as m, Decision as n, Limiter as o, StoreFailure as p, KeyState as r, LimiterEviction as s, Allowed as t, RefusalCause as u, idleSpan as v, longestRetryAfter as x, limitRule as y };
176
- //# sourceMappingURL=policy-G4QJ1ZZq.d.ts.map
211
+ export { limitRule as C, retryAfterSeconds as D, overCapacity as E, unitsOf as O, idleSpan as S, longestRetryAfter as T, WaitCause as _, LimitPolicy as a, decide as b, LimiterEviction as c, RefusalCause as d, Refused as f, TokenBucket as g, TakeStep as h, KeyState as i, LimiterSpec as l, StoreFailure as m, CapacityRefused as n, LimitRule as o, SlidingWindow as p, Decision as r, Limiter as s, Allowed as t, LimiterStoreSpec as u, WaitRefused as v, limiterProblems as w, freeAt as x, capacityOf as y };
212
+ //# sourceMappingURL=policy-CwYR95Sz.d.ts.map
@@ -122,20 +122,53 @@ const freeAt = (rule, state) => {
122
122
  const last = state.stamps[state.stamps.length - 1];
123
123
  return last === void 0 ? Number.NEGATIVE_INFINITY : last + (rule.type === "sliding-window" ? rule.window : 0);
124
124
  };
125
+ /** 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. */
126
+ const capacityOf = (rule) => rule.type === "token-bucket" ? rule.burst : rule.limit;
125
127
  /**
126
- * This function decides one take of a key at the time `now`, in milliseconds, from the state of the
127
- * key (`undefined` for a new key). It is the one decision of each store in this process. A store in
128
- * another process does the same arithmetic in its own atomic step.
128
+ * This function gives the units of a take: 1 when they are absent. It throws for units that are not
129
+ * a whole number of 1 or more, because such a take has no meaning.
130
+ */
131
+ const unitsOf = (units) => {
132
+ if (units === void 0) return 1;
133
+ if (typeof units !== "number" || !Number.isSafeInteger(units) || units < 1) throw new RangeError(`the units of a take are a whole number of 1 or more, not ${String(units)}`);
134
+ return units;
135
+ };
136
+ /** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */
137
+ const overCapacity = (rule, units) => {
138
+ const capacity = capacityOf(rule);
139
+ return units > capacity ? {
140
+ allowed: false,
141
+ cause: "capacity",
142
+ units,
143
+ capacity
144
+ } : void 0;
145
+ };
146
+ /**
147
+ * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in
148
+ * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each
149
+ * store in this process. A store in another process does the same arithmetic in its own atomic step.
150
+ * - A take over the capacity of the rule (`capacityOf`) is refused with the cause `capacity`, and
151
+ * the state does not change.
129
152
  * - A token bucket (GCRA): the store lets the take in when, with the take, the bucket is full
130
- * again in at most `burst` intervals. A refusal waits until one token is back.
131
- * - A sliding window: the store lets the take in when fewer than `limit` takes are in the window.
132
- * A refusal waits until the oldest take leaves the window.
153
+ * again in at most `burst` intervals. A refusal waits until `units` tokens are back.
154
+ * - A sliding window: the store lets the take in when at most `limit - units` takes are in the
155
+ * window. A refusal waits until enough of the oldest takes leave the window.
156
+ * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.
133
157
  */
134
- const decide = (rule, state, now) => {
158
+ const decide = (rule, state, now, units) => {
159
+ const n = unitsOf(units);
160
+ const over = overCapacity(rule, n);
135
161
  if (rule.type === "token-bucket") {
136
162
  const span = rule.interval * rule.burst;
137
163
  const full = state?.type === "token-bucket" ? Math.max(state.full, now) : now;
138
- const next = full + rule.interval;
164
+ if (over !== void 0) return {
165
+ decision: over,
166
+ state: {
167
+ type: "token-bucket",
168
+ full
169
+ }
170
+ };
171
+ const next = full + rule.interval * n;
139
172
  if (next - now > span + TOLERANCE) return {
140
173
  decision: {
141
174
  allowed: false,
@@ -159,10 +192,18 @@ const decide = (rule, state, now) => {
159
192
  };
160
193
  }
161
194
  const live = (state?.type === "sliding-window" ? state.stamps : []).filter((stamp) => stamp + rule.window > now + TOLERANCE);
162
- if (live.length >= rule.limit) return {
195
+ if (over !== void 0) return {
196
+ decision: over,
197
+ state: {
198
+ type: "sliding-window",
199
+ stamps: live
200
+ }
201
+ };
202
+ const excess = live.length + n - rule.limit;
203
+ if (excess > 0) return {
163
204
  decision: {
164
205
  allowed: false,
165
- retryAfter: ms(live[0] + rule.window - now),
206
+ retryAfter: ms(live[excess - 1] + rule.window - now),
166
207
  cause: "limit"
167
208
  },
168
209
  state: {
@@ -173,15 +214,15 @@ const decide = (rule, state, now) => {
173
214
  return {
174
215
  decision: {
175
216
  allowed: true,
176
- remaining: rule.limit - live.length - 1
217
+ remaining: rule.limit - live.length - n
177
218
  },
178
219
  state: {
179
220
  type: "sliding-window",
180
- stamps: [...live, now]
221
+ stamps: [...live, ...Array.from({ length: n }, () => now)]
181
222
  }
182
223
  };
183
224
  };
184
225
  //#endregion
185
- export { limiterProblems as a, limitRule as i, freeAt as n, longestRetryAfter as o, idleSpan as r, retryAfterSeconds as s, decide as t };
226
+ export { limitRule as a, overCapacity as c, idleSpan as i, retryAfterSeconds as l, decide as n, limiterProblems as o, freeAt as r, longestRetryAfter as s, capacityOf as t, unitsOf as u };
186
227
 
187
- //# sourceMappingURL=policy-CgS4y94U.js.map
228
+ //# sourceMappingURL=policy-G-Y3Meku.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-G-Y3Meku.js","names":["r"],"sources":["../src/limiter/policy.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, convertible, rationals as r } from \"@mark1russell7/quantity\";\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\nconst isCount = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count\");\nconst 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. */\nconst safely = (test: (amount: Quantity | undefined) => boolean, amount: Quantity | undefined): boolean => {\n try {\n return test(amount);\n } catch {\n return false;\n }\n};\nconst finiteAbove = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value > 0;\nconst wholeCount = (amount: Quantity): boolean => finiteAbove(amount) && Number.isInteger(r.toNumber(convertExact(r.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. */\nconst milliseconds = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"ms\"));\n/** This function gives a count as one number. */\nconst countOf = (amount: Quantity): number => r.toNumber(convertExact(r.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(r.fromNumber(policy.rate.value), policy.rate.unit, \"count/ms\");\n return { type: \"token-bucket\", interval: r.toNumber(r.div(r.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 = r.toNumber(convertExact(r.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":";;;;;;AA8KA,MAAM,YAAY;AAElB,MAAM,WAAW,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,OAAO;AACnH,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,GAAG;AAC9G,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,SAAS;;AAEpH,MAAM,UAAU,MAAiD,WAA0C;CACzG,IAAI;EACF,OAAO,KAAK,MAAM;CACpB,QAAQ;EACN,OAAO;CACT;AACF;AACA,MAAM,eAAe,WAA8B,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,OAAO,KAAK,KAAK,OAAO,QAAQ;AACvI,MAAM,cAAc,WAA8B,YAAY,MAAM,KAAK,OAAO,UAAUA,UAAE,SAAS,aAAaA,UAA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M,OAAO;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,5 +1,5 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { c as Logger } from "./logger-DhFgh48y.js";
2
+ import { c as Logger } from "./logger-BY1RFLzq.js";
3
3
  //#region src/host/ports.d.ts
4
4
  /** These options go with one command: the folder that it runs in, and the most time that it can take. */
5
5
  interface CommandOptions {
@@ -122,4 +122,4 @@ interface HostPorts {
122
122
  declare const joinPath: (platform: string, ...parts: readonly string[]) => string;
123
123
  //#endregion
124
124
  export { FilePort as a, ProcessMark as c, StopSignal as d, joinPath as f, CommandResult as i, ProcessesPort as l, CommandOptions as n, HostPorts as o, CommandPort as r, NetPort as s, ChildHandle as t, SpawnRequest as u };
125
- //# sourceMappingURL=ports-CZLzYK5d.d.ts.map
125
+ //# sourceMappingURL=ports-D1U2EHmR.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { n as Clock } from "./clock-mVqhXD0b.js";
2
- import { D as ServiceDescription } from "./logger-DhFgh48y.js";
3
- import { d as TransportImpl, r as Lifecycle } from "./lifecycle-Ks9Yd5CM.js";
2
+ import { D as ServiceDescription } from "./logger-BY1RFLzq.js";
3
+ import { d as TransportImpl, r as Lifecycle } from "./lifecycle-BuFfbY3s.js";
4
4
  import { Extent, Quantity } from "@mark1russell7/quantity";
5
5
  //#region src/units.d.ts
6
6
  /**
@@ -148,4 +148,4 @@ declare const redeliverOnce: <J>(then: JobAction | RedeliveryPolicy<J>, poison?:
148
148
  declare const queueDrain: <J>(knobs: QueueKnobs, options: QueueDrainOptions<J>) => QueueDrain;
149
149
  //#endregion
150
150
  export { JobSource as a, QueueKnobs as c, queueDrain as d, redeliverOnce as f, JobSettle as i, RedeliveryPolicy as l, JobContext as n, QueueDrain as o, UnitRequest as p, JobFailure as r, QueueDrainOptions as s, JobAction as t, RequeueCause as u };
151
- //# sourceMappingURL=queue-BjiGodqh.d.ts.map
151
+ //# sourceMappingURL=queue-CDYBywuU.d.ts.map
@@ -1,7 +1,7 @@
1
- import { j as Poll } from "./logger-DhFgh48y.js";
2
- import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, y as retryBackoff } from "./core-B1zbS4WY.js";
3
- import { t as Judge } from "./dial-CSGKVlZe.js";
4
- import { i as JobSettle } from "./queue-BjiGodqh.js";
1
+ import { j as Poll } from "./logger-BY1RFLzq.js";
2
+ import { C as MANIFESTATIONS, D as firstDetector, E as Situation, O as unwatched, S as Detector, T as Meeting, _ as Sent, a as ClientKnobs, b as retryProblems, c as ClientSpec, d as Factory, f as ReadyWait, g as SendOptions, h as STARTING_POLL, i as ClientJoin, l as ClientStep, n as CheckOptions, o as ClientOptions, p as RetryKnobs, r as Client, s as ClientSocket, t as Attempt, u as DialFn, v as readyWait, w as Manifestation, y as retryBackoff } from "./core-BkdE4pz1.js";
3
+ import { t as Judge } from "./dial-CyVazFF-.js";
4
+ import { i as JobSettle } from "./queue-CDYBywuU.js";
5
5
  import { Extent, Quantity } from "@mark1russell7/quantity";
6
6
  import { Machine } from "@mark1russell7/algebra";
7
7
  //#region src/rabbitmq/connection.d.ts