@weaveintel/resilience 0.0.1
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/dist/circuit-breaker.d.ts +48 -0
- package/dist/circuit-breaker.d.ts.map +1 -0
- package/dist/circuit-breaker.js +79 -0
- package/dist/circuit-breaker.js.map +1 -0
- package/dist/concurrency.d.ts +19 -0
- package/dist/concurrency.d.ts.map +1 -0
- package/dist/concurrency.js +37 -0
- package/dist/concurrency.js.map +1 -0
- package/dist/endpoint-registry.d.ts +70 -0
- package/dist/endpoint-registry.d.ts.map +1 -0
- package/dist/endpoint-registry.js +137 -0
- package/dist/endpoint-registry.js.map +1 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +34 -0
- package/dist/index.js.map +1 -0
- package/dist/keyed-rate-limiter.d.ts +35 -0
- package/dist/keyed-rate-limiter.d.ts.map +1 -0
- package/dist/keyed-rate-limiter.js +62 -0
- package/dist/keyed-rate-limiter.js.map +1 -0
- package/dist/latency-tracker.d.ts +116 -0
- package/dist/latency-tracker.d.ts.map +1 -0
- package/dist/latency-tracker.js +207 -0
- package/dist/latency-tracker.js.map +1 -0
- package/dist/pipeline.d.ts +45 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +204 -0
- package/dist/pipeline.js.map +1 -0
- package/dist/retry-policy.d.ts +30 -0
- package/dist/retry-policy.d.ts.map +1 -0
- package/dist/retry-policy.js +54 -0
- package/dist/retry-policy.js.map +1 -0
- package/dist/runtime-adapter.d.ts +44 -0
- package/dist/runtime-adapter.d.ts.map +1 -0
- package/dist/runtime-adapter.js +59 -0
- package/dist/runtime-adapter.js.map +1 -0
- package/dist/signal-bus.d.ts +23 -0
- package/dist/signal-bus.d.ts.map +1 -0
- package/dist/signal-bus.js +71 -0
- package/dist/signal-bus.js.map +1 -0
- package/dist/token-bucket.d.ts +33 -0
- package/dist/token-bucket.d.ts.map +1 -0
- package/dist/token-bucket.js +74 -0
- package/dist/token-bucket.js.map +1 -0
- package/dist/types.d.ts +71 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +5 -0
- package/dist/types.js.map +1 -0
- package/package.json +35 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @weaveintel/resilience — Per-endpoint latency percentile tracker
|
|
3
|
+
*
|
|
4
|
+
* Maintains a sliding-window of observed request durations per endpoint and
|
|
5
|
+
* exposes P50/P95/P99 statistics. These statistics serve two purposes:
|
|
6
|
+
*
|
|
7
|
+
* 1. Dynamic timeout fallback — `composeRequestSignal` in each provider uses
|
|
8
|
+
* `P95 × 2` as the fallback AbortSignal timeout so background calls adapt
|
|
9
|
+
* to actual observed latency instead of a hard-coded 5-minute constant.
|
|
10
|
+
*
|
|
11
|
+
* 2. Degradation detection — callers can compare the current call's latency
|
|
12
|
+
* against `P99 × DEGRADATION_MULTIPLIER` (3) to detect a provider that
|
|
13
|
+
* is still responding but taking 3× longer than its P99 baseline.
|
|
14
|
+
*
|
|
15
|
+
* Only successful call durations are recorded. Failures (auth errors, network
|
|
16
|
+
* errors) are excluded so the baseline reflects healthy-state latency.
|
|
17
|
+
*
|
|
18
|
+
* Design choices aligned with mid-2026 production patterns:
|
|
19
|
+
* - 60-second sliding time window (LiteLLM TTL default)
|
|
20
|
+
* - 100-sample hard cap per endpoint
|
|
21
|
+
* - Minimum 10 samples before percentiles are trusted (LiteLLM: 5, industry: 10–20)
|
|
22
|
+
* - P95 × 2 for dynamic timeout; P99 × 3 for degradation detection
|
|
23
|
+
*/
|
|
24
|
+
export interface LatencySnapshot {
|
|
25
|
+
readonly p50: number;
|
|
26
|
+
readonly p95: number;
|
|
27
|
+
readonly p99: number;
|
|
28
|
+
readonly sampleCount: number;
|
|
29
|
+
readonly windowMs: number;
|
|
30
|
+
}
|
|
31
|
+
export interface LatencyTracker {
|
|
32
|
+
/** Record one successful call duration for an endpoint. */
|
|
33
|
+
record(endpointId: string, latencyMs: number): void;
|
|
34
|
+
/** Returns percentile snapshot, or undefined if fewer than minSamples exist. */
|
|
35
|
+
getSnapshot(endpointId: string): LatencySnapshot | undefined;
|
|
36
|
+
/** Convenience: P50 or undefined if too few samples. */
|
|
37
|
+
getP50(endpointId: string): number | undefined;
|
|
38
|
+
/** Convenience: P95 or undefined if too few samples. */
|
|
39
|
+
getP95(endpointId: string): number | undefined;
|
|
40
|
+
/** Convenience: P99 or undefined if too few samples. */
|
|
41
|
+
getP99(endpointId: string): number | undefined;
|
|
42
|
+
/** Reset a specific endpoint (test-only). */
|
|
43
|
+
_reset(endpointId?: string): void;
|
|
44
|
+
}
|
|
45
|
+
export interface LatencyTrackerOptions {
|
|
46
|
+
/** Max number of samples to retain per endpoint. Default: 100 */
|
|
47
|
+
windowSize?: number;
|
|
48
|
+
/** Samples older than this are discarded. Default: 60_000 ms (60 s) */
|
|
49
|
+
windowMs?: number;
|
|
50
|
+
/** Minimum samples required before returning a percentile. Default: 10 */
|
|
51
|
+
minSamples?: number;
|
|
52
|
+
}
|
|
53
|
+
export declare function createLatencyTracker(opts?: LatencyTrackerOptions): LatencyTracker;
|
|
54
|
+
/** Returns the process-global LatencyTracker singleton (lazy-init). */
|
|
55
|
+
export declare function getGlobalLatencyTracker(): LatencyTracker;
|
|
56
|
+
/** Record one successful call latency in the process-global tracker. */
|
|
57
|
+
export declare function recordLatency(endpointId: string, latencyMs: number): void;
|
|
58
|
+
/** Returns P95 for an endpoint from the global tracker, or undefined if cold. */
|
|
59
|
+
export declare function getP95Latency(endpointId: string): number | undefined;
|
|
60
|
+
/** Returns P99 for an endpoint from the global tracker, or undefined if cold. */
|
|
61
|
+
export declare function getP99Latency(endpointId: string): number | undefined;
|
|
62
|
+
/** Returns full snapshot for an endpoint from the global tracker. */
|
|
63
|
+
export declare function getLatencySnapshot(endpointId: string): LatencySnapshot | undefined;
|
|
64
|
+
/** Replace the process-global tracker (test-only). */
|
|
65
|
+
export declare function _setGlobalLatencyTracker(t: LatencyTracker | undefined): void;
|
|
66
|
+
/** P99 multiplier that, when exceeded by a single call, signals degradation. */
|
|
67
|
+
export declare const DEGRADATION_MULTIPLIER = 3;
|
|
68
|
+
/** Minimum latency in ms for degradation detection to fire.
|
|
69
|
+
* Prevents false positives on very short P99 baselines (e.g. P99=1 s → 3 s threshold). */
|
|
70
|
+
export declare const MIN_DEGRADATION_LATENCY_MS = 15000;
|
|
71
|
+
/** Duration of the soft block applied when degradation is detected. */
|
|
72
|
+
export declare const DEGRADATION_BLOCK_MS = 30000;
|
|
73
|
+
/** Multiplier applied to P95 to compute a dynamic provider-level fallback timeout.
|
|
74
|
+
* Never below MIN_DYNAMIC_TIMEOUT_MS; never above the static DEFAULT. */
|
|
75
|
+
export declare const DYNAMIC_TIMEOUT_MULTIPLIER = 2;
|
|
76
|
+
/** Floor for the dynamic timeout — providers won't be given less than 30 s regardless of P95. */
|
|
77
|
+
export declare const MIN_DYNAMIC_TIMEOUT_MS = 30000;
|
|
78
|
+
/**
|
|
79
|
+
* Tracks observed milliseconds-per-output-token per endpoint.
|
|
80
|
+
* Feeds `selectStreamBudget` with a P50 ms/token value so the context
|
|
81
|
+
* deadline can be tightened to `estimated_tokens × p50MsPerToken × 1.5`
|
|
82
|
+
* rather than always using the static 2/5/10 minute caps.
|
|
83
|
+
*
|
|
84
|
+
* Only successful completions with > 0 output tokens are recorded.
|
|
85
|
+
* Rate-limited or errored calls are excluded so the baseline reflects
|
|
86
|
+
* healthy throughput, not degraded-state throughput.
|
|
87
|
+
*/
|
|
88
|
+
export interface ThroughputTracker {
|
|
89
|
+
/** Record one successful completion: total duration and number of output tokens. */
|
|
90
|
+
record(endpointId: string, durationMs: number, outputTokens: number): void;
|
|
91
|
+
/** P50 milliseconds-per-output-token, or undefined if fewer than minSamples. */
|
|
92
|
+
getP50MsPerToken(endpointId: string): number | undefined;
|
|
93
|
+
/** Reset (test-only). */
|
|
94
|
+
_reset(endpointId?: string): void;
|
|
95
|
+
}
|
|
96
|
+
export interface ThroughputTrackerOptions {
|
|
97
|
+
/** Max samples per endpoint. Default: 100 */
|
|
98
|
+
windowSize?: number;
|
|
99
|
+
/** Discard samples older than this. Default: 60_000 ms */
|
|
100
|
+
windowMs?: number;
|
|
101
|
+
/** Minimum samples before returning a value. Default: 5 */
|
|
102
|
+
minSamples?: number;
|
|
103
|
+
}
|
|
104
|
+
export declare function createThroughputTracker(opts?: ThroughputTrackerOptions): ThroughputTracker;
|
|
105
|
+
export declare function getGlobalThroughputTracker(): ThroughputTracker;
|
|
106
|
+
/** Record one successful completion in the process-global tracker. */
|
|
107
|
+
export declare function recordThroughput(endpointId: string, durationMs: number, outputTokens: number): void;
|
|
108
|
+
/** P50 ms/token for an endpoint from the global tracker, or undefined if cold. */
|
|
109
|
+
export declare function getP50MsPerToken(endpointId: string): number | undefined;
|
|
110
|
+
/** Replace the global throughput tracker (test-only). */
|
|
111
|
+
export declare function _setGlobalThroughputTracker(t: ThroughputTracker | undefined): void;
|
|
112
|
+
/** Safety multiplier applied on top of estimated_tokens × p50MsPerToken. */
|
|
113
|
+
export declare const ADAPTIVE_BUDGET_SAFETY_FACTOR = 1.5;
|
|
114
|
+
/** Never shrink the deadline below this floor regardless of token estimate. */
|
|
115
|
+
export declare const ADAPTIVE_BUDGET_MIN_MS = 30000;
|
|
116
|
+
//# sourceMappingURL=latency-tracker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"latency-tracker.d.ts","sourceRoot":"","sources":["../src/latency-tracker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;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,2BAA2B,CAAC,CAAC,EAAE,iBAAiB,GAAG,SAAS,GAAG,IAAI,CAElF;AAID,4EAA4E;AAC5E,eAAO,MAAM,6BAA6B,MAAM,CAAC;AAEjD,+EAA+E;AAC/E,eAAO,MAAM,sBAAsB,QAAS,CAAC"}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @weaveintel/resilience — Per-endpoint latency percentile tracker
|
|
3
|
+
*
|
|
4
|
+
* Maintains a sliding-window of observed request durations per endpoint and
|
|
5
|
+
* exposes P50/P95/P99 statistics. These statistics serve two purposes:
|
|
6
|
+
*
|
|
7
|
+
* 1. Dynamic timeout fallback — `composeRequestSignal` in each provider uses
|
|
8
|
+
* `P95 × 2` as the fallback AbortSignal timeout so background calls adapt
|
|
9
|
+
* to actual observed latency instead of a hard-coded 5-minute constant.
|
|
10
|
+
*
|
|
11
|
+
* 2. Degradation detection — callers can compare the current call's latency
|
|
12
|
+
* against `P99 × DEGRADATION_MULTIPLIER` (3) to detect a provider that
|
|
13
|
+
* is still responding but taking 3× longer than its P99 baseline.
|
|
14
|
+
*
|
|
15
|
+
* Only successful call durations are recorded. Failures (auth errors, network
|
|
16
|
+
* errors) are excluded so the baseline reflects healthy-state latency.
|
|
17
|
+
*
|
|
18
|
+
* Design choices aligned with mid-2026 production patterns:
|
|
19
|
+
* - 60-second sliding time window (LiteLLM TTL default)
|
|
20
|
+
* - 100-sample hard cap per endpoint
|
|
21
|
+
* - Minimum 10 samples before percentiles are trusted (LiteLLM: 5, industry: 10–20)
|
|
22
|
+
* - P95 × 2 for dynamic timeout; P99 × 3 for degradation detection
|
|
23
|
+
*/
|
|
24
|
+
export function createLatencyTracker(opts) {
|
|
25
|
+
const windowSize = opts?.windowSize ?? 100;
|
|
26
|
+
const windowMs = opts?.windowMs ?? 60_000;
|
|
27
|
+
const minSamples = opts?.minSamples ?? 10;
|
|
28
|
+
// Map<endpointId, [latencyMs, timestamp][]> — stored as pairs for memory efficiency
|
|
29
|
+
const store = new Map();
|
|
30
|
+
function getOrCreate(endpointId) {
|
|
31
|
+
let arr = store.get(endpointId);
|
|
32
|
+
if (!arr) {
|
|
33
|
+
arr = [];
|
|
34
|
+
store.set(endpointId, arr);
|
|
35
|
+
}
|
|
36
|
+
return arr;
|
|
37
|
+
}
|
|
38
|
+
function trim(arr) {
|
|
39
|
+
const cutoff = Date.now() - windowMs;
|
|
40
|
+
// arr is insertion-ordered; expired entries are at the front
|
|
41
|
+
let start = 0;
|
|
42
|
+
while (start < arr.length && arr[start][1] < cutoff)
|
|
43
|
+
start++;
|
|
44
|
+
if (start > 0)
|
|
45
|
+
arr.splice(0, start);
|
|
46
|
+
// Hard cap — keep only the most recent windowSize entries
|
|
47
|
+
if (arr.length > windowSize)
|
|
48
|
+
arr.splice(0, arr.length - windowSize);
|
|
49
|
+
}
|
|
50
|
+
function percentile(sorted, p) {
|
|
51
|
+
if (!sorted.length)
|
|
52
|
+
return 0;
|
|
53
|
+
const idx = Math.min(Math.floor(sorted.length * p), sorted.length - 1);
|
|
54
|
+
return sorted[idx];
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
record(endpointId, latencyMs) {
|
|
58
|
+
const arr = getOrCreate(endpointId);
|
|
59
|
+
arr.push([latencyMs, Date.now()]);
|
|
60
|
+
trim(arr);
|
|
61
|
+
},
|
|
62
|
+
getSnapshot(endpointId) {
|
|
63
|
+
const arr = getOrCreate(endpointId);
|
|
64
|
+
trim(arr);
|
|
65
|
+
if (arr.length < minSamples)
|
|
66
|
+
return undefined;
|
|
67
|
+
const sorted = arr.map(([ms]) => ms).sort((a, b) => a - b);
|
|
68
|
+
return {
|
|
69
|
+
p50: percentile(sorted, 0.50),
|
|
70
|
+
p95: percentile(sorted, 0.95),
|
|
71
|
+
p99: percentile(sorted, 0.99),
|
|
72
|
+
sampleCount: sorted.length,
|
|
73
|
+
windowMs,
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
getP50(endpointId) {
|
|
77
|
+
return this.getSnapshot(endpointId)?.p50;
|
|
78
|
+
},
|
|
79
|
+
getP95(endpointId) {
|
|
80
|
+
return this.getSnapshot(endpointId)?.p95;
|
|
81
|
+
},
|
|
82
|
+
getP99(endpointId) {
|
|
83
|
+
return this.getSnapshot(endpointId)?.p99;
|
|
84
|
+
},
|
|
85
|
+
_reset(endpointId) {
|
|
86
|
+
if (endpointId)
|
|
87
|
+
store.delete(endpointId);
|
|
88
|
+
else
|
|
89
|
+
store.clear();
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
// ─── Process-wide singleton ───────────────────────────────────────────────────
|
|
94
|
+
let _global;
|
|
95
|
+
/** Returns the process-global LatencyTracker singleton (lazy-init). */
|
|
96
|
+
export function getGlobalLatencyTracker() {
|
|
97
|
+
if (!_global)
|
|
98
|
+
_global = createLatencyTracker();
|
|
99
|
+
return _global;
|
|
100
|
+
}
|
|
101
|
+
/** Record one successful call latency in the process-global tracker. */
|
|
102
|
+
export function recordLatency(endpointId, latencyMs) {
|
|
103
|
+
getGlobalLatencyTracker().record(endpointId, latencyMs);
|
|
104
|
+
}
|
|
105
|
+
/** Returns P95 for an endpoint from the global tracker, or undefined if cold. */
|
|
106
|
+
export function getP95Latency(endpointId) {
|
|
107
|
+
return getGlobalLatencyTracker().getP95(endpointId);
|
|
108
|
+
}
|
|
109
|
+
/** Returns P99 for an endpoint from the global tracker, or undefined if cold. */
|
|
110
|
+
export function getP99Latency(endpointId) {
|
|
111
|
+
return getGlobalLatencyTracker().getP99(endpointId);
|
|
112
|
+
}
|
|
113
|
+
/** Returns full snapshot for an endpoint from the global tracker. */
|
|
114
|
+
export function getLatencySnapshot(endpointId) {
|
|
115
|
+
return getGlobalLatencyTracker().getSnapshot(endpointId);
|
|
116
|
+
}
|
|
117
|
+
/** Replace the process-global tracker (test-only). */
|
|
118
|
+
export function _setGlobalLatencyTracker(t) {
|
|
119
|
+
_global = t;
|
|
120
|
+
}
|
|
121
|
+
// ─── Degradation constants ────────────────────────────────────────────────────
|
|
122
|
+
/** P99 multiplier that, when exceeded by a single call, signals degradation. */
|
|
123
|
+
export const DEGRADATION_MULTIPLIER = 3;
|
|
124
|
+
/** Minimum latency in ms for degradation detection to fire.
|
|
125
|
+
* Prevents false positives on very short P99 baselines (e.g. P99=1 s → 3 s threshold). */
|
|
126
|
+
export const MIN_DEGRADATION_LATENCY_MS = 15_000;
|
|
127
|
+
/** Duration of the soft block applied when degradation is detected. */
|
|
128
|
+
export const DEGRADATION_BLOCK_MS = 30_000;
|
|
129
|
+
/** Multiplier applied to P95 to compute a dynamic provider-level fallback timeout.
|
|
130
|
+
* Never below MIN_DYNAMIC_TIMEOUT_MS; never above the static DEFAULT. */
|
|
131
|
+
export const DYNAMIC_TIMEOUT_MULTIPLIER = 2;
|
|
132
|
+
/** Floor for the dynamic timeout — providers won't be given less than 30 s regardless of P95. */
|
|
133
|
+
export const MIN_DYNAMIC_TIMEOUT_MS = 30_000;
|
|
134
|
+
export function createThroughputTracker(opts) {
|
|
135
|
+
const windowSize = opts?.windowSize ?? 100;
|
|
136
|
+
const windowMs = opts?.windowMs ?? 60_000;
|
|
137
|
+
const minSamples = opts?.minSamples ?? 5;
|
|
138
|
+
// Map<endpointId, [msPerToken, timestamp][]>
|
|
139
|
+
const store = new Map();
|
|
140
|
+
function getOrCreate(endpointId) {
|
|
141
|
+
let arr = store.get(endpointId);
|
|
142
|
+
if (!arr) {
|
|
143
|
+
arr = [];
|
|
144
|
+
store.set(endpointId, arr);
|
|
145
|
+
}
|
|
146
|
+
return arr;
|
|
147
|
+
}
|
|
148
|
+
function trim(arr) {
|
|
149
|
+
const cutoff = Date.now() - windowMs;
|
|
150
|
+
let start = 0;
|
|
151
|
+
while (start < arr.length && arr[start][1] < cutoff)
|
|
152
|
+
start++;
|
|
153
|
+
if (start > 0)
|
|
154
|
+
arr.splice(0, start);
|
|
155
|
+
if (arr.length > windowSize)
|
|
156
|
+
arr.splice(0, arr.length - windowSize);
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
record(endpointId, durationMs, outputTokens) {
|
|
160
|
+
if (outputTokens <= 0)
|
|
161
|
+
return;
|
|
162
|
+
const arr = getOrCreate(endpointId);
|
|
163
|
+
arr.push([durationMs / outputTokens, Date.now()]);
|
|
164
|
+
trim(arr);
|
|
165
|
+
},
|
|
166
|
+
getP50MsPerToken(endpointId) {
|
|
167
|
+
const arr = getOrCreate(endpointId);
|
|
168
|
+
trim(arr);
|
|
169
|
+
if (arr.length < minSamples)
|
|
170
|
+
return undefined;
|
|
171
|
+
const sorted = arr.map(([ms]) => ms).sort((a, b) => a - b);
|
|
172
|
+
const idx = Math.min(Math.floor(sorted.length * 0.5), sorted.length - 1);
|
|
173
|
+
return sorted[idx];
|
|
174
|
+
},
|
|
175
|
+
_reset(endpointId) {
|
|
176
|
+
if (endpointId)
|
|
177
|
+
store.delete(endpointId);
|
|
178
|
+
else
|
|
179
|
+
store.clear();
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
// ─── Throughput process-global singleton ─────────────────────────────────────
|
|
184
|
+
let _globalThroughput;
|
|
185
|
+
export function getGlobalThroughputTracker() {
|
|
186
|
+
if (!_globalThroughput)
|
|
187
|
+
_globalThroughput = createThroughputTracker();
|
|
188
|
+
return _globalThroughput;
|
|
189
|
+
}
|
|
190
|
+
/** Record one successful completion in the process-global tracker. */
|
|
191
|
+
export function recordThroughput(endpointId, durationMs, outputTokens) {
|
|
192
|
+
getGlobalThroughputTracker().record(endpointId, durationMs, outputTokens);
|
|
193
|
+
}
|
|
194
|
+
/** P50 ms/token for an endpoint from the global tracker, or undefined if cold. */
|
|
195
|
+
export function getP50MsPerToken(endpointId) {
|
|
196
|
+
return getGlobalThroughputTracker().getP50MsPerToken(endpointId);
|
|
197
|
+
}
|
|
198
|
+
/** Replace the global throughput tracker (test-only). */
|
|
199
|
+
export function _setGlobalThroughputTracker(t) {
|
|
200
|
+
_globalThroughput = t;
|
|
201
|
+
}
|
|
202
|
+
// ─── Adaptive budget constants (Phase 5) ─────────────────────────────────────
|
|
203
|
+
/** Safety multiplier applied on top of estimated_tokens × p50MsPerToken. */
|
|
204
|
+
export const ADAPTIVE_BUDGET_SAFETY_FACTOR = 1.5;
|
|
205
|
+
/** Never shrink the deadline below this floor regardless of token estimate. */
|
|
206
|
+
export const ADAPTIVE_BUDGET_MIN_MS = 30_000;
|
|
207
|
+
//# sourceMappingURL=latency-tracker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"latency-tracker.js","sourceRoot":"","sources":["../src/latency-tracker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAkCH,MAAM,UAAU,oBAAoB,CAAC,IAA4B;IAC/D,MAAM,UAAU,GAAG,IAAI,EAAE,UAAU,IAAI,GAAG,CAAC;IAC3C,MAAM,QAAQ,GAAK,IAAI,EAAE,QAAQ,IAAM,MAAM,CAAC;IAC9C,MAAM,UAAU,GAAG,IAAI,EAAE,UAAU,IAAI,EAAE,CAAC;IAE1C,oFAAoF;IACpF,MAAM,KAAK,GAAG,IAAI,GAAG,EAAmC,CAAC;IAEzD,SAAS,WAAW,CAAC,UAAkB;QACrC,IAAI,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAChC,IAAI,CAAC,GAAG,EAAE,CAAC;YAAC,GAAG,GAAG,EAAE,CAAC;YAAC,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;QAAC,CAAC;QACnD,OAAO,GAAG,CAAC;IACb,CAAC;IAED,SAAS,IAAI,CAAC,GAA4B;QACxC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC;QACrC,6DAA6D;QAC7D,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,OAAO,KAAK,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,KAAK,CAAE,CAAC,CAA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,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACzE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC;QAED,MAAM,CAAC,UAAU;YACf,IAAI,UAAU;gBAAE,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;;gBACpC,KAAK,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;KACF,CAAC;AACJ,CAAC;AAED,gFAAgF;AAEhF,IAAI,iBAAgD,CAAC;AAErD,MAAM,UAAU,0BAA0B;IACxC,IAAI,CAAC,iBAAiB;QAAE,iBAAiB,GAAG,uBAAuB,EAAE,CAAC;IACtE,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,gBAAgB,CAAC,UAAkB,EAAE,UAAkB,EAAE,YAAoB;IAC3F,0BAA0B,EAAE,CAAC,MAAM,CAAC,UAAU,EAAE,UAAU,EAAE,YAAY,CAAC,CAAC;AAC5E,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,gBAAgB,CAAC,UAAkB;IACjD,OAAO,0BAA0B,EAAE,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC;AACnE,CAAC;AAED,yDAAyD;AACzD,MAAM,UAAU,2BAA2B,CAAC,CAAgC;IAC1E,iBAAiB,GAAG,CAAC,CAAC;AACxB,CAAC;AAED,gFAAgF;AAEhF,4EAA4E;AAC5E,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AAEjD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @weaveintel/resilience — Pipeline composer
|
|
3
|
+
*
|
|
4
|
+
* `createResilientCallable(fn, opts)` wraps `fn` with the full resilience
|
|
5
|
+
* pipeline:
|
|
6
|
+
*
|
|
7
|
+
* 1. Circuit breaker check (open → throw CIRCUIT_OPEN, emit `shed`)
|
|
8
|
+
* 2. Concurrency limiter slot (queue full → throw OVERLOADED, emit `shed`)
|
|
9
|
+
* 3. Rate limiter (token bucket, endpoint-scoped, process-wide)
|
|
10
|
+
* ('wait' mode blocks; 'fail-fast' throws immediately)
|
|
11
|
+
* 4. Timeout (deadline composed with caller's signal)
|
|
12
|
+
* 5. Execute fn
|
|
13
|
+
* 6. On error → classifyError → retry decision (honours retryAfterMs)
|
|
14
|
+
* On RATE_LIMITED → pause the bucket so other callers also back off
|
|
15
|
+
* 7. Update circuit state
|
|
16
|
+
* 8. Emit signals on the bus throughout
|
|
17
|
+
*
|
|
18
|
+
* Endpoint identity is the unit of sharing. Two callables registered with the
|
|
19
|
+
* same `endpoint` share their token bucket, circuit, and concurrency state.
|
|
20
|
+
*/
|
|
21
|
+
import { type ClassifiedError } from '@weaveintel/core';
|
|
22
|
+
import { type EndpointStateOptions } from './endpoint-registry.js';
|
|
23
|
+
import { type RetryPolicy, type RetryPolicyOptions } from './retry-policy.js';
|
|
24
|
+
import { type ResilienceSignalBus } from './signal-bus.js';
|
|
25
|
+
import type { CallOverrides } from './types.js';
|
|
26
|
+
export interface ResilienceOptions extends EndpointStateOptions {
|
|
27
|
+
/** Endpoint id — the key everything is shared on. e.g. `'openai:chat:gpt-4o'`. */
|
|
28
|
+
readonly endpoint: string;
|
|
29
|
+
readonly retry?: RetryPolicy | RetryPolicyOptions;
|
|
30
|
+
/** Per-call timeout in ms. If unset, no timeout is enforced by the pipeline. */
|
|
31
|
+
readonly timeoutMs?: number;
|
|
32
|
+
/** Default rate-limit mode. `'wait'` (default) blocks; `'fail-fast'` throws. */
|
|
33
|
+
readonly defaultRateLimitMode?: 'wait' | 'fail-fast';
|
|
34
|
+
/** Bus to emit signals on. Defaults to the process-wide default bus. */
|
|
35
|
+
readonly signalBus?: ResilienceSignalBus;
|
|
36
|
+
}
|
|
37
|
+
export type ResilientCallable<Args extends unknown[], R> = ((...args: Args) => Promise<R>) & {
|
|
38
|
+
/** Run with per-call overrides (e.g. fail-fast for live-agent ticks). */
|
|
39
|
+
withOverrides(overrides: CallOverrides): (...args: Args) => Promise<R>;
|
|
40
|
+
};
|
|
41
|
+
export declare function createResilientCallable<Args extends unknown[], R>(fn: (...args: Args) => Promise<R>, opts: ResilienceOptions): ResilientCallable<Args, R>;
|
|
42
|
+
/** One-shot helper for ad-hoc resilient calls. */
|
|
43
|
+
export declare function runResilient<R>(fn: () => Promise<R>, opts: ResilienceOptions, overrides?: CallOverrides): Promise<R>;
|
|
44
|
+
export type { ClassifiedError };
|
|
45
|
+
//# sourceMappingURL=pipeline.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.d.ts","sourceRoot":"","sources":["../src/pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAkC,KAAK,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxF,OAAO,EAA4B,KAAK,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC7F,OAAO,EAAqB,KAAK,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACjG,OAAO,EAAuB,KAAK,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAChF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAGhD,MAAM,WAAW,iBAAkB,SAAQ,oBAAoB;IAC7D,kFAAkF;IAClF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,CAAC,EAAE,WAAW,GAAG,kBAAkB,CAAC;IAClD,gFAAgF;IAChF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,gFAAgF;IAChF,QAAQ,CAAC,oBAAoB,CAAC,EAAE,MAAM,GAAG,WAAW,CAAC;IACrD,wEAAwE;IACxE,QAAQ,CAAC,SAAS,CAAC,EAAE,mBAAmB,CAAC;CAC1C;AAED,MAAM,MAAM,iBAAiB,CAAC,IAAI,SAAS,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG;IAC3F,yEAAyE;IACzE,aAAa,CAAC,SAAS,EAAE,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;CACxE,CAAC;AAMF,wBAAgB,uBAAuB,CAAC,IAAI,SAAS,OAAO,EAAE,EAAE,CAAC,EAC/D,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,EACjC,IAAI,EAAE,iBAAiB,GACtB,iBAAiB,CAAC,IAAI,EAAE,CAAC,CAAC,CA0J5B;AAED,kDAAkD;AAClD,wBAAsB,YAAY,CAAC,CAAC,EAClC,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,IAAI,EAAE,iBAAiB,EACvB,SAAS,CAAC,EAAE,aAAa,GACxB,OAAO,CAAC,CAAC,CAAC,CAGZ;AA6BD,YAAY,EAAE,eAAe,EAAE,CAAC"}
|
package/dist/pipeline.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @weaveintel/resilience — Pipeline composer
|
|
3
|
+
*
|
|
4
|
+
* `createResilientCallable(fn, opts)` wraps `fn` with the full resilience
|
|
5
|
+
* pipeline:
|
|
6
|
+
*
|
|
7
|
+
* 1. Circuit breaker check (open → throw CIRCUIT_OPEN, emit `shed`)
|
|
8
|
+
* 2. Concurrency limiter slot (queue full → throw OVERLOADED, emit `shed`)
|
|
9
|
+
* 3. Rate limiter (token bucket, endpoint-scoped, process-wide)
|
|
10
|
+
* ('wait' mode blocks; 'fail-fast' throws immediately)
|
|
11
|
+
* 4. Timeout (deadline composed with caller's signal)
|
|
12
|
+
* 5. Execute fn
|
|
13
|
+
* 6. On error → classifyError → retry decision (honours retryAfterMs)
|
|
14
|
+
* On RATE_LIMITED → pause the bucket so other callers also back off
|
|
15
|
+
* 7. Update circuit state
|
|
16
|
+
* 8. Emit signals on the bus throughout
|
|
17
|
+
*
|
|
18
|
+
* Endpoint identity is the unit of sharing. Two callables registered with the
|
|
19
|
+
* same `endpoint` share their token bucket, circuit, and concurrency state.
|
|
20
|
+
*/
|
|
21
|
+
import { WeaveIntelError, classifyError } from '@weaveintel/core';
|
|
22
|
+
import { getOrCreateEndpointState } from './endpoint-registry.js';
|
|
23
|
+
import { createRetryPolicy } from './retry-policy.js';
|
|
24
|
+
import { getDefaultSignalBus } from './signal-bus.js';
|
|
25
|
+
import { recordLatency } from './latency-tracker.js';
|
|
26
|
+
function isRetryPolicy(x) {
|
|
27
|
+
return !!x && typeof x.shouldRetry === 'function';
|
|
28
|
+
}
|
|
29
|
+
export function createResilientCallable(fn, opts) {
|
|
30
|
+
const state = getOrCreateEndpointState(opts.endpoint, {
|
|
31
|
+
...(opts.rateLimit ? { rateLimit: opts.rateLimit } : {}),
|
|
32
|
+
...(opts.concurrency ? { concurrency: opts.concurrency } : {}),
|
|
33
|
+
...(opts.circuit ? { circuit: opts.circuit } : {}),
|
|
34
|
+
});
|
|
35
|
+
const retry = isRetryPolicy(opts.retry) ? opts.retry : createRetryPolicy(opts.retry ?? {});
|
|
36
|
+
const bus = opts.signalBus ?? getDefaultSignalBus();
|
|
37
|
+
const defaultMode = opts.defaultRateLimitMode ?? 'wait';
|
|
38
|
+
async function runOnce(args, overrides, attempt) {
|
|
39
|
+
// 1. Circuit
|
|
40
|
+
if (!overrides?.bypassCircuit && state.circuit) {
|
|
41
|
+
const decision = state.circuit.canPass();
|
|
42
|
+
if (!decision.allowed) {
|
|
43
|
+
bus.emit({ kind: 'shed', endpoint: opts.endpoint, reason: 'circuit_open', at: Date.now() });
|
|
44
|
+
throw new WeaveIntelError({
|
|
45
|
+
code: 'CIRCUIT_OPEN',
|
|
46
|
+
message: `Circuit open for endpoint ${opts.endpoint}`,
|
|
47
|
+
retryable: false,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// 2. Concurrency
|
|
52
|
+
let releaseConcurrency;
|
|
53
|
+
if (state.concurrency) {
|
|
54
|
+
try {
|
|
55
|
+
releaseConcurrency = await state.concurrency.acquire();
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
bus.emit({ kind: 'shed', endpoint: opts.endpoint, reason: 'queue_full', at: Date.now() });
|
|
59
|
+
throw new WeaveIntelError({
|
|
60
|
+
code: 'INTERNAL_ERROR',
|
|
61
|
+
message: `Concurrency queue full for endpoint ${opts.endpoint}`,
|
|
62
|
+
retryable: true,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
// 3. Rate limit
|
|
68
|
+
if (state.rateLimit) {
|
|
69
|
+
const mode = overrides?.rateLimitMode ?? defaultMode;
|
|
70
|
+
if (mode === 'fail-fast') {
|
|
71
|
+
if (!state.rateLimit.tryAcquire()) {
|
|
72
|
+
const waitMs = state.rateLimit.msUntilAvailable();
|
|
73
|
+
bus.emit({ kind: 'shed', endpoint: opts.endpoint, reason: 'rate_limit', at: Date.now() });
|
|
74
|
+
throw new WeaveIntelError({
|
|
75
|
+
code: 'RATE_LIMITED',
|
|
76
|
+
message: `Rate limit reached for endpoint ${opts.endpoint}`,
|
|
77
|
+
retryable: true,
|
|
78
|
+
retryAfterMs: waitMs,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
await state.rateLimit.acquire(overrides?.timeoutMs ?? opts.timeoutMs);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// 4. Timeout + 5. Execute
|
|
87
|
+
const start = Date.now();
|
|
88
|
+
try {
|
|
89
|
+
const result = await maybeWithTimeout(() => fn(...args), overrides?.timeoutMs ?? opts.timeoutMs, opts.endpoint);
|
|
90
|
+
const durationMs = Date.now() - start;
|
|
91
|
+
// 7. circuit success + latency tracking
|
|
92
|
+
state.circuit?.recordSuccess();
|
|
93
|
+
bus.emit({ kind: 'success', endpoint: opts.endpoint, attempt, durationMs, at: Date.now() });
|
|
94
|
+
recordLatency(opts.endpoint, durationMs);
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
catch (err) {
|
|
98
|
+
const durationMs = Date.now() - start;
|
|
99
|
+
const classified = classifyError(err);
|
|
100
|
+
// If upstream gave us a cooldown hint, pause the bucket so every
|
|
101
|
+
// other caller in the process also backs off automatically.
|
|
102
|
+
if (classified.cooldownHintMs !== undefined && state.rateLimit) {
|
|
103
|
+
state.rateLimit.pauseFor(classified.cooldownHintMs);
|
|
104
|
+
}
|
|
105
|
+
if (classified.class === 'rate_limited') {
|
|
106
|
+
bus.emit({
|
|
107
|
+
kind: 'rate_limited',
|
|
108
|
+
endpoint: opts.endpoint,
|
|
109
|
+
retryAfterMs: classified.retryAfterMs ?? 0,
|
|
110
|
+
attempt,
|
|
111
|
+
at: Date.now(),
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
// 7. circuit failure
|
|
115
|
+
const cf = state.circuit?.recordFailure();
|
|
116
|
+
if (cf?.transitionedToOpen) {
|
|
117
|
+
bus.emit({
|
|
118
|
+
kind: 'circuit_opened',
|
|
119
|
+
endpoint: opts.endpoint,
|
|
120
|
+
consecutiveFailures: cf.consecutiveFailures,
|
|
121
|
+
cooldownMs: state.circuit.snapshot().cooldownMs,
|
|
122
|
+
at: Date.now(),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
bus.emit({
|
|
126
|
+
kind: 'failed',
|
|
127
|
+
endpoint: opts.endpoint,
|
|
128
|
+
attempt,
|
|
129
|
+
durationMs,
|
|
130
|
+
cause: classified,
|
|
131
|
+
at: Date.now(),
|
|
132
|
+
});
|
|
133
|
+
// re-throw the classified error's cause so callers get a WeaveIntelError
|
|
134
|
+
throw classified.cause;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
releaseConcurrency?.();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function executeWithRetry(args, overrides) {
|
|
142
|
+
const maxAttempts = overrides?.maxRetries !== undefined ? overrides.maxRetries + 1 : retry.maxAttempts;
|
|
143
|
+
let attempt = 1;
|
|
144
|
+
// eslint-disable-next-line no-constant-condition
|
|
145
|
+
while (true) {
|
|
146
|
+
try {
|
|
147
|
+
return await runOnce(args, overrides, attempt);
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
const classified = classifyError(err);
|
|
151
|
+
const moreAttemptsLeft = attempt < maxAttempts;
|
|
152
|
+
const shouldRetry = moreAttemptsLeft && retry.shouldRetry(classified, attempt);
|
|
153
|
+
if (!shouldRetry)
|
|
154
|
+
throw classified.cause;
|
|
155
|
+
const nextDelayMs = retry.nextDelayMs(classified, attempt);
|
|
156
|
+
bus.emit({
|
|
157
|
+
kind: 'retrying',
|
|
158
|
+
endpoint: opts.endpoint,
|
|
159
|
+
attempt,
|
|
160
|
+
nextDelayMs,
|
|
161
|
+
cause: classified,
|
|
162
|
+
at: Date.now(),
|
|
163
|
+
});
|
|
164
|
+
await sleep(nextDelayMs);
|
|
165
|
+
attempt += 1;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const callable = ((...args) => executeWithRetry(args, undefined));
|
|
170
|
+
callable.withOverrides = (overrides) => (...args) => executeWithRetry(args, overrides);
|
|
171
|
+
return callable;
|
|
172
|
+
}
|
|
173
|
+
/** One-shot helper for ad-hoc resilient calls. */
|
|
174
|
+
export async function runResilient(fn, opts, overrides) {
|
|
175
|
+
const callable = createResilientCallable(fn, opts);
|
|
176
|
+
return overrides ? callable.withOverrides(overrides)() : callable();
|
|
177
|
+
}
|
|
178
|
+
function sleep(ms) {
|
|
179
|
+
return new Promise((r) => setTimeout(r, Math.max(0, ms)));
|
|
180
|
+
}
|
|
181
|
+
async function maybeWithTimeout(fn, timeoutMs, endpoint) {
|
|
182
|
+
if (timeoutMs === undefined)
|
|
183
|
+
return fn();
|
|
184
|
+
let timer;
|
|
185
|
+
try {
|
|
186
|
+
return await Promise.race([
|
|
187
|
+
fn(),
|
|
188
|
+
new Promise((_, reject) => {
|
|
189
|
+
timer = setTimeout(() => {
|
|
190
|
+
reject(new WeaveIntelError({
|
|
191
|
+
code: 'TIMEOUT',
|
|
192
|
+
message: `Endpoint ${endpoint} timed out after ${timeoutMs}ms`,
|
|
193
|
+
retryable: true,
|
|
194
|
+
}));
|
|
195
|
+
}, timeoutMs);
|
|
196
|
+
}),
|
|
197
|
+
]);
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
if (timer)
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
//# sourceMappingURL=pipeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../src/pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,eAAe,EAAE,aAAa,EAAwB,MAAM,kBAAkB,CAAC;AACxF,OAAO,EAAE,wBAAwB,EAA6B,MAAM,wBAAwB,CAAC;AAC7F,OAAO,EAAE,iBAAiB,EAA6C,MAAM,mBAAmB,CAAC;AACjG,OAAO,EAAE,mBAAmB,EAA4B,MAAM,iBAAiB,CAAC;AAEhF,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAmBrD,SAAS,aAAa,CAAC,CAA+C;IACpE,OAAO,CAAC,CAAC,CAAC,IAAI,OAAQ,CAAiB,CAAC,WAAW,KAAK,UAAU,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,uBAAuB,CACrC,EAAiC,EACjC,IAAuB;IAEvB,MAAM,KAAK,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,EAAE;QACpD,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAA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+
* next delay. Honours `classifier.retryAfterMs` (always wins over backoff).
|
|
6
|
+
*/
|
|
7
|
+
import type { ClassifiedError } from '@weaveintel/core';
|
|
8
|
+
export interface RetryPolicy {
|
|
9
|
+
readonly maxAttempts: number;
|
|
10
|
+
readonly baseDelayMs: number;
|
|
11
|
+
readonly maxDelayMs: number;
|
|
12
|
+
readonly factor: number;
|
|
13
|
+
readonly jitter: boolean;
|
|
14
|
+
shouldRetry(err: ClassifiedError, attempt: number): boolean;
|
|
15
|
+
nextDelayMs(err: ClassifiedError, attempt: number): number;
|
|
16
|
+
}
|
|
17
|
+
export interface RetryPolicyOptions {
|
|
18
|
+
readonly maxAttempts?: number;
|
|
19
|
+
readonly baseDelayMs?: number;
|
|
20
|
+
readonly maxDelayMs?: number;
|
|
21
|
+
readonly factor?: number;
|
|
22
|
+
readonly jitter?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Override the classifier-driven retry decision. Default behaviour:
|
|
25
|
+
* retry iff `err.retryable && err.class !== 'auth' && err.class !== 'invalid_input'`.
|
|
26
|
+
*/
|
|
27
|
+
readonly shouldRetry?: (err: ClassifiedError, attempt: number) => boolean;
|
|
28
|
+
}
|
|
29
|
+
export declare function createRetryPolicy(opts?: RetryPolicyOptions): RetryPolicy;
|
|
30
|
+
//# sourceMappingURL=retry-policy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry-policy.d.ts","sourceRoot":"","sources":["../src/retry-policy.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,WAAW,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC;IAC5D,WAAW,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC;CAC5D;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;CAC3E;AAUD,wBAAgB,iBAAiB,CAAC,IAAI,GAAE,kBAAuB,GAAG,WAAW,CAqC5E"}
|