@mark1russell7/service 0.8.18 → 0.8.19
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.
- package/README.md +19 -0
- package/build/index.d.ts +1 -1
- package/build/index.js +1 -1
- package/build/{limiter-Cm8nC-Gd.d.ts → limiter-BNKnwzeY.d.ts} +18 -2
- package/build/{limiter-Bgy6Gmvl.js → limiter-DrM0PQV9.js} +30 -8
- package/build/limiter-DrM0PQV9.js.map +1 -0
- package/build/limiter.d.ts +1 -1
- package/build/limiter.js +1 -1
- package/package.json +1 -1
- package/build/limiter-Bgy6Gmvl.js.map +0 -1
package/README.md
CHANGED
|
@@ -478,6 +478,25 @@ const decision = await limiter.take(tenantOf(req));
|
|
|
478
478
|
if (!decision.allowed) return limitedResponse(decision); // 429, with Retry-After from 1 to 60
|
|
479
479
|
```
|
|
480
480
|
|
|
481
|
+
### The quota of a key
|
|
482
|
+
|
|
483
|
+
A quota is the limit of a provider of an API: at most `limit` units in each window. The window is a calendar window or a rolling window. The gate refuses a take over it before the provider does.
|
|
484
|
+
|
|
485
|
+
| Export | Function |
|
|
486
|
+
| --- | --- |
|
|
487
|
+
| `keyedQuota(name, spec, store, clock)` | The runtime of a quota on a store and a wall clock: `take`, `note`, `giveBack` and `state` for each key |
|
|
488
|
+
| `quotaStep(rule, stored, instant, event)` | The pure step of one key, for a store of your own |
|
|
489
|
+
| `quotaRule(name, spec)`, `quotaProblems(name, spec)` | The spec in numbers, and the problems of a spec that `keyedQuota` refuses |
|
|
490
|
+
| `memoryQuotaStore()` | The store of one process |
|
|
491
|
+
| `takeQuotas(parts, options?)` | A take of several quotas, all or none |
|
|
492
|
+
|
|
493
|
+
- **No defaults.** A spec has a limit, a reserve and a window. A rolling window has a span and a count of buckets. A calendar window has a unit (`day` or `month`), a time zone and a time of day that starts it.
|
|
494
|
+
- **A reading of the provider.** `note(key, reading)` adds what an answer of the provider tells. The count can only become larger. A reset with no units left blocks the key until the reset.
|
|
495
|
+
- **The longest block.** `maxBlock` in the spec is a time above zero, or `window`. A reading at the instant `t` blocks the key until `t` plus that time at the latest. With `window`, the block ends at the latest when the bucket of `t` stops counting.
|
|
496
|
+
- **Why a bound.** A provider can give a reset in a wrong form, for example milliseconds in a header of seconds. Without a bound, such a reset stops the key for hours or for centuries.
|
|
497
|
+
- **The step applies the bound.** `quotaStep` caps the block of the stored record before each event, and the block of a note after it. The store keeps the capped record. When `maxBlock` is absent, no block has a bound.
|
|
498
|
+
- **A gate of your own.** A part of `takeQuotas` needs only `sync`, `take` and `giveBack`. Thus a gate of your own with these members can be a part, next to a `KeyedQuota`.
|
|
499
|
+
|
|
481
500
|
## The HTTP edge
|
|
482
501
|
|
|
483
502
|
`@mark1russell7/service/http` is the edge of a service in Node. Of the modules of Node, it imports only `node:http` and `node:net`. The root of the package does not import it. It is not a framework: it has no routing language, no body parser and no middleware.
|
package/build/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { C as symbolsOf, S as inequalities, _ as TimerMarks, a as O16, b as comp
|
|
|
5
5
|
import { a as realClock, i as platformClock, n as Clock, r as PlatformClockOptions, t as Cancel } from "./clock-DpVgpY4h.js";
|
|
6
6
|
import { Heartbeat, HeartbeatOptions, detectionTime, heartbeat } from "./heartbeat.js";
|
|
7
7
|
import { a as backoffDelay, i as backoffBand, n as DelayBand, o as backoffProblems, r as Jitter, t as Backoff } from "./backoff-QTRGfkEK.js";
|
|
8
|
-
import { A as takeQuotas, C as RollingWindow, D as quotaProblems, E as memoryQuotaStore, F as limiterStateOf, M as SLIDING_WINDOW_MACHINE, N as TOKEN_BUCKET_MACHINE, O as quotaRule, P as limiterMachine, S as QuotasVerdict, T as keyedQuota, _ as QuotaStore, a as QuotaAnswer, b as QuotaWaitRefused, c as QuotaEvent, d as QuotaRecord, f as QuotaRefused, g as QuotaStep, h as QuotaState, i as QuotaAllowed, j as LimiterState, k as quotaStep, l as QuotaPart, m as QuotaSpec, n as KeyedQuota, o as QuotaCapacityRefused, p as QuotaRule, r as MemoryQuotaStore, s as QuotaChange, t as CalendarWindow, u as QuotaReading, v as QuotaTakeStep, w as TakeQuotasOptions, x as QuotaWindow, y as QuotaVerdict } from "./limiter-
|
|
8
|
+
import { A as takeQuotas, C as RollingWindow, D as quotaProblems, E as memoryQuotaStore, F as limiterStateOf, M as SLIDING_WINDOW_MACHINE, N as TOKEN_BUCKET_MACHINE, O as quotaRule, P as limiterMachine, S as QuotasVerdict, T as keyedQuota, _ as QuotaStore, a as QuotaAnswer, b as QuotaWaitRefused, c as QuotaEvent, d as QuotaRecord, f as QuotaRefused, g as QuotaStep, h as QuotaState, i as QuotaAllowed, j as LimiterState, k as quotaStep, l as QuotaPart, m as QuotaSpec, n as KeyedQuota, o as QuotaCapacityRefused, p as QuotaRule, r as MemoryQuotaStore, s as QuotaChange, t as CalendarWindow, u as QuotaReading, v as QuotaTakeStep, w as TakeQuotasOptions, x as QuotaWindow, y as QuotaVerdict } from "./limiter-BNKnwzeY.js";
|
|
9
9
|
import { A as DurationHistogram, C as HealthVerdict, D as CheckFn, E as StartOptions, F as Outcome, I as Result, M as Episode, N as HealthMetrics, O as CheckMetrics, P as redact, S as Health, T as ProbeKind, _ as RequestFn, a as PhaseContext, b as RequestWork, c as STAGES, d as TransportImpl, f as UncaughtOptions, g as RequestEvent, h as RequestEnd, i as LifecycleState, j as EPISODES_KEPT, k as DURATION_FRACTIONS, l as ShutdownOptions, m as stageRank, n as HealthServer, o as PhaseWork, p as cooperativeAbortAt, r as Lifecycle, s as RunOptions, t as DependencyHandle, u as Stage, v as RequestOptions, w as ProbeAnswer, x as CheckVerdict, y as RequestStream } from "./lifecycle-D0J-zwZF.js";
|
|
10
10
|
import { a as TakeRequest, i as MemoryStore, n as LimiterStore, o as keyedLimiter, r as LocalLimiter, s as memoryStore, t as KeyedLimiter } from "./store-DFwFKrsB.js";
|
|
11
11
|
import { n as IncomingHeaders, t as CallContext } from "./call-context-DDhcVvn5.js";
|
package/build/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import { backoffBand, backoffDelay, backoffProblems } from "./backoff.js";
|
|
|
9
9
|
import { DRAIN_RULES, O04, O09, O10, O16 } from "./rules.js";
|
|
10
10
|
import { detectionTime, heartbeat } from "./heartbeat.js";
|
|
11
11
|
import { i as retryAfterDelay, r as retry, t as retrier } from "./retrier-Dnjhvxol.js";
|
|
12
|
-
import { a as quotaStep, c as TOKEN_BUCKET_MACHINE, d as keyedLimiter, f as memoryStore, i as quotaRule, l as limiterMachine, n as memoryQuotaStore, o as takeQuotas, r as quotaProblems, s as SLIDING_WINDOW_MACHINE, t as keyedQuota, u as limiterStateOf } from "./limiter-
|
|
12
|
+
import { a as quotaStep, c as TOKEN_BUCKET_MACHINE, d as keyedLimiter, f as memoryStore, i as quotaRule, l as limiterMachine, n as memoryQuotaStore, o as takeQuotas, r as quotaProblems, s as SLIDING_WINDOW_MACHINE, t as keyedQuota, u as limiterStateOf } from "./limiter-DrM0PQV9.js";
|
|
13
13
|
import { convertExact, convertible, rationals, valueIn } from "@mark1russell7/quantity";
|
|
14
14
|
import { replay } from "@mark1russell7/algebra/replay";
|
|
15
15
|
// src/description.ts
|
|
@@ -76,6 +76,14 @@ interface QuotaSpec {
|
|
|
76
76
|
/** The gate keeps this count of units unused: from 0 to less than the limit. */
|
|
77
77
|
readonly reserve: Quantity;
|
|
78
78
|
readonly window: QuotaWindow;
|
|
79
|
+
/**
|
|
80
|
+
* This value is the longest block that a reading of the provider can set: a time above zero, or
|
|
81
|
+
* `window`. A reading at the instant `t` blocks the key until `t` plus the time at the latest. With
|
|
82
|
+
* `window`, the block ends at the latest when the bucket of `t` stops counting. Thus a reset of the
|
|
83
|
+
* provider in a wrong form does not stop a key for much longer than one window. The step also
|
|
84
|
+
* applies this bound to a block that the stored record keeps. When it is absent, no block has a bound.
|
|
85
|
+
*/
|
|
86
|
+
readonly maxBlock?: Quantity | "window" | undefined;
|
|
79
87
|
}
|
|
80
88
|
/** A quota rule is a spec in numbers: each count as a number, and each time in milliseconds. */
|
|
81
89
|
interface QuotaRule {
|
|
@@ -91,6 +99,8 @@ interface QuotaRule {
|
|
|
91
99
|
readonly zone: string;
|
|
92
100
|
readonly start: number;
|
|
93
101
|
};
|
|
102
|
+
/** This value is the longest block in milliseconds, or `window`. When it is absent, no block has a bound. */
|
|
103
|
+
readonly maxBlock?: number | "window" | undefined;
|
|
94
104
|
}
|
|
95
105
|
/**
|
|
96
106
|
* A quota record is what a store keeps for one key. A store can keep it as JSON. Each instant is in
|
|
@@ -209,6 +219,8 @@ declare const quotaRule: (name: string, spec: QuotaSpec) => QuotaRule;
|
|
|
209
219
|
* is the end of that refusal, or a later instant when the window has room for the units.
|
|
210
220
|
* - A take over the room of the window is refused with the cause `limit`, until enough of the
|
|
211
221
|
* oldest units stop counting.
|
|
222
|
+
* - With `maxBlock` in the rule, a block ends at the latest at the bound of the instant. The step
|
|
223
|
+
* applies the bound to the stored block before the event, and to the block of a note after it.
|
|
212
224
|
*
|
|
213
225
|
* It throws a `RangeError` for an instant that is not a date, and for units that are not a finite
|
|
214
226
|
* count of 0 or more.
|
|
@@ -278,9 +290,13 @@ interface KeyedQuota<Sync extends boolean = boolean> {
|
|
|
278
290
|
* - With a store that answers with a promise, each method gives a promise. A `RangeError` rejects.
|
|
279
291
|
*/
|
|
280
292
|
declare function keyedQuota<Sync extends boolean>(name: string, spec: QuotaSpec, store: QuotaStore<Sync>, clock: Pick<WallClock, "time" | "now">): KeyedQuota<Sync>;
|
|
281
|
-
/**
|
|
293
|
+
/**
|
|
294
|
+
* A quota part is one take of a multi-quota take: a quota, a key, and the units of the take. The
|
|
295
|
+
* quota needs only `sync`, `take` and `giveBack`. Thus a gate of your own with these members can be
|
|
296
|
+
* a part, and a `KeyedQuota` is one.
|
|
297
|
+
*/
|
|
282
298
|
interface QuotaPart<Sync extends boolean = boolean> {
|
|
283
|
-
readonly quota: KeyedQuota<Sync>;
|
|
299
|
+
readonly quota: Pick<KeyedQuota<Sync>, "sync" | "take" | "giveBack">;
|
|
284
300
|
readonly key: string;
|
|
285
301
|
readonly units: number;
|
|
286
302
|
}
|
|
@@ -468,13 +468,18 @@ const quotaProblems = (name, spec) => {
|
|
|
468
468
|
else if (!safely(isTime, window.start)) problems.push(`${owner}'s start is not a time`);
|
|
469
469
|
else if (!atLeastZero(window.start) || !Number.isInteger(milliseconds(window.start)) || milliseconds(window.start) >= DAY_MS) problems.push(`${owner}'s start is not a whole count of milliseconds from 0 to less than 24 h`);
|
|
470
470
|
} else problems.push(`${owner}'s window is not rolling or calendar`);
|
|
471
|
+
const { maxBlock } = spec;
|
|
472
|
+
if (maxBlock !== void 0 && maxBlock !== "window") {
|
|
473
|
+
if (typeof maxBlock !== "object" || maxBlock === null || !safely(isTime, maxBlock)) problems.push(`${owner}'s maxBlock is not a time or "window"`);
|
|
474
|
+
else if (!finiteAbove(maxBlock)) problems.push(`${owner}'s maxBlock is not a finite time above zero`);
|
|
475
|
+
}
|
|
471
476
|
return problems;
|
|
472
477
|
};
|
|
473
478
|
/** This function gives the rule of a quota spec. It throws an error with the problems of a spec that has a problem. */
|
|
474
479
|
const quotaRule = (name, spec) => {
|
|
475
480
|
const problems = quotaProblems(name, spec);
|
|
476
481
|
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
477
|
-
const { window } = spec;
|
|
482
|
+
const { window, maxBlock } = spec;
|
|
478
483
|
return {
|
|
479
484
|
limit: countOf(spec.limit),
|
|
480
485
|
reserve: countOf(spec.reserve),
|
|
@@ -487,7 +492,8 @@ const quotaRule = (name, spec) => {
|
|
|
487
492
|
unit: window.unit,
|
|
488
493
|
zone: window.zone,
|
|
489
494
|
start: milliseconds(window.start)
|
|
490
|
-
}
|
|
495
|
+
},
|
|
496
|
+
...maxBlock === void 0 ? {} : { maxBlock: maxBlock === "window" ? "window" : milliseconds(maxBlock) }
|
|
491
497
|
};
|
|
492
498
|
};
|
|
493
499
|
/** This function gives the calendar window of the instant `t`: its start, and the start of the next window. */
|
|
@@ -557,6 +563,21 @@ const prune = (buckets, record, t) => {
|
|
|
557
563
|
...readAt !== void 0 && counts(buckets.bucket(readAt)[0]) ? { readAt } : {}
|
|
558
564
|
};
|
|
559
565
|
};
|
|
566
|
+
/**
|
|
567
|
+
* This function applies the bound of the rule to the block of a record at the instant `t`. The
|
|
568
|
+
* block ends at `t` plus the longest block at the latest. With `window`, it ends at the latest when
|
|
569
|
+
* the bucket of `t` stops counting. The bound is after `t`, thus a capped block stays a block.
|
|
570
|
+
*/
|
|
571
|
+
const capBlock = (rule, buckets, record, t) => {
|
|
572
|
+
const { maxBlock } = rule;
|
|
573
|
+
const { blockedUntil } = record;
|
|
574
|
+
if (maxBlock === void 0 || blockedUntil === void 0) return record;
|
|
575
|
+
const bound = maxBlock === "window" ? buckets.freeAt(buckets.bucket(t)[0]) : t + maxBlock;
|
|
576
|
+
return blockedUntil > bound ? {
|
|
577
|
+
...record,
|
|
578
|
+
blockedUntil: bound
|
|
579
|
+
} : record;
|
|
580
|
+
};
|
|
560
581
|
const usedOf = (record) => record.spent.reduce((sum, [, units]) => sum + units, 0);
|
|
561
582
|
/** This function adds units to the bucket of the instant `t`. */
|
|
562
583
|
const add = (buckets, record, t, units) => {
|
|
@@ -611,7 +632,7 @@ function quotaStep(rule, stored, instant, event) {
|
|
|
611
632
|
if (!isInstant(instant)) throw new RangeError(`the instant of a quota step is not a date: ${String(instant)}`);
|
|
612
633
|
checkEvent(event);
|
|
613
634
|
const buckets = bucketsOf(rule.window);
|
|
614
|
-
const record = prune(buckets, recordOf(stored), instant);
|
|
635
|
+
const record = capBlock(rule, buckets, prune(buckets, recordOf(stored), instant), instant);
|
|
615
636
|
const done = (next) => ({
|
|
616
637
|
record: next,
|
|
617
638
|
state: stateOf(rule, buckets, next, instant)
|
|
@@ -629,10 +650,10 @@ function quotaStep(rule, stored, instant, event) {
|
|
|
629
650
|
readAt: Math.max(next.readAt ?? instant, instant)
|
|
630
651
|
};
|
|
631
652
|
}
|
|
632
|
-
if ((remaining === void 0 || remaining <= 0) && isInstant(resetAt) && resetAt > instant) next = {
|
|
653
|
+
if ((remaining === void 0 || remaining <= 0) && isInstant(resetAt) && resetAt > instant) next = capBlock(rule, buckets, {
|
|
633
654
|
...next,
|
|
634
655
|
blockedUntil: Math.max(next.blockedUntil ?? resetAt, resetAt)
|
|
635
|
-
};
|
|
656
|
+
}, instant);
|
|
636
657
|
return done(next);
|
|
637
658
|
}
|
|
638
659
|
case "give-back": {
|
|
@@ -762,7 +783,7 @@ function keyedQuota(name, spec, store, clock) {
|
|
|
762
783
|
});
|
|
763
784
|
const verdictOf = (step) => step.verdict;
|
|
764
785
|
const stateOfStep = (step) => step.state;
|
|
765
|
-
const { window } = spec;
|
|
786
|
+
const { window, maxBlock } = spec;
|
|
766
787
|
return {
|
|
767
788
|
name,
|
|
768
789
|
spec: {
|
|
@@ -777,7 +798,8 @@ function keyedQuota(name, spec, store, clock) {
|
|
|
777
798
|
unit: window.unit,
|
|
778
799
|
zone: window.zone,
|
|
779
800
|
start: { ...window.start }
|
|
780
|
-
}
|
|
801
|
+
},
|
|
802
|
+
...maxBlock === void 0 ? {} : { maxBlock: maxBlock === "window" ? "window" : { ...maxBlock } }
|
|
781
803
|
},
|
|
782
804
|
rule,
|
|
783
805
|
sync: store.sync,
|
|
@@ -903,4 +925,4 @@ function takeQuotas(parts, options) {
|
|
|
903
925
|
}
|
|
904
926
|
export { quotaStep as a, TOKEN_BUCKET_MACHINE as c, keyedLimiter as d, memoryStore as f, quotaRule as i, limiterMachine as l, memoryQuotaStore as n, takeQuotas as o, quotaProblems as r, SLIDING_WINDOW_MACHINE as s, keyedQuota as t, limiterStateOf as u };
|
|
905
927
|
|
|
906
|
-
//# sourceMappingURL=limiter-
|
|
928
|
+
//# sourceMappingURL=limiter-DrM0PQV9.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limiter-DrM0PQV9.js","names":["r","isPromise"],"sources":["../src/limiter/store.ts","../src/limiter/machine.ts","../src/limiter/quota.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","// The quota of a key: at most `limit` units in each window of a calendar or of a rolling span. A\n// provider of an API gives such a quota, and the gate refuses a take over it before the provider\n// does. The count of the gate is not lower than the count of the provider: a reading of the\n// provider can make the count larger, but not smaller.\n//\n// A quota is data before it starts, with no defaults. Its pure step `quotaStep` takes the stored\n// record, an instant and an event, and gives the next record and the state. A store applies the\n// step to the record of one key in one atomic change. The time of a quota is the instant of a wall\n// clock, because a calendar window needs civil time.\n\nimport type { WallClock } from \"@mark1russell7/algebra/clock\";\nimport { firstInstantOf, localTime } from \"@mark1russell7/algebra/clock\";\nimport type { Quantity } from \"@mark1russell7/quantity\";\nimport { countOf, finiteAbove, isCount, isTime, milliseconds, safely, wholeCount } from \"./policy.ts\";\n\n/**\n * A rolling window counts the units of the last `span`. Use it when the provider does not tell when\n * its count starts again. The window puts each take in a time bucket. A unit counts until all of\n * its bucket is out of the window. Thus the count is not lower than the count of a fixed window.\n */\nexport interface RollingWindow {\n readonly kind: \"rolling\";\n /** This time is the length of the window, for example `{ value: 24, unit: \"h\" }`. */\n readonly span: Quantity;\n /** This count is the count of time buckets in the window: a whole count from 1 to 1000. */\n readonly buckets: Quantity;\n}\n\n/**\n * A calendar window counts the units of a day or of a month in a time zone. Each window starts at\n * the time of day `start`, on each day or on the first day of each month. When the clock of the\n * zone skips that time, the window starts at the end of the gap. When the clock shows that time\n * two times, the window starts at the first of the two.\n */\nexport interface CalendarWindow {\n readonly kind: \"calendar\";\n readonly unit: \"day\" | \"month\";\n /** The IANA name of the time zone, for example `America/Chicago` or `UTC`. */\n readonly zone: string;\n /** This time of day starts each window: from 0 to less than 24 hours, in whole milliseconds. */\n readonly start: Quantity;\n}\n\n/** A quota window is a rolling window or a calendar window. */\nexport type QuotaWindow = RollingWindow | CalendarWindow;\n\n/** A quota spec is the declaration of a quota. It has no defaults. */\nexport interface QuotaSpec {\n /** This count is the count of units that the provider gives in one window. */\n readonly limit: Quantity;\n /** The gate keeps this count of units unused: from 0 to less than the limit. */\n readonly reserve: Quantity;\n readonly window: QuotaWindow;\n /**\n * This value is the longest block that a reading of the provider can set: a time above zero, or\n * `window`. A reading at the instant `t` blocks the key until `t` plus the time at the latest. With\n * `window`, the block ends at the latest when the bucket of `t` stops counting. Thus a reset of the\n * provider in a wrong form does not stop a key for much longer than one window. The step also\n * applies this bound to a block that the stored record keeps. When it is absent, no block has a bound.\n */\n readonly maxBlock?: Quantity | \"window\" | undefined;\n}\n\n/** A quota rule is a spec in numbers: each count as a number, and each time in milliseconds. */\nexport interface QuotaRule {\n readonly limit: number;\n readonly reserve: number;\n readonly window:\n | { readonly kind: \"rolling\"; readonly span: number; readonly buckets: number }\n | { readonly kind: \"calendar\"; readonly unit: \"day\" | \"month\"; readonly zone: string; readonly start: number };\n /** This value is the longest block in milliseconds, or `window`. When it is absent, no block has a bound. */\n readonly maxBlock?: number | \"window\" | undefined;\n}\n\n/**\n * A quota record is what a store keeps for one key. A store can keep it as JSON. Each instant is in\n * milliseconds from 1970-01-01T00:00:00Z.\n */\nexport interface QuotaRecord {\n /** Each item is a time bucket: its start, and its count of units. The oldest bucket is first. */\n readonly spent: readonly (readonly [start: number, units: number])[];\n /** The provider refused the key until this instant. */\n readonly blockedUntil?: number | undefined;\n /** This instant is the last reading of the provider with a count. A give-back for a take at or before it changes nothing. */\n readonly readAt?: number | undefined;\n}\n\n/** A quota reading is what an answer of the provider tells of its count. */\nexport interface QuotaReading {\n /** This count is the count of units that the provider gives before its next reset. */\n readonly remaining?: number | undefined;\n /**\n * This instant is the next reset of the provider. When `remaining` is 0 or absent, the gate\n * refuses each take until this instant.\n */\n readonly resetAt?: number | undefined;\n}\n\n/** A quota state is the state of one key at the instant `at`. */\nexport interface QuotaState {\n /** This instant is the instant of the step. */\n readonly at: number;\n /** This count is the count of units in the window. */\n readonly used: number;\n /** This count is the count of units that the gate gives: the limit, less the reserve and `used`. It is 0 while the provider refuses the key. */\n readonly left: number;\n /** The oldest units stop counting at this instant. With no unit in the window, it is absent. */\n readonly resetAt?: number | undefined;\n /** The provider refused the key until this instant. */\n readonly blockedUntil?: number | undefined;\n}\n\n/** A permitted take counted its units at the instant `state.at`. */\nexport interface QuotaAllowed {\n readonly allowed: true;\n readonly state: QuotaState;\n}\n\n/**\n * A wait refusal counted nothing. Its cause is `limit` when the window has no room for the units,\n * and `provider` when the provider refused the key. At `resetAt`, the gate gives the same take,\n * when no other take comes first.\n */\nexport interface QuotaWaitRefused {\n readonly allowed: false;\n readonly cause: \"limit\" | \"provider\";\n readonly resetAt: number;\n /** This time is the time from `state.at` to `resetAt`. It is always above zero. */\n readonly retryAfter: Quantity;\n readonly state: QuotaState;\n}\n\n/**\n * A capacity refusal counted nothing, and the gate refuses the same take at each time. Its units\n * are more than the `capacity` of one window: the limit less the reserve.\n */\nexport interface QuotaCapacityRefused {\n readonly allowed: false;\n readonly cause: \"capacity\";\n readonly units: number;\n readonly capacity: number;\n readonly state: QuotaState;\n}\n\n/** A quota refusal is a wait refusal or a capacity refusal. */\nexport type QuotaRefused = QuotaWaitRefused | QuotaCapacityRefused;\n\n/** A quota verdict is the answer of a quota to one take. */\nexport type QuotaVerdict = QuotaAllowed | QuotaRefused;\n\n/**\n * A quota event is one change of a key:\n * - `take`: count `units` for a call that starts at the instant of the step, or refuse it.\n * - `note`: add what an answer of the provider tells. The count can only become larger.\n * - `give-back`: remove `units` that a take counted at the instant `at`, for a call that did not\n * start. It changes nothing when the bucket of `at` is out of the window, or when a reading of the\n * provider came at or after `at`.\n * - `read`: change nothing, and give the state.\n */\nexport type QuotaEvent =\n | { readonly type: \"take\"; readonly units: number }\n | { readonly type: \"note\"; readonly reading: QuotaReading }\n | { readonly type: \"give-back\"; readonly units: number; readonly at: number }\n | { readonly type: \"read\" };\n\n/** A quota step is the next record of a key and its state. Only a take gives a verdict. */\nexport interface QuotaStep {\n readonly record: QuotaRecord;\n readonly state: QuotaState;\n readonly verdict?: QuotaVerdict | undefined;\n}\n\n/** A take step is the step of a take: it always has a verdict. */\nexport interface QuotaTakeStep extends QuotaStep {\n readonly verdict: QuotaVerdict;\n}\n\nconst MAX_BUCKETS = 1000;\nconst DAY_MS = 86_400_000;\n/** The largest instant of a `Date`, in milliseconds from the epoch. */\nconst MAX_TIME = 8.64e15;\n/**\n * This slack is a part of a count. A comparison of counts permits it. The reason: a sum of units\n * with a fraction is not exact in floating point, and 0.1 + 0.2 is more than 0.3.\n */\nconst SLACK = 1e-9;\n\n/** This function tells if `total` is over `bound` by more than the slack. */\nconst over = (total: number, bound: number): boolean => total - bound > SLACK * Math.max(1, Math.abs(bound));\n\nconst isInstant = (value: unknown): value is number => typeof value === \"number\" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;\n\nconst iso = (instant: number): string => (isInstant(instant) ? new Date(instant).toISOString() : String(instant));\n\n/** A loose window is a window from any source, with each part optional, for the check of its parts. */\ninterface LooseWindow {\n readonly kind?: string;\n readonly span?: Quantity;\n readonly buckets?: Quantity;\n readonly unit?: string;\n readonly zone?: string;\n readonly start?: Quantity;\n}\n\nconst atLeastZero = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value >= 0;\n\n/**\n * This function gives the problems of a quota spec. `keyedQuota` and `quotaRule` refuse a spec with\n * a problem. A part that is absent is a problem, because a quota has no defaults.\n */\nexport const quotaProblems = (name: string, spec: Partial<QuotaSpec> | undefined): string[] => {\n const owner = `quota ${name}`;\n if (spec === undefined || (spec as unknown) === null) return [`${owner} has no spec: a quota has no defaults`];\n const problems: string[] = [];\n const missing = (part: string): void => {\n problems.push(`${owner} does not declare ${part}: a quota has no defaults`);\n };\n let limit: number | undefined;\n if (spec.limit === undefined) missing(\"its limit (limit)\");\n else if (!safely(isCount, spec.limit)) problems.push(`${owner}'s limit is not a count`);\n else if (!finiteAbove(spec.limit)) problems.push(`${owner}'s limit is not a finite count above zero`);\n else limit = countOf(spec.limit);\n if (spec.reserve === undefined) missing(\"its reserve (reserve), 0 for no reserve\");\n else if (!safely(isCount, spec.reserve)) problems.push(`${owner}'s reserve is not a count`);\n else if (!atLeastZero(spec.reserve)) problems.push(`${owner}'s reserve is not a finite count of 0 or more`);\n else if (limit !== undefined && countOf(spec.reserve) >= limit) problems.push(`${owner}'s reserve is not less than its limit`);\n const window = spec.window as LooseWindow | undefined;\n if (window === undefined || (window as unknown) === null) missing(\"its window (window)\");\n else if (window.kind === \"rolling\") {\n if (window.span === undefined) missing(\"the span of its window (window.span)\");\n else if (!safely(isTime, window.span)) problems.push(`${owner}'s span is not a time`);\n else if (!finiteAbove(window.span)) problems.push(`${owner}'s span is not a finite time above zero`);\n if (window.buckets === undefined) missing(\"the count of buckets of its window (window.buckets)\");\n else if (!safely(isCount, window.buckets)) problems.push(`${owner}'s buckets is not a count`);\n else if (!wholeCount(window.buckets) || countOf(window.buckets) > MAX_BUCKETS)\n problems.push(`${owner}'s buckets is not a whole count from 1 to ${String(MAX_BUCKETS)}`);\n } else if (window.kind === \"calendar\") {\n if (window.unit === undefined) missing(\"the unit of its window (window.unit)\");\n else if (window.unit !== \"day\" && window.unit !== \"month\") problems.push(`${owner}'s unit is not day or month`);\n if (window.zone === undefined) missing(\"the time zone of its window (window.zone)\");\n else if (typeof window.zone !== \"string\" || localTime(0, window.zone) === undefined)\n problems.push(`${owner}'s zone is not an IANA time zone: ${String(window.zone)}`);\n if (window.start === undefined) missing(\"the time of day that starts its window (window.start), 0 h for midnight\");\n else if (!safely(isTime, window.start)) problems.push(`${owner}'s start is not a time`);\n else if (!atLeastZero(window.start) || !Number.isInteger(milliseconds(window.start)) || milliseconds(window.start) >= DAY_MS)\n problems.push(`${owner}'s start is not a whole count of milliseconds from 0 to less than 24 h`);\n } else problems.push(`${owner}'s window is not rolling or calendar`);\n const { maxBlock } = spec;\n if (maxBlock !== undefined && maxBlock !== \"window\") {\n if (typeof maxBlock !== \"object\" || maxBlock === null || !safely(isTime, maxBlock)) problems.push(`${owner}'s maxBlock is not a time or \"window\"`);\n else if (!finiteAbove(maxBlock)) problems.push(`${owner}'s maxBlock is not a finite time above zero`);\n }\n return problems;\n};\n\n/** This function gives the rule of a quota spec. It throws an error with the problems of a spec that has a problem. */\nexport const quotaRule = (name: string, spec: QuotaSpec): QuotaRule => {\n const problems = quotaProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { window, maxBlock } = spec;\n return {\n limit: countOf(spec.limit),\n reserve: countOf(spec.reserve),\n window:\n window.kind === \"rolling\"\n ? { kind: \"rolling\", span: milliseconds(window.span), buckets: countOf(window.buckets) }\n : { kind: \"calendar\", unit: window.unit, zone: window.zone, start: milliseconds(window.start) },\n ...(maxBlock === undefined ? {} : { maxBlock: maxBlock === \"window\" ? \"window\" : milliseconds(maxBlock) }),\n };\n};\n\n/** The buckets of a window: the bucket of an instant, and the test of a bucket. */\ninterface Buckets {\n /** This function gives the start and the end of the bucket of the instant `t`. */\n bucket(t: number): readonly [start: number, end: number];\n /**\n * This function gives the test of the buckets that count at the instant `t`. A bucket of a later\n * window counts too: after a step back of the clock, the takes of that window still count.\n */\n counting(t: number): (start: number) => boolean;\n /** This function gives the instant at which the bucket that starts at `start` stops counting. */\n freeAt(start: number): number;\n}\n\n/** This function gives the calendar window of the instant `t`: its start, and the start of the next window. */\nconst calendarOf = (unit: \"day\" | \"month\", zone: string, start: number, t: number): readonly [number, number] => {\n const local = localTime(t, zone);\n if (local === undefined) throw new RangeError(`the instant ${String(t)} is not a date in the zone ${zone}`);\n const { year, month, day } = local;\n // the start of the window that is `back` windows before the window of the date of `t`\n const startOf = (back: number): number => {\n const wall = (unit === \"day\" ? Date.UTC(year, month - 1, day - back) : Date.UTC(year, month - 1 - back, 1)) + start;\n const instant = firstInstantOf(wall, zone);\n if (instant === undefined) throw new RangeError(`the clock of ${zone} does not show or skip the local time ${iso(wall)}`);\n return instant;\n };\n const first = startOf(0);\n return first <= t ? [first, startOf(-1)] : [startOf(1), first];\n};\n\nconst bucketsOf = (window: QuotaRule[\"window\"]): Buckets => {\n if (window.kind === \"rolling\") {\n const { span } = window;\n const size = Math.ceil(span / window.buckets);\n return {\n bucket: (t) => {\n const start = Math.floor(t / size) * size;\n return [start, start + size];\n },\n counting: (t) => (start) => start + size + span > t,\n freeAt: (start) => start + size + span,\n };\n }\n const { unit, zone, start } = window;\n return {\n bucket: (t) => calendarOf(unit, zone, start, t),\n // only the windows before the window of `t` stop counting\n counting: (t) => {\n const [first] = calendarOf(unit, zone, start, t);\n return (bucket) => bucket >= first;\n },\n freeAt: (bucket) => calendarOf(unit, zone, start, bucket)[1],\n };\n};\n\n/**\n * This function gives the record of a store. A value that is not a record gives an empty record.\n * The function removes each item that is not valid and keeps the other items, thus the count stays\n * as high as the record lets it. It adds the items of one bucket together.\n */\nconst recordOf = (value: unknown): QuotaRecord => {\n if (typeof value !== \"object\" || value === null) return { spent: [] };\n const { spent, blockedUntil, readAt } = value as { spent?: unknown; blockedUntil?: unknown; readAt?: unknown };\n const counts = new Map<number, number>();\n if (Array.isArray(spent))\n for (const item of spent as unknown[]) {\n if (!Array.isArray(item) || item.length !== 2) continue;\n const [start, units] = item as unknown[];\n if (isInstant(start) && typeof units === \"number\" && Number.isFinite(units) && units > 0) counts.set(start, (counts.get(start) ?? 0) + units);\n }\n const items = [...counts].sort((a, b) => a[0] - b[0]);\n return {\n spent: items,\n ...(isInstant(blockedUntil) ? { blockedUntil } : {}),\n ...(isInstant(readAt) ? { readAt } : {}),\n };\n};\n\n/** This function removes the buckets that do not count at the instant `t`, an ended refusal, and a reading that no give-back can meet. */\nconst prune = (buckets: Buckets, record: QuotaRecord, t: number): QuotaRecord => {\n const counts = buckets.counting(t);\n const { blockedUntil, readAt } = record;\n return {\n spent: record.spent.filter(([start]) => counts(start)),\n ...(blockedUntil !== undefined && blockedUntil > t ? { blockedUntil } : {}),\n // a give-back changes only a bucket that counts, and each such bucket starts after the bucket of an older reading\n ...(readAt !== undefined && counts(buckets.bucket(readAt)[0]) ? { readAt } : {}),\n };\n};\n\n/**\n * This function applies the bound of the rule to the block of a record at the instant `t`. The\n * block ends at `t` plus the longest block at the latest. With `window`, it ends at the latest when\n * the bucket of `t` stops counting. The bound is after `t`, thus a capped block stays a block.\n */\nconst capBlock = (rule: QuotaRule, buckets: Buckets, record: QuotaRecord, t: number): QuotaRecord => {\n const { maxBlock } = rule;\n const { blockedUntil } = record;\n if (maxBlock === undefined || blockedUntil === undefined) return record;\n const bound = maxBlock === \"window\" ? buckets.freeAt(buckets.bucket(t)[0]) : t + maxBlock;\n return blockedUntil > bound ? { ...record, blockedUntil: bound } : record;\n};\n\nconst usedOf = (record: QuotaRecord): number => record.spent.reduce((sum, [, units]) => sum + units, 0);\n\n/** This function adds units to the bucket of the instant `t`. */\nconst add = (buckets: Buckets, record: QuotaRecord, t: number, units: number): QuotaRecord => {\n const [start] = buckets.bucket(t);\n let found = false;\n const spent = record.spent.map(([at, count]): readonly [number, number] => {\n if (at !== start) return [at, count];\n found = true;\n return [at, count + units];\n });\n if (!found) spent.push([start, units]);\n spent.sort((a, b) => a[0] - b[0]);\n return { ...record, spent };\n};\n\n/** This function gives the instant at which `need` units of the oldest buckets stop counting. */\nconst freeTime = (buckets: Buckets, record: QuotaRecord, need: number): number | undefined => {\n let freed = 0;\n for (const [start, units] of record.spent) {\n freed += units;\n if (!over(need, freed)) return buckets.freeAt(start);\n }\n return undefined;\n};\n\nconst stateOf = (rule: QuotaRule, buckets: Buckets, record: QuotaRecord, t: number): QuotaState => {\n const used = usedOf(record);\n const oldest = record.spent[0];\n const { blockedUntil } = record;\n return {\n at: t,\n used,\n left: blockedUntil === undefined ? Math.max(0, rule.limit - rule.reserve - used) : 0,\n ...(oldest === undefined ? {} : { resetAt: buckets.freeAt(oldest[0]) }),\n ...(blockedUntil === undefined ? {} : { blockedUntil }),\n };\n};\n\n/** This function checks the units of a take or of a give-back: a finite count of 0 or more. */\nconst checkUnits = (units: unknown): number => {\n if (typeof units !== \"number\" || !Number.isFinite(units) || units < 0) throw new RangeError(`the units of a quota are not a finite count of 0 or more: ${String(units)}`);\n return units;\n};\n\n/** This function checks an event before a store gets it, thus a store does not start a change for an event that is not valid. */\nconst checkEvent = (event: QuotaEvent): void => {\n if (event.type === \"take\") checkUnits(event.units);\n else if (event.type === \"give-back\") {\n checkUnits(event.units);\n if (!isInstant(event.at)) throw new RangeError(`the instant of a give-back is not a date: ${String(event.at)}`);\n }\n};\n\n/**\n * This function is the pure step of a quota. It reads the stored record of one key at the instant\n * `instant`, applies the event, and gives the next record and the state. It removes what does not\n * count at the instant first. Only a take can be refused, and a refusal counts nothing.\n * - A take of 0 units is permitted and counts nothing, also while the provider refuses the key.\n * - A take over the capacity is refused with the cause `capacity`.\n * - While the provider refuses the key, a take is refused with the cause `provider`. Its `resetAt`\n * is the end of that refusal, or a later instant when the window has room for the units.\n * - A take over the room of the window is refused with the cause `limit`, until enough of the\n * oldest units stop counting.\n * - With `maxBlock` in the rule, a block ends at the latest at the bound of the instant. The step\n * applies the bound to the stored block before the event, and to the block of a note after it.\n *\n * It throws a `RangeError` for an instant that is not a date, and for units that are not a finite\n * count of 0 or more.\n */\nexport function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: Extract<QuotaEvent, { type: \"take\" }>): QuotaTakeStep;\nexport function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep;\nexport function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep {\n if (!isInstant(instant)) throw new RangeError(`the instant of a quota step is not a date: ${String(instant)}`);\n checkEvent(event);\n const buckets = bucketsOf(rule.window);\n // the bound of the rule applies to the stored block before the event, thus the step writes back the capped record\n const record = capBlock(rule, buckets, prune(buckets, recordOf(stored), instant), instant);\n const done = (next: QuotaRecord): QuotaStep => ({ record: next, state: stateOf(rule, buckets, next, instant) });\n switch (event.type) {\n case \"read\":\n return done(record);\n case \"note\": {\n let next = record;\n const { remaining, resetAt } = event.reading;\n if (typeof remaining === \"number\" && Number.isFinite(remaining) && remaining >= 0) {\n const more = rule.limit - remaining - usedOf(next);\n if (over(more, 0)) next = add(buckets, next, instant, more);\n next = { ...next, readAt: Math.max(next.readAt ?? instant, instant) };\n }\n const exhausted = remaining === undefined || remaining <= 0;\n if (exhausted && isInstant(resetAt) && resetAt > instant)\n next = capBlock(rule, buckets, { ...next, blockedUntil: Math.max(next.blockedUntil ?? resetAt, resetAt) }, instant);\n return done(next);\n }\n case \"give-back\": {\n const { units, at } = event;\n if (units === 0 || (record.readAt !== undefined && record.readAt >= at)) return done(record);\n const [start] = buckets.bucket(at);\n if (!record.spent.some(([bucket]) => bucket === start)) return done(record);\n const spent: (readonly [number, number])[] = [];\n for (const [bucket, count] of record.spent) {\n const left = bucket === start ? count - Math.min(units, count) : count;\n if (over(left, 0)) spent.push([bucket, left]);\n }\n return done({ ...record, spent });\n }\n case \"take\": {\n const { units } = event;\n const allowed = rule.limit - rule.reserve;\n const refuse = (verdict: QuotaRefused): QuotaTakeStep => ({ record, state: verdict.state, verdict });\n const state = stateOf(rule, buckets, record, instant);\n if (units === 0) return { record, state, verdict: { allowed: true, state } };\n if (over(units, allowed)) return refuse({ allowed: false, cause: \"capacity\", units, capacity: allowed, state });\n const used = usedOf(record);\n // the need is not more than the units of the window, because the units are not over the capacity\n const free = over(used + units, allowed) ? (freeTime(buckets, record, used + units - allowed) ?? buckets.bucket(instant)[1]) : undefined;\n const wait = (cause: \"limit\" | \"provider\", resetAt: number): QuotaTakeStep =>\n refuse({ allowed: false, cause, resetAt, retryAfter: { value: resetAt - instant, unit: \"ms\" }, state });\n if (record.blockedUntil !== undefined) return wait(\"provider\", Math.max(record.blockedUntil, free ?? record.blockedUntil));\n if (free !== undefined) return wait(\"limit\", free);\n const next = done(add(buckets, record, instant, units));\n return { ...next, verdict: { allowed: true, state: next.state } };\n }\n }\n}\n\n/** A quota answer is a value at once for a store that answers at once, else a promise. */\nexport type QuotaAnswer<Sync extends boolean, T> = Sync extends true ? T : Promise<T>;\n\n/** A quota change is what a step gives a store: the record to keep, and the result for the caller. */\nexport interface QuotaChange<T> {\n readonly record: QuotaRecord;\n readonly result: T;\n}\n\n/**\n * A quota store keeps the record of each quota and key, and it changes one record in one atomic\n * step. Thus two takes of one key do not read the same record. A store of this process can answer\n * at once (`sync: true`), for example a store in memory or in SQLite. A store that the replicas\n * share answers with a promise (`sync: false`).\n */\nexport interface QuotaStore<Sync extends boolean = boolean> {\n readonly sync: Sync;\n /**\n * This method gives `step` the stored record of the quota and the key, or undefined for a new key.\n * It keeps the record that `step` gives, and it gives the result. The record of a new key is\n * empty: a store can remove a key whose record has no item and no instant. A store can call\n * `step` again, for example after a conflict of a write. Thus `step` must have no other effect.\n */\n change<T>(quota: string, key: string, step: (stored: unknown) => QuotaChange<T>): QuotaAnswer<Sync, T>;\n}\n\n/** A memory quota store is the store of one process. Its records are in memory. */\nexport interface MemoryQuotaStore extends QuotaStore<true> {\n /** This method gives the count of keys that the store holds for a quota. */\n size(quota: string): number;\n}\n\n/** This function tells if a record is equal to the record of a new key. */\nconst isEmpty = (record: QuotaRecord): boolean => record.spent.length === 0 && record.blockedUntil === undefined && record.readAt === undefined;\n\n/**\n * This function makes a store of records in memory. Each quota of one process can share it, and it\n * keeps the records of each quota apart. It removes a key when its record is equal to the record\n * of a new key. It does not sweep the other keys: use it for a set of keys with a bound, for\n * example the accounts of an API.\n */\nexport const memoryQuotaStore = (): MemoryQuotaStore => {\n const tables = new Map<string, Map<string, QuotaRecord>>();\n return {\n sync: true,\n change(quota, key, step) {\n let table = tables.get(quota);\n if (table === undefined) {\n table = new Map();\n tables.set(quota, table);\n }\n const { record, result } = step(table.get(key));\n if (isEmpty(record)) table.delete(key);\n else table.set(key, record);\n if (table.size === 0) tables.delete(quota);\n return result;\n },\n size(quota) {\n return tables.get(quota)?.size ?? 0;\n },\n };\n};\n\n/** A keyed quota is the runtime of one quota: its spec, its rule in numbers, its store and its wall clock. */\nexport interface KeyedQuota<Sync extends boolean = boolean> {\n /** This name is the quota. A store keeps the keys of each quota apart. */\n readonly name: string;\n readonly spec: QuotaSpec;\n readonly rule: QuotaRule;\n /** True: each method gives its answer at once. False: each method gives a promise. */\n readonly sync: Sync;\n /** This method counts `units` units (1 when absent) for a call of the key that starts at this instant, or refuses the call. */\n take(key: string, units?: number): QuotaAnswer<Sync, QuotaVerdict>;\n /** This method adds what an answer of the provider tells. The count can only become larger. */\n note(key: string, reading: QuotaReading): QuotaAnswer<Sync, QuotaState>;\n /** This method removes `units` that a take counted at the instant `at`, for a call that did not start. */\n giveBack(key: string, units: number, at: number): QuotaAnswer<Sync, QuotaState>;\n /** This method gives the state of the key, and changes nothing. */\n state(key: string): QuotaAnswer<Sync, QuotaState>;\n}\n\n/** This function tells if a value is a promise. */\nconst isPromise = (value: unknown): value is Promise<unknown> =>\n typeof value === \"object\" && value !== null && typeof (value as { then?: unknown }).then === \"function\";\n\n/**\n * This function makes the runtime of a quota from its spec, its store and a wall clock. It refuses\n * a spec with a problem, because a quota has no defaults. It reads the instant inside the change of\n * the store, thus a store that waits for a lock reads the instant after the wait.\n * - With a store that answers at once, each method answers at once. A `RangeError` throws, and a\n * store that gives a promise throws an error.\n * - With a store that answers with a promise, each method gives a promise. A `RangeError` rejects.\n */\nexport function keyedQuota<Sync extends boolean>(\n name: string,\n spec: QuotaSpec,\n store: QuotaStore<Sync>,\n clock: Pick<WallClock, \"time\" | \"now\">,\n): KeyedQuota<Sync> {\n const rule = quotaRule(name, spec);\n if (clock.time !== \"wall\") throw new Error(`quota ${name} needs a wall clock, which gives the instant: a calendar window needs civil time`);\n const answer = <T>(compute: () => T | Promise<T>): QuotaAnswer<Sync, T> => {\n if (!store.sync) return (async () => compute())() as QuotaAnswer<Sync, T>;\n const value = compute();\n if (isPromise(value)) {\n // the change of the store happened: its promise has the result, and its rejection is not left unhandled\n value.then(undefined, () => {});\n throw new Error(`quota ${name} has a store that says it answers at once, but its change gave a promise`);\n }\n return value as QuotaAnswer<Sync, T>;\n };\n const change = <T>(key: string, event: QuotaEvent, pick: (step: QuotaStep) => T): QuotaAnswer<Sync, T> =>\n answer(() => {\n checkEvent(event);\n return store.change(name, key, (stored) => {\n const step = quotaStep(rule, stored, clock.now(), event);\n return { record: step.record, result: pick(step) };\n }) as T | Promise<T>;\n });\n const verdictOf = (step: QuotaStep): QuotaVerdict => step.verdict as QuotaVerdict;\n const stateOfStep = (step: QuotaStep): QuotaState => step.state;\n const { window, maxBlock } = spec;\n return {\n name,\n spec: {\n limit: { ...spec.limit },\n reserve: { ...spec.reserve },\n window:\n window.kind === \"rolling\"\n ? { kind: \"rolling\", span: { ...window.span }, buckets: { ...window.buckets } }\n : { kind: \"calendar\", unit: window.unit, zone: window.zone, start: { ...window.start } },\n ...(maxBlock === undefined ? {} : { maxBlock: maxBlock === \"window\" ? \"window\" : { ...maxBlock } }),\n },\n rule,\n sync: store.sync,\n take: (key, units = 1) => change(key, { type: \"take\", units }, verdictOf),\n note: (key, reading) => change(key, { type: \"note\", reading: { ...reading } }, stateOfStep),\n giveBack: (key, units, at) => change(key, { type: \"give-back\", units, at }, stateOfStep),\n state: (key) => change(key, { type: \"read\" }, stateOfStep),\n };\n}\n\n/**\n * A quota part is one take of a multi-quota take: a quota, a key, and the units of the take. The\n * quota needs only `sync`, `take` and `giveBack`. Thus a gate of your own with these members can be\n * a part, and a `KeyedQuota` is one.\n */\nexport interface QuotaPart<Sync extends boolean = boolean> {\n readonly quota: Pick<KeyedQuota<Sync>, \"sync\" | \"take\" | \"giveBack\">;\n readonly key: string;\n readonly units: number;\n}\n\n/**\n * A quotas verdict is the answer of a take of several quotas, all or none. Each state is the state\n * of its part after the take, and after the give-back of a refused take.\n * - A permitted take counted the units of each part.\n * - A refused take counted nothing. `refusal` is the refusal of the part `index`: the first\n * capacity refusal, else the wait refusal with the latest `resetAt`.\n */\nexport type QuotasVerdict =\n | { readonly allowed: true; readonly states: readonly QuotaState[] }\n | { readonly allowed: false; readonly index: number; readonly refusal: QuotaRefused; readonly states: readonly QuotaState[] };\n\n/** The options of `takeQuotas`. */\nexport interface TakeQuotasOptions {\n /**\n * This function gets each error of a give-back, with the index of its part. The units of that\n * part stay counted, thus its quota refuses sooner, not later. It gets the errors after the last\n * give-back, thus its own error stops no give-back. An error that it throws ends the take.\n */\n readonly onGiveBackError?: ((error: unknown, index: number) => void) | undefined;\n}\n\n/** A request of the walk of a multi-quota take: a call of one method of a quota. */\ntype Request = () => unknown;\n\n/** A walk gives a verdict or the error of a failed take, and the errors of the give-backs. */\ntype Walked = { readonly failures: readonly { readonly index: number; readonly error: unknown }[] } & (\n | { readonly verdict: QuotasVerdict }\n | { readonly error: unknown }\n);\n\n/** This function tells which refusal decides: a capacity refusal, else the latest `resetAt`. The first part wins a tie. */\nconst decisive = (verdicts: readonly QuotaVerdict[]): number => {\n let best = -1;\n for (let index = 0; index < verdicts.length; index += 1) {\n const verdict = verdicts[index]!;\n if (verdict.allowed) continue;\n const current = best < 0 ? undefined : (verdicts[best] as QuotaRefused);\n if (current === undefined) best = index;\n else if (current.cause === \"capacity\") continue;\n else if (verdict.cause === \"capacity\" || verdict.resetAt > current.resetAt) best = index;\n }\n return best;\n};\n\n/**\n * This walk takes each part in order, then gives back the counted parts of a refused or failed\n * take. The driver answers each request. A failed give-back does not stop the next give-backs.\n * The walk keeps its error, and the state of its part is the state after the take.\n */\nfunction* walk(parts: readonly QuotaPart[]): Generator<Request, Walked, unknown> {\n const verdicts: QuotaVerdict[] = [];\n const failures: { readonly index: number; readonly error: unknown }[] = [];\n /** This walk gives back the units of a part, and gives the state after the give-back, or after the take when the give-back fails. */\n function* giveBack(index: number): Generator<Request, QuotaState, unknown> {\n const verdict = verdicts[index]!;\n const part = parts[index]!;\n if (!verdict.allowed || part.units === 0) return verdict.state;\n try {\n return (yield () => part.quota.giveBack(part.key, part.units, verdict.state.at)) as QuotaState;\n } catch (error) {\n failures.push({ index, error });\n return verdict.state;\n }\n }\n try {\n for (const part of parts) verdicts.push((yield () => part.quota.take(part.key, part.units)) as QuotaVerdict);\n } catch (error) {\n // a failed take of a part: give back the parts before it, then give its error\n for (let index = 0; index < verdicts.length; index += 1) yield* giveBack(index);\n return { error, failures };\n }\n const index = decisive(verdicts);\n if (index < 0) return { verdict: { allowed: true, states: verdicts.map((verdict) => verdict.state) }, failures };\n const states: QuotaState[] = [];\n for (let at = 0; at < parts.length; at += 1) states.push(yield* giveBack(at));\n return { verdict: { allowed: false, index, refusal: verdicts[index] as QuotaRefused, states }, failures };\n}\n\n/** This function gives each error of a give-back to the option, then gives the verdict or throws the error of the take. */\nconst finish = (walked: Walked, options: TakeQuotasOptions | undefined): QuotasVerdict => {\n for (const failure of walked.failures) options?.onGiveBackError?.(failure.error, failure.index);\n if (\"error\" in walked) throw walked.error;\n return walked.verdict;\n};\n\nconst driveSync = (parts: readonly QuotaPart[], options: TakeQuotasOptions | undefined): QuotasVerdict => {\n const steps = walk(parts);\n let next = steps.next();\n while (!next.done) {\n let value: unknown;\n let failure: { error: unknown } | undefined;\n try {\n value = next.value();\n } catch (error) {\n failure = { error };\n }\n next = failure === undefined ? steps.next(value) : steps.throw(failure.error);\n }\n return finish(next.value, options);\n};\n\nconst driveAsync = async (parts: readonly QuotaPart[], options: TakeQuotasOptions | undefined): Promise<QuotasVerdict> => {\n const steps = walk(parts);\n let next = steps.next();\n while (!next.done) {\n let value: unknown;\n let failure: { error: unknown } | undefined;\n try {\n value = await next.value();\n } catch (error) {\n failure = { error };\n }\n next = failure === undefined ? steps.next(value) : steps.throw(failure.error);\n }\n return finish(next.value, options);\n};\n\n/**\n * This function takes from several quotas, all or none. It takes each part in order. When a part\n * is refused, the next parts still answer, and each part that counted gives back its units. Thus\n * the refusal tells the latest instant at which all parts can have room. When a take fails, the\n * parts before it give back their units, and the error throws.\n *\n * A failed give-back does not change the verdict and does not stop the other give-backs. The units\n * of its part stay counted, and `options.onGiveBackError` gets its error.\n *\n * With quotas that answer at once, it answers at once. Else it gives a promise.\n */\nexport function takeQuotas(parts: readonly QuotaPart<true>[], options?: TakeQuotasOptions): QuotasVerdict;\nexport function takeQuotas(parts: readonly QuotaPart[], options?: TakeQuotasOptions): QuotasVerdict | Promise<QuotasVerdict>;\nexport function takeQuotas(parts: readonly QuotaPart[], options?: TakeQuotasOptions): QuotasVerdict | Promise<QuotasVerdict> {\n return parts.every((part) => part.quota.sync) ? driveSync(parts, options) : driveAsync(parts, options);\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,K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
|
1
1
|
import { C as limitRule, D as retryAfterSeconds, E as overCapacity, O as unitsOf, S as idleSpan, T as longestRetryAfter, _ as WaitCause, a as LimitPolicy, b as decide, c as LimiterEviction, d as RefusalCause, f as Refused, g as TokenBucket, h as TakeStep, i as KeyState, l as LimiterSpec, m as StoreFailure, n as CapacityRefused, o as LimitRule, p as SlidingWindow, r as Decision, s as Limiter, t as Allowed, u as LimiterStoreSpec, v as WaitRefused, w as limiterProblems, x as freeAt, y as capacityOf } from "./policy-CBcK2XGg.js";
|
|
2
2
|
import { a as TakeRequest, i as MemoryStore, n as LimiterStore, o as keyedLimiter, r as LocalLimiter, s as memoryStore, t as KeyedLimiter } from "./store-DFwFKrsB.js";
|
|
3
|
-
import { A as takeQuotas, C as RollingWindow, D as quotaProblems, E as memoryQuotaStore, F as limiterStateOf, M as SLIDING_WINDOW_MACHINE, N as TOKEN_BUCKET_MACHINE, O as quotaRule, P as limiterMachine, S as QuotasVerdict, T as keyedQuota, _ as QuotaStore, a as QuotaAnswer, b as QuotaWaitRefused, c as QuotaEvent, d as QuotaRecord, f as QuotaRefused, g as QuotaStep, h as QuotaState, i as QuotaAllowed, j as LimiterState, k as quotaStep, l as QuotaPart, m as QuotaSpec, n as KeyedQuota, o as QuotaCapacityRefused, p as QuotaRule, r as MemoryQuotaStore, s as QuotaChange, t as CalendarWindow, u as QuotaReading, v as QuotaTakeStep, w as TakeQuotasOptions, x as QuotaWindow, y as QuotaVerdict } from "./limiter-
|
|
3
|
+
import { A as takeQuotas, C as RollingWindow, D as quotaProblems, E as memoryQuotaStore, F as limiterStateOf, M as SLIDING_WINDOW_MACHINE, N as TOKEN_BUCKET_MACHINE, O as quotaRule, P as limiterMachine, S as QuotasVerdict, T as keyedQuota, _ as QuotaStore, a as QuotaAnswer, b as QuotaWaitRefused, c as QuotaEvent, d as QuotaRecord, f as QuotaRefused, g as QuotaStep, h as QuotaState, i as QuotaAllowed, j as LimiterState, k as quotaStep, l as QuotaPart, m as QuotaSpec, n as KeyedQuota, o as QuotaCapacityRefused, p as QuotaRule, r as MemoryQuotaStore, s as QuotaChange, t as CalendarWindow, u as QuotaReading, v as QuotaTakeStep, w as TakeQuotasOptions, x as QuotaWindow, y as QuotaVerdict } from "./limiter-BNKnwzeY.js";
|
|
4
4
|
export { type Allowed, type CalendarWindow, type CapacityRefused, type Decision, type KeyState, type KeyedLimiter, type KeyedQuota, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type MemoryQuotaStore, type MemoryStore, type QuotaAllowed, type QuotaAnswer, type QuotaCapacityRefused, type QuotaChange, type QuotaEvent, type QuotaPart, type QuotaReading, type QuotaRecord, type QuotaRefused, type QuotaRule, type QuotaSpec, type QuotaState, type QuotaStep, type QuotaStore, type QuotaTakeStep, type QuotaVerdict, type QuotaWaitRefused, type QuotaWindow, type QuotasVerdict, type RefusalCause, type Refused, type RollingWindow, SLIDING_WINDOW_MACHINE, type SlidingWindow, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeQuotasOptions, type TakeRequest, type TakeStep, type TokenBucket, type WaitCause, type WaitRefused, capacityOf, decide, freeAt, idleSpan, keyedLimiter, keyedQuota, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryQuotaStore, memoryStore, overCapacity, quotaProblems, quotaRule, quotaStep, retryAfterSeconds, takeQuotas, unitsOf };
|
package/build/limiter.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { a as freeAt, d as longestRetryAfter, g as unitsOf, l as limitRule, m as retryAfterSeconds, o as idleSpan, p as overCapacity, r as decide, t as capacityOf, u as limiterProblems } from "./policy-UYALkqVq.js";
|
|
2
|
-
import { a as quotaStep, c as TOKEN_BUCKET_MACHINE, d as keyedLimiter, f as memoryStore, i as quotaRule, l as limiterMachine, n as memoryQuotaStore, o as takeQuotas, r as quotaProblems, s as SLIDING_WINDOW_MACHINE, t as keyedQuota, u as limiterStateOf } from "./limiter-
|
|
2
|
+
import { a as quotaStep, c as TOKEN_BUCKET_MACHINE, d as keyedLimiter, f as memoryStore, i as quotaRule, l as limiterMachine, n as memoryQuotaStore, o as takeQuotas, r as quotaProblems, s as SLIDING_WINDOW_MACHINE, t as keyedQuota, u as limiterStateOf } from "./limiter-DrM0PQV9.js";
|
|
3
3
|
export { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, capacityOf, decide, freeAt, idleSpan, keyedLimiter, keyedQuota, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryQuotaStore, memoryStore, overCapacity, quotaProblems, quotaRule, quotaStep, retryAfterSeconds, takeQuotas, unitsOf };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/service",
|
|
4
|
-
"version": "0.8.
|
|
4
|
+
"version": "0.8.19",
|
|
5
5
|
"description": "A service declared as data before it starts, and its runtime: checks on jittered loops, a latch for each policy, probes from the cache, the startup in its sequence, and a staged, capped drain. The timer-ordering law checks the declaration. Its clock, heartbeat and backoff also work alone, in a browser too.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"service",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"limiter-Bgy6Gmvl.js","names":["r","isPromise"],"sources":["../src/limiter/store.ts","../src/limiter/machine.ts","../src/limiter/quota.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","// The quota of a key: at most `limit` units in each window of a calendar or of a rolling span. A\n// provider of an API gives such a quota, and the gate refuses a take over it before the provider\n// does. The count of the gate is not lower than the count of the provider: a reading of the\n// provider can make the count larger, but not smaller.\n//\n// A quota is data before it starts, with no defaults. Its pure step `quotaStep` takes the stored\n// record, an instant and an event, and gives the next record and the state. A store applies the\n// step to the record of one key in one atomic change. The time of a quota is the instant of a wall\n// clock, because a calendar window needs civil time.\n\nimport type { WallClock } from \"@mark1russell7/algebra/clock\";\nimport { firstInstantOf, localTime } from \"@mark1russell7/algebra/clock\";\nimport type { Quantity } from \"@mark1russell7/quantity\";\nimport { countOf, finiteAbove, isCount, isTime, milliseconds, safely, wholeCount } from \"./policy.ts\";\n\n/**\n * A rolling window counts the units of the last `span`. Use it when the provider does not tell when\n * its count starts again. The window puts each take in a time bucket. A unit counts until all of\n * its bucket is out of the window. Thus the count is not lower than the count of a fixed window.\n */\nexport interface RollingWindow {\n readonly kind: \"rolling\";\n /** This time is the length of the window, for example `{ value: 24, unit: \"h\" }`. */\n readonly span: Quantity;\n /** This count is the count of time buckets in the window: a whole count from 1 to 1000. */\n readonly buckets: Quantity;\n}\n\n/**\n * A calendar window counts the units of a day or of a month in a time zone. Each window starts at\n * the time of day `start`, on each day or on the first day of each month. When the clock of the\n * zone skips that time, the window starts at the end of the gap. When the clock shows that time\n * two times, the window starts at the first of the two.\n */\nexport interface CalendarWindow {\n readonly kind: \"calendar\";\n readonly unit: \"day\" | \"month\";\n /** The IANA name of the time zone, for example `America/Chicago` or `UTC`. */\n readonly zone: string;\n /** This time of day starts each window: from 0 to less than 24 hours, in whole milliseconds. */\n readonly start: Quantity;\n}\n\n/** A quota window is a rolling window or a calendar window. */\nexport type QuotaWindow = RollingWindow | CalendarWindow;\n\n/** A quota spec is the declaration of a quota. It has no defaults. */\nexport interface QuotaSpec {\n /** This count is the count of units that the provider gives in one window. */\n readonly limit: Quantity;\n /** The gate keeps this count of units unused: from 0 to less than the limit. */\n readonly reserve: Quantity;\n readonly window: QuotaWindow;\n}\n\n/** A quota rule is a spec in numbers: each count as a number, and each time in milliseconds. */\nexport interface QuotaRule {\n readonly limit: number;\n readonly reserve: number;\n readonly window:\n | { readonly kind: \"rolling\"; readonly span: number; readonly buckets: number }\n | { readonly kind: \"calendar\"; readonly unit: \"day\" | \"month\"; readonly zone: string; readonly start: number };\n}\n\n/**\n * A quota record is what a store keeps for one key. A store can keep it as JSON. Each instant is in\n * milliseconds from 1970-01-01T00:00:00Z.\n */\nexport interface QuotaRecord {\n /** Each item is a time bucket: its start, and its count of units. The oldest bucket is first. */\n readonly spent: readonly (readonly [start: number, units: number])[];\n /** The provider refused the key until this instant. */\n readonly blockedUntil?: number | undefined;\n /** This instant is the last reading of the provider with a count. A give-back for a take at or before it changes nothing. */\n readonly readAt?: number | undefined;\n}\n\n/** A quota reading is what an answer of the provider tells of its count. */\nexport interface QuotaReading {\n /** This count is the count of units that the provider gives before its next reset. */\n readonly remaining?: number | undefined;\n /**\n * This instant is the next reset of the provider. When `remaining` is 0 or absent, the gate\n * refuses each take until this instant.\n */\n readonly resetAt?: number | undefined;\n}\n\n/** A quota state is the state of one key at the instant `at`. */\nexport interface QuotaState {\n /** This instant is the instant of the step. */\n readonly at: number;\n /** This count is the count of units in the window. */\n readonly used: number;\n /** This count is the count of units that the gate gives: the limit, less the reserve and `used`. It is 0 while the provider refuses the key. */\n readonly left: number;\n /** The oldest units stop counting at this instant. With no unit in the window, it is absent. */\n readonly resetAt?: number | undefined;\n /** The provider refused the key until this instant. */\n readonly blockedUntil?: number | undefined;\n}\n\n/** A permitted take counted its units at the instant `state.at`. */\nexport interface QuotaAllowed {\n readonly allowed: true;\n readonly state: QuotaState;\n}\n\n/**\n * A wait refusal counted nothing. Its cause is `limit` when the window has no room for the units,\n * and `provider` when the provider refused the key. At `resetAt`, the gate gives the same take,\n * when no other take comes first.\n */\nexport interface QuotaWaitRefused {\n readonly allowed: false;\n readonly cause: \"limit\" | \"provider\";\n readonly resetAt: number;\n /** This time is the time from `state.at` to `resetAt`. It is always above zero. */\n readonly retryAfter: Quantity;\n readonly state: QuotaState;\n}\n\n/**\n * A capacity refusal counted nothing, and the gate refuses the same take at each time. Its units\n * are more than the `capacity` of one window: the limit less the reserve.\n */\nexport interface QuotaCapacityRefused {\n readonly allowed: false;\n readonly cause: \"capacity\";\n readonly units: number;\n readonly capacity: number;\n readonly state: QuotaState;\n}\n\n/** A quota refusal is a wait refusal or a capacity refusal. */\nexport type QuotaRefused = QuotaWaitRefused | QuotaCapacityRefused;\n\n/** A quota verdict is the answer of a quota to one take. */\nexport type QuotaVerdict = QuotaAllowed | QuotaRefused;\n\n/**\n * A quota event is one change of a key:\n * - `take`: count `units` for a call that starts at the instant of the step, or refuse it.\n * - `note`: add what an answer of the provider tells. The count can only become larger.\n * - `give-back`: remove `units` that a take counted at the instant `at`, for a call that did not\n * start. It changes nothing when the bucket of `at` is out of the window, or when a reading of the\n * provider came at or after `at`.\n * - `read`: change nothing, and give the state.\n */\nexport type QuotaEvent =\n | { readonly type: \"take\"; readonly units: number }\n | { readonly type: \"note\"; readonly reading: QuotaReading }\n | { readonly type: \"give-back\"; readonly units: number; readonly at: number }\n | { readonly type: \"read\" };\n\n/** A quota step is the next record of a key and its state. Only a take gives a verdict. */\nexport interface QuotaStep {\n readonly record: QuotaRecord;\n readonly state: QuotaState;\n readonly verdict?: QuotaVerdict | undefined;\n}\n\n/** A take step is the step of a take: it always has a verdict. */\nexport interface QuotaTakeStep extends QuotaStep {\n readonly verdict: QuotaVerdict;\n}\n\nconst MAX_BUCKETS = 1000;\nconst DAY_MS = 86_400_000;\n/** The largest instant of a `Date`, in milliseconds from the epoch. */\nconst MAX_TIME = 8.64e15;\n/**\n * This slack is a part of a count. A comparison of counts permits it. The reason: a sum of units\n * with a fraction is not exact in floating point, and 0.1 + 0.2 is more than 0.3.\n */\nconst SLACK = 1e-9;\n\n/** This function tells if `total` is over `bound` by more than the slack. */\nconst over = (total: number, bound: number): boolean => total - bound > SLACK * Math.max(1, Math.abs(bound));\n\nconst isInstant = (value: unknown): value is number => typeof value === \"number\" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;\n\nconst iso = (instant: number): string => (isInstant(instant) ? new Date(instant).toISOString() : String(instant));\n\n/** A loose window is a window from any source, with each part optional, for the check of its parts. */\ninterface LooseWindow {\n readonly kind?: string;\n readonly span?: Quantity;\n readonly buckets?: Quantity;\n readonly unit?: string;\n readonly zone?: string;\n readonly start?: Quantity;\n}\n\nconst atLeastZero = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value >= 0;\n\n/**\n * This function gives the problems of a quota spec. `keyedQuota` and `quotaRule` refuse a spec with\n * a problem. A part that is absent is a problem, because a quota has no defaults.\n */\nexport const quotaProblems = (name: string, spec: Partial<QuotaSpec> | undefined): string[] => {\n const owner = `quota ${name}`;\n if (spec === undefined || (spec as unknown) === null) return [`${owner} has no spec: a quota has no defaults`];\n const problems: string[] = [];\n const missing = (part: string): void => {\n problems.push(`${owner} does not declare ${part}: a quota has no defaults`);\n };\n let limit: number | undefined;\n if (spec.limit === undefined) missing(\"its limit (limit)\");\n else if (!safely(isCount, spec.limit)) problems.push(`${owner}'s limit is not a count`);\n else if (!finiteAbove(spec.limit)) problems.push(`${owner}'s limit is not a finite count above zero`);\n else limit = countOf(spec.limit);\n if (spec.reserve === undefined) missing(\"its reserve (reserve), 0 for no reserve\");\n else if (!safely(isCount, spec.reserve)) problems.push(`${owner}'s reserve is not a count`);\n else if (!atLeastZero(spec.reserve)) problems.push(`${owner}'s reserve is not a finite count of 0 or more`);\n else if (limit !== undefined && countOf(spec.reserve) >= limit) problems.push(`${owner}'s reserve is not less than its limit`);\n const window = spec.window as LooseWindow | undefined;\n if (window === undefined || (window as unknown) === null) missing(\"its window (window)\");\n else if (window.kind === \"rolling\") {\n if (window.span === undefined) missing(\"the span of its window (window.span)\");\n else if (!safely(isTime, window.span)) problems.push(`${owner}'s span is not a time`);\n else if (!finiteAbove(window.span)) problems.push(`${owner}'s span is not a finite time above zero`);\n if (window.buckets === undefined) missing(\"the count of buckets of its window (window.buckets)\");\n else if (!safely(isCount, window.buckets)) problems.push(`${owner}'s buckets is not a count`);\n else if (!wholeCount(window.buckets) || countOf(window.buckets) > MAX_BUCKETS)\n problems.push(`${owner}'s buckets is not a whole count from 1 to ${String(MAX_BUCKETS)}`);\n } else if (window.kind === \"calendar\") {\n if (window.unit === undefined) missing(\"the unit of its window (window.unit)\");\n else if (window.unit !== \"day\" && window.unit !== \"month\") problems.push(`${owner}'s unit is not day or month`);\n if (window.zone === undefined) missing(\"the time zone of its window (window.zone)\");\n else if (typeof window.zone !== \"string\" || localTime(0, window.zone) === undefined)\n problems.push(`${owner}'s zone is not an IANA time zone: ${String(window.zone)}`);\n if (window.start === undefined) missing(\"the time of day that starts its window (window.start), 0 h for midnight\");\n else if (!safely(isTime, window.start)) problems.push(`${owner}'s start is not a time`);\n else if (!atLeastZero(window.start) || !Number.isInteger(milliseconds(window.start)) || milliseconds(window.start) >= DAY_MS)\n problems.push(`${owner}'s start is not a whole count of milliseconds from 0 to less than 24 h`);\n } else problems.push(`${owner}'s window is not rolling or calendar`);\n return problems;\n};\n\n/** This function gives the rule of a quota spec. It throws an error with the problems of a spec that has a problem. */\nexport const quotaRule = (name: string, spec: QuotaSpec): QuotaRule => {\n const problems = quotaProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { window } = spec;\n return {\n limit: countOf(spec.limit),\n reserve: countOf(spec.reserve),\n window:\n window.kind === \"rolling\"\n ? { kind: \"rolling\", span: milliseconds(window.span), buckets: countOf(window.buckets) }\n : { kind: \"calendar\", unit: window.unit, zone: window.zone, start: milliseconds(window.start) },\n };\n};\n\n/** The buckets of a window: the bucket of an instant, and the test of a bucket. */\ninterface Buckets {\n /** This function gives the start and the end of the bucket of the instant `t`. */\n bucket(t: number): readonly [start: number, end: number];\n /**\n * This function gives the test of the buckets that count at the instant `t`. A bucket of a later\n * window counts too: after a step back of the clock, the takes of that window still count.\n */\n counting(t: number): (start: number) => boolean;\n /** This function gives the instant at which the bucket that starts at `start` stops counting. */\n freeAt(start: number): number;\n}\n\n/** This function gives the calendar window of the instant `t`: its start, and the start of the next window. */\nconst calendarOf = (unit: \"day\" | \"month\", zone: string, start: number, t: number): readonly [number, number] => {\n const local = localTime(t, zone);\n if (local === undefined) throw new RangeError(`the instant ${String(t)} is not a date in the zone ${zone}`);\n const { year, month, day } = local;\n // the start of the window that is `back` windows before the window of the date of `t`\n const startOf = (back: number): number => {\n const wall = (unit === \"day\" ? Date.UTC(year, month - 1, day - back) : Date.UTC(year, month - 1 - back, 1)) + start;\n const instant = firstInstantOf(wall, zone);\n if (instant === undefined) throw new RangeError(`the clock of ${zone} does not show or skip the local time ${iso(wall)}`);\n return instant;\n };\n const first = startOf(0);\n return first <= t ? [first, startOf(-1)] : [startOf(1), first];\n};\n\nconst bucketsOf = (window: QuotaRule[\"window\"]): Buckets => {\n if (window.kind === \"rolling\") {\n const { span } = window;\n const size = Math.ceil(span / window.buckets);\n return {\n bucket: (t) => {\n const start = Math.floor(t / size) * size;\n return [start, start + size];\n },\n counting: (t) => (start) => start + size + span > t,\n freeAt: (start) => start + size + span,\n };\n }\n const { unit, zone, start } = window;\n return {\n bucket: (t) => calendarOf(unit, zone, start, t),\n // only the windows before the window of `t` stop counting\n counting: (t) => {\n const [first] = calendarOf(unit, zone, start, t);\n return (bucket) => bucket >= first;\n },\n freeAt: (bucket) => calendarOf(unit, zone, start, bucket)[1],\n };\n};\n\n/**\n * This function gives the record of a store. A value that is not a record gives an empty record.\n * The function removes each item that is not valid and keeps the other items, thus the count stays\n * as high as the record lets it. It adds the items of one bucket together.\n */\nconst recordOf = (value: unknown): QuotaRecord => {\n if (typeof value !== \"object\" || value === null) return { spent: [] };\n const { spent, blockedUntil, readAt } = value as { spent?: unknown; blockedUntil?: unknown; readAt?: unknown };\n const counts = new Map<number, number>();\n if (Array.isArray(spent))\n for (const item of spent as unknown[]) {\n if (!Array.isArray(item) || item.length !== 2) continue;\n const [start, units] = item as unknown[];\n if (isInstant(start) && typeof units === \"number\" && Number.isFinite(units) && units > 0) counts.set(start, (counts.get(start) ?? 0) + units);\n }\n const items = [...counts].sort((a, b) => a[0] - b[0]);\n return {\n spent: items,\n ...(isInstant(blockedUntil) ? { blockedUntil } : {}),\n ...(isInstant(readAt) ? { readAt } : {}),\n };\n};\n\n/** This function removes the buckets that do not count at the instant `t`, an ended refusal, and a reading that no give-back can meet. */\nconst prune = (buckets: Buckets, record: QuotaRecord, t: number): QuotaRecord => {\n const counts = buckets.counting(t);\n const { blockedUntil, readAt } = record;\n return {\n spent: record.spent.filter(([start]) => counts(start)),\n ...(blockedUntil !== undefined && blockedUntil > t ? { blockedUntil } : {}),\n // a give-back changes only a bucket that counts, and each such bucket starts after the bucket of an older reading\n ...(readAt !== undefined && counts(buckets.bucket(readAt)[0]) ? { readAt } : {}),\n };\n};\n\nconst usedOf = (record: QuotaRecord): number => record.spent.reduce((sum, [, units]) => sum + units, 0);\n\n/** This function adds units to the bucket of the instant `t`. */\nconst add = (buckets: Buckets, record: QuotaRecord, t: number, units: number): QuotaRecord => {\n const [start] = buckets.bucket(t);\n let found = false;\n const spent = record.spent.map(([at, count]): readonly [number, number] => {\n if (at !== start) return [at, count];\n found = true;\n return [at, count + units];\n });\n if (!found) spent.push([start, units]);\n spent.sort((a, b) => a[0] - b[0]);\n return { ...record, spent };\n};\n\n/** This function gives the instant at which `need` units of the oldest buckets stop counting. */\nconst freeTime = (buckets: Buckets, record: QuotaRecord, need: number): number | undefined => {\n let freed = 0;\n for (const [start, units] of record.spent) {\n freed += units;\n if (!over(need, freed)) return buckets.freeAt(start);\n }\n return undefined;\n};\n\nconst stateOf = (rule: QuotaRule, buckets: Buckets, record: QuotaRecord, t: number): QuotaState => {\n const used = usedOf(record);\n const oldest = record.spent[0];\n const { blockedUntil } = record;\n return {\n at: t,\n used,\n left: blockedUntil === undefined ? Math.max(0, rule.limit - rule.reserve - used) : 0,\n ...(oldest === undefined ? {} : { resetAt: buckets.freeAt(oldest[0]) }),\n ...(blockedUntil === undefined ? {} : { blockedUntil }),\n };\n};\n\n/** This function checks the units of a take or of a give-back: a finite count of 0 or more. */\nconst checkUnits = (units: unknown): number => {\n if (typeof units !== \"number\" || !Number.isFinite(units) || units < 0) throw new RangeError(`the units of a quota are not a finite count of 0 or more: ${String(units)}`);\n return units;\n};\n\n/** This function checks an event before a store gets it, thus a store does not start a change for an event that is not valid. */\nconst checkEvent = (event: QuotaEvent): void => {\n if (event.type === \"take\") checkUnits(event.units);\n else if (event.type === \"give-back\") {\n checkUnits(event.units);\n if (!isInstant(event.at)) throw new RangeError(`the instant of a give-back is not a date: ${String(event.at)}`);\n }\n};\n\n/**\n * This function is the pure step of a quota. It reads the stored record of one key at the instant\n * `instant`, applies the event, and gives the next record and the state. It removes what does not\n * count at the instant first. Only a take can be refused, and a refusal counts nothing.\n * - A take of 0 units is permitted and counts nothing, also while the provider refuses the key.\n * - A take over the capacity is refused with the cause `capacity`.\n * - While the provider refuses the key, a take is refused with the cause `provider`. Its `resetAt`\n * is the end of that refusal, or a later instant when the window has room for the units.\n * - A take over the room of the window is refused with the cause `limit`, until enough of the\n * oldest units stop counting.\n *\n * It throws a `RangeError` for an instant that is not a date, and for units that are not a finite\n * count of 0 or more.\n */\nexport function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: Extract<QuotaEvent, { type: \"take\" }>): QuotaTakeStep;\nexport function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep;\nexport function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep {\n if (!isInstant(instant)) throw new RangeError(`the instant of a quota step is not a date: ${String(instant)}`);\n checkEvent(event);\n const buckets = bucketsOf(rule.window);\n const record = prune(buckets, recordOf(stored), instant);\n const done = (next: QuotaRecord): QuotaStep => ({ record: next, state: stateOf(rule, buckets, next, instant) });\n switch (event.type) {\n case \"read\":\n return done(record);\n case \"note\": {\n let next = record;\n const { remaining, resetAt } = event.reading;\n if (typeof remaining === \"number\" && Number.isFinite(remaining) && remaining >= 0) {\n const more = rule.limit - remaining - usedOf(next);\n if (over(more, 0)) next = add(buckets, next, instant, more);\n next = { ...next, readAt: Math.max(next.readAt ?? instant, instant) };\n }\n const exhausted = remaining === undefined || remaining <= 0;\n if (exhausted && isInstant(resetAt) && resetAt > instant)\n next = { ...next, blockedUntil: Math.max(next.blockedUntil ?? resetAt, resetAt) };\n return done(next);\n }\n case \"give-back\": {\n const { units, at } = event;\n if (units === 0 || (record.readAt !== undefined && record.readAt >= at)) return done(record);\n const [start] = buckets.bucket(at);\n if (!record.spent.some(([bucket]) => bucket === start)) return done(record);\n const spent: (readonly [number, number])[] = [];\n for (const [bucket, count] of record.spent) {\n const left = bucket === start ? count - Math.min(units, count) : count;\n if (over(left, 0)) spent.push([bucket, left]);\n }\n return done({ ...record, spent });\n }\n case \"take\": {\n const { units } = event;\n const allowed = rule.limit - rule.reserve;\n const refuse = (verdict: QuotaRefused): QuotaTakeStep => ({ record, state: verdict.state, verdict });\n const state = stateOf(rule, buckets, record, instant);\n if (units === 0) return { record, state, verdict: { allowed: true, state } };\n if (over(units, allowed)) return refuse({ allowed: false, cause: \"capacity\", units, capacity: allowed, state });\n const used = usedOf(record);\n // the need is not more than the units of the window, because the units are not over the capacity\n const free = over(used + units, allowed) ? (freeTime(buckets, record, used + units - allowed) ?? buckets.bucket(instant)[1]) : undefined;\n const wait = (cause: \"limit\" | \"provider\", resetAt: number): QuotaTakeStep =>\n refuse({ allowed: false, cause, resetAt, retryAfter: { value: resetAt - instant, unit: \"ms\" }, state });\n if (record.blockedUntil !== undefined) return wait(\"provider\", Math.max(record.blockedUntil, free ?? record.blockedUntil));\n if (free !== undefined) return wait(\"limit\", free);\n const next = done(add(buckets, record, instant, units));\n return { ...next, verdict: { allowed: true, state: next.state } };\n }\n }\n}\n\n/** A quota answer is a value at once for a store that answers at once, else a promise. */\nexport type QuotaAnswer<Sync extends boolean, T> = Sync extends true ? T : Promise<T>;\n\n/** A quota change is what a step gives a store: the record to keep, and the result for the caller. */\nexport interface QuotaChange<T> {\n readonly record: QuotaRecord;\n readonly result: T;\n}\n\n/**\n * A quota store keeps the record of each quota and key, and it changes one record in one atomic\n * step. Thus two takes of one key do not read the same record. A store of this process can answer\n * at once (`sync: true`), for example a store in memory or in SQLite. A store that the replicas\n * share answers with a promise (`sync: false`).\n */\nexport interface QuotaStore<Sync extends boolean = boolean> {\n readonly sync: Sync;\n /**\n * This method gives `step` the stored record of the quota and the key, or undefined for a new key.\n * It keeps the record that `step` gives, and it gives the result. The record of a new key is\n * empty: a store can remove a key whose record has no item and no instant. A store can call\n * `step` again, for example after a conflict of a write. Thus `step` must have no other effect.\n */\n change<T>(quota: string, key: string, step: (stored: unknown) => QuotaChange<T>): QuotaAnswer<Sync, T>;\n}\n\n/** A memory quota store is the store of one process. Its records are in memory. */\nexport interface MemoryQuotaStore extends QuotaStore<true> {\n /** This method gives the count of keys that the store holds for a quota. */\n size(quota: string): number;\n}\n\n/** This function tells if a record is equal to the record of a new key. */\nconst isEmpty = (record: QuotaRecord): boolean => record.spent.length === 0 && record.blockedUntil === undefined && record.readAt === undefined;\n\n/**\n * This function makes a store of records in memory. Each quota of one process can share it, and it\n * keeps the records of each quota apart. It removes a key when its record is equal to the record\n * of a new key. It does not sweep the other keys: use it for a set of keys with a bound, for\n * example the accounts of an API.\n */\nexport const memoryQuotaStore = (): MemoryQuotaStore => {\n const tables = new Map<string, Map<string, QuotaRecord>>();\n return {\n sync: true,\n change(quota, key, step) {\n let table = tables.get(quota);\n if (table === undefined) {\n table = new Map();\n tables.set(quota, table);\n }\n const { record, result } = step(table.get(key));\n if (isEmpty(record)) table.delete(key);\n else table.set(key, record);\n if (table.size === 0) tables.delete(quota);\n return result;\n },\n size(quota) {\n return tables.get(quota)?.size ?? 0;\n },\n };\n};\n\n/** A keyed quota is the runtime of one quota: its spec, its rule in numbers, its store and its wall clock. */\nexport interface KeyedQuota<Sync extends boolean = boolean> {\n /** This name is the quota. A store keeps the keys of each quota apart. */\n readonly name: string;\n readonly spec: QuotaSpec;\n readonly rule: QuotaRule;\n /** True: each method gives its answer at once. False: each method gives a promise. */\n readonly sync: Sync;\n /** This method counts `units` units (1 when absent) for a call of the key that starts at this instant, or refuses the call. */\n take(key: string, units?: number): QuotaAnswer<Sync, QuotaVerdict>;\n /** This method adds what an answer of the provider tells. The count can only become larger. */\n note(key: string, reading: QuotaReading): QuotaAnswer<Sync, QuotaState>;\n /** This method removes `units` that a take counted at the instant `at`, for a call that did not start. */\n giveBack(key: string, units: number, at: number): QuotaAnswer<Sync, QuotaState>;\n /** This method gives the state of the key, and changes nothing. */\n state(key: string): QuotaAnswer<Sync, QuotaState>;\n}\n\n/** This function tells if a value is a promise. */\nconst isPromise = (value: unknown): value is Promise<unknown> =>\n typeof value === \"object\" && value !== null && typeof (value as { then?: unknown }).then === \"function\";\n\n/**\n * This function makes the runtime of a quota from its spec, its store and a wall clock. It refuses\n * a spec with a problem, because a quota has no defaults. It reads the instant inside the change of\n * the store, thus a store that waits for a lock reads the instant after the wait.\n * - With a store that answers at once, each method answers at once. A `RangeError` throws, and a\n * store that gives a promise throws an error.\n * - With a store that answers with a promise, each method gives a promise. A `RangeError` rejects.\n */\nexport function keyedQuota<Sync extends boolean>(\n name: string,\n spec: QuotaSpec,\n store: QuotaStore<Sync>,\n clock: Pick<WallClock, \"time\" | \"now\">,\n): KeyedQuota<Sync> {\n const rule = quotaRule(name, spec);\n if (clock.time !== \"wall\") throw new Error(`quota ${name} needs a wall clock, which gives the instant: a calendar window needs civil time`);\n const answer = <T>(compute: () => T | Promise<T>): QuotaAnswer<Sync, T> => {\n if (!store.sync) return (async () => compute())() as QuotaAnswer<Sync, T>;\n const value = compute();\n if (isPromise(value)) {\n // the change of the store happened: its promise has the result, and its rejection is not left unhandled\n value.then(undefined, () => {});\n throw new Error(`quota ${name} has a store that says it answers at once, but its change gave a promise`);\n }\n return value as QuotaAnswer<Sync, T>;\n };\n const change = <T>(key: string, event: QuotaEvent, pick: (step: QuotaStep) => T): QuotaAnswer<Sync, T> =>\n answer(() => {\n checkEvent(event);\n return store.change(name, key, (stored) => {\n const step = quotaStep(rule, stored, clock.now(), event);\n return { record: step.record, result: pick(step) };\n }) as T | Promise<T>;\n });\n const verdictOf = (step: QuotaStep): QuotaVerdict => step.verdict as QuotaVerdict;\n const stateOfStep = (step: QuotaStep): QuotaState => step.state;\n const { window } = spec;\n return {\n name,\n spec: {\n limit: { ...spec.limit },\n reserve: { ...spec.reserve },\n window:\n window.kind === \"rolling\"\n ? { kind: \"rolling\", span: { ...window.span }, buckets: { ...window.buckets } }\n : { kind: \"calendar\", unit: window.unit, zone: window.zone, start: { ...window.start } },\n },\n rule,\n sync: store.sync,\n take: (key, units = 1) => change(key, { type: \"take\", units }, verdictOf),\n note: (key, reading) => change(key, { type: \"note\", reading: { ...reading } }, stateOfStep),\n giveBack: (key, units, at) => change(key, { type: \"give-back\", units, at }, stateOfStep),\n state: (key) => change(key, { type: \"read\" }, stateOfStep),\n };\n}\n\n/** A quota part is one take of a multi-quota take: a quota, a key, and the units of the take. */\nexport interface QuotaPart<Sync extends boolean = boolean> {\n readonly quota: KeyedQuota<Sync>;\n readonly key: string;\n readonly units: number;\n}\n\n/**\n * A quotas verdict is the answer of a take of several quotas, all or none. Each state is the state\n * of its part after the take, and after the give-back of a refused take.\n * - A permitted take counted the units of each part.\n * - A refused take counted nothing. `refusal` is the refusal of the part `index`: the first\n * capacity refusal, else the wait refusal with the latest `resetAt`.\n */\nexport type QuotasVerdict =\n | { readonly allowed: true; readonly states: readonly QuotaState[] }\n | { readonly allowed: false; readonly index: number; readonly refusal: QuotaRefused; readonly states: readonly QuotaState[] };\n\n/** The options of `takeQuotas`. */\nexport interface TakeQuotasOptions {\n /**\n * This function gets each error of a give-back, with the index of its part. The units of that\n * part stay counted, thus its quota refuses sooner, not later. It gets the errors after the last\n * give-back, thus its own error stops no give-back. An error that it throws ends the take.\n */\n readonly onGiveBackError?: ((error: unknown, index: number) => void) | undefined;\n}\n\n/** A request of the walk of a multi-quota take: a call of one method of a quota. */\ntype Request = () => unknown;\n\n/** A walk gives a verdict or the error of a failed take, and the errors of the give-backs. */\ntype Walked = { readonly failures: readonly { readonly index: number; readonly error: unknown }[] } & (\n | { readonly verdict: QuotasVerdict }\n | { readonly error: unknown }\n);\n\n/** This function tells which refusal decides: a capacity refusal, else the latest `resetAt`. The first part wins a tie. */\nconst decisive = (verdicts: readonly QuotaVerdict[]): number => {\n let best = -1;\n for (let index = 0; index < verdicts.length; index += 1) {\n const verdict = verdicts[index]!;\n if (verdict.allowed) continue;\n const current = best < 0 ? undefined : (verdicts[best] as QuotaRefused);\n if (current === undefined) best = index;\n else if (current.cause === \"capacity\") continue;\n else if (verdict.cause === \"capacity\" || verdict.resetAt > current.resetAt) best = index;\n }\n return best;\n};\n\n/**\n * This walk takes each part in order, then gives back the counted parts of a refused or failed\n * take. The driver answers each request. A failed give-back does not stop the next give-backs.\n * The walk keeps its error, and the state of its part is the state after the take.\n */\nfunction* walk(parts: readonly QuotaPart[]): Generator<Request, Walked, unknown> {\n const verdicts: QuotaVerdict[] = [];\n const failures: { readonly index: number; readonly error: unknown }[] = [];\n /** This walk gives back the units of a part, and gives the state after the give-back, or after the take when the give-back fails. */\n function* giveBack(index: number): Generator<Request, QuotaState, unknown> {\n const verdict = verdicts[index]!;\n const part = parts[index]!;\n if (!verdict.allowed || part.units === 0) return verdict.state;\n try {\n return (yield () => part.quota.giveBack(part.key, part.units, verdict.state.at)) as QuotaState;\n } catch (error) {\n failures.push({ index, error });\n return verdict.state;\n }\n }\n try {\n for (const part of parts) verdicts.push((yield () => part.quota.take(part.key, part.units)) as QuotaVerdict);\n } catch (error) {\n // a failed take of a part: give back the parts before it, then give its error\n for (let index = 0; index < verdicts.length; index += 1) yield* giveBack(index);\n return { error, failures };\n }\n const index = decisive(verdicts);\n if (index < 0) return { verdict: { allowed: true, states: verdicts.map((verdict) => verdict.state) }, failures };\n const states: QuotaState[] = [];\n for (let at = 0; at < parts.length; at += 1) states.push(yield* giveBack(at));\n return { verdict: { allowed: false, index, refusal: verdicts[index] as QuotaRefused, states }, failures };\n}\n\n/** This function gives each error of a give-back to the option, then gives the verdict or throws the error of the take. */\nconst finish = (walked: Walked, options: TakeQuotasOptions | undefined): QuotasVerdict => {\n for (const failure of walked.failures) options?.onGiveBackError?.(failure.error, failure.index);\n if (\"error\" in walked) throw walked.error;\n return walked.verdict;\n};\n\nconst driveSync = (parts: readonly QuotaPart[], options: TakeQuotasOptions | undefined): QuotasVerdict => {\n const steps = walk(parts);\n let next = steps.next();\n while (!next.done) {\n let value: unknown;\n let failure: { error: unknown } | undefined;\n try {\n value = next.value();\n } catch (error) {\n failure = { error };\n }\n next = failure === undefined ? steps.next(value) : steps.throw(failure.error);\n }\n return finish(next.value, options);\n};\n\nconst driveAsync = async (parts: readonly QuotaPart[], options: TakeQuotasOptions | undefined): Promise<QuotasVerdict> => {\n const steps = walk(parts);\n let next = steps.next();\n while (!next.done) {\n let value: unknown;\n let failure: { error: unknown } | undefined;\n try {\n value = await next.value();\n } catch (error) {\n failure = { error };\n }\n next = failure === undefined ? steps.next(value) : steps.throw(failure.error);\n }\n return finish(next.value, options);\n};\n\n/**\n * This function takes from several quotas, all or none. It takes each part in order. When a part\n * is refused, the next parts still answer, and each part that counted gives back its units. Thus\n * the refusal tells the latest instant at which all parts can have room. When a take fails, the\n * parts before it give back their units, and the error throws.\n *\n * A failed give-back does not change the verdict and does not stop the other give-backs. The units\n * of its part stay counted, and `options.onGiveBackError` gets its error.\n *\n * With quotas that answer at once, it answers at once. Else it gives a promise.\n */\nexport function takeQuotas(parts: readonly QuotaPart<true>[], options?: TakeQuotasOptions): QuotasVerdict;\nexport function takeQuotas(parts: readonly QuotaPart[], options?: TakeQuotasOptions): QuotasVerdict | Promise<QuotasVerdict>;\nexport function takeQuotas(parts: readonly QuotaPart[], options?: TakeQuotasOptions): QuotasVerdict | Promise<QuotasVerdict> {\n return parts.every((part) => part.quota.sync) ? driveSync(parts, options) : driveAsync(parts, options);\n}\n"],"mappings":";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