@mark1russell7/service 0.6.0 → 0.6.2

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 (48) hide show
  1. package/README.md +42 -3
  2. package/build/{builder-BNAkpeTT.d.ts → builder-0OlfomVU.d.ts} +2 -2
  3. package/build/{core-CWsGgr9J.d.ts → core-Iy9rIXOT.d.ts} +3 -3
  4. package/build/{dial-JEJavY0U.d.ts → dial-DLT7bTlA.d.ts} +2 -2
  5. package/build/grpc.d.ts +3 -3
  6. package/build/grpc.js +1 -1
  7. package/build/http-client.d.ts +3 -3
  8. package/build/http-client.js +1 -1
  9. package/build/http.d.ts +17 -3
  10. package/build/http.js +53 -10
  11. package/build/http.js.map +1 -1
  12. package/build/index.d.ts +48 -131
  13. package/build/index.js +98 -13
  14. package/build/index.js.map +1 -1
  15. package/build/{lifecycle-CCDLvXLF.d.ts → lifecycle-DXK880vG.d.ts} +44 -3
  16. package/build/{limiter-B0849Vhp.d.ts → limiter-BoZkXIxk.d.ts} +2 -2
  17. package/build/{limiter-pkBZUp-t.js → limiter-CmC4vCjk.js} +21 -13
  18. package/build/limiter-CmC4vCjk.js.map +1 -0
  19. package/build/limiter.d.ts +3 -3
  20. package/build/limiter.js +1 -1
  21. package/build/{machine-DZMb_QEU.js → machine-Dq2OlzCG.js} +7 -20
  22. package/build/machine-Dq2OlzCG.js.map +1 -0
  23. package/build/mongodb.d.ts +3 -3
  24. package/build/mongodb.js +1 -1
  25. package/build/pg.d.ts +2 -2
  26. package/build/pg.js +1 -1
  27. package/build/{queue-eLs5IruM.d.ts → queue-CvBNNZZJ.d.ts} +2 -2
  28. package/build/rabbitmq.d.ts +4 -4
  29. package/build/rabbitmq.js +1 -1
  30. package/build/redis.d.ts +3 -3
  31. package/build/redis.js +1 -1
  32. package/build/retrier-CRda6z9G.js +73 -0
  33. package/build/retrier-CRda6z9G.js.map +1 -0
  34. package/build/rules-BBRopO1e.d.ts +145 -0
  35. package/build/rules.d.ts +2 -0
  36. package/build/rules.js +128 -0
  37. package/build/rules.js.map +1 -0
  38. package/build/{store-D5HLgBnW.d.ts → store-Cwuepb-z.d.ts} +14 -3
  39. package/build/testing.d.ts +4 -2
  40. package/build/testing.js +12 -1
  41. package/build/testing.js.map +1 -1
  42. package/build/websocket.d.ts +3 -3
  43. package/build/websocket.js +1 -1
  44. package/package.json +7 -3
  45. package/build/limiter-pkBZUp-t.js.map +0 -1
  46. package/build/machine-DZMb_QEU.js.map +0 -1
  47. package/build/operation-DL5RxFds.js +0 -25
  48. package/build/operation-DL5RxFds.js.map +0 -1
package/build/index.d.ts CHANGED
@@ -1,139 +1,16 @@
1
1
  import { a as backoffDelay, i as backoffBand, n as DelayBand, o as backoffProblems, r as Jitter, t as Backoff } from "./backoff-B-jGWVDm.js";
2
2
  import { a as realClock, i as platformClock, n as Clock, r as PlatformClockOptions, t as Cancel } from "./clock-mVqhXD0b.js";
3
3
  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";
