@mark1russell7/service 0.8.14 → 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.
package/build/http.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { realClock } from "./clock.js";
2
2
  import { c as ownerOf, i as holdLate, o as noteOutside, r as millisecondsOf$1, s as ownStream } from "./knobs-BJcz6m01.js";
3
- import { l as retryAfterSeconds } from "./policy-B23MY52l.js";
3
+ import { m as retryAfterSeconds } from "./policy-UYALkqVq.js";
4
4
  import { convertible, valueIn } from "@mark1russell7/quantity";
5
5
  import { createServer } from "node:http";
6
6
  // src/http/answers.ts
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 limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-Djw39d_S.js";
8
+ import { A as LimiterState, C as RollingWindow, D as quotaRule, E as quotaProblems, M as TOKEN_BUCKET_MACHINE, N as limiterMachine, O as quotaStep, P as limiterStateOf, S as QuotasVerdict, T as memoryQuotaStore, _ 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 SLIDING_WINDOW_MACHINE, k as takeQuotas, 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 keyedQuota, x as QuotaWindow, y as QuotaVerdict } from "./limiter-Dvh0YW25.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";
@@ -411,4 +411,4 @@ export declare const capKnob: (phase: string) => string;
411
411
  export declare const drainMachine: (description: ServiceDescription) => Machine;
412
412
  /** These are the static machines of the runtime, by the name that their events carry. */
413
413
  export declare const MACHINES: Readonly<Record<Exclude<MachineName, "drain" | "client">, Machine>>;
