@cleocode/lafs 2026.4.0 → 2026.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +97 -68
- package/dist/src/a2a/bindings/grpc.d.ts +117 -11
- package/dist/src/a2a/bindings/grpc.d.ts.map +1 -1
- package/dist/src/a2a/bindings/grpc.js +79 -8
- package/dist/src/a2a/bindings/grpc.js.map +1 -1
- package/dist/src/a2a/bindings/http.d.ts +129 -14
- package/dist/src/a2a/bindings/http.d.ts.map +1 -1
- package/dist/src/a2a/bindings/http.js +93 -12
- package/dist/src/a2a/bindings/http.js.map +1 -1
- package/dist/src/a2a/bindings/index.d.ts +80 -7
- package/dist/src/a2a/bindings/index.d.ts.map +1 -1
- package/dist/src/a2a/bindings/index.js +69 -2
- package/dist/src/a2a/bindings/index.js.map +1 -1
- package/dist/src/a2a/bindings/jsonrpc.d.ts +193 -9
- package/dist/src/a2a/bindings/jsonrpc.d.ts.map +1 -1
- package/dist/src/a2a/bindings/jsonrpc.js +152 -9
- package/dist/src/a2a/bindings/jsonrpc.js.map +1 -1
- package/dist/src/a2a/bridge.d.ts +232 -37
- package/dist/src/a2a/bridge.d.ts.map +1 -1
- package/dist/src/a2a/bridge.js +172 -24
- package/dist/src/a2a/bridge.js.map +1 -1
- package/dist/src/a2a/extensions.d.ts +221 -12
- package/dist/src/a2a/extensions.d.ts.map +1 -1
- package/dist/src/a2a/extensions.js +175 -11
- package/dist/src/a2a/extensions.js.map +1 -1
- package/dist/src/a2a/index.d.ts +2 -0
- package/dist/src/a2a/index.d.ts.map +1 -1
- package/dist/src/a2a/index.js +2 -0
- package/dist/src/a2a/index.js.map +1 -1
- package/dist/src/a2a/streaming.d.ts +274 -2
- package/dist/src/a2a/streaming.d.ts.map +1 -1
- package/dist/src/a2a/streaming.js +245 -2
- package/dist/src/a2a/streaming.js.map +1 -1
- package/dist/src/a2a/task-lifecycle.d.ts +339 -19
- package/dist/src/a2a/task-lifecycle.d.ts.map +1 -1
- package/dist/src/a2a/task-lifecycle.js +302 -19
- package/dist/src/a2a/task-lifecycle.js.map +1 -1
- package/dist/src/budgetEnforcement.d.ts +88 -14
- package/dist/src/budgetEnforcement.d.ts.map +1 -1
- package/dist/src/budgetEnforcement.js +132 -19
- package/dist/src/budgetEnforcement.js.map +1 -1
- package/dist/src/circuit-breaker/index.d.ts +254 -9
- package/dist/src/circuit-breaker/index.d.ts.map +1 -1
- package/dist/src/circuit-breaker/index.js +218 -9
- package/dist/src/circuit-breaker/index.js.map +1 -1
- package/dist/src/compliance.d.ts +176 -0
- package/dist/src/compliance.d.ts.map +1 -1
- package/dist/src/compliance.js +100 -0
- package/dist/src/compliance.js.map +1 -1
- package/dist/src/conformance.d.ts +52 -0
- package/dist/src/conformance.d.ts.map +1 -1
- package/dist/src/conformance.js +41 -0
- package/dist/src/conformance.js.map +1 -1
- package/dist/src/conformanceProfiles.d.ts +66 -0
- package/dist/src/conformanceProfiles.d.ts.map +1 -1
- package/dist/src/conformanceProfiles.js +51 -0
- package/dist/src/conformanceProfiles.js.map +1 -1
- package/dist/src/deprecationRegistry.d.ts +80 -0
- package/dist/src/deprecationRegistry.d.ts.map +1 -1
- package/dist/src/deprecationRegistry.js +50 -0
- package/dist/src/deprecationRegistry.js.map +1 -1
- package/dist/src/discovery.d.ts +344 -63
- package/dist/src/discovery.d.ts.map +1 -1
- package/dist/src/discovery.js +67 -13
- package/dist/src/discovery.js.map +1 -1
- package/dist/src/envelope.d.ts +252 -0
- package/dist/src/envelope.d.ts.map +1 -1
- package/dist/src/envelope.js +165 -0
- package/dist/src/envelope.js.map +1 -1
- package/dist/src/errorRegistry.d.ts +159 -0
- package/dist/src/errorRegistry.d.ts.map +1 -1
- package/dist/src/errorRegistry.js +115 -0
- package/dist/src/errorRegistry.js.map +1 -1
- package/dist/src/fieldExtraction.d.ts +125 -25
- package/dist/src/fieldExtraction.d.ts.map +1 -1
- package/dist/src/fieldExtraction.js +85 -16
- package/dist/src/fieldExtraction.js.map +1 -1
- package/dist/src/flagResolver.d.ts +75 -9
- package/dist/src/flagResolver.d.ts.map +1 -1
- package/dist/src/flagResolver.js +20 -4
- package/dist/src/flagResolver.js.map +1 -1
- package/dist/src/flagSemantics.d.ts +76 -1
- package/dist/src/flagSemantics.d.ts.map +1 -1
- package/dist/src/flagSemantics.js +66 -0
- package/dist/src/flagSemantics.js.map +1 -1
- package/dist/src/health/index.d.ts +87 -6
- package/dist/src/health/index.d.ts.map +1 -1
- package/dist/src/health/index.js +54 -6
- package/dist/src/health/index.js.map +1 -1
- package/dist/src/index.d.ts +12 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +12 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/mviProjection.d.ts +42 -6
- package/dist/src/mviProjection.d.ts.map +1 -1
- package/dist/src/mviProjection.js +31 -5
- package/dist/src/mviProjection.js.map +1 -1
- package/dist/src/native-loader.d.ts +49 -0
- package/dist/src/native-loader.d.ts.map +1 -0
- package/dist/src/native-loader.js +56 -0
- package/dist/src/native-loader.js.map +1 -0
- package/dist/src/problemDetails.d.ts +70 -4
- package/dist/src/problemDetails.d.ts.map +1 -1
- package/dist/src/problemDetails.js +21 -3
- package/dist/src/problemDetails.js.map +1 -1
- package/dist/src/shutdown/index.d.ts +96 -7
- package/dist/src/shutdown/index.d.ts.map +1 -1
- package/dist/src/shutdown/index.js +72 -7
- package/dist/src/shutdown/index.js.map +1 -1
- package/dist/src/tokenEstimator.d.ts +97 -11
- package/dist/src/tokenEstimator.d.ts.map +1 -1
- package/dist/src/tokenEstimator.js +90 -11
- package/dist/src/tokenEstimator.js.map +1 -1
- package/dist/src/types.d.ts +467 -2
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js +64 -0
- package/dist/src/types.js.map +1 -1
- package/dist/src/validateEnvelope.d.ts +59 -1
- package/dist/src/validateEnvelope.d.ts.map +1 -1
- package/dist/src/validateEnvelope.js +75 -9
- package/dist/src/validateEnvelope.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/lafs.md +3 -4
- package/package.json +6 -3
- package/dist/src/mcpAdapter.d.ts +0 -29
- package/dist/src/mcpAdapter.d.ts.map +0 -1
- package/dist/src/mcpAdapter.js +0 -286
- package/dist/src/mcpAdapter.js.map +0 -1
- package/schemas/v1/conformance-profiles.d.ts +0 -15
- package/schemas/v1/envelope.schema.d.ts +0 -14
- package/schemas/v1/error-registry.d.ts +0 -24
|
@@ -6,15 +6,31 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { TokenEstimator } from './tokenEstimator.js';
|
|
8
8
|
/**
|
|
9
|
-
* Budget exceeded error code from LAFS error registry
|
|
9
|
+
* Budget exceeded error code from LAFS error registry.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* Used as the `code` field in {@link LAFSError} when a response exceeds
|
|
13
|
+
* its declared MVI token budget.
|
|
10
14
|
*/
|
|
11
15
|
const BUDGET_EXCEEDED_CODE = 'E_MVI_BUDGET_EXCEEDED';
|
|
12
16
|
/**
|
|
13
|
-
* Default category for budget exceeded errors
|
|
17
|
+
* Default category for budget exceeded errors.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* Budget violations are treated as validation errors since they represent
|
|
21
|
+
* a contract violation between the caller's budget declaration and the response size.
|
|
14
22
|
*/
|
|
15
23
|
const BUDGET_ERROR_CATEGORY = 'VALIDATION';
|
|
16
24
|
/**
|
|
17
|
-
* Create a budget exceeded error object
|
|
25
|
+
* Create a budget exceeded error object.
|
|
26
|
+
*
|
|
27
|
+
* @param estimated - Estimated token count of the response
|
|
28
|
+
* @param budget - Maximum allowed token count
|
|
29
|
+
* @returns A {@link LAFSError} with code `E_MVI_BUDGET_EXCEEDED` and detailed metadata
|
|
30
|
+
*
|
|
31
|
+
* @remarks
|
|
32
|
+
* The error details include the exact token counts, the absolute overage,
|
|
33
|
+
* and the percentage by which the budget was exceeded.
|
|
18
34
|
*/
|
|
19
35
|
function createBudgetExceededError(estimated, budget) {
|
|
20
36
|
return {
|
|
@@ -32,8 +48,17 @@ function createBudgetExceededError(estimated, budget) {
|
|
|
32
48
|
};
|
|
33
49
|
}
|
|
34
50
|
/**
|
|
35
|
-
* Truncate a result to fit within budget.
|
|
36
|
-
*
|
|
51
|
+
* Truncate a result to fit within a token budget.
|
|
52
|
+
*
|
|
53
|
+
* @param result - The result payload (object, array, or `null`)
|
|
54
|
+
* @param targetTokens - Maximum allowed token count
|
|
55
|
+
* @param estimator - Token estimator instance for measuring sizes
|
|
56
|
+
* @returns Object containing the truncated result and a flag indicating if truncation occurred
|
|
57
|
+
*
|
|
58
|
+
* @remarks
|
|
59
|
+
* Delegates to array or object-specific truncation strategies. Arrays are
|
|
60
|
+
* truncated by removing trailing items via binary search; objects are truncated
|
|
61
|
+
* by removing trailing top-level keys.
|
|
37
62
|
*/
|
|
38
63
|
function truncateResult(result, targetTokens, estimator) {
|
|
39
64
|
if (result === null) {
|
|
@@ -52,7 +77,18 @@ function truncateResult(result, targetTokens, estimator) {
|
|
|
52
77
|
return truncateObject(result, targetChars, targetTokens, estimator);
|
|
53
78
|
}
|
|
54
79
|
/**
|
|
55
|
-
* Truncate an array to fit within budget.
|
|
80
|
+
* Truncate an array to fit within a token budget.
|
|
81
|
+
*
|
|
82
|
+
* @param arr - Array of result objects
|
|
83
|
+
* @param targetChars - Target character count (used for sizing heuristic)
|
|
84
|
+
* @param targetTokens - Target token budget
|
|
85
|
+
* @param estimator - Token estimator instance
|
|
86
|
+
* @returns Object containing the truncated array and a flag indicating if truncation occurred
|
|
87
|
+
*
|
|
88
|
+
* @remarks
|
|
89
|
+
* Uses binary search to find the maximum number of items that fit within
|
|
90
|
+
* the budget. Appends `_truncated` and `remainingItems` metadata to the
|
|
91
|
+
* last item when truncation occurs.
|
|
56
92
|
*/
|
|
57
93
|
function truncateArray(arr, targetChars, targetTokens, estimator) {
|
|
58
94
|
if (arr.length === 0) {
|
|
@@ -101,7 +137,18 @@ function truncateArray(arr, targetChars, targetTokens, estimator) {
|
|
|
101
137
|
return { result: truncated, wasTruncated: true };
|
|
102
138
|
}
|
|
103
139
|
/**
|
|
104
|
-
* Truncate an object to fit within budget.
|
|
140
|
+
* Truncate an object to fit within a token budget.
|
|
141
|
+
*
|
|
142
|
+
* @param obj - Object to truncate
|
|
143
|
+
* @param targetChars - Target character count (used for sizing heuristic)
|
|
144
|
+
* @param targetTokens - Target token budget
|
|
145
|
+
* @param estimator - Token estimator instance
|
|
146
|
+
* @returns Object containing the truncated object and a flag indicating if truncation occurred
|
|
147
|
+
*
|
|
148
|
+
* @remarks
|
|
149
|
+
* Uses binary search over the object's keys to find the maximum number of
|
|
150
|
+
* top-level properties that fit within the budget. Truncated results include
|
|
151
|
+
* `_truncated` and `_truncatedFields` metadata.
|
|
105
152
|
*/
|
|
106
153
|
function truncateObject(obj, targetChars, targetTokens, estimator) {
|
|
107
154
|
const keys = Object.keys(obj);
|
|
@@ -154,9 +201,23 @@ function truncateObject(obj, targetChars, targetTokens, estimator) {
|
|
|
154
201
|
* Apply budget enforcement to an envelope.
|
|
155
202
|
*
|
|
156
203
|
* @param envelope - The LAFS envelope to check
|
|
157
|
-
* @param budget - Maximum allowed
|
|
158
|
-
* @param options - Budget enforcement options
|
|
159
|
-
* @returns
|
|
204
|
+
* @param budget - Maximum allowed token count
|
|
205
|
+
* @param options - Budget enforcement options (truncation, callbacks)
|
|
206
|
+
* @returns Enforcement result with the (possibly modified) envelope, budget status, and token estimates
|
|
207
|
+
*
|
|
208
|
+
* @remarks
|
|
209
|
+
* When the envelope is within budget, the token estimate is attached to metadata.
|
|
210
|
+
* When exceeded, behavior depends on `options.truncateOnExceed`: if enabled,
|
|
211
|
+
* truncation is attempted first; otherwise, the result is replaced with a
|
|
212
|
+
* budget-exceeded error. The `onBudgetExceeded` callback fires before truncation.
|
|
213
|
+
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```typescript
|
|
216
|
+
* const result = applyBudgetEnforcement(envelope, 1000, { truncateOnExceed: true });
|
|
217
|
+
* if (!result.withinBudget) {
|
|
218
|
+
* console.warn("Budget exceeded:", result.estimatedTokens);
|
|
219
|
+
* }
|
|
220
|
+
* ```
|
|
160
221
|
*/
|
|
161
222
|
export function applyBudgetEnforcement(envelope, budget, options = {}) {
|
|
162
223
|
const { truncateOnExceed = false, onBudgetExceeded } = options;
|
|
@@ -235,9 +296,14 @@ export function applyBudgetEnforcement(envelope, budget, options = {}) {
|
|
|
235
296
|
/**
|
|
236
297
|
* Create a budget enforcement middleware function.
|
|
237
298
|
*
|
|
238
|
-
* @param budget - Maximum allowed
|
|
239
|
-
* @param options - Budget enforcement options
|
|
240
|
-
* @returns
|
|
299
|
+
* @param budget - Maximum allowed token count for the response
|
|
300
|
+
* @param options - Budget enforcement options (truncation, callbacks)
|
|
301
|
+
* @returns Async middleware function that enforces the token budget
|
|
302
|
+
*
|
|
303
|
+
* @remarks
|
|
304
|
+
* Wraps the next handler in the chain, applying {@link applyBudgetEnforcement}
|
|
305
|
+
* to its output. The returned envelope may be truncated or replaced with an
|
|
306
|
+
* error depending on the enforcement result.
|
|
241
307
|
*
|
|
242
308
|
* @example
|
|
243
309
|
* ```typescript
|
|
@@ -258,8 +324,20 @@ export function withBudget(budget, options = {}) {
|
|
|
258
324
|
* Check if an envelope has exceeded its budget without modifying it.
|
|
259
325
|
*
|
|
260
326
|
* @param envelope - The LAFS envelope to check
|
|
261
|
-
* @param budget - Maximum allowed
|
|
262
|
-
* @returns
|
|
327
|
+
* @param budget - Maximum allowed token count
|
|
328
|
+
* @returns Object with `exceeded` flag, `estimated` token count, and `remaining` budget
|
|
329
|
+
*
|
|
330
|
+
* @remarks
|
|
331
|
+
* A read-only budget check that does not alter the envelope. Useful for
|
|
332
|
+
* pre-flight checks or logging before deciding how to handle overages.
|
|
333
|
+
*
|
|
334
|
+
* @example
|
|
335
|
+
* ```typescript
|
|
336
|
+
* const { exceeded, estimated, remaining } = checkBudget(envelope, 500);
|
|
337
|
+
* if (exceeded) {
|
|
338
|
+
* console.warn(`Over budget by ${estimated - 500} tokens`);
|
|
339
|
+
* }
|
|
340
|
+
* ```
|
|
263
341
|
*/
|
|
264
342
|
export function checkBudget(envelope, budget) {
|
|
265
343
|
const estimator = new TokenEstimator();
|
|
@@ -273,9 +351,19 @@ export function checkBudget(envelope, budget) {
|
|
|
273
351
|
/**
|
|
274
352
|
* Synchronous version of withBudget for non-async contexts.
|
|
275
353
|
*
|
|
276
|
-
* @param budget - Maximum allowed
|
|
277
|
-
* @param options - Budget enforcement options
|
|
278
|
-
* @returns
|
|
354
|
+
* @param budget - Maximum allowed token count for the response
|
|
355
|
+
* @param options - Budget enforcement options (truncation, callbacks)
|
|
356
|
+
* @returns Synchronous middleware function that enforces the token budget
|
|
357
|
+
*
|
|
358
|
+
* @remarks
|
|
359
|
+
* Identical to {@link withBudget} but operates synchronously. Use this when the
|
|
360
|
+
* next handler in the chain is guaranteed to return synchronously.
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* ```typescript
|
|
364
|
+
* const middleware = withBudgetSync(500);
|
|
365
|
+
* const result = middleware(envelope, () => nextEnvelope);
|
|
366
|
+
* ```
|
|
279
367
|
*/
|
|
280
368
|
export function withBudgetSync(budget, options = {}) {
|
|
281
369
|
return (envelope, next) => {
|
|
@@ -288,10 +376,19 @@ export function withBudgetSync(budget, options = {}) {
|
|
|
288
376
|
* Higher-order function that wraps a handler with budget enforcement.
|
|
289
377
|
*
|
|
290
378
|
* @param handler - The handler function to wrap
|
|
379
|
+
* @typeParam TArgs - Tuple type representing the handler's parameter list
|
|
380
|
+
* @typeParam TResult - Return type of the handler, must extend LAFSEnvelope
|
|
381
|
+
* @param handler - The handler function to wrap with budget enforcement
|
|
291
382
|
* @param budget - Maximum allowed tokens
|
|
292
383
|
* @param options - Budget enforcement options
|
|
293
384
|
* @returns Wrapped handler with budget enforcement
|
|
294
385
|
*
|
|
386
|
+
* @remarks
|
|
387
|
+
* The returned function has the same parameter signature as the original handler
|
|
388
|
+
* but always returns a `Promise<LAFSEnvelope>`. When the budget is exceeded and
|
|
389
|
+
* `truncateOnExceed` is enabled, the envelope is truncated to fit; otherwise an
|
|
390
|
+
* `E_MVI_BUDGET_EXCEEDED` error envelope is returned.
|
|
391
|
+
*
|
|
295
392
|
* @example
|
|
296
393
|
* ```typescript
|
|
297
394
|
* const myHandler = async (request: Request) => ({ success: true, result: { data } });
|
|
@@ -308,7 +405,23 @@ export function wrapWithBudget(handler, budget, options = {}) {
|
|
|
308
405
|
}
|
|
309
406
|
/**
|
|
310
407
|
* Compose multiple middleware functions into a single middleware.
|
|
311
|
-
*
|
|
408
|
+
*
|
|
409
|
+
* @param middlewares - Middleware functions to compose (executed left to right)
|
|
410
|
+
* @returns A single middleware function that chains all provided middlewares
|
|
411
|
+
*
|
|
412
|
+
* @remarks
|
|
413
|
+
* Middleware is executed in array order (left to right). Each middleware receives
|
|
414
|
+
* the envelope and a `next` function that invokes the subsequent middleware.
|
|
415
|
+
* The final middleware's `next` call invokes the original terminal handler.
|
|
416
|
+
*
|
|
417
|
+
* @example
|
|
418
|
+
* ```typescript
|
|
419
|
+
* const pipeline = composeMiddleware(
|
|
420
|
+
* withBudget(1000),
|
|
421
|
+
* loggingMiddleware,
|
|
422
|
+
* );
|
|
423
|
+
* const result = await pipeline(envelope, () => finalEnvelope);
|
|
424
|
+
* ```
|
|
312
425
|
*/
|
|
313
426
|
export function composeMiddleware(...middlewares) {
|
|
314
427
|
return async (envelope, next) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"budgetEnforcement.js","sourceRoot":"","sources":["../../src/budgetEnforcement.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAWrD
|
|
1
|
+
{"version":3,"file":"budgetEnforcement.js","sourceRoot":"","sources":["../../src/budgetEnforcement.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE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C/B,IAAI,CAAC,IAAI,WAAW,CAAC,MAAM,EAAE,CAAC;gBAC5B,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,MAAM,UAAU,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;YAClC,IAAI,CAAC,UAAU,EAAE,CAAC;gBAChB,OAAO,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACzB,CAAC;YAED,OAAO,UAAU,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACrD,CAAC;QAED,OAAO,QAAQ,CAAC,CAAC,CAAC,CAAC;IACrB,CAAC,CAAC;AACJ,CAAC;AAID,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,CAAC"}
|
|
@@ -1,29 +1,97 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* LAFS Circuit Breaker Module
|
|
3
3
|
*
|
|
4
|
-
* Provides circuit breaker pattern for resilient service calls
|
|
4
|
+
* Provides circuit breaker pattern for resilient service calls.
|
|
5
|
+
*
|
|
6
|
+
* @packageDocumentation
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Represents the three possible states of a circuit breaker.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* - `CLOSED` means the circuit is operating normally and requests pass through.
|
|
13
|
+
* - `OPEN` means the circuit has tripped due to failures and requests are rejected.
|
|
14
|
+
* - `HALF_OPEN` means the circuit is testing whether the downstream service has recovered.
|
|
5
15
|
*/
|
|
6
16
|
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
17
|
+
/** Configuration options for a {@link CircuitBreaker} instance. */
|
|
7
18
|
export interface CircuitBreakerConfig {
|
|
19
|
+
/** Unique identifier for this circuit breaker, used in log messages and metrics. */
|
|
8
20
|
name: string;
|
|
21
|
+
/**
|
|
22
|
+
* Number of failures required to trip the circuit from CLOSED to OPEN.
|
|
23
|
+
* @defaultValue 5
|
|
24
|
+
*/
|
|
9
25
|
failureThreshold?: number;
|
|
26
|
+
/**
|
|
27
|
+
* Milliseconds to wait before transitioning from OPEN to HALF_OPEN.
|
|
28
|
+
* @defaultValue 30000
|
|
29
|
+
*/
|
|
10
30
|
resetTimeout?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Maximum number of trial calls allowed while in the HALF_OPEN state.
|
|
33
|
+
* @defaultValue 3
|
|
34
|
+
*/
|
|
11
35
|
halfOpenMaxCalls?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Consecutive successes required in HALF_OPEN to close the circuit.
|
|
38
|
+
* @defaultValue 2
|
|
39
|
+
*/
|
|
12
40
|
successThreshold?: number;
|
|
13
41
|
}
|
|
42
|
+
/** Snapshot of runtime metrics for a {@link CircuitBreaker}. */
|
|
14
43
|
export interface CircuitBreakerMetrics {
|
|
44
|
+
/** Current state of the circuit breaker. */
|
|
15
45
|
state: CircuitState;
|
|
46
|
+
/** Total number of recorded failures since the last reset. */
|
|
16
47
|
failures: number;
|
|
48
|
+
/** Total number of recorded successes since the last reset. */
|
|
17
49
|
successes: number;
|
|
50
|
+
/**
|
|
51
|
+
* Timestamp of the most recent failure, if any.
|
|
52
|
+
* @defaultValue undefined
|
|
53
|
+
*/
|
|
18
54
|
lastFailureTime?: Date;
|
|
55
|
+
/** Number of consecutive successes since the last failure. */
|
|
19
56
|
consecutiveSuccesses: number;
|
|
57
|
+
/** Total number of calls made through this circuit breaker. */
|
|
20
58
|
totalCalls: number;
|
|
21
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* Error thrown when a circuit breaker rejects a call.
|
|
62
|
+
*
|
|
63
|
+
* @remarks
|
|
64
|
+
* This error is raised when the circuit is in the OPEN state or when the
|
|
65
|
+
* HALF_OPEN call limit has been reached. Callers should catch this to
|
|
66
|
+
* implement fallback logic or return a 503 response.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```typescript
|
|
70
|
+
* try {
|
|
71
|
+
* await breaker.execute(() => fetch('/api'));
|
|
72
|
+
* } catch (err) {
|
|
73
|
+
* if (err instanceof CircuitBreakerError) {
|
|
74
|
+
* console.log('Circuit open, using fallback');
|
|
75
|
+
* }
|
|
76
|
+
* }
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
22
79
|
export declare class CircuitBreakerError extends Error {
|
|
80
|
+
/**
|
|
81
|
+
* Creates a new CircuitBreakerError.
|
|
82
|
+
*
|
|
83
|
+
* @param message - Descriptive error message indicating why the call was rejected
|
|
84
|
+
*/
|
|
23
85
|
constructor(message: string);
|
|
24
86
|
}
|
|
25
87
|
/**
|
|
26
|
-
* Circuit breaker for protecting against cascading failures
|
|
88
|
+
* Circuit breaker for protecting against cascading failures.
|
|
89
|
+
*
|
|
90
|
+
* @remarks
|
|
91
|
+
* Implements the circuit breaker pattern with three states: CLOSED (normal),
|
|
92
|
+
* OPEN (rejecting calls), and HALF_OPEN (testing recovery). The breaker
|
|
93
|
+
* automatically transitions between states based on failure and success
|
|
94
|
+
* thresholds, and schedules reset timers when the circuit opens.
|
|
27
95
|
*
|
|
28
96
|
* @example
|
|
29
97
|
* ```typescript
|
|
@@ -48,44 +116,134 @@ export declare class CircuitBreakerError extends Error {
|
|
|
48
116
|
*/
|
|
49
117
|
export declare class CircuitBreaker {
|
|
50
118
|
private config;
|
|
119
|
+
/** Current circuit state. */
|
|
51
120
|
private state;
|
|
121
|
+
/** Total failure count since last reset. */
|
|
52
122
|
private failures;
|
|
123
|
+
/** Total success count since last reset. */
|
|
53
124
|
private successes;
|
|
125
|
+
/** Timestamp of the most recent failure. */
|
|
54
126
|
private lastFailureTime?;
|
|
127
|
+
/** Consecutive successes since the last failure. */
|
|
55
128
|
private consecutiveSuccesses;
|
|
129
|
+
/** Lifetime call count. */
|
|
56
130
|
private totalCalls;
|
|
131
|
+
/** Number of calls made while in the HALF_OPEN state. */
|
|
57
132
|
private halfOpenCalls;
|
|
133
|
+
/** Timer handle for the scheduled OPEN-to-HALF_OPEN transition. */
|
|
58
134
|
private resetTimer?;
|
|
135
|
+
/**
|
|
136
|
+
* Creates a new CircuitBreaker with the given configuration.
|
|
137
|
+
*
|
|
138
|
+
* @param config - Circuit breaker configuration with name, thresholds, and timeouts
|
|
139
|
+
*/
|
|
59
140
|
constructor(config: CircuitBreakerConfig);
|
|
60
141
|
/**
|
|
61
|
-
* Execute a function with circuit breaker protection
|
|
142
|
+
* Execute a function with circuit breaker protection.
|
|
143
|
+
*
|
|
144
|
+
* @remarks
|
|
145
|
+
* When the circuit is CLOSED, calls pass through normally. When OPEN, calls
|
|
146
|
+
* are rejected with a {@link CircuitBreakerError} unless the reset timeout has
|
|
147
|
+
* elapsed (triggering HALF_OPEN). In HALF_OPEN, a limited number of trial
|
|
148
|
+
* calls are permitted; successes may close the circuit while failures re-open it.
|
|
149
|
+
*
|
|
150
|
+
* @typeParam T - Return type of the wrapped function
|
|
151
|
+
* @param fn - Async function to execute under circuit breaker protection
|
|
152
|
+
* @returns The result of invoking `fn`
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```typescript
|
|
156
|
+
* const result = await breaker.execute(async () => {
|
|
157
|
+
* return await fetch('https://api.example.com/data');
|
|
158
|
+
* });
|
|
159
|
+
* ```
|
|
62
160
|
*/
|
|
63
161
|
execute<T>(fn: () => Promise<T>): Promise<T>;
|
|
64
162
|
/**
|
|
65
|
-
* Get current circuit breaker state
|
|
163
|
+
* Get the current circuit breaker state.
|
|
164
|
+
*
|
|
165
|
+
* @remarks
|
|
166
|
+
* Returns one of `'CLOSED'`, `'OPEN'`, or `'HALF_OPEN'`. Useful for
|
|
167
|
+
* dashboards or conditional logic that needs to know whether calls will
|
|
168
|
+
* be accepted.
|
|
169
|
+
*
|
|
170
|
+
* @returns The current {@link CircuitState}
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```typescript
|
|
174
|
+
* if (breaker.getState() === 'OPEN') {
|
|
175
|
+
* console.log('Circuit is open, requests will be rejected');
|
|
176
|
+
* }
|
|
177
|
+
* ```
|
|
66
178
|
*/
|
|
67
179
|
getState(): CircuitState;
|
|
68
180
|
/**
|
|
69
|
-
* Get circuit breaker metrics
|
|
181
|
+
* Get a snapshot of the circuit breaker's runtime metrics.
|
|
182
|
+
*
|
|
183
|
+
* @remarks
|
|
184
|
+
* Returns a copy of the internal counters including failure/success counts,
|
|
185
|
+
* the current state, and the timestamp of the last failure. Useful for
|
|
186
|
+
* monitoring and observability.
|
|
187
|
+
*
|
|
188
|
+
* @returns A {@link CircuitBreakerMetrics} snapshot
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```typescript
|
|
192
|
+
* const metrics = breaker.getMetrics();
|
|
193
|
+
* console.log(`State: ${metrics.state}, Failures: ${metrics.failures}`);
|
|
194
|
+
* ```
|
|
70
195
|
*/
|
|
71
196
|
getMetrics(): CircuitBreakerMetrics;
|
|
72
197
|
/**
|
|
73
|
-
* Manually open the circuit breaker
|
|
198
|
+
* Manually open the circuit breaker, rejecting all subsequent calls.
|
|
199
|
+
*
|
|
200
|
+
* @remarks
|
|
201
|
+
* Forces the circuit into the OPEN state regardless of the current failure
|
|
202
|
+
* count. Useful for administrative controls or when an external signal
|
|
203
|
+
* indicates the downstream service is unavailable.
|
|
204
|
+
*
|
|
205
|
+
* @example
|
|
206
|
+
* ```typescript
|
|
207
|
+
* breaker.forceOpen();
|
|
208
|
+
* console.log(breaker.getState()); // 'OPEN'
|
|
209
|
+
* ```
|
|
74
210
|
*/
|
|
75
211
|
forceOpen(): void;
|
|
76
212
|
/**
|
|
77
|
-
* Manually close the circuit breaker
|
|
213
|
+
* Manually close the circuit breaker and reset all counters.
|
|
214
|
+
*
|
|
215
|
+
* @remarks
|
|
216
|
+
* Forces the circuit into the CLOSED state and clears failure/success
|
|
217
|
+
* counters and any pending reset timer. Useful for administrative recovery
|
|
218
|
+
* after a known issue has been resolved.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* ```typescript
|
|
222
|
+
* breaker.forceClose();
|
|
223
|
+
* console.log(breaker.getState()); // 'CLOSED'
|
|
224
|
+
* ```
|
|
78
225
|
*/
|
|
79
226
|
forceClose(): void;
|
|
227
|
+
/** Records a successful call and may transition from HALF_OPEN to CLOSED. */
|
|
80
228
|
private onSuccess;
|
|
229
|
+
/** Records a failed call and may trip the circuit to OPEN. */
|
|
81
230
|
private onFailure;
|
|
231
|
+
/** Transitions the circuit to the given state, resetting HALF_OPEN call count when entering HALF_OPEN. */
|
|
82
232
|
private transitionTo;
|
|
233
|
+
/** Returns `true` if enough time has elapsed since the last failure to attempt a reset. */
|
|
83
234
|
private shouldAttemptReset;
|
|
235
|
+
/** Schedules a timer to transition from OPEN to HALF_OPEN after the configured reset timeout. */
|
|
84
236
|
private scheduleReset;
|
|
237
|
+
/** Resets all failure/success counters and clears the pending reset timer. */
|
|
85
238
|
private reset;
|
|
86
239
|
}
|
|
87
240
|
/**
|
|
88
|
-
*
|
|
241
|
+
* Registry for managing multiple named circuit breakers.
|
|
242
|
+
*
|
|
243
|
+
* @remarks
|
|
244
|
+
* Provides centralized creation, lookup, and metrics aggregation for
|
|
245
|
+
* circuit breakers. Each breaker is stored by name and can be retrieved
|
|
246
|
+
* or lazily created via {@link CircuitBreakerRegistry.getOrCreate}.
|
|
89
247
|
*
|
|
90
248
|
* @example
|
|
91
249
|
* ```typescript
|
|
@@ -100,15 +258,102 @@ export declare class CircuitBreaker {
|
|
|
100
258
|
* ```
|
|
101
259
|
*/
|
|
102
260
|
export declare class CircuitBreakerRegistry {
|
|
261
|
+
/** Internal map of circuit breaker name to instance. */
|
|
103
262
|
private breakers;
|
|
263
|
+
/**
|
|
264
|
+
* Register a new circuit breaker with the given name and configuration.
|
|
265
|
+
*
|
|
266
|
+
* @remarks
|
|
267
|
+
* Creates a new {@link CircuitBreaker}, stores it in the registry, and
|
|
268
|
+
* returns it. If a breaker with the same name already exists, it is replaced.
|
|
269
|
+
*
|
|
270
|
+
* @param name - Unique name for the circuit breaker
|
|
271
|
+
* @param config - Configuration options (name is set automatically)
|
|
272
|
+
* @returns The newly created {@link CircuitBreaker}
|
|
273
|
+
*
|
|
274
|
+
* @example
|
|
275
|
+
* ```typescript
|
|
276
|
+
* const breaker = registry.add('user-service', { failureThreshold: 3 });
|
|
277
|
+
* ```
|
|
278
|
+
*/
|
|
104
279
|
add(name: string, config: Omit<CircuitBreakerConfig, 'name'>): CircuitBreaker;
|
|
280
|
+
/**
|
|
281
|
+
* Retrieve a circuit breaker by name.
|
|
282
|
+
*
|
|
283
|
+
* @remarks
|
|
284
|
+
* Returns `undefined` if no breaker with the given name has been registered.
|
|
285
|
+
*
|
|
286
|
+
* @param name - Name of the circuit breaker to look up
|
|
287
|
+
* @returns The matching {@link CircuitBreaker}, or `undefined` if not found
|
|
288
|
+
*
|
|
289
|
+
* @example
|
|
290
|
+
* ```typescript
|
|
291
|
+
* const breaker = registry.get('payment-api');
|
|
292
|
+
* if (breaker) {
|
|
293
|
+
* await breaker.execute(() => callPaymentApi());
|
|
294
|
+
* }
|
|
295
|
+
* ```
|
|
296
|
+
*/
|
|
105
297
|
get(name: string): CircuitBreaker | undefined;
|
|
298
|
+
/**
|
|
299
|
+
* Retrieve an existing circuit breaker or create one if it does not exist.
|
|
300
|
+
*
|
|
301
|
+
* @remarks
|
|
302
|
+
* This is useful when callers want a breaker but do not know whether it
|
|
303
|
+
* has already been registered, avoiding duplicate creation.
|
|
304
|
+
*
|
|
305
|
+
* @param name - Name of the circuit breaker
|
|
306
|
+
* @param config - Configuration to use if a new breaker must be created
|
|
307
|
+
* @returns The existing or newly created {@link CircuitBreaker}
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* ```typescript
|
|
311
|
+
* const breaker = registry.getOrCreate('cache-api', { failureThreshold: 10 });
|
|
312
|
+
* ```
|
|
313
|
+
*/
|
|
106
314
|
getOrCreate(name: string, config: Omit<CircuitBreakerConfig, 'name'>): CircuitBreaker;
|
|
315
|
+
/**
|
|
316
|
+
* Collect metrics from all registered circuit breakers.
|
|
317
|
+
*
|
|
318
|
+
* @remarks
|
|
319
|
+
* Returns a record keyed by breaker name with each value being the
|
|
320
|
+
* corresponding {@link CircuitBreakerMetrics} snapshot.
|
|
321
|
+
*
|
|
322
|
+
* @returns A record mapping breaker names to their current metrics
|
|
323
|
+
*
|
|
324
|
+
* @example
|
|
325
|
+
* ```typescript
|
|
326
|
+
* const allMetrics = registry.getAllMetrics();
|
|
327
|
+
* for (const [name, metrics] of Object.entries(allMetrics)) {
|
|
328
|
+
* console.log(`${name}: ${metrics.state}`);
|
|
329
|
+
* }
|
|
330
|
+
* ```
|
|
331
|
+
*/
|
|
107
332
|
getAllMetrics(): Record<string, CircuitBreakerMetrics>;
|
|
333
|
+
/**
|
|
334
|
+
* Force-close all registered circuit breakers, resetting their counters.
|
|
335
|
+
*
|
|
336
|
+
* @remarks
|
|
337
|
+
* Iterates over every registered breaker and calls {@link CircuitBreaker.forceClose}.
|
|
338
|
+
* Useful for administrative recovery or test teardown.
|
|
339
|
+
*
|
|
340
|
+
* @example
|
|
341
|
+
* ```typescript
|
|
342
|
+
* registry.resetAll();
|
|
343
|
+
* ```
|
|
344
|
+
*/
|
|
108
345
|
resetAll(): void;
|
|
109
346
|
}
|
|
110
347
|
/**
|
|
111
|
-
* Create a circuit breaker
|
|
348
|
+
* Create an Express middleware that wraps downstream handlers with a circuit breaker.
|
|
349
|
+
*
|
|
350
|
+
* @remarks
|
|
351
|
+
* Instantiates a {@link CircuitBreaker} from the provided config and wraps the
|
|
352
|
+
* `next()` call. When the circuit is open, the middleware responds with a 503
|
|
353
|
+
* status and a JSON error body instead of forwarding the request.
|
|
354
|
+
*
|
|
355
|
+
* @param config - Circuit breaker configuration for the middleware instance
|
|
356
|
+
* @returns An Express-compatible middleware function
|
|
112
357
|
*
|
|
113
358
|
* @example
|
|
114
359
|
* ```typescript
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/circuit-breaker/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/circuit-breaker/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;AAE3D,mEAAmE;AACnE,MAAM,WAAW,oBAAoB;IACnC,oFAAoF;IACpF,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,gEAAgE;AAChE,MAAM,WAAW,qBAAqB;IACpC,4CAA4C;IAC5C,KAAK,EAAE,YAAY,CAAC;IAEpB,8DAA8D;IAC9D,QAAQ,EAAE,MAAM,CAAC;IAEjB,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,eAAe,CAAC,EAAE,IAAI,CAAC;IAEvB,8DAA8D;IAC9D,oBAAoB,EAAE,MAAM,CAAC;IAE7B,+DAA+D;IAC/D,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C;;;;OAIG;gBACS,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,qBAAa,cAAc;IA8Bb,OAAO,CAAC,MAAM;IA7B1B,6BAA6B;IAC7B,OAAO,CAAC,KAAK,CAA0B;IAEvC,4CAA4C;IAC5C,OAAO,CAAC,QAAQ,CAAK;IAErB,4CAA4C;IAC5C,OAAO,CAAC,SAAS,CAAK;IAEtB,4CAA4C;IAC5C,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