4
- import { $ as Coupling, A as EPISODES_KEPT, At as ProcessHost, B as Logger, Bt as Idempotency, C as ProbeAnswer, Ct as EXIT_SIGNALS, D as CheckMetrics, Dt as HostStream, E as CheckFn, Et as ExitTrigger, F as ConsoleTarget, Ft as isExitSignal, G as Result, H as consoleLogger, Ht as mayReissue, I as LOG_LEVELS, It as isMessageShape, J as MachineName, L as LogEntry, Lt as matchesMessage, M as HealthMetrics, Mt as ProcessTrigger, N as redact, Nt as embeddedProcess, O as DURATION_FRACTIONS, Ot as MessageShape, P as ConsoleLoggerOptions, Pt as isExitCode, Q as CooperativeFloor, R as LogFields, Rt as nodeProcess, S as HealthVerdict, St as RouteRequest, T as StartOptions, Tt as ExitSignal, U as logEvents, V as atLeast, Vt as Operation, W as Outcome, X as Check, Y as Recorder, Z as Controller, _ as RequestOptions, _t as failSpan, a as PhaseContext, at as Phase, b as CheckVerdict, bt as OperationOf, c as STAGES, ct as ServiceDescription, d as TransportImpl, dt as FailsBy, et as Dependency, f as cooperativeAbortAt, ft as Poll, g as RequestFn, gt as asWindow, h as RequestEvent, ht as asDebounce, i as LifecycleState, it as MessageTrigger, j as Episode, jt as ProcessPort, k as DurationHistogram, kt as PROCESS_TRIGGERS, l as ShutdownOptions, lt as Step, m as RequestEnd, mt as Timing, n as HealthServer, nt as FORMAT, o as PhaseWork, ot as ProgressMarks, p as stageRank, pt as Span, q as LifecycleEvent, r as Lifecycle, rt as Gate, s as RunOptions, st as RepeatSignal, t as DependencyHandle, tt as ExitCodes, u as Stage, ut as Transport, v as RequestStream, vt as heartbeatDetection, w as ProbeKind, wt as EmbeddedProcess, x as Health, xt as RoutePattern, y as RequestWork, yt as recoverSpan, z as LogLevel, zt as processPortOf } from "./lifecycle-CCDLvXLF.js";
5
- import { a as WatchdogSpec, c as Profile, d as kubernetes, f as localDev, i as Watchdog, l as daemon, n as ServiceBuilder, o as watchdog, r as service, s as PodTiming, t as ControllerBuilder, u as ephemeral } from "./builder-BNAkpeTT.js";
4
+ import { $ as Controller, A as DurationHistogram, At as MessageShape, B as LogFormat, Bt as isMessageShape, C as HealthVerdict, Ct as RoutePattern, D as CheckFn, Dt as ExitSignal, E as StartOptions, Et as EmbeddedProcess, F as ConsoleLoggerOptions, Ft as UNCAUGHT_ORIGINS, G as logEvents, Gt as Operation, H as Logger, Ht as nodeProcess, I as ConsoleTarget, It as UncaughtOrigin, K as Outcome, Kt as mayReissue, L as LOG_LEVELS, Lt as embeddedProcess, M as Episode, Mt as ProcessHost, N as HealthMetrics, Nt as ProcessPort, O as CheckMetrics, Ot as ExitTrigger, P as redact, Pt as ProcessTrigger, Q as Check, R as LogEntry, Rt as isExitCode, S as Health, St as OperationOf, T as ProbeKind, Tt as EXIT_SIGNALS, U as atLeast, Ut as processPortOf, V as LogLevel, Vt as matchesMessage, W as consoleLogger, Wt as Idempotency, X as MachineName, Y as LifecycleEvent, Z as Recorder, _ as RequestFn, _t as asDebounce, a as PhaseContext, at as Gate, b as RequestWork, bt as heartbeatDetection, c as STAGES, ct as ProgressMarks, d as TransportImpl, dt as Step, et as CooperativeFloor, f as UncaughtOptions, ft as Transport, g as RequestEvent, gt as Timing, h as RequestEnd, ht as Span, i as LifecycleState, it as FORMAT, j as EPISODES_KEPT, jt as PROCESS_TRIGGERS, k as DURATION_FRACTIONS, kt as HostStream, l as ShutdownOptions, lt as RepeatSignal, m as stageRank, mt as Poll, n as HealthServer, nt as Dependency, o as PhaseWork, ot as MessageTrigger, p as cooperativeAbortAt, pt as FailsBy, q as Result, r as Lifecycle, rt as ExitCodes, s as RunOptions, st as Phase, t as DependencyHandle, tt as Coupling, u as Stage, ut as ServiceDescription, v as RequestOptions, vt as asWindow, w as ProbeAnswer, wt as RouteRequest, x as CheckVerdict, xt as recoverSpan, y as RequestStream, yt as failSpan, z as LogFields, zt as isExitSignal } from "./lifecycle-DXK880vG.js";
5
+ import { a as WatchdogSpec, c as Profile, d as kubernetes, f as localDev, i as Watchdog, l as daemon, n as ServiceBuilder, o as watchdog, r as service, s as PodTiming, t as ControllerBuilder, u as ephemeral } from "./builder-0OlfomVU.js";
6
6
  import { Heartbeat, HeartbeatOptions, detectionTime, heartbeat } from "./heartbeat.js";