414
- export { type Allowed, type Backoff, type Binding, type Bound, type CallContext, type Cancel, type CapacityRefused, type Change, type Check, type CheckFn, type CheckMetrics, type CheckVerdict, type Claim, type Clock, type Compressed, type Compression, type ConsoleLoggerOptions, type ConsoleTarget, type Controller, type ControllerBuilder, type CooperativeFloor, type Coupling, DRAIN_RULES, DURATION_FRACTIONS, type Decision, type DelayBand, type Dependency, type DependencyHandle, type DurationHistogram, EPISODES_KEPT, EXIT_SIGNALS, type EmbeddedProcess, type Episode, type Epochs, type Evaluated, type ExitCodes, type ExitSignal, type ExitTrigger, FORMAT, type FailsBy, type Finding, type Gate, type Health, type HealthMetrics, type HealthServer, type HealthVerdict, type Heartbeat, type HeartbeatOptions, type HostStream, type Idempotency, type IdentityType, type IncomingHeaders, type Inequality, type IterationContext, type Jitter, type JobAction, type JobContext, type JobFailure, type JobSettle, type JobSource, type KeyState, type KeyedLimiter, LOG_LEVELS, type Lifecycle, type LifecycleEvent, type LifecycleState, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type LogEntry, type LogFields, type LogFormat, type LogLevel, type Logger, type MachineName, type MemoryStore, type MessageShape, type MessageTrigger, O04, O09, O10, O16, type Operation, type OperationOf, type Outcome, PROCESS_TRIGGERS, type Phase, type PhaseContext, type PhaseWork, type PlatformClockOptions, type PodTiming, type Poll, type ProbeAnswer, type ProbeKind, type ProcessHost, type ProcessPort, type ProcessTrigger, type Profile, type ProgressMarks, type QueueDrain, type QueueDrainOptions, type QueueKnobs, type Recorder, type RedeliveryPolicy, type RefusalCause, type Refused, type RepeatSignal, type RequestEnd, type RequestEvent, type RequestFn, type RequestOptions, type RequestStream, type RequestWork, type RequeueCause, type Result, type Retrier, type RetrierOptions, type RetryOptions, type RoutePattern, type RouteRequest, type Rule, type RunOptions, SLIDING_WINDOW_MACHINE, STAGES, type Scenario, type ScenarioValue, type ScopedChange, type ServiceBuilder, type ServiceDescription, type ShutdownOptions, type Side, type SlidingWindow, type Span, type Stage, type StartOptions, type Statistic, type Step, type Stop, type StopWay, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type Term, type TimerMark, type TimerMarks, type Timing, type TokenBucket, type TraceIds, type TraceIdsSource, type Transport, type TransportImpl, UNCAUGHT_ORIGINS, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, type WaitCause, type WaitRefused, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capacityOf, compress, compression, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, stageRank, symbolsOf, unitsOf, verdictOf, watchdog };
414
+ export { type Allowed, type Backoff, type Binding, type Bound, type CalendarWindow, type CallContext, type Cancel, type CapacityRefused, type Change, type Check, type CheckFn, type CheckMetrics, type CheckVerdict, type Claim, type Clock, type Compressed, type Compression, type ConsoleLoggerOptions, type ConsoleTarget, type Controller, type ControllerBuilder, type CooperativeFloor, type Coupling, DRAIN_RULES, DURATION_FRACTIONS, type Decision, type DelayBand, type Dependency, type DependencyHandle, type DurationHistogram, EPISODES_KEPT, EXIT_SIGNALS, type EmbeddedProcess, type Episode, type Epochs, type Evaluated, type ExitCodes, type ExitSignal, type ExitTrigger, FORMAT, type FailsBy, type Finding, type Gate, type Health, type HealthMetrics, type HealthServer, type HealthVerdict, type Heartbeat, type HeartbeatOptions, type HostStream, type Idempotency, type IdentityType, type IncomingHeaders, type Inequality, type IterationContext, type Jitter, type JobAction, type JobContext, type JobFailure, type JobSettle, type JobSource, type KeyState, type KeyedLimiter, type KeyedQuota, LOG_LEVELS, type Lifecycle, type LifecycleEvent, type LifecycleState, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type LogEntry, type LogFields, type LogFormat, type LogLevel, type Logger, type MachineName, type MemoryQuotaStore, type MemoryStore, type MessageShape, type MessageTrigger, O04, O09, O10, O16, type Operation, type OperationOf, type Outcome, PROCESS_TRIGGERS, type Phase, type PhaseContext, type PhaseWork, type PlatformClockOptions, type PodTiming, type Poll, type ProbeAnswer, type ProbeKind, type ProcessHost, type ProcessPort, type ProcessTrigger, type Profile, type ProgressMarks, type QueueDrain, type QueueDrainOptions, type QueueKnobs, 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 Recorder, type RedeliveryPolicy, type RefusalCause, type Refused, type RepeatSignal, type RequestEnd, type RequestEvent, type RequestFn, type RequestOptions, type RequestStream, type RequestWork, type RequeueCause, type Result, type Retrier, type RetrierOptions, type RetryOptions, type RollingWindow, type RoutePattern, type RouteRequest, type Rule, type RunOptions, SLIDING_WINDOW_MACHINE, STAGES, type Scenario, type ScenarioValue, type ScopedChange, type ServiceBuilder, type ServiceDescription, type ShutdownOptions, type Side, type SlidingWindow, type Span, type Stage, type StartOptions, type Statistic, type Step, type Stop, type StopWay, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type Term, type TimerMark, type TimerMarks, type Timing, type TokenBucket, type TraceIds, type TraceIdsSource, type Transport, type TransportImpl, UNCAUGHT_ORIGINS, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, type WaitCause, type WaitRefused, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capacityOf, compress, compression, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, keyedQuota, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryQuotaStore, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, quotaProblems, quotaRule, quotaStep, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, stageRank, symbolsOf, takeQuotas, unitsOf, verdictOf, watchdog };
package/build/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as recoverSpan, i as heartbeatDetection, n as asWindow, r as failSpan, t as asDebounce } from "./timing-DZl36uXs.js";
2
2
  import { n as operationProblems, t as mayReissue } from "./operation-DF73RZOI.js";
3
3
  import { platformClock, realClock } from "./clock.js";
