@mark1russell7/service 0.6.1 → 0.6.3
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 +114 -5
- package/build/{builder-BNAkpeTT.d.ts → builder-bXJqMe2p.d.ts} +3 -2
- package/build/{core-CWsGgr9J.d.ts → core-B1zbS4WY.d.ts} +4 -3
- package/build/{dial-JEJavY0U.d.ts → dial-CSGKVlZe.d.ts} +2 -2
- package/build/grpc.d.ts +3 -3
- package/build/grpc.js +1 -1
- package/build/host.d.ts +556 -0
- package/build/host.js +1738 -0
- package/build/host.js.map +1 -0
- package/build/http-client.d.ts +3 -3
- package/build/http-client.js +1 -1
- package/build/http.d.ts +17 -3
- package/build/http.js +53 -10
- package/build/http.js.map +1 -1
- package/build/index.d.ts +44 -6
- package/build/index.js +78 -158
- package/build/index.js.map +1 -1
- package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
- package/build/{limiter-B0849Vhp.d.ts → limiter-BoZkXIxk.d.ts} +2 -2
- package/build/{limiter-pkBZUp-t.js → limiter-CmC4vCjk.js} +21 -13
- package/build/limiter-CmC4vCjk.js.map +1 -0
- package/build/limiter.d.ts +3 -3
- package/build/limiter.js +1 -1
- package/build/{lifecycle-CCDLvXLF.d.ts → logger-DhFgh48y.d.ts} +25 -367
- package/build/{machine-DZMb_QEU.js → machine-DKWLZOqu.js} +7 -19
- package/build/machine-DKWLZOqu.js.map +1 -0
- package/build/mongodb.d.ts +3 -3
- package/build/mongodb.js +1 -1
- package/build/pg.d.ts +2 -2
- package/build/pg.js +1 -1
- package/build/ports-CZLzYK5d.d.ts +125 -0
- package/build/process-DG_im2zc.js +171 -0
- package/build/process-DG_im2zc.js.map +1 -0
- package/build/{queue-eLs5IruM.d.ts → queue-BjiGodqh.d.ts} +3 -2
- package/build/rabbitmq.d.ts +4 -4
- package/build/rabbitmq.js +1 -1
- package/build/redis.d.ts +3 -3
- package/build/redis.js +1 -1
- package/build/retrier-Bzkme_yM.js +51 -0
- package/build/retrier-Bzkme_yM.js.map +1 -0
- package/build/{store-D5HLgBnW.d.ts → store-Cwuepb-z.d.ts} +14 -3
- package/build/testing.d.ts +86 -3
- package/build/testing.js +238 -2
- package/build/testing.js.map +1 -1
- package/build/websocket.d.ts +3 -3
- package/build/websocket.js +1 -1
- package/package.json +6 -2
- package/build/limiter-pkBZUp-t.js.map +0 -1
- package/build/machine-DZMb_QEU.js.map +0 -1
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { n as Clock } from "./clock-mVqhXD0b.js";
|
|
2
|
+
import { $ as UncaughtOrigin, S as Gate, X as ProcessPort, _ as CooperativeFloor, c as Logger, h as Check, m as Recorder } from "./logger-DhFgh48y.js";
|
|
3
|
+
import { Extent } from "@mark1russell7/quantity";
|
|
4
|
+
//#region src/latch.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* An outcome is the result of one poll of a check. Only `"ok"` passes. An `"indeterminate"`
|
|
7
|
+
* outcome measured nothing: it does not pass, and it does not fail.
|
|
8
|
+
*/
|
|
9
|
+
type Outcome = "ok" | "error" | "indeterminate";
|
|
10
|
+
/** A result is one poll of a check, as the runtime records it. */
|
|
11
|
+
interface Result {
|
|
12
|
+
readonly outcome: Outcome;
|
|
13
|
+
/** This time is when the result came, on the monotonic clock, in milliseconds. */
|
|
14
|
+
readonly at: number;
|
|
15
|
+
/** This time is how long the poll took, in milliseconds. */
|
|
16
|
+
readonly took: number;
|
|
17
|
+
/** This text tells why the poll did not pass, or it is null. */
|
|
18
|
+
readonly cause: string | null;
|
|
19
|
+
/** This flag tells if the poll failed at its timeout. */
|
|
20
|
+
readonly timedOut: boolean;
|
|
21
|
+
/** This flag tells if the check threw. A throw is an error with a flag. */
|
|
22
|
+
readonly thrown: boolean;
|
|
23
|
+
/** This flag tells if the force-fail list made the poll fail. */
|
|
24
|
+
readonly forced: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* A trace receives each transition of a machine of the runtime: the state before, the state after,
|
|
28
|
+
* and the event. The machine documents of the lifecycle name the same states and events, thus a
|
|
29
|
+
* test can replay a trace against its document.
|
|
30
|
+
*/
|
|
31
|
+
type Trace = (from: string, to: string, on: string) => void;
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/metrics.d.ts
|
|
34
|
+
/**
|
|
35
|
+
* A histogram of durations counts the polls of a check by how long each one took (B18). Each bound
|
|
36
|
+
* is a fraction of the timeout of the poll, thus the last bound is the timeout. A poll that failed
|
|
37
|
+
* at its timeout goes into `timedOut`, not into a bucket. Thus the histogram marks the timeouts.
|
|
38
|
+
*/
|
|
39
|
+
interface DurationHistogram {
|
|
40
|
+
/** These bounds are in milliseconds, from the smallest. A bucket counts each poll that took more than the bound before it, up to its own bound. */
|
|
41
|
+
readonly le: readonly number[];
|
|
42
|
+
/** These counts are not cumulative: one count for each bound. */
|
|
43
|
+
readonly counts: readonly number[];
|
|
44
|
+
readonly timedOut: number;
|
|
45
|
+
}
|
|
46
|
+
/** An episode of failure starts at the first error of a sequence, and ends at the next pass (B18). */
|
|
47
|
+
interface Episode {
|
|
48
|
+
/** This time is the first error, in milliseconds on the monotonic clock. */
|
|
49
|
+
readonly start: number;
|
|
50
|
+
/** This time is the pass that ended the episode, or null while the episode continues. */
|
|
51
|
+
readonly end: number | null;
|
|
52
|
+
/** This count is the polls that failed in the episode. */
|
|
53
|
+
readonly failures: number;
|
|
54
|
+
/** This cause is the cause of the first error, with each secret removed. */
|
|
55
|
+
readonly cause: string | null;
|
|
56
|
+
}
|
|
57
|
+
/** The metrics of one check: the count of each outcome, its durations and its last episodes. */
|
|
58
|
+
interface CheckMetrics {
|
|
59
|
+
readonly outcomes: {
|
|
60
|
+
readonly ok: number;
|
|
61
|
+
readonly error: number;
|
|
62
|
+
readonly indeterminate: number;
|
|
63
|
+
};
|
|
64
|
+
readonly thrown: number;
|
|
65
|
+
readonly forced: number;
|
|
66
|
+
readonly durations: DurationHistogram;
|
|
67
|
+
/** These are the last episodes, from the oldest. The runtime keeps `EPISODES_KEPT` of them. */
|
|
68
|
+
readonly episodes: readonly Episode[];
|
|
69
|
+
}
|
|
70
|
+
/** The metrics of a health runtime. Nothing in them starts a check. */
|
|
71
|
+
interface HealthMetrics {
|
|
72
|
+
readonly checks: Readonly<Record<string, CheckMetrics>>;
|
|
73
|
+
/** Each count is the transitions of one machine of the runtime, by the key `machine instance from -> to`. */
|
|
74
|
+
readonly transitions: Readonly<Record<string, number>>;
|
|
75
|
+
}
|
|
76
|
+
/** These fractions of the timeout of a poll are the bounds of its histogram. */
|
|
77
|
+
declare const DURATION_FRACTIONS: readonly number[];
|
|
78
|
+
/** The runtime keeps this many episodes of each check. */
|
|
79
|
+
declare const EPISODES_KEPT = 8;
|
|
80
|
+
/**
|
|
81
|
+
* This function removes the secrets that a cause can hold. These are the user and the password of a
|
|
82
|
+
* URL, and the value of a key, for example `password=`. A driver error can hold a connection string.
|
|
83
|
+
*/
|
|
84
|
+
declare const redact: (cause: string) => string;
|
|
85
|
+
//#endregion
|
|
86
|
+
//#region src/poller.d.ts
|
|
87
|
+
/**
|
|
88
|
+
* A check function measures one step of a connection. It ends with nothing or `"ok"` for a pass,
|
|
89
|
+
* or with `"error"` or `"indeterminate"`. A throw is an error with a flag. The runtime aborts the
|
|
90
|
+
* signal at the timeout of the poll.
|
|
91
|
+
*/
|
|
92
|
+
type CheckFn = (signal: AbortSignal) => Outcome | void | Promise<Outcome | void>;
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/health.d.ts
|
|
95
|
+
/** These options start the runtime. Without them, it uses the real clock and `Math.random`. */
|
|
96
|
+
interface StartOptions {
|
|
97
|
+
readonly clock?: Clock | undefined;
|
|
98
|
+
/** This function gives a number in [0, 1) for the jitter of each poll. */
|
|
99
|
+
readonly random?: (() => number) | undefined;
|
|
100
|
+
/** This list names the checks or dependencies whose polls fail at once (a seam for tests). */
|
|
101
|
+
readonly forceFail?: readonly string[] | undefined;
|
|
102
|
+
/** This function receives each transition of each machine of the runtime. */
|
|
103
|
+
readonly record?: Recorder | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* This logger receives each transition too, as a log entry with a level and fields (`logEvents`).
|
|
106
|
+
* Without it, the runtime writes no log, as before. For the console, give `consoleLogger()`.
|
|
107
|
+
*/
|
|
108
|
+
readonly logger?: Logger | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* This function can replace the function of a check, for example to add a delay to each call
|
|
111
|
+
* (a seam for tests: a degraded dependency). It gives the function to use.
|
|
112
|
+
*/
|
|
113
|
+
readonly wrapCheck?: ((check: Check, run: CheckFn) => CheckFn) | undefined;
|
|
114
|
+
}
|
|
115
|
+
/** A check verdict is the cached state of one check, for the probes and the report. */
|
|
116
|
+
interface CheckVerdict {
|
|
117
|
+
readonly gates: Gate | null;
|
|
118
|
+
readonly dependency: string | null;
|
|
119
|
+
/** This flag tells if the latch of the check is tripped, or it is null for a check that only reports. */
|
|
120
|
+
readonly tripped: boolean | null;
|
|
121
|
+
readonly streak: number;
|
|
122
|
+
/** This time is when the latch last changed, in milliseconds on the monotonic clock. */
|
|
123
|
+
readonly since: number | null;
|
|
124
|
+
readonly last: Result | null;
|
|
125
|
+
}
|
|
126
|
+
/** A verdict is the state of the service, from its cache. Nothing in it starts a check. */
|
|
127
|
+
interface HealthVerdict {
|
|
128
|
+
/** This flag becomes true one time, after the warm-up sweep. */
|
|
129
|
+
readonly started: boolean;
|
|
130
|
+
readonly draining: boolean;
|
|
131
|
+
/** This flag tells if the service can take new work: started, not draining, and each readiness latch released. */
|
|
132
|
+
readonly ready: boolean;
|
|
133
|
+
/** This flag tells if each liveness latch is released. */
|
|
134
|
+
readonly alive: boolean;
|
|
135
|
+
/** These flags tell if each controller can take new work, from the dependencies that it needs. */
|
|
136
|
+
readonly controllers: Readonly<Record<string, boolean>>;
|
|
137
|
+
readonly dependencies: Readonly<Record<string, boolean>>;
|
|
138
|
+
readonly checks: Readonly<Record<string, CheckVerdict>>;
|
|
139
|
+
readonly startup: {
|
|
140
|
+
readonly budget: number;
|
|
141
|
+
readonly elapsed: number;
|
|
142
|
+
readonly overBudget: boolean;
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** A probe kind is the question that a probe asks: the startup, the readiness, the liveness, or the whole report. */
|
|
146
|
+
type ProbeKind = "startup" | "readiness" | "liveness" | "report";
|
|
147
|
+
/** A probe answer is a status and a body, for any HTTP framework or none. */
|
|
148
|
+
interface ProbeAnswer {
|
|
149
|
+
readonly status: 200 | 503;
|
|
150
|
+
readonly contentType: "application/health+json";
|
|
151
|
+
readonly body: {
|
|
152
|
+
readonly status: "pass" | "fail";
|
|
153
|
+
readonly service: string;
|
|
154
|
+
readonly probe: ProbeKind;
|
|
155
|
+
readonly controller?: string | undefined;
|
|
156
|
+
readonly verdict?: HealthVerdict | undefined;
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/** The health runtime of a started service. It reads its timing and its checks from the declaration. */
|
|
160
|
+
interface Health {
|
|
161
|
+
verdict(): HealthVerdict;
|
|
162
|
+
/**
|
|
163
|
+
* This method answers a probe from the cache, in constant time, and it starts no check. A
|
|
164
|
+
* readiness probe with a controller asks about that controller. The report always answers 200.
|
|
165
|
+
*/
|
|
166
|
+
probe(kind: ProbeKind, controller?: string): ProbeAnswer;
|
|
167
|
+
/**
|
|
168
|
+
* This method gives the counts of the runtime (B18). They are the outcomes, the durations and the
|
|
169
|
+
* episodes of failure of each check, and the transitions of its machines. It starts no check.
|
|
170
|
+
*/
|
|
171
|
+
metrics(): HealthMetrics;
|
|
172
|
+
/** This method gives each change of the verdict to `listener`, and gives the function that stops it. */
|
|
173
|
+
subscribe(listener: (verdict: HealthVerdict) => void): () => void;
|
|
174
|
+
/** This method adds a name to the force-fail list, or removes it. */
|
|
175
|
+
forceFail(name: string, on: boolean): void;
|
|
176
|
+
/** This method fails readiness for good. The drain of the lifecycle starts with it. */
|
|
177
|
+
drain(): void;
|
|
178
|
+
/** This method stops each poller and each timer of the runtime. */
|
|
179
|
+
stop(): void;
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
182
|
+
//#region src/requests.d.ts
|
|
183
|
+
/**
|
|
184
|
+
* A request end is the one final result of the stream of a request. Its count `delivered` is the
|
|
185
|
+
* number of items that the stream gave before it. An end after the first item is in-band. The
|
|
186
|
+
* transport sent its answer, thus it writes the end as the last line of the stream, not as a status.
|
|
187
|
+
* - `done`: the work gave each of its items.
|
|
188
|
+
* - `failed`: the work failed for a cause of its own. Before the first item, the adapter answers it
|
|
189
|
+
* as it answers any error of the route.
|
|
190
|
+
* - `refused`: the service did not admit the request. A refused request did not start, thus its
|
|
191
|
+
* caller can send it again: 503, retryable.
|
|
192
|
+
* - `cut`: the shutdown stopped the request. Before the first item, a route whose callers can send
|
|
193
|
+
* it again answers 503, retryable, and each other route answers 500. After the first item, the
|
|
194
|
+
* status is null, and the end is in-band.
|
|
195
|
+
*/
|
|
196
|
+
type RequestEnd = {
|
|
197
|
+
readonly kind: "done";
|
|
198
|
+
readonly delivered: number;
|
|
199
|
+
} | {
|
|
200
|
+
readonly kind: "failed";
|
|
201
|
+
readonly error: unknown;
|
|
202
|
+
readonly delivered: number;
|
|
203
|
+
} | {
|
|
204
|
+
readonly kind: "refused";
|
|
205
|
+
readonly status: 503;
|
|
206
|
+
readonly retryable: true;
|
|
207
|
+
readonly cause: string;
|
|
208
|
+
readonly delivered: 0;
|
|
209
|
+
} | {
|
|
210
|
+
readonly kind: "cut";
|
|
211
|
+
readonly status: 503 | 500 | null;
|
|
212
|
+
readonly retryable: boolean;
|
|
213
|
+
readonly cause: string;
|
|
214
|
+
readonly delivered: number;
|
|
215
|
+
};
|
|
216
|
+
/** A request event is one event of the stream of a request: an item, or the one end, which comes last. */
|
|
217
|
+
type RequestEvent<T> = {
|
|
218
|
+
readonly kind: "item";
|
|
219
|
+
readonly value: T;
|
|
220
|
+
} | RequestEnd;
|
|
221
|
+
/**
|
|
222
|
+
* A request stream is what a request comes to: its items, then one end. A unary work gives a stream
|
|
223
|
+
* of one item. The stream gives an item only when its reader asks for the next event. Thus a slow
|
|
224
|
+
* reader slows the work, and the request stays in flight until the work ends. When the reader
|
|
225
|
+
* stops before the end, the work gets its abort and the `return()` of its iterator.
|
|
226
|
+
*/
|
|
227
|
+
interface RequestStream<T> extends AsyncIterable<RequestEvent<T>> {
|
|
228
|
+
/** This method reads the whole stream, and gives its items and its end. */
|
|
229
|
+
collect(): Promise<{
|
|
230
|
+
readonly items: readonly T[];
|
|
231
|
+
readonly end: RequestEnd;
|
|
232
|
+
}>;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* A request work is what a request function gives: one value, or a stream of values. A work that
|
|
236
|
+
* gives an async iterable is a stream, also through a promise. Each other value is a stream of one.
|
|
237
|
+
*/
|
|
238
|
+
type RequestWork<T> = T | PromiseLike<T> | AsyncIterable<T> | PromiseLike<AsyncIterable<T>>;
|
|
239
|
+
/** A request function does the work of one request. It receives a signal that the shutdown aborts. */
|
|
240
|
+
type RequestFn<T> = (signal: AbortSignal) => RequestWork<T>;
|
|
241
|
+
/** These options go with one request. */
|
|
242
|
+
interface RequestOptions {
|
|
243
|
+
/** This value goes to the function of a route pattern, for example the metadata of a procedure. */
|
|
244
|
+
readonly detail?: unknown;
|
|
245
|
+
}
|
|
246
|
+
//#endregion
|
|
247
|
+
//#region src/lifecycle.d.ts
|
|
248
|
+
/**
|
|
249
|
+
* A transport is a source of work: a server, a consumer or a worker. Each has one contract. It
|
|
250
|
+
* starts, stops its intake, and drains to a deadline without a throw. It counts its work in flight,
|
|
251
|
+
* and it closes. A second close has no effect.
|
|
252
|
+
*/
|
|
253
|
+
interface TransportImpl {
|
|
254
|
+
/**
|
|
255
|
+
* This method starts the transport. The lifecycle is the object that `run()` gives at the end of
|
|
256
|
+
* the startup. Its request tracking operates from the start: a request before the startup ends
|
|
257
|
+
* gets a retryable refusal, and `keepAlive()` is false. Do not wait for `life.started` here,
|
|
258
|
+
* because the startup waits for this method.
|
|
259
|
+
*/
|
|
260
|
+
start(signal: AbortSignal, life: Lifecycle): Promise<void> | void;
|
|
261
|
+
stopIntake(): Promise<void> | void;
|
|
262
|
+
/**
|
|
263
|
+
* This method lets the work in flight end until `deadline` (milliseconds on the monotonic
|
|
264
|
+
* clock). The signal is the cooperative abort, which comes before the deadline.
|
|
265
|
+
*/
|
|
266
|
+
drain(deadline: number, signal: AbortSignal): Promise<void> | void;
|
|
267
|
+
inFlight(): number;
|
|
268
|
+
close(): Promise<void> | void;
|
|
269
|
+
}
|
|
270
|
+
/** A dependency handle connects to a dependency at the start, and closes the connection at the end. */
|
|
271
|
+
interface DependencyHandle {
|
|
272
|
+
connect(signal: AbortSignal): Promise<void> | void;
|
|
273
|
+
close(): Promise<void> | void;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* A health server answers the probes, on its own port. It starts first, thus the probes answer
|
|
277
|
+
* while the dependencies connect, and it closes last.
|
|
278
|
+
*/
|
|
279
|
+
interface HealthServer {
|
|
280
|
+
listen(health: Health): Promise<void> | void;
|
|
281
|
+
close(): Promise<void> | void;
|
|
282
|
+
}
|
|
283
|
+
/** A phase context is what a phase gives its work: its deadline, its signal and the clock. */
|
|
284
|
+
interface PhaseContext {
|
|
285
|
+
/** This time is the end of the cap of the phase, in milliseconds on the monotonic clock. */
|
|
286
|
+
readonly deadline: number;
|
|
287
|
+
/** This signal aborts at the end of the cap of the phase. */
|
|
288
|
+
readonly signal: AbortSignal;
|
|
289
|
+
readonly clock: Clock;
|
|
290
|
+
}
|
|
291
|
+
/** A phase work is a step of the shutdown that an owner adds to a phase. */
|
|
292
|
+
type PhaseWork = (context: PhaseContext) => Promise<void> | void;
|
|
293
|
+
/**
|
|
294
|
+
* These are the stages of the shutdown, in their sequence. A declared phase with one of these
|
|
295
|
+
* names gets the work of the runtime for its stage. A phase with another name gets only the work of
|
|
296
|
+
* its owners.
|
|
297
|
+
* - `fail readiness`: readiness fails at the start of the shutdown. This phase then holds for its
|
|
298
|
+
* cap, while the endpoints of the platform remove the service.
|
|
299
|
+
* - `stop intake`: each transport stops its intake, and new requests get a retryable 503.
|
|
300
|
+
* - `drain`: the transports and the requests in flight end, until the cap. The cooperative abort
|
|
301
|
+
* comes before the end of the cap, by the cooperative window.
|
|
302
|
+
* - `close transports`: each transport closes.
|
|
303
|
+
* - `stop the poller`: each check and watchdog stops. Then the signal of the service aborts.
|
|
304
|
+
* - `tear down dependencies`: each dependency closes, in the reverse sequence of its connection.
|
|
305
|
+
* - `close the health server`: the probes stop.
|
|
306
|
+
* - `flush the output`: the work of the owners of this phase ends, and then the process port
|
|
307
|
+
* writes the buffered output. Without this phase, the process exits without a wait.
|
|
308
|
+
*/
|
|
309
|
+
declare const STAGES: readonly ["fail readiness", "stop intake", "drain", "close transports", "stop the poller", "tear down dependencies", "close the health server", "flush the output"];
|
|
310
|
+
type Stage = (typeof STAGES)[number];
|
|
311
|
+
/** This function gives the place of a stage in the sequence, or -1 for a phase of another name. */
|
|
312
|
+
declare const stageRank: (name: string) => number;
|
|
313
|
+
/**
|
|
314
|
+
* This function gives the time of the cooperative abort, in milliseconds after the drain starts. It
|
|
315
|
+
* is the cap less the cooperative window. With the floor `half`, it is not less than half the cap,
|
|
316
|
+
* and a window without a bound gives half the cap. With the floor `none`, it is not less than 0.
|
|
317
|
+
*/
|
|
318
|
+
declare const cooperativeAbortAt: (cap: number, window: Extent, floor?: CooperativeFloor) => number;
|
|
319
|
+
/**
|
|
320
|
+
* These options make each error that no code caught a trigger of the shutdown. They are an uncaught
|
|
321
|
+
* exception and an unhandled rejection.
|
|
322
|
+
*/
|
|
323
|
+
interface UncaughtOptions {
|
|
324
|
+
/** This code is the exit code after an uncaught error, a whole number from 0 to 255. The default is 1. */
|
|
325
|
+
readonly exitCode?: number | undefined;
|
|
326
|
+
/**
|
|
327
|
+
* This function tells if the runtime skips an error, for example an `ECONNRESET` of a peer socket.
|
|
328
|
+
* The logger gets a skipped error at `warn`, and the service continues. A throw of this function skips nothing.
|
|
329
|
+
*/
|
|
330
|
+
readonly ignore?: ((error: unknown, origin: UncaughtOrigin) => boolean) | undefined;
|
|
331
|
+
}
|
|
332
|
+
/** These options run the lifecycle. Without them, it uses the real clock and the process of Node. */
|
|
333
|
+
interface RunOptions extends StartOptions {
|
|
334
|
+
readonly process?: ProcessPort | undefined;
|
|
335
|
+
/**
|
|
336
|
+
* With these options, the lifecycle adds a handler for the errors that no code caught, from its start
|
|
337
|
+
* to its exit. Each error that it does not skip is an error of the lifecycle at `error`. It then
|
|
338
|
+
* starts the shutdown with its exit code, as a signal does. Without them, the runtime adds no handler.
|
|
339
|
+
*/
|
|
340
|
+
readonly uncaught?: UncaughtOptions | undefined;
|
|
341
|
+
}
|
|
342
|
+
/** These options go with a request for the shutdown. */
|
|
343
|
+
interface ShutdownOptions {
|
|
344
|
+
/**
|
|
345
|
+
* This code is the exit code that the work of the process gives, a whole number from 0 to 255. The
|
|
346
|
+
* first exit request with a code sets it. A code of 0 lets an error make the exit code 1.
|
|
347
|
+
*/
|
|
348
|
+
readonly code?: number | undefined;
|
|
349
|
+
}
|
|
350
|
+
/** A lifecycle state tells where the service is in its life. */
|
|
351
|
+
type LifecycleState = "starting" | "running" | "draining" | "exited";
|
|
352
|
+
/** The lifecycle of a running service. */
|
|
353
|
+
interface Lifecycle {
|
|
354
|
+
readonly health: Health;
|
|
355
|
+
readonly state: LifecycleState;
|
|
356
|
+
/** This code is the exit code, or null before the exit. */
|
|
357
|
+
readonly exitCode: number | null;
|
|
358
|
+
/** These texts are the errors of the lifecycle. An error makes the exit code 1, unless an exit request gives another code. */
|
|
359
|
+
readonly errors: readonly string[];
|
|
360
|
+
/** This promise ends when the startup ends: the service runs, or its startup failed. */
|
|
361
|
+
readonly started: Promise<void>;
|
|
362
|
+
/** This promise gives the exit code when the shutdown ends. */
|
|
363
|
+
readonly done: Promise<number>;
|
|
364
|
+
/** This signal aborts after the poller stops: the background work of the service stops with it. */
|
|
365
|
+
readonly signal: AbortSignal;
|
|
366
|
+
/**
|
|
367
|
+
* This method asks for the shutdown, as an exit signal does. A second request does not start a
|
|
368
|
+
* second shutdown. It can give the exit code, when no request gave one before.
|
|
369
|
+
*/
|
|
370
|
+
shutdown(cause?: string, options?: ShutdownOptions): Promise<number>;
|
|
371
|
+
/**
|
|
372
|
+
* This method does one request of a controller, on a route or a route pattern that the controller
|
|
373
|
+
* declares. It gives the stream of the request: each item of the work, then one end. The service
|
|
374
|
+
* refuses the request while it cannot take new work, and the shutdown can cut it. An undeclared
|
|
375
|
+
* route throws, because it has no idempotency.
|
|
376
|
+
*/
|
|
377
|
+
request<T>(controller: string, route: string, work: RequestFn<T>, options?: RequestOptions): RequestStream<T>;
|
|
378
|
+
inFlight(controller?: string): number;
|
|
379
|
+
/**
|
|
380
|
+
* This method tells if a response can keep its connection open. It is false while the service is
|
|
381
|
+
* not ready, thus each response then closes its connection.
|
|
382
|
+
*/
|
|
383
|
+
keepAlive(): boolean;
|
|
384
|
+
}
|
|
385
|
+
//#endregion
|
|
386
|
+
export { DurationHistogram as A, HealthVerdict as C, CheckFn as D, StartOptions as E, Outcome as F, Result as I, Trace as L, Episode as M, HealthMetrics as N, CheckMetrics as O, redact as P, Health as S, ProbeKind as T, RequestFn as _, PhaseContext as a, RequestWork as b, STAGES as c, TransportImpl as d, UncaughtOptions as f, RequestEvent as g, RequestEnd as h, LifecycleState as i, EPISODES_KEPT as j, DURATION_FRACTIONS as k, ShutdownOptions as l, stageRank as m, HealthServer as n, PhaseWork as o, cooperativeAbortAt as p, Lifecycle as r, RunOptions as s, DependencyHandle as t, Stage as u, RequestOptions as v, ProbeAnswer as w, CheckVerdict as x, RequestStream as y };
|
|
387
|
+
//# sourceMappingURL=lifecycle-Ks9Yd5CM.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as LimitRule, i as LimitPolicy, r as KeyState } from "./policy-G4QJ1ZZq.js";
|
|
2
|
-
import "./store-
|
|
2
|
+
import "./store-Cwuepb-z.js";
|
|
3
3
|
import { Machine } from "@mark1russell7/algebra";
|
|
4
4
|
//#region src/limiter/machine.d.ts
|
|
5
5
|
/**
|
|
@@ -42,4 +42,4 @@ declare const limiterMachine: (policy: LimitPolicy) => Machine;
|
|
|
42
42
|
declare const limiterStateOf: (rule: LimitRule, state: KeyState | undefined, now: number) => LimiterState;
|
|
43
43
|
//#endregion
|
|
44
44
|
export { limiterStateOf as a, limiterMachine as i, SLIDING_WINDOW_MACHINE as n, TOKEN_BUCKET_MACHINE as r, LimiterState as t };
|
|
45
|
-
//# sourceMappingURL=limiter-
|
|
45
|
+
//# sourceMappingURL=limiter-BoZkXIxk.d.ts.map
|
|
@@ -65,16 +65,7 @@ const memoryStore = (clock) => {
|
|
|
65
65
|
};
|
|
66
66
|
/** This function gives the text of a failure. */
|
|
67
67
|
const failureOf = (error) => error instanceof Error ? error.message : String(error);
|
|
68
|
-
|
|
69
|
-
* This function makes the runtime of a limiter from its spec and its store. It refuses a spec with a
|
|
70
|
-
* problem, because the limiter has no defaults. It also refuses a store of the wrong kind: a spec
|
|
71
|
-
* with a shared store needs a store that the replicas share.
|
|
72
|
-
* - A failure of a shared store gives the decision of `onStoreFailure`. With `open`, the take is
|
|
73
|
-
* permitted with `remaining` 0. With `closed`, it is refused with the cause `store`.
|
|
74
|
-
* - The `retryAfter` of the cause `store` is the longest `retryAfter` of the policy.
|
|
75
|
-
* - A failure of a local store rejects the take, because a local store has no `onStoreFailure`.
|
|
76
|
-
*/
|
|
77
|
-
const keyedLimiter = (name, spec, store) => {
|
|
68
|
+
function keyedLimiter(name, spec, store) {
|
|
78
69
|
const problems = limiterProblems(name, spec);
|
|
79
70
|
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
80
71
|
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}`);
|
|
@@ -107,6 +98,20 @@ const keyedLimiter = (name, spec, store) => {
|
|
|
107
98
|
};
|
|
108
99
|
}
|
|
109
100
|
};
|
|
101
|
+
const tryTakeSync = (key) => {
|
|
102
|
+
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()`);
|
|
103
|
+
const decision = store.take({
|
|
104
|
+
limiter: name,
|
|
105
|
+
key,
|
|
106
|
+
rule,
|
|
107
|
+
maxKeys
|
|
108
|
+
});
|
|
109
|
+
if (isPromise(decision)) {
|
|
110
|
+
decision.then(void 0, () => {});
|
|
111
|
+
throw new Error(`limiter ${name} has a store whose take gives a promise: tryTakeSync needs a memory store, thus use take()`);
|
|
112
|
+
}
|
|
113
|
+
return decision;
|
|
114
|
+
};
|
|
110
115
|
return {
|
|
111
116
|
name,
|
|
112
117
|
spec: {
|
|
@@ -117,9 +122,12 @@ const keyedLimiter = (name, spec, store) => {
|
|
|
117
122
|
},
|
|
118
123
|
rule,
|
|
119
124
|
maxKeys,
|
|
120
|
-
take
|
|
125
|
+
take,
|
|
126
|
+
tryTakeSync
|
|
121
127
|
};
|
|
122
|
-
}
|
|
128
|
+
}
|
|
129
|
+
/** This function tells if a decision of a store is a promise. */
|
|
130
|
+
const isPromise = (value) => typeof value.then === "function";
|
|
123
131
|
//#endregion
|
|
124
132
|
//#region src/limiter/machine.ts
|
|
125
133
|
const t = (id, from, on, to, extra = {}) => ({
|
|
@@ -399,4 +407,4 @@ const limiterStateOf = (rule, state, now) => {
|
|
|
399
407
|
//#endregion
|
|
400
408
|
export { keyedLimiter as a, limiterStateOf as i, TOKEN_BUCKET_MACHINE as n, memoryStore as o, limiterMachine as r, SLIDING_WINDOW_MACHINE as t };
|
|
401
409
|
|
|
402
|
-
//# sourceMappingURL=limiter-
|
|
410
|
+
//# sourceMappingURL=limiter-CmC4vCjk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limiter-CmC4vCjk.js","names":["r"],"sources":["../src/limiter/store.ts","../src/limiter/machine.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, rationals as r } from \"@mark1russell7/quantity\";\nimport type { Clock } from \"../clock.ts\";\nimport type { Decision, KeyState, LimiterSpec, LimitRule } from \"./policy.ts\";\nimport { decide, freeAt, limitRule, limiterProblems, longestRetryAfter } 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\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. It removes a key only when its state is equal to the state of a\n * new key. It holds at most `maxKeys` keys for each limiter. A failure of a shared store rejects\n * 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 }) {\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 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 one unit for a key, and gives the decision of the store. When a shared store\n * fails, it gives the decision of `onStoreFailure`, with the failure as text.\n */\n take(key: string): Promise<Decision>;\n /**\n * This method takes one unit for a key, and gives the decision at once, with no promise. Only a\n * local store whose take gives its decision at once permits it, for example `memoryStore`. A shared store throws.\n */\n tryTakeSync?(key: string): 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): 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 * - `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): Promise<Decision> => {\n const request: TakeRequest = { limiter: name, key, rule, maxKeys };\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): 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 decision = store.take({ limiter: name, key, rule, maxKeys });\n if (isPromise(decision)) {\n // the take of the store happened: its promise has the decision, and its rejection is not left unhandled\n decision.then(undefined, () => {});\n throw new Error(`limiter ${name} has a store whose take gives a promise: tryTakeSync needs a memory store, thus use take()`);\n }\n return decision;\n };\n return {\n name,\n spec: {\n key: spec.key,\n policy: { ...spec.policy },\n store: { ...spec.store },\n evict: { maxKeys: { ...spec.evict.maxKeys } },\n },\n rule,\n maxKeys,\n take,\n tryTakeSync,\n };\n}\n\n/** This function tells if a decision of a store is a promise. */\nconst isPromise = (value: Decision | Promise<Decision>): value is Promise<Decision> =>\n typeof (value as { then?: unknown }).then === \"function\";\n","import type { Machine, TransitionDef } from \"@mark1russell7/algebra\";\nimport type { KeyState, LimitPolicy, LimitRule } from \"./policy.ts\";\nimport { decide, freeAt } from \"./policy.ts\";\n\nconst t = (id: string, from: string | readonly string[], on: string | readonly string[], to: string, extra: Partial<TransitionDef> = {}): TransitionDef => ({\n id,\n from,\n on,\n to,\n ...extra,\n});\nconst count = (key: string) => ({ key, scope: \"limiter\", unit: \"count\", default: null }) as const;\n\n/**\n * A limiter state is the state of one key of a keyed limiter, as its machine document names it:\n * - `new`: the store holds no state for the key, or a state that is equal to the state of a new key.\n * - `open`: the key holds a count, and its next take is permitted.\n * - `limited`: the next take of the key is refused with the cause `limit`, until a unit is back.\n */\nexport type LimiterState = \"new\" | \"open\" | \"limited\";\n\n/** These are the states of a key that a store can hold. A store fails in each of them. */\nconst HELD = [\"new\", \"open\", \"limited\"] as const;\n\n/** These are the parts of each document of a limiter that do not change with its policy. */\nconst COMMON = {\n format: \"mark1russell7.machine/1\",\n layer: \"self\",\n version: \"0.1.0\",\n sources: [\n { ref: \"packages/service/src/limiter (the runtime implements this document: decide, memoryStore, keyedLimiter)\", rung: \"implemented\" },\n { ref: \"RFC 6585 §4: 429 Too Many Requests, which can carry Retry-After\", rung: \"normative\" },\n { ref: \"RFC 9110 §10.2.3: Retry-After, as delay-seconds or an HTTP-date\", rung: \"normative\" },\n ],\n conditions: {\n \"store.local\": \"the counts are in the memory of one replica: a limit L over N replicas is L / N on each replica, and that sum holds only on average\",\n \"store.shared\": \"the counts are in a store that the replicas share: one atomic step on the clock of the store decides each take\",\n },\n states: {\n new: { initial: true, note: \"the store holds no state for the key, or a state equal to a new key. The store can remove the key\" },\n open: { note: \"the key holds a count, and its next take is permitted\" },\n limited: { note: \"the next take is refused with the cause limit, until a unit is back\" },\n },\n} as const;\n\n/** These are the events of each document of a limiter. */\nconst EVENTS = {\n take: { kind: \"app\", note: \"one call of take(key): one request of the key. A permitted take uses one unit\" },\n \"unit.back\": { kind: \"timer\", note: \"the next take of a limited key is permitted again\" },\n idle: { kind: \"timer\", note: \"the key is equal to a new key. The store can remove it, and no decision changes\" },\n \"store.fail\": { kind: \"local\", note: \"a shared store fails the take. The state of the key does not change\" },\n} as const;\n\n/** These are the knobs of each document of a limiter that do not change with its policy. */\nconst KNOBS = {\n max_keys: count(\"limiters.<name>.evict.maxKeys\"),\n on_store_failure: { key: \"limiters.<name>.store.onStoreFailure\", scope: \"limiter\", unit: null, default: null },\n} as const;\n\n/**\n * These are the transitions of each document of a limiter that do not change with its policy. They\n * are the refusal of a limited key, a new key at the cap of keys, and a failure of a shared store.\n */\nconst COMMON_TRANSITIONS: readonly TransitionDef[] = [\n t(\"refuse\", \"limited\", \"take\", \"limited\", {\n emits: [\"429 limit\"],\n note: \"Retry-After is the time until the next take is permitted, in whole seconds, rounded up. The count of the key does not change\",\n }),\n t(\"cap\", \"new\", \"take\", \"new\", {\n guard: \"the store holds max_keys keys for the limiter, and no held key is equal to a new key\",\n emits: [\"429 cap\"],\n note: \"Retry-After is the time until the earliest held key is free: at most the idle span. A held key keeps its count\",\n }),\n ...HELD.map((state) =>\n t(`store-failed-${state}`, state, \"store.fail\", state, {\n guard: \"the store is shared\",\n emits: [\"allow, or 429 store\"],\n note: \"on_store_failure open lets the take in, with remaining 0. closed refuses it with the cause store, and its Retry-After is the longest of the policy\",\n }),\n ),\n];\n\n/**\n * A token bucket of one key (GCRA), as a `mark1russell7.machine/1` document. The bucket holds\n * `burst` tokens, and it gets one token back in each interval, `1 / rate`. The store keeps one time\n * for the key: when its bucket is full again.\n * - A take is permitted when, with the take, the bucket is full again in at most `burst` intervals.\n * - A refused take waits until one token is back: at most one interval. That interval is the\n * longest `Retry-After` of the policy (`retry_after@limiter` of the law).\n * - After `burst / rate` with no take, the bucket is full, and the key is equal to a new key. That\n * span is the idle span, and the longest wait of a new key at the cap of keys\n * (`retry_after_at_cap@limiter`).\n */\nexport const TOKEN_BUCKET_MACHINE: Machine = {\n ...COMMON,\n id: \"service.machine.limiter.token-bucket\",\n title: \"A token bucket of one key of the keyed limiter\",\n events: EVENTS,\n knobs: {\n rate: { key: \"limiters.<name>.policy.rate\", scope: \"limiter\", unit: \"count/s\", default: null },\n burst: count(\"limiters.<name>.policy.burst\"),\n ...KNOBS,\n },\n timers: {\n token: {\n duration: { expr: \"1 / rate\", unit: \"s\" },\n early: { expr: \"1 / rate\", unit: \"s\" },\n arms: [\"enter:limited\"],\n cancels: [\"idle\"],\n fires: \"unit.back\",\n note: \"one token comes back at most one interval after the take that used the last token. The Retry-After of each refusal is the time to this firing\",\n },\n full: {\n duration: { expr: \"burst / rate\", unit: \"s\" },\n early: { expr: \"(burst - 1) / rate\", unit: \"s\" },\n arms: [\"take\"],\n fires: \"idle\",\n note: \"the bucket is full again from one to burst intervals after a permitted take. A refused take does not move it\",\n },\n },\n transitions: [\n t(\"first\", \"new\", \"take\", \"open\", { guard: \"burst > 1\", emits: [\"allow\"] }),\n t(\"first-last\", \"new\", \"take\", \"limited\", { guard: \"burst = 1\", emits: [\"allow\"] }),\n t(\"take\", \"open\", \"take\", \"open\", { guard: \"a token remains after the take\", emits: [\"allow\"] }),\n t(\"take-last\", \"open\", \"take\", \"limited\", { guard: \"the take uses the last token\", emits: [\"allow\"] }),\n ...COMMON_TRANSITIONS,\n t(\"token-back\", \"limited\", \"unit.back\", \"open\", { timer: \"token\", guard: \"burst > 1\" }),\n t(\"full\", \"open\", \"idle\", \"new\", { timer: \"full\" }),\n t(\"full-at-once\", \"limited\", \"idle\", \"new\", {\n timer: \"full\",\n guard: \"burst = 1: the one token is back when the bucket is full\",\n }),\n ],\n};\n\n/**\n * A sliding window of one key, as a `mark1russell7.machine/1` document. The store keeps the time of\n * each permitted take of the key in the window, and each take counts for one window from its time.\n * - A take is permitted when fewer than `limit` takes are in the window.\n * - A refused take waits until the oldest take leaves the window: at most one window. That window is\n * the longest `Retry-After` of the policy (`retry_after@limiter` of the law).\n * - One window after the last take, no take is in the window, and the key is equal to a new key.\n * That window is the idle span, and the longest wait of a new key at the cap of keys\n * (`retry_after_at_cap@limiter`).\n */\nexport const SLIDING_WINDOW_MACHINE: Machine = {\n ...COMMON,\n id: \"service.machine.limiter.sliding-window\",\n title: \"A sliding window of one key of the keyed limiter\",\n events: EVENTS,\n knobs: {\n limit: count(\"limiters.<name>.policy.limit\"),\n window: { key: \"limiters.<name>.policy.window\", scope: \"limiter\", unit: \"s\", default: null },\n ...KNOBS,\n },\n timers: {\n oldest: {\n duration: { knob: \"window\", unit: \"s\" },\n early: { knob: \"window\", unit: \"s\" },\n arms: [\"enter:limited\"],\n cancels: [\"idle\"],\n fires: \"unit.back\",\n note: \"the oldest take leaves the window at most one window after the take that filled it. The Retry-After of each refusal is the time to this firing\",\n },\n last: {\n duration: { knob: \"window\", unit: \"s\" },\n arms: [\"take\"],\n fires: \"idle\",\n note: \"the last permitted take leaves the window one window after its time. A refused take does not move it\",\n },\n },\n transitions: [\n t(\"first\", \"new\", \"take\", \"open\", { guard: \"limit > 1\", emits: [\"allow\"] }),\n t(\"first-last\", \"new\", \"take\", \"limited\", { guard: \"limit = 1\", emits: [\"allow\"] }),\n t(\"take\", \"open\", \"take\", \"open\", { guard: \"fewer than limit - 1 takes are in the window before the take\", emits: [\"allow\"] }),\n t(\"take-last\", \"open\", \"take\", \"limited\", { guard: \"the take is the limit-th take in the window\", emits: [\"allow\"] }),\n ...COMMON_TRANSITIONS,\n t(\"oldest-leaves\", \"limited\", \"unit.back\", \"open\", { timer: \"oldest\", guard: \"a later take stays in the window\" }),\n t(\"last-leaves\", \"open\", \"idle\", \"new\", { timer: \"last\" }),\n t(\"all-leave\", \"limited\", \"idle\", \"new\", {\n timer: \"last\",\n guard: \"each take of the window has one time: limit = 1, or each take came at once\",\n }),\n ],\n};\n\n/** This function gives the machine document of the policy of a limiter. */\nexport const limiterMachine = (policy: LimitPolicy): Machine =>\n policy.type === \"token-bucket\" ? TOKEN_BUCKET_MACHINE : SLIDING_WINDOW_MACHINE;\n\n/**\n * This function gives the state of a key of a store as its machine document names it, at the time\n * `now` in milliseconds. `state` is what the store keeps for the key, or `undefined` when it keeps\n * nothing. A key equal to a new key is `new`, and a key whose next take `decide` refuses is `limited`.\n */\nexport const limiterStateOf = (rule: LimitRule, state: KeyState | undefined, now: number): LimiterState => {\n if (state === undefined || freeAt(rule, state) <= now) return \"new\";\n return decide(rule, state, now).decision.allowed ? \"open\" : \"limited\";\n};\n"],"mappings":";;;AAmDA,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,MAA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KAAa,OAAO,MAAM,KAAK,KAAK,KAAK,OAAO;CAC9D,OAAO,OAAO,MAAM,OAAO,GAAG,CAAC,CAAC,SAAS,UAAU,SAAS;AAC9D"}
|
package/build/limiter.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { S as retryAfterSeconds, _ as freeAt, a as LimitRule, b as limiterProblems, c as LimiterSpec, d as Refused, f as SlidingWindow, g as decide, h as TokenBucket, i as LimitPolicy, l as LimiterStoreSpec, m as TakeStep, n as Decision, o as Limiter, p as StoreFailure, r as KeyState, s as LimiterEviction, t as Allowed, u as RefusalCause, v as idleSpan, x as longestRetryAfter, y as limitRule } from "./policy-G4QJ1ZZq.js";
|
|
2
|
-
import { a as
|
|
3
|
-
import { a as limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-
|
|
4
|
-
export { type Allowed, type Decision, type KeyState, type KeyedLimiter, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type MemoryStore, type RefusalCause, type Refused, SLIDING_WINDOW_MACHINE, type SlidingWindow, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type TokenBucket, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, retryAfterSeconds };
|
|
2
|
+
import { a as TakeRequest, i as MemoryStore, n as LimiterStore, o as keyedLimiter, r as LocalLimiter, s as memoryStore, t as KeyedLimiter } from "./store-Cwuepb-z.js";
|
|
3
|
+
import { a as limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-BoZkXIxk.js";
|
|
4
|
+
export { type Allowed, type Decision, type KeyState, type KeyedLimiter, type LimitPolicy, type LimitRule, type Limiter, type LimiterEviction, type LimiterSpec, type LimiterState, type LimiterStore, type LimiterStoreSpec, type LocalLimiter, type MemoryStore, type RefusalCause, type Refused, SLIDING_WINDOW_MACHINE, type SlidingWindow, type StoreFailure, TOKEN_BUCKET_MACHINE, type TakeRequest, type TakeStep, type TokenBucket, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, retryAfterSeconds };
|
package/build/limiter.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { a as limiterProblems, i as limitRule, n as freeAt, o as longestRetryAfter, r as idleSpan, s as retryAfterSeconds, t as decide } from "./policy-CgS4y94U.js";
|
|
2
|
-
import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-
|
|
2
|
+
import { a as keyedLimiter, i as limiterStateOf, n as TOKEN_BUCKET_MACHINE, o as memoryStore, r as limiterMachine, t as SLIDING_WINDOW_MACHINE } from "./limiter-CmC4vCjk.js";
|
|
3
3
|
export { SLIDING_WINDOW_MACHINE, TOKEN_BUCKET_MACHINE, decide, freeAt, idleSpan, keyedLimiter, limitRule, limiterMachine, limiterProblems, limiterStateOf, longestRetryAfter, memoryStore, retryAfterSeconds };
|