7
- import { a as keyedLimiter, i as TakeRequest, n as LimiterStore, o as memoryStore, r as MemoryStore, t as KeyedLimiter } from "./store-D5HLgBnW.js";
8
- import { a as limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-B0849Vhp.js";
9
- import { a as JobSource, c as QueueKnobs, d as queueDrain, f as redeliverOnce, i as JobSettle, l as RedeliveryPolicy, n as JobContext, o as QueueDrain, p as UnitRequest, r as JobFailure, s as QueueDrainOptions, t as JobAction, u as RequeueCause } from "./queue-eLs5IruM.js";
7
+ import { C as symbolsOf, S as inequalities, _ as TimerMarks, a as O16, b as compression, c as Change, d as Evaluated, f as Inequality, g as TimerMark, h as Term, i as O10, l as Compressed, m as Side, n as O04, o as Binding, p as Rule, r as O09, s as Bound, t as DRAIN_RULES, u as Compression, v as Verdict, w as verdictOf, x as evaluate, y as compress } from "./rules-BBRopO1e.js";
8
+ 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";
9
+ import { a as limiterStateOf, i as limiterMachine, n as SLIDING_WINDOW_MACHINE, r as TOKEN_BUCKET_MACHINE, t as LimiterState } from "./limiter-BoZkXIxk.js";
10
+ import { a as JobSource, c as QueueKnobs, d as queueDrain, f as redeliverOnce, i as JobSettle, l as RedeliveryPolicy, n as JobContext, o as QueueDrain, p as UnitRequest, r as JobFailure, s as QueueDrainOptions, t as JobAction, u as RequeueCause } from "./queue-CvBNNZZJ.js";
10
11
  import { Extent, Quantity } from "@mark1russell7/quantity";
11
12
  import { replay } from "@mark1russell7/algebra/replay";
12
13
  import { Machine } from "@mark1russell7/algebra";
13
- //#region src/law.d.ts
14
- /**
15
- * This module is the evaluator of the timer-ordering law. Its decisions are the same as the
16
- * decisions of the research evaluator, except when absent timers leave no order (`evaluate`). The
17
- * rules are data, and the caller gives them. Each rule
18
- * is one or more linear inequalities over symbols at a hop (`readiness_detection_window@pod`),
19
- * with a margin. A binding maps `symbol@hop` to seconds, or to "inf" for a timer that is absent.
20
- */
21
- /** A term is a coefficient times one symbol, at a hop when it has one. */
22
- interface Term {
23
- readonly knob: string;
24
- readonly coef: number;
25
- readonly at?: string | undefined;
26
- }
27
- /** A side is a sum of terms, plus a constant. */
28
- interface Side {
29
- readonly terms: readonly Term[];
30
- readonly const?: number | undefined;
31
- }
32
- /** An inequality compares two sides, with a margin. */
33
- interface Inequality {
34
- readonly lhs: Side;
35
- readonly op: "<" | "<=" | ">" | ">=";
36
- readonly rhs: Side;
37
- /** The margin is in seconds, or it is words for a margin that no binding gives ("a factor of several"). Words count as 0. */
38
- readonly margin?: number | string | undefined;
39
- }
40
- /** A rule is one or more inequalities, with their statement in words. */
41
- interface Rule {
42
- readonly id: string;
43
- /** This text is the rule in words. */
44
- readonly rule: string;
45
- /** This text is the window that a violation opens. */
46
- readonly window?: string | undefined;
47
- readonly expr: Inequality;
48
- readonly expr_more?: readonly Inequality[] | undefined;
49
- }
50
- /** A bound is in seconds, or it is "inf" for an absent timer, or "off" for a disabled feature. The last two have no limit. */
51
- type Bound = number | "inf" | "off";
52
- /**
53
- * A binding maps `symbol@hop` to its bound. Its "margin" replaces the margin of each inequality.
54
- * Its "margins" replace them one by one, in sequence, as the binding of a chain can.
55
- */
56
- type Binding = Readonly<Record<string, Bound | readonly number[] | undefined>> & {
57
- readonly margin?: number | undefined;
58
- readonly margins?: readonly number[] | undefined;
59
- };
60
- /** A verdict is "holds", "violated", "unbounded" (it holds only because a timer is absent) or "depends" (nothing is bound). */
61
- type Verdict = "holds" | "violated" | "unbounded" | "depends";
62
- /** An evaluation is the value of each side of one inequality, its margin, and if it holds. */
63
- interface Evaluated {
64
- readonly lhs: number | null;
65
- readonly rhs: number | null;
66
- readonly margin: number;
67
- readonly holds: boolean | null;
68
- }
69
- /** This function gives the inequalities of a rule: its expr, then the others. */
70
- export declare const inequalities: (rule: Rule) => readonly Inequality[];
71
- /** This function gives the symbols that a rule reads, as `symbol@hop`. */
72
- export declare const symbolsOf: (rule: Rule) => string[];
73
- /**
74
- * This function evaluates each inequality on one binding. "<" holds when lhs + margin < rhs, and
75
- * ">" holds when lhs > rhs + margin. Only the inequalities with all their symbols bound apply.
76
- * The others are null. Absent timers can leave no order: the same infinity on each side, or both
77
- * signs of infinity on one side. Then the inequality holds only because a timer is absent.
78
- */
79
- export declare const evaluate: (rule: Rule, bind: Binding) => Evaluated[];
80
- /**
81
- * This function gives the verdict of an evaluation. When an applicable inequality fails, the
82
- * verdict is "violated". When all hold only because a timer is absent, the verdict is "unbounded",
83
- * because nothing then limits the window. Otherwise the verdict is "holds". When no inequality
84
- * applies, the arithmetic cannot decide, and the verdict is "depends".
85
- */
86
- export declare const verdictOf: (rule: Rule, bind: Binding, evaluated: readonly Evaluated[]) => Verdict;
87
- /**
88
- * A mark tells how a timer moves when a compression scales time by k (E10). A "scalable" timer
89
- * becomes k times its value. A "fixed" timer keeps its value. A "stepped" timer takes only
90
- * multiples of its step, thus it rounds up. A "floored" timer has a floor that a peer sets, for
91
- * example the minimum retransmission timeout of the kernel. The step and the floor are in seconds.
92
- */
93
- type TimerMark = {
94
- readonly kind: "scalable";
95
- } | {
96
- readonly kind: "fixed";
97
- } | {
98
- readonly kind: "stepped";
99
- readonly step: number;
100
- } | {
101
- readonly kind: "floored";
102
- readonly floor: number;
103
- readonly by: string;
104
- };
105
- /** The marks map `symbol@hop` to a mark. A bare symbol marks the symbol at each hop. */
106
- type TimerMarks = Readonly<Record<string, TimerMark | undefined>>;
107
- /** A compressed binding, and the symbols that have no mark. */
108
- interface Compressed {
109
- readonly bind: Binding;
110
- /** These symbols have no mark. They keep their values, thus the compression proves nothing about them. */
111
- readonly unmarked: readonly string[];
112
- }
113
- /** A change is a rule whose verdict a compression changes. */
114
- interface Change {
115
- readonly rule: string;
116
- readonly before: Verdict;
117
- readonly after: Verdict;
118
- }
119
- /** The result of a compression: the rules whose verdict it changes, and the symbols of the rules that have no mark. */
120
- interface Compression {
121
- readonly changed: readonly Change[];
122
- readonly unmarked: readonly string[];
123
- }
124
- /**
125
- * This function scales each timer of a binding by k, by its mark (E10). An absent timer ("inf" or
126
- * "off") stays absent. A chain scales each value. The margins of the binding and the constants of
127
- * the rules do not scale: they are tolerances, not timers. A symbol with no mark keeps its value.
128
- */
129
- export declare const compress: (bind: Binding, k: number, marks: TimerMarks) => Compressed;
130
- /**
131
- * This function tells which rules a compression by k changes. A compression keeps each ordering
132
- * when no verdict changes. A change in either direction counts: a violation that the compression
133
- * hides is as wrong as one that it makes. The unmarked symbols are the symbols that the rules read.
134
- */
135
- export declare const compression: (rules: readonly Rule[], bind: Binding, k: number, marks: TimerMarks) => Compression;
136
- //#endregion
137
14
  //#region src/lint.d.ts
138
15
  /**
139
16
  * This module applies the ordering law to a declaration. The declaration binds the symbols of the
@@ -309,7 +186,10 @@ interface Stop {
309
186
  /** These are the identifiers of the rules of the drain that guard this way. */
310
187
  readonly rules: readonly string[];
311
188
  }