4
- import { a as limitRule, c as overCapacity, i as idleSpan, l as retryAfterSeconds, n as decide, o as limiterProblems, r as freeAt, s as longestRetryAfter, t as capacityOf, u as unitsOf } from "./policy-B23MY52l.js";
4
+ 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";
5
5
  import { a as isExitCode, c as matchesMessage, d as poller, f as latch, i as embeddedProcess, l as nodeProcess, n as PROCESS_TRIGGERS, o as isExitSignal, r as UNCAUGHT_ORIGINS, s as isMessageShape, t as EXIT_SIGNALS, u as processPortOf } from "./process-7R9M29wN.js";
6
6
  import { a as lateHolds, l as takeOutside, n as countOf, r as millisecondsOf, s as ownStream, t as boundedMillisecondsOf } from "./knobs-BJcz6m01.js";
7
7
  import { a as runUnit, c as untilAbort, i as retryOf, l as routePatternProblems, n as boundProblems, o as settleWithin, r as flights, s as sleeper, t as tracker } from "./requests-DD2ALv0_.js";
@@ -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 keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-BwGxEWpP.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-sT9fUFdW.js";
13
13
  import { convertExact, convertible, rationals, valueIn } from "@mark1russell7/quantity";
14
14
  import { replay } from "@mark1russell7/algebra/replay";
15
15
  // src/description.ts
@@ -3276,6 +3276,6 @@ const MACHINES = {
3276
3276
  exit: EXIT_MACHINE,
3277
3277
  watchdog: WATCHDOG_MACHINE
3278
3278
  };
3279
- export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, unitsOf, verdictOf, watchdog, workerLoop };
3279
+ export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, IDENTITY_TYPES, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, O04, O09, O10, O16, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNCAUGHT_ORIGINS, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, capacityOf, compress, compression, compressionOf, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, drainMachine, embeddedProcess, ephemeral, evaluate, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, inequalities, isExitCode, isExitSignal, isMessageShape, keyedLimiter, keyedQuota, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, lint, lintStop, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryQuotaStore, memoryStore, nodeProcess, overCapacity, platformClock, processPortOf, queueDrain, quotaProblems, quotaRule, quotaStep, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retry, retryAfterDelay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, takeQuotas, unitsOf, verdictOf, watchdog, workerLoop };
3280
3280
 
