@mark1russell7/service 0.8.13 → 0.8.15

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.
@@ -0,0 +1,883 @@
1
+ import { _ as wholeCount, a as freeAt, c as isTime, d as longestRetryAfter, f as milliseconds, g as unitsOf, h as safely, i as finiteAbove, l as limitRule, n as countOf, p as overCapacity, r as decide, s as isCount, u as limiterProblems } from "./policy-UYALkqVq.js";
2
+ import { convertExact, rationals } from "@mark1russell7/quantity";
3
+ import { firstInstantOf, localTime } from "@mark1russell7/algebra/clock";
4
+ // src/limiter/store.ts
5
+ const ms = (value) => ({
6
+ value,
7
+ unit: "ms"
8
+ });
9
+ /**
10
+ * This function makes the store of one replica. It reads time only through the clock. Thus a step
11
+ * of the wall clock does not move a count, and a fake clock gives exact decisions in a test.
12
+ * - The eviction is exact. A key whose bucket is full again, or whose window has no take, is equal
13
+ * to a new key. The store removes it at its next take, or at a sweep.
14
+ * - The count of keys has a bound. At the cap, a take of a new key sweeps the table, but only when
15
+ * a held key can be free. Each sweep reads each key one time. When no key is free, the store
16
+ * refuses the new key with the cause `cap`. Its `retryAfter` is at most the time until the
17
+ * earliest held key is free, and that time is at most `idleSpan` of the policy.
18
+ */
19
+ const memoryStore = (clock) => {
20
+ const tables = /* @__PURE__ */ new Map();
21
+ const sweep = (table, rule, now) => {
22
+ let next = Number.POSITIVE_INFINITY;
23
+ for (const [key, state] of table.states) {
24
+ const free = freeAt(rule, state);
25
+ if (free <= now) table.states.delete(key);
26
+ else next = Math.min(next, free);
27
+ }
28
+ table.next = next;
29
+ };
30
+ return {
31
+ kind: "local",
32
+ take({ limiter, key, rule, maxKeys, units }) {
33
+ const n = unitsOf(units);
34
+ const over = overCapacity(rule, n);
35
+ if (over !== void 0) return over;
36
+ const now = clock.now();
37
+ let table = tables.get(limiter);
38
+ if (table === void 0) {
39
+ table = {
40
+ states: /* @__PURE__ */ new Map(),
41
+ next: Number.POSITIVE_INFINITY
42
+ };
43
+ tables.set(limiter, table);
44
+ }
45
+ let state = table.states.get(key);
46
+ if (state !== void 0 && freeAt(rule, state) <= now) {
47
+ table.states.delete(key);
48
+ state = void 0;
49
+ }
50
+ if (state === void 0 && table.states.size >= maxKeys) {
51
+ if (table.next <= now) sweep(table, rule, now);
52
+ if (table.states.size >= maxKeys) return {
53
+ allowed: false,
54
+ retryAfter: ms(table.next - now),
55
+ cause: "cap"
56
+ };
57
+ }
58
+ const step = decide(rule, state, now, n);
59
+ if (state === void 0) {
60
+ table.states.set(key, step.state);
61
+ table.next = Math.min(table.next, freeAt(rule, step.state));
62
+ } else table.states.set(key, step.state);
63
+ return step.decision;
64
+ },
65
+ size(limiter) {
66
+ return tables.get(limiter)?.states.size ?? 0;
67
+ }
68
+ };
69
+ };
70
+ /** This function gives the text of a failure. */
71
+ const failureOf = (error) => error instanceof Error ? error.message : String(error);
72
+ function keyedLimiter(name, spec, store) {
73
+ const problems = limiterProblems(name, spec);
74
+ if (problems.length > 0) throw new Error(problems.join("; "));
75
+ if (store.kind !== spec.store.kind) throw new Error(`limiter ${name} declares a ${spec.store.kind} store, but the store that it got is ${store.kind}`);
76
+ const rule = limitRule(spec.policy);
77
+ const maxKeys = rationals.toNumber(convertExact(rationals.fromNumber(spec.evict.maxKeys.value), spec.evict.maxKeys.unit, "count"));
78
+ const onStoreFailure = spec.store.kind === "shared" ? spec.store.onStoreFailure : void 0;
79
+ const closedAfter = longestRetryAfter(spec.policy);
80
+ const take = async (key, units) => {
81
+ const n = unitsOf(units);
82
+ const over = overCapacity(rule, n);
83
+ if (over !== void 0) return over;
84
+ const request = {
85
+ limiter: name,
86
+ key,
87
+ rule,
88
+ maxKeys,
89
+ units: n
90
+ };
91
+ if (onStoreFailure === void 0) return store.take(request);
92
+ try {
93
+ return await store.take(request);
94
+ } catch (error) {
95
+ const failure = failureOf(error);
96
+ if (onStoreFailure === "open") return {
97
+ allowed: true,
98
+ remaining: 0,
99
+ failure
100
+ };
101
+ return {
102
+ allowed: false,
103
+ retryAfter: { ...closedAfter },
104
+ cause: "store",
105
+ failure
106
+ };
107
+ }
108
+ };
109
+ const tryTakeSync = (key, units) => {
110
+ if (store.kind === "shared") throw new Error(`limiter ${name} has a shared store, which decides in a promise: tryTakeSync needs a memory store, thus use take()`);
111
+ const n = unitsOf(units);
112
+ const over = overCapacity(rule, n);
113
+ if (over !== void 0) return over;
114
+ const decision = store.take({
115
+ limiter: name,
116
+ key,
117
+ rule,
118
+ maxKeys,
119
+ units: n
120
+ });
121
+ if (isPromise$1(decision)) {
122
+ decision.then(void 0, () => {});
123
+ throw new Error(`limiter ${name} has a store whose take gives a promise: tryTakeSync needs a memory store, thus use take()`);
124
+ }
125
+ return decision;
126
+ };
127
+ return {
128
+ name,
129
+ spec: {
130
+ key: spec.key,
131
+ policy: { ...spec.policy },
132
+ store: { ...spec.store },
133
+ evict: { maxKeys: { ...spec.evict.maxKeys } }
134
+ },
135
+ rule,
136
+ maxKeys,
137
+ take,
138
+ tryTakeSync
139
+ };
140
+ }
141
+ /** This function tells if a decision of a store is a promise. */
142
+ const isPromise$1 = (value) => typeof value.then === "function";
143
+ // src/limiter/machine.ts
144
+ const t = (id, from, on, to, extra = {}) => ({
145
+ id,
146
+ from,
147
+ on,
148
+ to,
149
+ ...extra
150
+ });
151
+ const count = (key) => ({
152
+ key,
153
+ scope: "limiter",
154
+ unit: "count",
155
+ default: null
156
+ });
157
+ /** These are the states of a key that a store can hold. A store fails in each of them. */
158
+ const HELD = [
159
+ "new",
160
+ "open",
161
+ "limited"
162
+ ];
163
+ /** These are the parts of each document of a limiter that do not change with its policy. */
164
+ const COMMON = {
165
+ format: "mark1russell7.machine/1",
166
+ layer: "self",
167
+ version: "0.1.0",
168
+ sources: [
169
+ {
170
+ ref: "packages/service/src/limiter (the runtime implements this document: decide, memoryStore, keyedLimiter)",
171
+ rung: "implemented"
172
+ },
173
+ {
174
+ ref: "RFC 6585 §4: 429 Too Many Requests, which can carry Retry-After",
175
+ rung: "normative"
176
+ },
177
+ {
178
+ ref: "RFC 9110 §10.2.3: Retry-After, as delay-seconds or an HTTP-date",
179
+ rung: "normative"
180
+ }
181
+ ],
182
+ conditions: {
183
+ "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",
184
+ "store.shared": "the counts are in a store that the replicas share: one atomic step on the clock of the store decides each take"
185
+ },
186
+ states: {
187
+ new: {
188
+ initial: true,
189
+ note: "the store holds no state for the key, or a state equal to a new key. The store can remove the key"
190
+ },
191
+ open: { note: "the key holds a count, and its next take is permitted" },
192
+ limited: { note: "the next take is refused with the cause limit, until a unit is back" }
193
+ }
194
+ };
195
+ /** These are the events of each document of a limiter. */
196
+ const EVENTS = {
197
+ take: {
198
+ kind: "app",
199
+ note: "one call of take(key): one request of the key. A permitted take uses one unit"
200
+ },
201
+ "unit.back": {
202
+ kind: "timer",
203
+ note: "the next take of a limited key is permitted again"
204
+ },
205
+ idle: {
206
+ kind: "timer",
207
+ note: "the key is equal to a new key. The store can remove it, and no decision changes"
208
+ },
209
+ "store.fail": {
210
+ kind: "local",
211
+ note: "a shared store fails the take. The state of the key does not change"
212
+ }
213
+ };
214
+ /** These are the knobs of each document of a limiter that do not change with its policy. */
215
+ const KNOBS = {
216
+ max_keys: count("limiters.<name>.evict.maxKeys"),
217
+ on_store_failure: {
218
+ key: "limiters.<name>.store.onStoreFailure",
219
+ scope: "limiter",
220
+ unit: null,
221
+ default: null
222
+ }
223
+ };
224
+ /**
225
+ * These are the transitions of each document of a limiter that do not change with its policy. They
226
+ * are the refusal of a limited key, a new key at the cap of keys, and a failure of a shared store.
227
+ */
228
+ const COMMON_TRANSITIONS = [
229
+ t("refuse", "limited", "take", "limited", {
230
+ emits: ["429 limit"],
231
+ 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"
232
+ }),
233
+ t("cap", "new", "take", "new", {
234
+ guard: "the store holds max_keys keys for the limiter, and no held key is equal to a new key",
235
+ emits: ["429 cap"],
236
+ note: "Retry-After is the time until the earliest held key is free: at most the idle span. A held key keeps its count"
237
+ }),
238
+ ...HELD.map((state) => t(`store-failed-${state}`, state, "store.fail", state, {
239
+ guard: "the store is shared",
240
+ emits: ["allow, or 429 store"],
241
+ 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"
242
+ }))
243
+ ];
244
+ /**
245
+ * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds
246
+ * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time
247
+ * for the key: when its bucket is full again.
248
+ * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.
249
+ * - A refused take waits until one token is back: at most one interval. That interval is the
250
+ * longest `Retry-After` of the policy (`retry_after@limiter` of the law).
251
+ * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That
252
+ * span is the idle span, and the longest wait of a new key at the cap of keys
253
+ * (`retry_after_at_cap@limiter`).
254
+ */
255
+ const TOKEN_BUCKET_MACHINE = {
256
+ ...COMMON,
257
+ id: "service.machine.limiter.token-bucket",
258
+ title: "A token bucket of one key of the keyed limiter",
259
+ events: EVENTS,
260
+ knobs: {
261
+ rate: {
262
+ key: "limiters.<name>.policy.rate",
263
+ scope: "limiter",
264
+ unit: "count/s",
265
+ default: null
266
+ },
267
+ burst: count("limiters.<name>.policy.burst"),
268
+ ...KNOBS
269
+ },
270
+ timers: {
271
+ token: {
272
+ duration: {
273
+ expr: "1 / rate",
274
+ unit: "s"
275
+ },
276
+ early: {
277
+ expr: "1 / rate",
278
+ unit: "s"
279
+ },
280
+ arms: ["enter:limited"],
281
+ cancels: ["idle"],
282
+ fires: "unit.back",
283
+ 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"
284
+ },
285
+ full: {
286
+ duration: {
287
+ expr: "burst / rate",
288
+ unit: "s"
289
+ },
290
+ early: {
291
+ expr: "(burst - 1) / rate",
292
+ unit: "s"
293
+ },
294
+ arms: ["take"],
295
+ fires: "idle",
296
+ note: "the bucket is full again from one to burst intervals after a permitted take. A refused take does not move it"
297
+ }
298
+ },
299
+ transitions: [
300
+ t("first", "new", "take", "open", {
301
+ guard: "burst > 1",
302
+ emits: ["allow"]
303
+ }),
304
+ t("first-last", "new", "take", "limited", {
305
+ guard: "burst = 1",
306
+ emits: ["allow"]
307
+ }),
308
+ t("take", "open", "take", "open", {
309
+ guard: "a token remains after the take",
310
+ emits: ["allow"]
311
+ }),
312
+ t("take-last", "open", "take", "limited", {
313
+ guard: "the take uses the last token",
314
+ emits: ["allow"]
315
+ }),
316
+ ...COMMON_TRANSITIONS,
317
+ t("token-back", "limited", "unit.back", "open", {
318
+ timer: "token",
319
+ guard: "burst > 1"
320
+ }),
321
+ t("full", "open", "idle", "new", { timer: "full" }),
322
+ t("full-at-once", "limited", "idle", "new", {
323
+ timer: "full",
324
+ guard: "burst = 1: the one token is back when the bucket is full"
325
+ })
326
+ ]
327
+ };
328
+ /**
329
+ * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of
330
+ * each permitted take of the key in the window, and each take counts for one window from its time.
331
+ * - A take is permitted when fewer than `limit` takes are in the window.
332
+ * - A refused take waits until the oldest take leaves the window: at most one window. That window is
333
+ * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).
334
+ * - One window after the last take, no take is in the window, and the key is equal to a new key.
335
+ * That window is the idle span, and the longest wait of a new key at the cap of keys
336
+ * (`retry_after_at_cap@limiter`).
337
+ */
338
+ const SLIDING_WINDOW_MACHINE = {
339
+ ...COMMON,
340
+ id: "service.machine.limiter.sliding-window",
341
+ title: "A sliding window of one key of the keyed limiter",
342
+ events: EVENTS,
343
+ knobs: {
344
+ limit: count("limiters.<name>.policy.limit"),
345
+ window: {
346
+ key: "limiters.<name>.policy.window",
347
+ scope: "limiter",
348
+ unit: "s",
349
+ default: null
350
+ },
351
+ ...KNOBS
352
+ },
353
+ timers: {
354
+ oldest: {
355
+ duration: {
356
+ knob: "window",
357
+ unit: "s"
358
+ },
359
+ early: {
360
+ knob: "window",
361
+ unit: "s"
362
+ },
363
+ arms: ["enter:limited"],
364
+ cancels: ["idle"],
365
+ fires: "unit.back",
366
+ 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"
367
+ },
368
+ last: {
369
+ duration: {
370
+ knob: "window",
371
+ unit: "s"
372
+ },
373
+ arms: ["take"],
374
+ fires: "idle",
375
+ note: "the last permitted take leaves the window one window after its time. A refused take does not move it"
376
+ }
377
+ },
378
+ transitions: [
379
+ t("first", "new", "take", "open", {
380
+ guard: "limit > 1",
381
+ emits: ["allow"]
382
+ }),
383
+ t("first-last", "new", "take", "limited", {
384
+ guard: "limit = 1",
385
+ emits: ["allow"]
386
+ }),
387
+ t("take", "open", "take", "open", {
388
+ guard: "fewer than limit - 1 takes are in the window before the take",
389
+ emits: ["allow"]
390
+ }),
391
+ t("take-last", "open", "take", "limited", {
392
+ guard: "the take is the limit-th take in the window",
393
+ emits: ["allow"]
394
+ }),
395
+ ...COMMON_TRANSITIONS,
396
+ t("oldest-leaves", "limited", "unit.back", "open", {
397
+ timer: "oldest",
398
+ guard: "a later take stays in the window"
399
+ }),
400
+ t("last-leaves", "open", "idle", "new", { timer: "last" }),
401
+ t("all-leave", "limited", "idle", "new", {
402
+ timer: "last",
403
+ guard: "each take of the window has one time: limit = 1, or each take came at once"
404
+ })
405
+ ]
406
+ };
407
+ /** This function gives the machine document of the policy of a limiter. */
408
+ const limiterMachine = (policy) => policy.type === "token-bucket" ? TOKEN_BUCKET_MACHINE : SLIDING_WINDOW_MACHINE;
409
+ /**
410
+ * This function gives the state of a key of a store as its machine document names it, at the time
411
+ * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps
412
+ * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.
413
+ */
414
+ const limiterStateOf = (rule, state, now) => {
415
+ if (state === void 0 || freeAt(rule, state) <= now) return "new";
416
+ return decide(rule, state, now).decision.allowed ? "open" : "limited";
417
+ };
418
+ // src/limiter/quota.ts
419
+ const MAX_BUCKETS = 1e3;
420
+ const DAY_MS = 864e5;
421
+ /** The largest instant of a `Date`, in milliseconds from the epoch. */
422
+ const MAX_TIME = 864e13;
423
+ /**
424
+ * This slack is a part of a count. A comparison of counts permits it. The reason: a sum of units
425
+ * with a fraction is not exact in floating point, and 0.1 + 0.2 is more than 0.3.
426
+ */
427
+ const SLACK = 1e-9;
428
+ /** This function tells if `total` is over `bound` by more than the slack. */
429
+ const over = (total, bound) => total - bound > SLACK * Math.max(1, Math.abs(bound));
430
+ const isInstant = (value) => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_TIME;
431
+ const iso = (instant) => isInstant(instant) ? new Date(instant).toISOString() : String(instant);
432
+ const atLeastZero = (amount) => typeof amount.value === "number" && Number.isFinite(amount.value) && amount.value >= 0;
433
+ /**
434
+ * This function gives the problems of a quota spec. `keyedQuota` and `quotaRule` refuse a spec with
435
+ * a problem. A part that is absent is a problem, because a quota has no defaults.
436
+ */
437
+ const quotaProblems = (name, spec) => {
438
+ const owner = `quota ${name}`;
439
+ if (spec === void 0 || spec === null) return [`${owner} has no spec: a quota has no defaults`];
440
+ const problems = [];
441
+ const missing = (part) => {
442
+ problems.push(`${owner} does not declare ${part}: a quota has no defaults`);
443
+ };
444
+ let limit;
445
+ if (spec.limit === void 0) missing("its limit (limit)");
446
+ else if (!safely(isCount, spec.limit)) problems.push(`${owner}'s limit is not a count`);
447
+ else if (!finiteAbove(spec.limit)) problems.push(`${owner}'s limit is not a finite count above zero`);
448
+ else limit = countOf(spec.limit);
449
+ if (spec.reserve === void 0) missing("its reserve (reserve), 0 for no reserve");
450
+ else if (!safely(isCount, spec.reserve)) problems.push(`${owner}'s reserve is not a count`);
451
+ else if (!atLeastZero(spec.reserve)) problems.push(`${owner}'s reserve is not a finite count of 0 or more`);
452
+ else if (limit !== void 0 && countOf(spec.reserve) >= limit) problems.push(`${owner}'s reserve is not less than its limit`);
453
+ const window = spec.window;
454
+ if (window === void 0 || window === null) missing("its window (window)");
455
+ else if (window.kind === "rolling") {
456
+ if (window.span === void 0) missing("the span of its window (window.span)");
457
+ else if (!safely(isTime, window.span)) problems.push(`${owner}'s span is not a time`);
458
+ else if (!finiteAbove(window.span)) problems.push(`${owner}'s span is not a finite time above zero`);
459
+ if (window.buckets === void 0) missing("the count of buckets of its window (window.buckets)");
460
+ else if (!safely(isCount, window.buckets)) problems.push(`${owner}'s buckets is not a count`);
461
+ else if (!wholeCount(window.buckets) || countOf(window.buckets) > MAX_BUCKETS) problems.push(`${owner}'s buckets is not a whole count from 1 to ${String(MAX_BUCKETS)}`);
462
+ } else if (window.kind === "calendar") {
463
+ if (window.unit === void 0) missing("the unit of its window (window.unit)");
464
+ else if (window.unit !== "day" && window.unit !== "month") problems.push(`${owner}'s unit is not day or month`);
465
+ if (window.zone === void 0) missing("the time zone of its window (window.zone)");
466
+ else if (typeof window.zone !== "string" || localTime(0, window.zone) === void 0) problems.push(`${owner}'s zone is not an IANA time zone: ${String(window.zone)}`);
467
+ if (window.start === void 0) missing("the time of day that starts its window (window.start), 0 h for midnight");
468
+ else if (!safely(isTime, window.start)) problems.push(`${owner}'s start is not a time`);
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
+ } else problems.push(`${owner}'s window is not rolling or calendar`);
471
+ return problems;
472
+ };
473
+ /** This function gives the rule of a quota spec. It throws an error with the problems of a spec that has a problem. */
474
+ const quotaRule = (name, spec) => {
475
+ const problems = quotaProblems(name, spec);
476
+ if (problems.length > 0) throw new Error(problems.join("; "));
477
+ const { window } = spec;
478
+ return {
479
+ limit: countOf(spec.limit),
480
+ reserve: countOf(spec.reserve),
481
+ window: window.kind === "rolling" ? {
482
+ kind: "rolling",
483
+ span: milliseconds(window.span),
484
+ buckets: countOf(window.buckets)
485
+ } : {
486
+ kind: "calendar",
487
+ unit: window.unit,
488
+ zone: window.zone,
489
+ start: milliseconds(window.start)
490
+ }
491
+ };
492
+ };
493
+ /** This function gives the calendar window of the instant `t`: its start, and the start of the next window. */
494
+ const calendarOf = (unit, zone, start, t) => {
495
+ const local = localTime(t, zone);
496
+ if (local === void 0) throw new RangeError(`the instant ${String(t)} is not a date in the zone ${zone}`);
497
+ const { year, month, day } = local;
498
+ const startOf = (back) => {
499
+ const wall = (unit === "day" ? Date.UTC(year, month - 1, day - back) : Date.UTC(year, month - 1 - back, 1)) + start;
500
+ const instant = firstInstantOf(wall, zone);
501
+ if (instant === void 0) throw new RangeError(`the clock of ${zone} does not show or skip the local time ${iso(wall)}`);
502
+ return instant;
503
+ };
504
+ const first = startOf(0);
505
+ return first <= t ? [first, startOf(-1)] : [startOf(1), first];
506
+ };
507
+ const bucketsOf = (window) => {
508
+ if (window.kind === "rolling") {
509
+ const { span } = window;
510
+ const size = Math.ceil(span / window.buckets);
511
+ return {
512
+ bucket: (t) => {
513
+ const start = Math.floor(t / size) * size;
514
+ return [start, start + size];
515
+ },
516
+ counting: (t) => (start) => start + size + span > t,
517
+ freeAt: (start) => start + size + span
518
+ };
519
+ }
520
+ const { unit, zone, start } = window;
521
+ return {
522
+ bucket: (t) => calendarOf(unit, zone, start, t),
523
+ counting: (t) => {
524
+ const [first] = calendarOf(unit, zone, start, t);
525
+ return (bucket) => bucket >= first;
526
+ },
527
+ freeAt: (bucket) => calendarOf(unit, zone, start, bucket)[1]
528
+ };
529
+ };
530
+ /**
531
+ * This function gives the record of a store. A value that is not a record gives an empty record.
532
+ * The function removes each item that is not valid and keeps the other items, thus the count stays
533
+ * as high as the record lets it. It adds the items of one bucket together.
534
+ */
535
+ const recordOf = (value) => {
536
+ if (typeof value !== "object" || value === null) return { spent: [] };
537
+ const { spent, blockedUntil, readAt } = value;
538
+ const counts = /* @__PURE__ */ new Map();
539
+ if (Array.isArray(spent)) for (const item of spent) {
540
+ if (!Array.isArray(item) || item.length !== 2) continue;
541
+ const [start, units] = item;
542
+ if (isInstant(start) && typeof units === "number" && Number.isFinite(units) && units > 0) counts.set(start, (counts.get(start) ?? 0) + units);
543
+ }
544
+ return {
545
+ spent: [...counts].sort((a, b) => a[0] - b[0]),
546
+ ...isInstant(blockedUntil) ? { blockedUntil } : {},
547
+ ...isInstant(readAt) ? { readAt } : {}
548
+ };
549
+ };
550
+ /** 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. */
551
+ const prune = (buckets, record, t) => {
552
+ const counts = buckets.counting(t);
553
+ const { blockedUntil, readAt } = record;
554
+ return {
555
+ spent: record.spent.filter(([start]) => counts(start)),
556
+ ...blockedUntil !== void 0 && blockedUntil > t ? { blockedUntil } : {},
557
+ ...readAt !== void 0 && counts(buckets.bucket(readAt)[0]) ? { readAt } : {}
558
+ };
559
+ };
560
+ const usedOf = (record) => record.spent.reduce((sum, [, units]) => sum + units, 0);
561
+ /** This function adds units to the bucket of the instant `t`. */
562
+ const add = (buckets, record, t, units) => {
563
+ const [start] = buckets.bucket(t);
564
+ let found = false;
565
+ const spent = record.spent.map(([at, count]) => {
566
+ if (at !== start) return [at, count];
567
+ found = true;
568
+ return [at, count + units];
569
+ });
570
+ if (!found) spent.push([start, units]);
571
+ spent.sort((a, b) => a[0] - b[0]);
572
+ return {
573
+ ...record,
574
+ spent
575
+ };
576
+ };
577
+ /** This function gives the instant at which `need` units of the oldest buckets stop counting. */
578
+ const freeTime = (buckets, record, need) => {
579
+ let freed = 0;
580
+ for (const [start, units] of record.spent) {
581
+ freed += units;
582
+ if (!over(need, freed)) return buckets.freeAt(start);
583
+ }
584
+ };
585
+ const stateOf = (rule, buckets, record, t) => {
586
+ const used = usedOf(record);
587
+ const oldest = record.spent[0];
588
+ const { blockedUntil } = record;
589
+ return {
590
+ at: t,
591
+ used,
592
+ left: blockedUntil === void 0 ? Math.max(0, rule.limit - rule.reserve - used) : 0,
593
+ ...oldest === void 0 ? {} : { resetAt: buckets.freeAt(oldest[0]) },
594
+ ...blockedUntil === void 0 ? {} : { blockedUntil }
595
+ };
596
+ };
597
+ /** This function checks the units of a take or of a give-back: a finite count of 0 or more. */
598
+ const checkUnits = (units) => {
599
+ 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)}`);
600
+ return units;
601
+ };
602
+ /** 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. */
603
+ const checkEvent = (event) => {
604
+ if (event.type === "take") checkUnits(event.units);
605
+ else if (event.type === "give-back") {
606
+ checkUnits(event.units);
607
+ if (!isInstant(event.at)) throw new RangeError(`the instant of a give-back is not a date: ${String(event.at)}`);
608
+ }
609
+ };
610
+ function quotaStep(rule, stored, instant, event) {
611
+ if (!isInstant(instant)) throw new RangeError(`the instant of a quota step is not a date: ${String(instant)}`);
612
+ checkEvent(event);
613
+ const buckets = bucketsOf(rule.window);
614
+ const record = prune(buckets, recordOf(stored), instant);
615
+ const done = (next) => ({
616
+ record: next,
617
+ state: stateOf(rule, buckets, next, instant)
618
+ });
619
+ switch (event.type) {
620
+ case "read": return done(record);
621
+ case "note": {
622
+ let next = record;
623
+ const { remaining, resetAt } = event.reading;
624
+ if (typeof remaining === "number" && Number.isFinite(remaining) && remaining >= 0) {
625
+ const more = rule.limit - remaining - usedOf(next);
626
+ if (over(more, 0)) next = add(buckets, next, instant, more);
627
+ next = {
628
+ ...next,
629
+ readAt: Math.max(next.readAt ?? instant, instant)
630
+ };
631
+ }
632
+ if ((remaining === void 0 || remaining <= 0) && isInstant(resetAt) && resetAt > instant) next = {
633
+ ...next,
634
+ blockedUntil: Math.max(next.blockedUntil ?? resetAt, resetAt)
635
+ };
636
+ return done(next);
637
+ }
638
+ case "give-back": {
639
+ const { units, at } = event;
640
+ if (units === 0 || record.readAt !== void 0 && record.readAt >= at) return done(record);
641
+ const [start] = buckets.bucket(at);
642
+ if (!record.spent.some(([bucket]) => bucket === start)) return done(record);
643
+ const spent = [];
644
+ for (const [bucket, count] of record.spent) {
645
+ const left = bucket === start ? count - Math.min(units, count) : count;
646
+ if (over(left, 0)) spent.push([bucket, left]);
647
+ }
648
+ return done({
649
+ ...record,
650
+ spent
651
+ });
652
+ }
653
+ case "take": {
654
+ const { units } = event;
655
+ const allowed = rule.limit - rule.reserve;
656
+ const refuse = (verdict) => ({
657
+ record,
658
+ state: verdict.state,
659
+ verdict
660
+ });
661
+ const state = stateOf(rule, buckets, record, instant);
662
+ if (units === 0) return {
663
+ record,
664
+ state,
665
+ verdict: {
666
+ allowed: true,
667
+ state
668
+ }
669
+ };
670
+ if (over(units, allowed)) return refuse({
671
+ allowed: false,
672
+ cause: "capacity",
673
+ units,
674
+ capacity: allowed,
675
+ state
676
+ });
677
+ const used = usedOf(record);
678
+ const free = over(used + units, allowed) ? freeTime(buckets, record, used + units - allowed) ?? buckets.bucket(instant)[1] : void 0;
679
+ const wait = (cause, resetAt) => refuse({
680
+ allowed: false,
681
+ cause,
682
+ resetAt,
683
+ retryAfter: {
684
+ value: resetAt - instant,
685
+ unit: "ms"
686
+ },
687
+ state
688
+ });
689
+ if (record.blockedUntil !== void 0) return wait("provider", Math.max(record.blockedUntil, free ?? record.blockedUntil));
690
+ if (free !== void 0) return wait("limit", free);
691
+ const next = done(add(buckets, record, instant, units));
692
+ return {
693
+ ...next,
694
+ verdict: {
695
+ allowed: true,
696
+ state: next.state
697
+ }
698
+ };
699
+ }
700
+ }
701
+ }
702
+ /** This function tells if a record is equal to the record of a new key. */
703
+ const isEmpty = (record) => record.spent.length === 0 && record.blockedUntil === void 0 && record.readAt === void 0;
704
+ /**
705
+ * This function makes a store of records in memory. Each quota of one process can share it, and it
706
+ * keeps the records of each quota apart. It removes a key when its record is equal to the record
707
+ * of a new key. It does not sweep the other keys: use it for a set of keys with a bound, for
708
+ * example the accounts of an API.
709
+ */
710
+ const memoryQuotaStore = () => {
711
+ const tables = /* @__PURE__ */ new Map();
712
+ return {
713
+ sync: true,
714
+ change(quota, key, step) {
715
+ let table = tables.get(quota);
716
+ if (table === void 0) {
717
+ table = /* @__PURE__ */ new Map();
718
+ tables.set(quota, table);
719
+ }
720
+ const { record, result } = step(table.get(key));
721
+ if (isEmpty(record)) table.delete(key);
722
+ else table.set(key, record);
723
+ if (table.size === 0) tables.delete(quota);
724
+ return result;
725
+ },
726
+ size(quota) {
727
+ return tables.get(quota)?.size ?? 0;
728
+ }
729
+ };
730
+ };
731
+ /** This function tells if a value is a promise. */
732
+ const isPromise = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
733
+ /**
734
+ * This function makes the runtime of a quota from its spec, its store and a wall clock. It refuses
735
+ * a spec with a problem, because a quota has no defaults. It reads the instant inside the change of
736
+ * the store, thus a store that waits for a lock reads the instant after the wait.
737
+ * - With a store that answers at once, each method answers at once. A `RangeError` throws, and a
738
+ * store that gives a promise throws an error.
739
+ * - With a store that answers with a promise, each method gives a promise. A `RangeError` rejects.
740
+ */
741
+ function keyedQuota(name, spec, store, clock) {
742
+ const rule = quotaRule(name, spec);
743
+ if (clock.time !== "wall") throw new Error(`quota ${name} needs a wall clock, which gives the instant: a calendar window needs civil time`);
744
+ const answer = (compute) => {
745
+ if (!store.sync) return (async () => compute())();
746
+ const value = compute();
747
+ if (isPromise(value)) {
748
+ value.then(void 0, () => {});
749
+ throw new Error(`quota ${name} has a store that says it answers at once, but its change gave a promise`);
750
+ }
751
+ return value;
752
+ };
753
+ const change = (key, event, pick) => answer(() => {
754
+ checkEvent(event);
755
+ return store.change(name, key, (stored) => {
756
+ const step = quotaStep(rule, stored, clock.now(), event);
757
+ return {
758
+ record: step.record,
759
+ result: pick(step)
760
+ };
761
+ });
762
+ });
763
+ const verdictOf = (step) => step.verdict;
764
+ const stateOfStep = (step) => step.state;
765
+ const { window } = spec;
766
+ return {
767
+ name,
768
+ spec: {
769
+ limit: { ...spec.limit },
770
+ reserve: { ...spec.reserve },
771
+ window: window.kind === "rolling" ? {
772
+ kind: "rolling",
773
+ span: { ...window.span },
774
+ buckets: { ...window.buckets }
775
+ } : {
776
+ kind: "calendar",
777
+ unit: window.unit,
778
+ zone: window.zone,
779
+ start: { ...window.start }
780
+ }
781
+ },
782
+ rule,
783
+ sync: store.sync,
784
+ take: (key, units = 1) => change(key, {
785
+ type: "take",
786
+ units
787
+ }, verdictOf),
788
+ note: (key, reading) => change(key, {
789
+ type: "note",
790
+ reading: { ...reading }
791
+ }, stateOfStep),
792
+ giveBack: (key, units, at) => change(key, {
793
+ type: "give-back",
794
+ units,
795
+ at
796
+ }, stateOfStep),
797
+ state: (key) => change(key, { type: "read" }, stateOfStep)
798
+ };
799
+ }
800
+ /** This function tells which refusal decides: a capacity refusal, else the latest `resetAt`. The first part wins a tie. */
801
+ const decisive = (verdicts) => {
802
+ let best = -1;
803
+ for (let index = 0; index < verdicts.length; index += 1) {
804
+ const verdict = verdicts[index];
805
+ if (verdict.allowed) continue;
806
+ const current = best < 0 ? void 0 : verdicts[best];
807
+ if (current === void 0) best = index;
808
+ else if (current.cause === "capacity") continue;
809
+ else if (verdict.cause === "capacity" || verdict.resetAt > current.resetAt) best = index;
810
+ }
811
+ return best;
812
+ };
813
+ /** This walk takes each part in order, then gives back the counted parts of a refused take. The driver answers each request. */
814
+ function* walk(parts) {
815
+ const verdicts = [];
816
+ try {
817
+ for (const part of parts) verdicts.push(yield () => part.quota.take(part.key, part.units));
818
+ } catch (error) {
819
+ for (let index = 0; index < verdicts.length; index += 1) {
820
+ const verdict = verdicts[index];
821
+ const part = parts[index];
822
+ if (!verdict.allowed || part.units === 0) continue;
823
+ try {
824
+ yield () => part.quota.giveBack(part.key, part.units, verdict.state.at);
825
+ } catch {}
826
+ }
827
+ throw error;
828
+ }
829
+ const index = decisive(verdicts);
830
+ if (index < 0) return {
831
+ allowed: true,
832
+ states: verdicts.map((verdict) => verdict.state)
833
+ };
834
+ const states = [];
835
+ for (let at = 0; at < parts.length; at += 1) {
836
+ const verdict = verdicts[at];
837
+ const part = parts[at];
838
+ if (!verdict.allowed || part.units === 0) states.push(verdict.state);
839
+ else states.push(yield () => part.quota.giveBack(part.key, part.units, verdict.state.at));
840
+ }
841
+ return {
842
+ allowed: false,
843
+ index,
844
+ refusal: verdicts[index],
845
+ states
846
+ };
847
+ }
848
+ const driveSync = (parts) => {
849
+ const steps = walk(parts);
850
+ let next = steps.next();
851
+ while (!next.done) {
852
+ let value;
853
+ let failure;
854
+ try {
855
+ value = next.value();
856
+ } catch (error) {
857
+ failure = { error };
858
+ }
859
+ next = failure === void 0 ? steps.next(value) : steps.throw(failure.error);
860
+ }
861
+ return next.value;
862
+ };
863
+ const driveAsync = async (parts) => {
864
+ const steps = walk(parts);
865
+ let next = steps.next();
866
+ while (!next.done) {
867
+ let value;
868
+ let failure;
869
+ try {
870
+ value = await next.value();
871
+ } catch (error) {
872
+ failure = { error };
873
+ }
874
+ next = failure === void 0 ? steps.next(value) : steps.throw(failure.error);
875
+ }
876
+ return next.value;
877
+ };
878
+ function takeQuotas(parts) {
879
+ return parts.every((part) => part.quota.sync) ? driveSync(parts) : driveAsync(parts);
880
+ }
881
+ 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 };
882
+
883
+ //# sourceMappingURL=limiter-sT9fUFdW.js.map