312
- /** These are the rules of the drain. Each way of stopping applies only its own rules of this set. */
189
+ /**
190
+ * These are the identifiers of the rules of the drain, from the data of the entry `./rules`. Each
191
+ * way that a pod stops applies only its own rules of this set.
192
+ */
313
193
  export declare const DRAIN_RULE_IDS: readonly string[];
314
194
  /**
315
195
  * These are the four ways that a pod stops.
@@ -332,6 +212,43 @@ export declare const STOP_RULE = "stop";
332
212
  */
333
213
  export declare const lintStop: (svc: ServiceDescription, scenario: Scenario, rules: readonly Rule[], way: StopWay) => Finding[];
334
214
  //#endregion
215
+ //#region src/retrier.d.ts
216
+ /** These options make a retrier: a backoff policy, the clock of its timers, and the signal that cancels it. */
217
+ interface RetrierOptions extends Backoff {
218
+ /** This clock starts each retry. The default is the real clock. A test gives a fake clock. */
219
+ readonly clock?: Clock | undefined;
220
+ /** This function gives a number in [0, 1) for the jitter of each delay. The default is `Math.random`. */
221
+ readonly random?: (() => number) | undefined;
222
+ /**
223
+ * This signal cancels the retrier when it aborts, for example the `signal` of the lifecycle, which
224
+ * aborts in the drain. After the abort, `schedule` starts nothing.
225
+ */
226
+ readonly signal?: AbortSignal | undefined;
227
+ }
228
+ /** A retrier starts a function again after the backoff of each try, on its clock. */
229
+ interface Retrier {
230
+ /** This count is the number of tries since the last reset. */
231
+ readonly attempts: number;
232
+ /** This flag tells if a retry waits for its timer. */
233
+ readonly pending: boolean;
234
+ /**
235
+ * This method counts one more try, and starts `run` after the backoff delay of that try. It gives
236
+ * the delay in milliseconds. A retry that waits stops, thus one retry at most waits. After the
237
+ * abort of the signal, it starts nothing and gives null. The function catches its own errors.
238
+ */
239
+ schedule(run: () => void): number | null;
240
+ /** This method sets the count of tries to 0, for example after a start that succeeded. A retry that waits stays. */
241
+ reset(): void;
242
+ /** This method stops the retry that waits. The count of tries stays. */
243
+ cancel(): void;
244
+ }
245
+ /**
246
+ * This function makes a retrier over `backoffDelay`. The first try waits `base`, and each try after
247
+ * it waits `factor` times more, to the `cap`, with the jitter of the policy. It refuses a policy
248
+ * with a problem of `backoffProblems`.
249
+ */
250
+ export declare const retrier: (options: RetrierOptions) => Retrier;
251
+ //#endregion
335
252
  //#region src/worker.d.ts