3281
3281
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,313 @@
1
+ import { a as LimitPolicy, i as KeyState, o as LimitRule } from "./policy-CBcK2XGg.js";
2
+ import "./store-DFwFKrsB.js";
3
+ import { Quantity } from "@mark1russell7/quantity";
4
+ import { WallClock } from "@mark1russell7/algebra/clock";
5
+ import { Machine } from "@mark1russell7/algebra";
6
+ /**
7
+ * A limiter state is the state of one key of a keyed limiter, as its machine document names it:
8
+ * - `new`: the store holds no state for the key, or a state that is equal to the state of a new key.
9
+ * - `open`: the key holds a count, and its next take is permitted.
10
+ * - `limited`: the next take of the key is refused with the cause `limit`, until a unit is back.
11
+ */
12
+ type LimiterState = "new" | "open" | "limited";
13
+ /**
14
+ * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds
15
+ * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time
16
+ * for the key: when its bucket is full again.
17
+ * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.
18
+ * - A refused take waits until one token is back: at most one interval. That interval is the
19
+ * longest `Retry-After` of the policy (`retry_after@limiter` of the law).
20
+ * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That
21
+ * span is the idle span, and the longest wait of a new key at the cap of keys
22
+ * (`retry_after_at_cap@limiter`).
23
+ */
24
+ declare const TOKEN_BUCKET_MACHINE: Machine;
25
+ /**
26
+ * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of
27
+ * each permitted take of the key in the window, and each take counts for one window from its time.
28
+ * - A take is permitted when fewer than `limit` takes are in the window.
29
+ * - A refused take waits until the oldest take leaves the window: at most one window. That window is
30
+ * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).
31
+ * - One window after the last take, no take is in the window, and the key is equal to a new key.
32
+ * That window is the idle span, and the longest wait of a new key at the cap of keys
33
+ * (`retry_after_at_cap@limiter`).
34
+ */
35
+ declare const SLIDING_WINDOW_MACHINE: Machine;
36
+ /** This function gives the machine document of the policy of a limiter. */
37
+ declare const limiterMachine: (policy: LimitPolicy) => Machine;
38
+ /**
39
+ * This function gives the state of a key of a store as its machine document names it, at the time
40
+ * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps
41
+ * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.
42
+ */
43
+ declare const limiterStateOf: (rule: LimitRule, state: KeyState | undefined, now: number) => LimiterState;
44
+ /**
45
+ * A rolling window counts the units of the last `span`. Use it when the provider does not tell when
46
+ * its count starts again. The window puts each take in a time bucket. A unit counts until all of
47
+ * its bucket is out of the window. Thus the count is not lower than the count of a fixed window.
48
+ */
49
+ interface RollingWindow {
50
+ readonly kind: "rolling";
51
+ /** This time is the length of the window, for example `{ value: 24, unit: "h" }`. */
52
+ readonly span: Quantity;
53
+ /** This count is the count of time buckets in the window: a whole count from 1 to 1000. */
54
+ readonly buckets: Quantity;
55
+ }
56
+ /**
57
+ * A calendar window counts the units of a day or of a month in a time zone. Each window starts at
58
+ * the time of day `start`, on each day or on the first day of each month. When the clock of the
59
+ * zone skips that time, the window starts at the end of the gap. When the clock shows that time
60
+ * two times, the window starts at the first of the two.
61
+ */
62
+ interface CalendarWindow {
63
+ readonly kind: "calendar";
64
+ readonly unit: "day" | "month";
65
+ /** The IANA name of the time zone, for example `America/Chicago` or `UTC`. */
66
+ readonly zone: string;
67
+ /** This time of day starts each window: from 0 to less than 24 hours, in whole milliseconds. */
68
+ readonly start: Quantity;
69
+ }
70
+ /** A quota window is a rolling window or a calendar window. */
71
+ type QuotaWindow = RollingWindow | CalendarWindow;
72
+ /** A quota spec is the declaration of a quota. It has no defaults. */
73
+ interface QuotaSpec {
74
+ /** This count is the count of units that the provider gives in one window. */
75
+ readonly limit: Quantity;
76
+ /** The gate keeps this count of units unused: from 0 to less than the limit. */
77
+ readonly reserve: Quantity;
78
+ readonly window: QuotaWindow;
79
+ }
80
+ /** A quota rule is a spec in numbers: each count as a number, and each time in milliseconds. */
81
+ interface QuotaRule {
82
+ readonly limit: number;
83
+ readonly reserve: number;
84
+ readonly window: {
85
+ readonly kind: "rolling";
86
+ readonly span: number;
87
+ readonly buckets: number;
88
+ } | {
89
+ readonly kind: "calendar";
90
+ readonly unit: "day" | "month";
91
+ readonly zone: string;
92
+ readonly start: number;
93
+ };
94
+ }
95
+ /**
96
+ * A quota record is what a store keeps for one key. A store can keep it as JSON. Each instant is in
97
+ * milliseconds from 1970-01-01T00:00:00Z.
98
+ */
99
+ interface QuotaRecord {
100
+ /** Each item is a time bucket: its start, and its count of units. The oldest bucket is first. */
101
+ readonly spent: readonly (readonly [start: number, units: number])[];
102
+ /** The provider refused the key until this instant. */
103
+ readonly blockedUntil?: number | undefined;
104
+ /** This instant is the last reading of the provider with a count. A give-back for a take at or before it changes nothing. */
105
+ readonly readAt?: number | undefined;
106
+ }
107
+ /** A quota reading is what an answer of the provider tells of its count. */
108
+ interface QuotaReading {
109
+ /** This count is the count of units that the provider gives before its next reset. */
110
+ readonly remaining?: number | undefined;
111
+ /**
112
+ * This instant is the next reset of the provider. When `remaining` is 0 or absent, the gate
113
+ * refuses each take until this instant.
114
+ */
115
+ readonly resetAt?: number | undefined;
116
+ }
117
+ /** A quota state is the state of one key at the instant `at`. */
118
+ interface QuotaState {
119
+ /** This instant is the instant of the step. */
120
+ readonly at: number;
121
+ /** This count is the count of units in the window. */
122
+ readonly used: number;
123
+ /** 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. */
124
+ readonly left: number;
125
+ /** The oldest units stop counting at this instant. With no unit in the window, it is absent. */
126
+ readonly resetAt?: number | undefined;
127
+ /** The provider refused the key until this instant. */
128
+ readonly blockedUntil?: number | undefined;
129
+ }
130
+ /** A permitted take counted its units at the instant `state.at`. */
131
+ interface QuotaAllowed {
132
+ readonly allowed: true;
133
+ readonly state: QuotaState;
134
+ }
135
+ /**
136
+ * A wait refusal counted nothing. Its cause is `limit` when the window has no room for the units,
137
+ * and `provider` when the provider refused the key. At `resetAt`, the gate gives the same take,
138
+ * when no other take comes first.
139
+ */
140
+ interface QuotaWaitRefused {
141
+ readonly allowed: false;
142
+ readonly cause: "limit" | "provider";
143
+ readonly resetAt: number;
144
+ /** This time is the time from `state.at` to `resetAt`. It is always above zero. */
145
+ readonly retryAfter: Quantity;
146
+ readonly state: QuotaState;
147
+ }
148
+ /**
149
+ * A capacity refusal counted nothing, and the gate refuses the same take at each time. Its units
150
+ * are more than the `capacity` of one window: the limit less the reserve.
151
+ */
152
+ interface QuotaCapacityRefused {
153
+ readonly allowed: false;
154
+ readonly cause: "capacity";
155
+ readonly units: number;
156
+ readonly capacity: number;
157
+ readonly state: QuotaState;
158
+ }
159
+ /** A quota refusal is a wait refusal or a capacity refusal. */
160
+ type QuotaRefused = QuotaWaitRefused | QuotaCapacityRefused;
161
+ /** A quota verdict is the answer of a quota to one take. */
162
+ type QuotaVerdict = QuotaAllowed | QuotaRefused;
163
+ /**
164
+ * A quota event is one change of a key:
165
+ * - `take`: count `units` for a call that starts at the instant of the step, or refuse it.
166
+ * - `note`: add what an answer of the provider tells. The count can only become larger.
167
+ * - `give-back`: remove `units` that a take counted at the instant `at`, for a call that did not
168
+ * start. It changes nothing when the bucket of `at` is out of the window, or when a reading of the
169
+ * provider came at or after `at`.
170
+ * - `read`: change nothing, and give the state.
171
+ */
172
+ type QuotaEvent = {
173
+ readonly type: "take";
174
+ readonly units: number;
175
+ } | {
176
+ readonly type: "note";
177
+ readonly reading: QuotaReading;
178
+ } | {
179
+ readonly type: "give-back";
180
+ readonly units: number;
181
+ readonly at: number;
182
+ } | {
183
+ readonly type: "read";
184
+ };
185
+ /** A quota step is the next record of a key and its state. Only a take gives a verdict. */
186
+ interface QuotaStep {
187
+ readonly record: QuotaRecord;
188
+ readonly state: QuotaState;
189
+ readonly verdict?: QuotaVerdict | undefined;
190
+ }
191
+ /** A take step is the step of a take: it always has a verdict. */
192
+ interface QuotaTakeStep extends QuotaStep {
193
+ readonly verdict: QuotaVerdict;
194
+ }
195
+ /**
196
+ * This function gives the problems of a quota spec. `keyedQuota` and `quotaRule` refuse a spec with
197
+ * a problem. A part that is absent is a problem, because a quota has no defaults.
198
+ */
199
+ declare const quotaProblems: (name: string, spec: Partial<QuotaSpec> | undefined) => string[];
200
+ /** This function gives the rule of a quota spec. It throws an error with the problems of a spec that has a problem. */
201
+ declare const quotaRule: (name: string, spec: QuotaSpec) => QuotaRule;
202
+ /**
203
+ * This function is the pure step of a quota. It reads the stored record of one key at the instant
204
+ * `instant`, applies the event, and gives the next record and the state. It removes what does not
205
+ * count at the instant first. Only a take can be refused, and a refusal counts nothing.
206
+ * - A take of 0 units is permitted and counts nothing, also while the provider refuses the key.
207
+ * - A take over the capacity is refused with the cause `capacity`.
208
+ * - While the provider refuses the key, a take is refused with the cause `provider`. Its `resetAt`
209
+ * is the end of that refusal, or a later instant when the window has room for the units.
210
+ * - A take over the room of the window is refused with the cause `limit`, until enough of the
211
+ * oldest units stop counting.
212
+ *
213
+ * It throws a `RangeError` for an instant that is not a date, and for units that are not a finite
214
+ * count of 0 or more.
215
+ */
216
+ declare function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: Extract<QuotaEvent, {
217
+ type: "take";
218
+ }>): QuotaTakeStep;
219
+ declare function quotaStep(rule: QuotaRule, stored: unknown, instant: number, event: QuotaEvent): QuotaStep;
220
+ /** A quota answer is a value at once for a store that answers at once, else a promise. */
221
+ type QuotaAnswer<Sync extends boolean, T> = Sync extends true ? T : Promise<T>;
222
+ /** A quota change is what a step gives a store: the record to keep, and the result for the caller. */
223
+ interface QuotaChange<T> {
224
+ readonly record: QuotaRecord;
225
+ readonly result: T;
226
+ }
227
+ /**
228
+ * A quota store keeps the record of each quota and key, and it changes one record in one atomic
229
+ * step. Thus two takes of one key do not read the same record. A store of this process can answer
230
+ * at once (`sync: true`), for example a store in memory or in SQLite. A store that the replicas
231
+ * share answers with a promise (`sync: false`).
232
+ */
233
+ interface QuotaStore<Sync extends boolean = boolean> {
234
+ readonly sync: Sync;
235
+ /**
236
+ * This method gives `step` the stored record of the quota and the key, or undefined for a new key.
237
+ * It keeps the record that `step` gives, and it gives the result. The record of a new key is
238
+ * empty: a store can remove a key whose record has no item and no instant. A store can call
239
+ * `step` again, for example after a conflict of a write. Thus `step` must have no other effect.
240
+ */
241
+ change<T>(quota: string, key: string, step: (stored: unknown) => QuotaChange<T>): QuotaAnswer<Sync, T>;
242
+ }
243
+ /** A memory quota store is the store of one process. Its records are in memory. */
244
+ interface MemoryQuotaStore extends QuotaStore<true> {
245
+ /** This method gives the count of keys that the store holds for a quota. */
246
+ size(quota: string): number;
247
+ }
248
+ /**
249
+ * This function makes a store of records in memory. Each quota of one process can share it, and it
250
+ * keeps the records of each quota apart. It removes a key when its record is equal to the record
251
+ * of a new key. It does not sweep the other keys: use it for a set of keys with a bound, for
252
+ * example the accounts of an API.
253
+ */
254
+ declare const memoryQuotaStore: () => MemoryQuotaStore;
255
+ /** A keyed quota is the runtime of one quota: its spec, its rule in numbers, its store and its wall clock. */
256
+ interface KeyedQuota<Sync extends boolean = boolean> {
257
+ /** This name is the quota. A store keeps the keys of each quota apart. */
258
+ readonly name: string;
259
+ readonly spec: QuotaSpec;
260
+ readonly rule: QuotaRule;
261
+ /** True: each method gives its answer at once. False: each method gives a promise. */
262
+ readonly sync: Sync;
263
+ /** This method counts `units` units (1 when absent) for a call of the key that starts at this instant, or refuses the call. */
264
+ take(key: string, units?: number): QuotaAnswer<Sync, QuotaVerdict>;
265
+ /** This method adds what an answer of the provider tells. The count can only become larger. */
266
+ note(key: string, reading: QuotaReading): QuotaAnswer<Sync, QuotaState>;
267
+ /** This method removes `units` that a take counted at the instant `at`, for a call that did not start. */
268
+ giveBack(key: string, units: number, at: number): QuotaAnswer<Sync, QuotaState>;
269
+ /** This method gives the state of the key, and changes nothing. */
270
+ state(key: string): QuotaAnswer<Sync, QuotaState>;
271
+ }
272
+ /**
273
+ * This function makes the runtime of a quota from its spec, its store and a wall clock. It refuses
274
+ * a spec with a problem, because a quota has no defaults. It reads the instant inside the change of
275
+ * the store, thus a store that waits for a lock reads the instant after the wait.
276
+ * - With a store that answers at once, each method answers at once. A `RangeError` throws, and a
277
+ * store that gives a promise throws an error.
278
+ * - With a store that answers with a promise, each method gives a promise. A `RangeError` rejects.
279
+ */
280
+ declare function keyedQuota<Sync extends boolean>(name: string, spec: QuotaSpec, store: QuotaStore<Sync>, clock: Pick<WallClock, "time" | "now">): KeyedQuota<Sync>;
281
+ /** A quota part is one take of a multi-quota take: a quota, a key, and the units of the take. */
282
+ interface QuotaPart<Sync extends boolean = boolean> {
283
+ readonly quota: KeyedQuota<Sync>;
284
+ readonly key: string;
285
+ readonly units: number;
286
+ }
287
+ /**
288
+ * A quotas verdict is the answer of a take of several quotas, all or none. Each state is the state
289
+ * of its part after the take, and after the give-back of a refused take.
290
+ * - A permitted take counted the units of each part.
291
+ * - A refused take counted nothing. `refusal` is the refusal of the part `index`: the first
292
+ * capacity refusal, else the wait refusal with the latest `resetAt`.
293
+ */
294
+ type QuotasVerdict = {
295
+ readonly allowed: true;
296
+ readonly states: readonly QuotaState[];
297
+ } | {
298
+ readonly allowed: false;
299
+ readonly index: number;
300
+ readonly refusal: QuotaRefused;
301
+ readonly states: readonly QuotaState[];
302
+ };
303
+ /**
304
+ * This function takes from several quotas, all or none. It takes each part in order. When a part
305
+ * is refused, the next parts still answer, and each part that counted gives back its units. Thus
306
+ * the refusal tells the latest instant at which all parts can have room. When a take fails, the
307
+ * parts before it give back their units, and the error throws.
308
+ *
309
+ * With quotas that answer at once, it answers at once. Else it gives a promise.
310
+ */
311
+ declare function takeQuotas(parts: readonly QuotaPart<true>[]): QuotasVerdict;
312
+ declare function takeQuotas(parts: readonly QuotaPart[]): QuotasVerdict | Promise<QuotasVerdict>;
313
+ export { LimiterState as A, RollingWindow as C, quotaRule as D, quotaProblems as E, TOKEN_BUCKET_MACHINE as M, limiterMachine as N, quotaStep as O, limiterStateOf as P, QuotasVerdict as S, memoryQuotaStore as T, QuotaStore as _, QuotaAnswer as a, QuotaWaitRefused as b, QuotaEvent as c, QuotaRecord as d, QuotaRefused as f, QuotaStep as g, QuotaState as h, QuotaAllowed as i, SLIDING_WINDOW_MACHINE as j, takeQuotas as k, QuotaPart as l, QuotaSpec as m, KeyedQuota as n, QuotaCapacityRefused as o, QuotaRule as p, MemoryQuotaStore as r, QuotaChange as s, CalendarWindow as t, QuotaReading as u, QuotaTakeStep as v, keyedQuota as w, QuotaWindow as x, QuotaVerdict as y };