@mark1russell7/service 0.6.2 → 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.
Files changed (42) hide show
  1. package/README.md +88 -2
  2. package/build/{builder-0OlfomVU.d.ts → builder-bXJqMe2p.d.ts} +3 -2
  3. package/build/{core-Iy9rIXOT.d.ts → core-B1zbS4WY.d.ts} +4 -3
  4. package/build/{dial-DLT7bTlA.d.ts → dial-CSGKVlZe.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/grpc.js +1 -1
  7. package/build/host.d.ts +556 -0
  8. package/build/host.js +1738 -0
  9. package/build/host.js.map +1 -0
  10. package/build/http-client.d.ts +3 -3
  11. package/build/http-client.js +1 -1
  12. package/build/http.d.ts +1 -1
  13. package/build/index.d.ts +4 -3
  14. package/build/index.js +3 -169
  15. package/build/index.js.map +1 -1
  16. package/build/lifecycle-Ks9Yd5CM.d.ts +387 -0
  17. package/build/{lifecycle-DXK880vG.d.ts → logger-DhFgh48y.d.ts} +2 -385
  18. package/build/{machine-Dq2OlzCG.js → machine-DKWLZOqu.js} +3 -2
  19. package/build/{machine-Dq2OlzCG.js.map → machine-DKWLZOqu.js.map} +1 -1
  20. package/build/mongodb.d.ts +3 -3
  21. package/build/mongodb.js +1 -1
  22. package/build/operation-DL5RxFds.js +25 -0
  23. package/build/operation-DL5RxFds.js.map +1 -0
  24. package/build/pg.d.ts +2 -2
  25. package/build/pg.js +1 -1
  26. package/build/ports-CZLzYK5d.d.ts +125 -0
  27. package/build/process-DG_im2zc.js +171 -0
  28. package/build/process-DG_im2zc.js.map +1 -0
  29. package/build/{queue-CvBNNZZJ.d.ts → queue-BjiGodqh.d.ts} +3 -2
  30. package/build/rabbitmq.d.ts +4 -4
  31. package/build/rabbitmq.js +1 -1
  32. package/build/redis.d.ts +2 -2
  33. package/build/redis.js +1 -1
  34. package/build/{retrier-CRda6z9G.js → retrier-Bzkme_yM.js} +2 -24
  35. package/build/retrier-Bzkme_yM.js.map +1 -0
  36. package/build/testing.d.ts +84 -3
  37. package/build/testing.js +226 -1
  38. package/build/testing.js.map +1 -1
  39. package/build/websocket.d.ts +3 -3
  40. package/build/websocket.js +1 -1
  41. package/package.json +5 -1
  42. package/build/retrier-CRda6z9G.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