336
253
  /**
337
254
  * These are the knobs of a worker loop, by the names of the ordering law where the law has them.
@@ -461,5 +378,5 @@ export declare const drainMachine: (description: ServiceDescription) => Machine;
461
378
  /** These are the static machines of the runtime, by the name that their events carry. */
462
379
  export declare const MACHINES: Readonly<Record<Exclude<MachineName, "drain" | "client">, Machine>>;
463
380
  //#endregion
464
- export { type Allowed, type Backoff, type Binding, type Bound, type Cancel, 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, 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 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 LogEntry, type LogFields, type LogLevel, type Logger, type MachineName, type MemoryStore, type MessageShape, type MessageTrigger, 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 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 Transport, type TransportImpl, type UnitRequest, type Verdict, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, consoleLogger, cooperativeAbortAt, daemon, decide, detectionTime, embeddedProcess, ephemeral, failSpan, freeAt, heartbeat, heartbeatDetection, idleSpan, isExitCode, isExitSignal, isMessageShape, keyedLimiter, kubernetes, limitRule, limiterMachine, limiterProblems, limiterStateOf, localDev, logEvents, longestRetryAfter, matchesMessage, mayReissue, memoryStore, nodeProcess, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, stageRank, watchdog };
381
+ export { type Allowed, type Backoff, type Binding, type Bound, type Cancel, 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 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 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 Transport, type TransportImpl, UNCAUGHT_ORIGINS, type UncaughtOptions, type UncaughtOrigin, type UnitRequest, type Verdict, type Watchdog, type WatchdogSpec, type WorkerKnobs, type WorkerLoop, type WorkerLoopOptions, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, 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, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, stageRank, symbolsOf, verdictOf, watchdog };
465
382
  //# sourceMappingURL=index.d.ts.map
package/build/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { platformClock, realClock } from "./clock.js";
2
2
  import { detectionTime, heartbeat } from "./heartbeat.js";
3
3
  import { a as recoverSpan, i as heartbeatDetection, n as asWindow, r as failSpan, t as asDebounce } from "./timing-DGRi3XCI.js";
4
- import { n as operationProblems, t as mayReissue } from "./operation-DL5RxFds.js";
4
+ import { i as operationProblems, r as mayReissue, t as retrier } from "./retrier-CRda6z9G.js";
5
5
  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";
6
6
  import { a as lateHolds, l as takeOutside, n as countOf, r as millisecondsOf, s as ownStream, t as boundedMillisecondsOf } from "./knobs-D2ClI68I.js";
7
7
  import { backoffBand, backoffDelay, backoffProblems } from "./backoff.js";
8
- 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-pkBZUp-t.js";
8
+ import { DRAIN_RULES, O04, O09, O10, O16 } from "./rules.js";
9
+ 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";
9
10
  import { convertExact, convertible, quantity, rationals, valueIn } from "@mark1russell7/quantity";
10
11
  import { replay } from "@mark1russell7/algebra/replay";
11
12
  //#region src/description.ts
@@ -619,16 +620,50 @@ const LOG_LEVELS = [
619
620
  ];
620
621
  /** This function tells if `level` is at `least` or more severe. */
621
622
  const atLeast = (level, least) => LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(least);
623
+ /** This function gives a value of a field that JSON can write: an error as its name, message and stack, and a bigint as text. */
624
+ const jsonValue = (_key, value) => {
625
+ if (typeof value === "bigint") return value.toString();
626
+ if (value instanceof Error) return {
627
+ name: value.name,
628
+ message: value.message,
629
+ ...value.stack === void 0 ? {} : { stack: value.stack }
630
+ };
631
+ return value;
632
+ };
633
+ /**
634
+ * This function gives one line of JSON for an entry. A field named `level` or `message` does not
635
+ * replace the level or the message. A field that JSON cannot write, for example a cycle, gives its failure as text.
636
+ */
637
+ const jsonLine = (level, message, fields) => {
638
+ const { level: _level, message: _message, ...rest } = fields;
639
+ try {
640
+ return JSON.stringify({
641
+ level,
642
+ message,
643
+ ...rest
644
+ }, jsonValue);
645
+ } catch (error) {
646
+ return JSON.stringify({
647
+ level,
648
+ message,
649
+ unwritten: error instanceof Error ? error.message : String(error)
650
+ });
651
+ }
652
+ };
622
653
  /**
623
654
  * This function makes the console logger. It writes each entry at its level or more severe to the
624
- * method of that level, with the message first and then the fields.
655
+ * method of that level. In the format `text`, it writes the message first and then the fields. In
656
+ * the format `json`, it writes one line of JSON.
625
657
  */
626
658
  const consoleLogger = (options = {}) => {
627
659
  const least = options.level ?? "info";
660
+ const format = options.format ?? "text";
661
+ if (format !== "text" && format !== "json") throw new Error(`the log format ${JSON.stringify(format)} is not "text" or "json"`);
628
662
  return { log(level, message, fields) {
629
663
  if (!atLeast(level, least)) return;
630
664
  const target = options.console ?? globalThis.console;
631
- if (Object.keys(fields).length === 0) target[level](message);
665
+ if (format === "json") target[level](jsonLine(level, message, fields));
666
+ else if (Object.keys(fields).length === 0) target[level](message);
632
667
  else target[level](message, fields);
633
668
  } };
634
669
  };
@@ -756,6 +791,8 @@ const PROCESS_TRIGGERS = [
756
791
  "ipc-close",
757
792
  "ipc-message"
758
793
  ];
794
+ /** These are the origins of the errors that the option `uncaught` of `run()` receives. */
795
+ const UNCAUGHT_ORIGINS = ["uncaughtException", "unhandledRejection"];
759
796
  /** This function tells if a number is an exit code of a process: a whole number from 0 to 255. */
760
797
  const isExitCode = (code) => Number.isInteger(code) && code >= 0 && code <= 255;
761
798
  /** This function tells if a trigger is an exit signal. A repeat signal obeys `onRepeatSignal`. */
@@ -847,6 +884,19 @@ const processPortOf = (find) => {
847
884
  host.off(trigger, handler);
848
885
  };
849
886
  },
887
+ onUncaught(handler) {
888
+ const host = hostProcess();
889
+ const offs = UNCAUGHT_ORIGINS.map((origin) => {
890
+ const receive = (error) => handler(error, origin);
891
+ host.on(origin, receive);
892
+ return () => {
893
+ host.off(origin, receive);
894
+ };
895
+ });
896
+ return () => {
897
+ for (const off of offs) off();
898
+ };
899
+ },
850
900
  async flush() {
851
901
  const host = hostProcess();
852
902
  await Promise.all([written(host.stdout), written(host.stderr)]);
@@ -1515,7 +1565,18 @@ const cooperativeAbortAt = (cap, window, floor = "half") => {
1515
1565
  const before = window.value === "infinite" ? Number.POSITIVE_INFINITY : valueIn(window, "ms");
1516
1566
  return Math.max(cap - before, floor === "none" ? 0 : cap / 2);
1517
1567
  };
1568
+ /** This function gives the problems of the option `uncaught`: an exit code that is not from 0 to 255. */
1569
+ const uncaughtProblems = (uncaught) => {
1570
+ const code = uncaught?.exitCode;
1571
+ return code === void 0 || isExitCode(code) ? [] : [`the exit code ${code} of an uncaught error is not a whole number from 0 to 255`];
1572
+ };
1518
1573
  const message = (error) => error instanceof Error ? error.message : String(error);
1574
+ /** This function gives the text of an error with its stack, when it has one. */
1575
+ const withStack = (error) => error instanceof Error && typeof error.stack === "string" && error.stack.length > 0 ? error.stack : message(error);
1576
+ const UNCAUGHT_NAMES = {
1577
+ uncaughtException: "an uncaught exception",
1578
+ unhandledRejection: "an unhandled rejection"
1579
+ };
1519
1580
  /**
1520
1581
  * This function gives the problems of a declaration that the lifecycle cannot start: a stage with
1521
1582
  * work and no declared phase. The runtime has no defaults, thus a transport without a drain phase
@@ -1630,6 +1691,31 @@ const lifecycle = (description, runtime, components, options = {}, bind = () =>
1630
1691
  if (found.as === void 0) triggered("ipc-message");
1631
1692
  else triggered(found.as, `${found.as} (a message of the IPC channel)`);
1632
1693
  };
1694
+ const uncaught = options.uncaught;
1695
+ const uncaughtCode = uncaught?.exitCode !== void 0 && isExitCode(uncaught.exitCode) ? uncaught.exitCode : 1;
1696
+ /**
1697
+ * This function receives an error that no code caught. A skipped error goes to the logger at
1698
+ * `warn`. Each other error is an error of the lifecycle, and it starts the shutdown with its code.
1699
+ */
1700
+ const caught = (error, origin) => {
1701
+ if (exitState === "exited") return;
1702
+ const name = UNCAUGHT_NAMES[origin];
1703
+ let skip = false;
1704
+ try {
1705
+ skip = uncaught?.ignore?.(error, origin) === true;
1706
+ } catch {}
1707
+ if (skip) {
1708
+ try {
1709
+ options.logger?.log("warn", `${name} was skipped: ${message(error)}`, {
1710
+ origin,
1711
+ error: withStack(error)
1712
+ });
1713
+ } catch {}
1714
+ return;
1715
+ }
1716
+ fail(`${name}: ${withStack(error)}`);
1717
+ shutdown(`${name}: ${message(error)}`, { code: uncaughtCode });
1718
+ };
1633
1719
  /**
1634
1720
  * This function does the work of one phase, until its cap. It tells if the work ended in time. When
1635
1721
  * work is left at the cap, `excuse` gives the cause of a cap that is not a failure, or null.
@@ -1801,6 +1887,7 @@ const lifecycle = (description, runtime, components, options = {}, bind = () =>
1801
1887
  bind(life);
1802
1888
  release = port.hold?.() ?? (() => {});
1803
1889
  offs = [...EXIT_SIGNALS, ...description.shutdown.triggers ?? []].map((trigger) => port.on(trigger, trigger === "ipc-message" ? received : () => triggered(trigger)));
1890
+ if (uncaught !== void 0 && port.onUncaught !== void 0) offs.push(port.onUncaught(caught));
1804
1891
  (async () => {
1805
1892
  const started = (what) => record("gate", "starting", "starting", "component.started", what);
1806
1893
  try {
@@ -2357,7 +2444,7 @@ const service = (name) => {
2357
2444
  choices,
2358
2445
  stopPollers: () => {}
2359
2446
  };
2360
- const problems = lifecycleProblems(description, components);
2447
+ const problems = [...lifecycleProblems(description, components), ...uncaughtProblems(options.uncaught)];
2361
2448
  if (problems.length > 0) throw new Error(`${name}: ${problems.join("; ")}`);
2362
2449
  const made = makeRuntime(options);
2363
2450
  started = true;
@@ -3095,13 +3182,11 @@ const lint = (svc, scenario, rules) => {
3095
3182
  };
3096
3183
  //#endregion
3097
3184
  //#region src/stops.ts
3098
- /** These are the rules of the drain. Each way of stopping applies only its own rules of this set. */
3099
- const DRAIN_RULE_IDS = [
3100
- "O04",
3101
- "O09",
3102
- "O10",
3103
- "O16"
3104
- ];
3185
+ /**
3186
+ * These are the identifiers of the rules of the drain, from the data of the entry `./rules`. Each
3187
+ * way that a pod stops applies only its own rules of this set.
3188
+ */
3189
+ const DRAIN_RULE_IDS = DRAIN_RULES.map((rule) => rule.id);
3105
3190
  /**
3106
3191
  * These are the four ways that a pod stops.
3107
3192
  * - A deletion runs the preStop hook, then SIGTERM. The endpoints drop the pod at its deletion,
@@ -4164,6 +4249,6 @@ const MACHINES = {
4164
4249
  watchdog: WATCHDOG_MACHINE
4165
4250
  };
4166
4251
  //#endregion
4167
- export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, LATCH_MACHINE, LAW_STATISTIC, LIMITER_RULES, LOG_LEVELS, MACHINES, NAME_RULE, PLATFORM_MARKS, POLLER_MACHINE, PROCESS_TRIGGERS, PROGRESS_RULE, SERVICE_RULES, SLIDING_WINDOW_MACHINE, STAGES, STOPS, STOP_RULE, TOKEN_BUCKET_MACHINE, UNIT_BOUND_RULE, WATCHDOG_MACHINE, WINDOW_MACHINE, asDebounce, asWindow, atLeast, backoffBand, backoffDelay, backoffProblems, capKnob, 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, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
4252
+ export { BOUND_RULES, CLOSE_BOUND_RULE, DECLARATION_RULE, DRAIN_RULES, DRAIN_RULE_IDS, DURATION_FRACTIONS, EPISODES_KEPT, EXIT_MACHINE, EXIT_SIGNALS, FORMAT, GATE_MACHINE, 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, 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, platformClock, processPortOf, queueDrain, realClock, recoverSpan, redact, redeliverOnce, replay, retrier, retryAfterSeconds, service, serviceBindings, stageRank, symbolsOf, verdictOf, watchdog, workerLoop };
4168
4253
 
4169
4254
  //# sourceMappingURL=index.js.map