@argos-js/bff 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +228 -2
- package/dist/composition/aggregator.d.ts +10 -0
- package/dist/composition/aggregator.d.ts.map +1 -0
- package/dist/composition/aggregator.js +95 -0
- package/dist/composition/aggregator.js.map +1 -0
- package/dist/composition/types.d.ts +47 -0
- package/dist/composition/types.d.ts.map +1 -0
- package/dist/composition/types.js +24 -0
- package/dist/composition/types.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/resilience/circuit-breaker.d.ts +65 -0
- package/dist/resilience/circuit-breaker.d.ts.map +1 -0
- package/dist/resilience/circuit-breaker.js +203 -0
- package/dist/resilience/circuit-breaker.js.map +1 -0
- package/dist/resilience/types.d.ts +40 -0
- package/dist/resilience/types.d.ts.map +1 -0
- package/dist/resilience/types.js +24 -0
- package/dist/resilience/types.js.map +1 -0
- package/package.json +30 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Argos-JS Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,229 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @argos-js/bff
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Ultra-fast, resilient API Composition, Scatter-Gather Data Aggregation, and Circuit Breaker pattern designed for Backend-for-Frontend (BFF) architectures in Argos-JS.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## ⚡ Overview
|
|
8
|
+
|
|
9
|
+
In modern microservices and distributed backends, BFF (Backend-For-Frontend) layers often need to query multiple upstream services simultaneously, combine their payloads, handle timeouts, and gracefully degrade when downstream dependencies fail.
|
|
10
|
+
|
|
11
|
+
`@argos-js/bff` delivers:
|
|
12
|
+
- **Resilient Scatter-Gather Aggregator (`composeAggregator`)**: Execute multiple async requests in parallel with strictly typed output mapping.
|
|
13
|
+
- **Circuit Breaker (`CircuitBreaker` / `createCircuitBreaker`)**: Protects failing downstream systems, fast-failing in 0ms without hitting the network when OPEN.
|
|
14
|
+
- **Graceful Fallbacks & Partial Failures**: Distinguish between critical (`required: true`) and non-critical (`required: false`) dependencies.
|
|
15
|
+
- **Native AbortSignal & Timeouts**: Cancel slow network requests automatically with `AbortController`.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## 📦 Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pnpm add @argos-js/bff
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 🛡️ Circuit Breaker
|
|
28
|
+
|
|
29
|
+
The Circuit Breaker pattern prevents recurring cascading failures across microservices.
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
[Success]
|
|
33
|
+
┌───────────────┐
|
|
34
|
+
│ CLOSED │◄───────────────────┐
|
|
35
|
+
└───────┬───────┘ │
|
|
36
|
+
│ [failureThreshold exceeded]│ [halfOpenSuccessThreshold met]
|
|
37
|
+
▼ │
|
|
38
|
+
┌───────────────┐ ┌───────┴───────┐
|
|
39
|
+
│ OPEN │───────────►│ HALF_OPEN │
|
|
40
|
+
└───────────────┘ └───────────────┘
|
|
41
|
+
(0ms fail-fast) [resetTimeoutMs elapsed]
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Usage
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { createCircuitBreaker, CircuitBreakerOpenError } from '@argos-js/bff';
|
|
48
|
+
|
|
49
|
+
// 1. Create a circuit breaker
|
|
50
|
+
const paymentBreaker = createCircuitBreaker({
|
|
51
|
+
name: 'stripe-gateway',
|
|
52
|
+
failureThreshold: 5, // Trip to OPEN after 5 consecutive failures
|
|
53
|
+
resetTimeoutMs: 10000, // Wait 10s before testing with a canary request
|
|
54
|
+
halfOpenSuccessThreshold: 2,// 2 consecutive successful canary probes to close
|
|
55
|
+
timeoutMs: 3000, // 3s timeout for each execution
|
|
56
|
+
onStateChange: (from, to) => {
|
|
57
|
+
console.warn(`[CircuitBreaker] stripe-gateway transitioned: ${from} -> ${to}`);
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// 2. Execute protected requests
|
|
62
|
+
try {
|
|
63
|
+
const result = await paymentBreaker.execute(
|
|
64
|
+
async (signal) => {
|
|
65
|
+
const response = await fetch('https://api.stripe.com/v1/charges', { signal });
|
|
66
|
+
return await response.json();
|
|
67
|
+
},
|
|
68
|
+
// Optional fallback (value or factory function)
|
|
69
|
+
{ status: 'queued_offline' }
|
|
70
|
+
);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error instanceof CircuitBreakerOpenError) {
|
|
73
|
+
console.error('Circuit is OPEN! Short-circuited without network overhead.');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 🔀 Concurrency Orchestrator: `composeAggregator`
|
|
81
|
+
|
|
82
|
+
`composeAggregator` implements the scatter-gather pattern using `Promise.allSettled`, executing multiple upstream calls concurrently while managing individual timeouts and resilience fallbacks.
|
|
83
|
+
|
|
84
|
+
### Features
|
|
85
|
+
1. **Parallel Execution**: Aggregation runs concurrently, taking approximately the time of the slowest task rather than the sum of all tasks.
|
|
86
|
+
2. **Type Inference**: TypeScript automatically infers the return type of each task directly from its `fetch` function.
|
|
87
|
+
3. **Required vs Optional Tasks**:
|
|
88
|
+
- `required: true` (default): If the task fails or times out, the entire aggregator rejects immediately with `AggregatorError`.
|
|
89
|
+
- `required: false`: If the task fails or times out, it is replaced with its `fallback` value without aborting the other tasks.
|
|
90
|
+
4. **AbortSignal Propagation**: Tasks receive an `AbortSignal` that triggers automatically when `timeoutMs` expires.
|
|
91
|
+
5. **Direct Circuit Breaker Coupling**: Attach a `CircuitBreaker` instance directly to any task.
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## 💡 Practical Example: BFF Controller
|
|
96
|
+
|
|
97
|
+
Here is how you can build a high-performance Dashboard BFF endpoint in Argos-JS:
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { ArgosApp } from '@argos-js/core';
|
|
101
|
+
import { composeAggregator, createCircuitBreaker } from '@argos-js/bff';
|
|
102
|
+
|
|
103
|
+
const app = new ArgosApp();
|
|
104
|
+
|
|
105
|
+
// Circuit breaker for external/unstable recommendation engine
|
|
106
|
+
const recommendationsBreaker = createCircuitBreaker({
|
|
107
|
+
name: 'ai-recs-engine',
|
|
108
|
+
failureThreshold: 3,
|
|
109
|
+
resetTimeoutMs: 15000,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
app.get('/api/bff/home-screen', async (ctx) => {
|
|
113
|
+
const userId = ctx.req.headers['x-user-id'] as string;
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
const dashboardData = await composeAggregator({
|
|
117
|
+
// Critical task: Must succeed or the entire screen cannot be displayed
|
|
118
|
+
userProfile: {
|
|
119
|
+
required: true,
|
|
120
|
+
timeoutMs: 2000,
|
|
121
|
+
fetch: async (signal) => {
|
|
122
|
+
const res = await fetch(`http://users-service/users/${userId}`, { signal });
|
|
123
|
+
return (await res.json()) as { id: string; name: string; email: string };
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
// Critical task: Orders list
|
|
128
|
+
recentOrders: {
|
|
129
|
+
required: true,
|
|
130
|
+
timeoutMs: 2500,
|
|
131
|
+
fetch: async (signal) => {
|
|
132
|
+
const res = await fetch(`http://orders-service/orders?userId=${userId}`, { signal });
|
|
133
|
+
return (await res.json()) as Array<{ id: string; total: number }>;
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
|
|
137
|
+
// Non-critical task with Circuit Breaker and Fallback
|
|
138
|
+
recommendations: {
|
|
139
|
+
required: false,
|
|
140
|
+
timeoutMs: 1500,
|
|
141
|
+
circuitBreaker: recommendationsBreaker,
|
|
142
|
+
fallback: { items: [], source: 'fallback_popular_items' },
|
|
143
|
+
fetch: async (signal) => {
|
|
144
|
+
const res = await fetch(`http://recommendations-service/recs/${userId}`, { signal });
|
|
145
|
+
return (await res.json()) as { items: string[]; source: string };
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
// Non-critical promotional banner
|
|
150
|
+
promotions: {
|
|
151
|
+
required: false,
|
|
152
|
+
timeoutMs: 1000,
|
|
153
|
+
fallback: [],
|
|
154
|
+
fetch: async (signal) => {
|
|
155
|
+
const res = await fetch('http://cms-service/active-promos', { signal });
|
|
156
|
+
return (await res.json()) as Array<{ bannerUrl: string }>;
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// All types are 100% strictly inferred:
|
|
162
|
+
// dashboardData.userProfile -> { id: string; name: string; email: string }
|
|
163
|
+
// dashboardData.recentOrders -> Array<{ id: string; total: number }>
|
|
164
|
+
// dashboardData.recommendations -> { items: string[]; source: string }
|
|
165
|
+
// dashboardData.promotions -> Array<{ bannerUrl: string }>
|
|
166
|
+
|
|
167
|
+
return ctx.json({
|
|
168
|
+
success: true,
|
|
169
|
+
data: dashboardData,
|
|
170
|
+
});
|
|
171
|
+
} catch (error) {
|
|
172
|
+
return ctx.status(502).json({
|
|
173
|
+
success: false,
|
|
174
|
+
message: 'Failed to aggregate core dashboard data',
|
|
175
|
+
error: error instanceof Error ? error.message : String(error),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
## 📚 API Reference
|
|
184
|
+
|
|
185
|
+
### `CircuitBreaker`
|
|
186
|
+
```typescript
|
|
187
|
+
class CircuitBreaker {
|
|
188
|
+
readonly name: string;
|
|
189
|
+
readonly failureThreshold: number;
|
|
190
|
+
readonly resetTimeoutMs: number;
|
|
191
|
+
readonly halfOpenSuccessThreshold: number;
|
|
192
|
+
readonly timeoutMs?: number;
|
|
193
|
+
|
|
194
|
+
get state(): 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
195
|
+
get failures(): number;
|
|
196
|
+
get lastStateChange(): number;
|
|
197
|
+
|
|
198
|
+
isOpen(): boolean;
|
|
199
|
+
isClosed(): boolean;
|
|
200
|
+
isHalfOpen(): boolean;
|
|
201
|
+
|
|
202
|
+
reset(): void;
|
|
203
|
+
trip(): void;
|
|
204
|
+
|
|
205
|
+
execute<T>(
|
|
206
|
+
fn: (signal?: AbortSignal) => Promise<T>,
|
|
207
|
+
fallback?: T | (() => Promise<T> | T)
|
|
208
|
+
): Promise<T>;
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### `composeAggregator`
|
|
213
|
+
```typescript
|
|
214
|
+
function composeAggregator<TTasks extends TaskDefinitions>(
|
|
215
|
+
tasks: TTasks
|
|
216
|
+
): Promise<AggregatedResult<TTasks>>;
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Errors
|
|
220
|
+
- `CircuitBreakerOpenError`: Thrown when a call is attempted on an `OPEN` breaker without a fallback.
|
|
221
|
+
- `CircuitBreakerTimeoutError`: Thrown when execution through the breaker exceeds `timeoutMs`.
|
|
222
|
+
- `AggregatorError`: Thrown by `composeAggregator` if any task with `required: true` fails or times out.
|
|
223
|
+
- `TaskTimeoutError`: Thrown when a task in `composeAggregator` exceeds its configured `timeoutMs`.
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## 📄 License
|
|
228
|
+
|
|
229
|
+
MIT © Argos-JS
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { AggregatedResult, TaskDefinitions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Concurrently orchestrates and aggregates multiple async data sources (scatter-gather pattern)
|
|
4
|
+
* with individual timeouts, AbortSignal propagation, circuit breakers, and graceful fallback degradation.
|
|
5
|
+
*
|
|
6
|
+
* @param tasks Record of task definitions
|
|
7
|
+
* @returns Inferred typed aggregated results
|
|
8
|
+
*/
|
|
9
|
+
export declare function composeAggregator<TTasks extends TaskDefinitions>(tasks: TTasks): Promise<AggregatedResult<TTasks>>;
|
|
10
|
+
//# sourceMappingURL=aggregator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aggregator.d.ts","sourceRoot":"","sources":["../../src/composition/aggregator.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAGhB,eAAe,EAEhB,MAAM,YAAY,CAAC;AAgDpB;;;;;;GAMG;AACH,wBAAsB,iBAAiB,CAAC,MAAM,SAAS,eAAe,EACpE,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,CA8CnC"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.composeAggregator = composeAggregator;
|
|
4
|
+
const types_js_1 = require("./types.js");
|
|
5
|
+
const circuit_breaker_js_1 = require("../resilience/circuit-breaker.js");
|
|
6
|
+
async function runTask(name, def) {
|
|
7
|
+
const controller = new AbortController();
|
|
8
|
+
let timer;
|
|
9
|
+
let timeoutPromise;
|
|
10
|
+
if (def.timeoutMs && def.timeoutMs > 0) {
|
|
11
|
+
const timeoutLimit = def.timeoutMs;
|
|
12
|
+
timeoutPromise = new Promise((_, reject) => {
|
|
13
|
+
timer = setTimeout(() => {
|
|
14
|
+
controller.abort();
|
|
15
|
+
reject(new types_js_1.TaskTimeoutError(name, timeoutLimit));
|
|
16
|
+
}, timeoutLimit);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
const runner = async () => {
|
|
21
|
+
if (def.circuitBreaker) {
|
|
22
|
+
return await def.circuitBreaker.execute(async (cbSignal) => {
|
|
23
|
+
if (cbSignal) {
|
|
24
|
+
if (cbSignal.aborted) {
|
|
25
|
+
controller.abort();
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
cbSignal.addEventListener('abort', () => controller.abort(), { once: true });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return await def.fetch(controller.signal);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return await def.fetch(controller.signal);
|
|
35
|
+
};
|
|
36
|
+
const taskExecution = runner();
|
|
37
|
+
if (timeoutPromise) {
|
|
38
|
+
return await Promise.race([taskExecution, timeoutPromise]);
|
|
39
|
+
}
|
|
40
|
+
return await taskExecution;
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
if (timer) {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Concurrently orchestrates and aggregates multiple async data sources (scatter-gather pattern)
|
|
50
|
+
* with individual timeouts, AbortSignal propagation, circuit breakers, and graceful fallback degradation.
|
|
51
|
+
*
|
|
52
|
+
* @param tasks Record of task definitions
|
|
53
|
+
* @returns Inferred typed aggregated results
|
|
54
|
+
*/
|
|
55
|
+
async function composeAggregator(tasks) {
|
|
56
|
+
const keys = Object.keys(tasks);
|
|
57
|
+
if (keys.length === 0) {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
const executionPromises = keys.map((key) => runTask(key, tasks[key]));
|
|
61
|
+
const settled = await Promise.allSettled(executionPromises);
|
|
62
|
+
const results = {};
|
|
63
|
+
const failedRequiredTasks = [];
|
|
64
|
+
for (let i = 0; i < keys.length; i++) {
|
|
65
|
+
const key = keys[i];
|
|
66
|
+
const def = tasks[key];
|
|
67
|
+
const item = settled[i];
|
|
68
|
+
const isRequired = def.required !== false;
|
|
69
|
+
if (item.status === 'fulfilled') {
|
|
70
|
+
results[key] = item.value;
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
if (isRequired) {
|
|
74
|
+
failedRequiredTasks.push({ task: key, error: item.reason });
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
// Optional task graceful degradation
|
|
78
|
+
if (def.fallback !== undefined) {
|
|
79
|
+
results[key] = await (0, circuit_breaker_js_1.resolveFallback)(def.fallback);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
results[key] = undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (failedRequiredTasks.length > 0) {
|
|
88
|
+
const taskNames = failedRequiredTasks.map((f) => `"${f.task}"`).join(', ');
|
|
89
|
+
const firstReason = failedRequiredTasks[0].error;
|
|
90
|
+
const details = firstReason instanceof Error ? firstReason.message : String(firstReason);
|
|
91
|
+
throw new types_js_1.AggregatorError(`[composeAggregator] Aggregation failed: Required task(s) [${taskNames}] failed. Reason: ${details}`, failedRequiredTasks);
|
|
92
|
+
}
|
|
93
|
+
return results;
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=aggregator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aggregator.js","sourceRoot":"","sources":["../../src/composition/aggregator.ts"],"names":[],"mappings":";;AA6DA,8CAgDC;AA7GD,yCAMoB;AACpB,yEAAmE;AAEnE,KAAK,UAAU,OAAO,CAAI,IAAY,EAAE,GAAsB;IAC5D,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,IAAI,KAAiC,CAAC;IAEtC,IAAI,cAA0C,CAAC;IAC/C,IAAI,GAAG,CAAC,SAAS,IAAI,GAAG,CAAC,SAAS,GAAG,CAAC,EAAE,CAAC;QACvC,MAAM,YAAY,GAAG,GAAG,CAAC,SAAS,CAAC;QACnC,cAAc,GAAG,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;YAChD,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;gBACtB,UAAU,CAAC,KAAK,EAAE,CAAC;gBACnB,MAAM,CAAC,IAAI,2BAAgB,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC;YACnD,CAAC,EAAE,YAAY,CAAC,CAAC;QACnB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,KAAK,IAAgB,EAAE;YACpC,IAAI,GAAG,CAAC,cAAc,EAAE,CAAC;gBACvB,OAAO,MAAM,GAAG,CAAC,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;oBACzD,IAAI,QAAQ,EAAE,CAAC;wBACb,IAAI,QAAQ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C,CAAC,KAAK,CAAC;QACjD,MAAM,OAAO,GAAG,WAAW,YAAY,KAAK,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;QACzF,MAAM,IAAI,0BAAe,CACvB,6DAA6D,SAAS,qBAAqB,OAAO,EAAE,EACpG,mBAAmB,CACpB,CAAC;IACJ,CAAC;IAED,OAAO,OAAmC,CAAC;AAC7C,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { CircuitBreaker } from '../resilience/circuit-breaker.js';
|
|
2
|
+
export interface TaskDefinition<T = any> {
|
|
3
|
+
/**
|
|
4
|
+
* The asynchronous fetch function to execute. Receives an AbortSignal.
|
|
5
|
+
*/
|
|
6
|
+
fetch: (signal: AbortSignal) => Promise<T>;
|
|
7
|
+
/**
|
|
8
|
+
* Whether this task is required for the entire aggregation.
|
|
9
|
+
* If true, failure of this task rejects the entire composeAggregator promise.
|
|
10
|
+
* If false, failure of this task results in fallback value.
|
|
11
|
+
* @default true
|
|
12
|
+
*/
|
|
13
|
+
required?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Maximum allowed execution time in milliseconds before triggering AbortController.abort().
|
|
16
|
+
*/
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Fallback value or factory function returned when required is false and the task fails or times out.
|
|
20
|
+
*/
|
|
21
|
+
fallback?: T | (() => Promise<T> | T);
|
|
22
|
+
/**
|
|
23
|
+
* Optional Circuit Breaker instance protecting this task.
|
|
24
|
+
*/
|
|
25
|
+
circuitBreaker?: CircuitBreaker;
|
|
26
|
+
}
|
|
27
|
+
export type TaskDefinitions = Record<string, TaskDefinition<any>>;
|
|
28
|
+
export type InferTaskOutput<TDef> = TDef extends TaskDefinition<infer TResult> ? TResult : never;
|
|
29
|
+
export type AggregatedResult<TTasks extends TaskDefinitions> = {
|
|
30
|
+
[K in keyof TTasks]: InferTaskOutput<TTasks[K]>;
|
|
31
|
+
};
|
|
32
|
+
export declare class AggregatorError extends Error {
|
|
33
|
+
readonly failedTasks: Array<{
|
|
34
|
+
task: string;
|
|
35
|
+
error: unknown;
|
|
36
|
+
}>;
|
|
37
|
+
constructor(message: string, failedTasks: Array<{
|
|
38
|
+
task: string;
|
|
39
|
+
error: unknown;
|
|
40
|
+
}>);
|
|
41
|
+
}
|
|
42
|
+
export declare class TaskTimeoutError extends Error {
|
|
43
|
+
readonly taskName: string;
|
|
44
|
+
readonly timeoutMs: number;
|
|
45
|
+
constructor(taskName: string, timeoutMs: number);
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/composition/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAEvE,MAAM,WAAW,cAAc,CAAC,CAAC,GAAG,GAAG;IACrC;;OAEG;IACH,KAAK,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;IAE3C;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAEtC;;OAEG;IACH,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAED,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC;AAElE,MAAM,MAAM,eAAe,CAAC,IAAI,IAAI,IAAI,SAAS,cAAc,CAAC,MAAM,OAAO,CAAC,GAAG,OAAO,GAAG,KAAK,CAAC;AAEjG,MAAM,MAAM,gBAAgB,CAAC,MAAM,SAAS,eAAe,IAAI;KAC5D,CAAC,IAAI,MAAM,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;CAChD,CAAC;AAEF,qBAAa,eAAgB,SAAQ,KAAK;IACxC,SAAgB,WAAW,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;gBAEzD,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC;CAKlF;AAED,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,SAAgB,QAAQ,EAAE,MAAM,CAAC;IACjC,SAAgB,SAAS,EAAE,MAAM,CAAC;gBAEtB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;CAMhD"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TaskTimeoutError = exports.AggregatorError = void 0;
|
|
4
|
+
class AggregatorError extends Error {
|
|
5
|
+
failedTasks;
|
|
6
|
+
constructor(message, failedTasks) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'AggregatorError';
|
|
9
|
+
this.failedTasks = failedTasks;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.AggregatorError = AggregatorError;
|
|
13
|
+
class TaskTimeoutError extends Error {
|
|
14
|
+
taskName;
|
|
15
|
+
timeoutMs;
|
|
16
|
+
constructor(taskName, timeoutMs) {
|
|
17
|
+
super(`[composeAggregator] Task "${taskName}" timed out after ${timeoutMs}ms.`);
|
|
18
|
+
this.name = 'TaskTimeoutError';
|
|
19
|
+
this.taskName = taskName;
|
|
20
|
+
this.timeoutMs = timeoutMs;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.TaskTimeoutError = TaskTimeoutError;
|
|
24
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/composition/types.ts"],"names":[],"mappings":";;;AAwCA,MAAa,eAAgB,SAAQ,KAAK;IACxB,WAAW,CAA0C;IAErE,YAAY,OAAe,EAAE,WAAoD;QAC/E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AARD,0CAQC;AAED,MAAa,gBAAiB,SAAQ,KAAK;IACzB,QAAQ,CAAS;IACjB,SAAS,CAAS;IAElC,YAAY,QAAgB,EAAE,SAAiB;QAC7C,KAAK,CAAC,6BAA6B,QAAQ,qBAAqB,SAAS,KAAK,CAAC,CAAC;QAChF,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAVD,4CAUC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { CircuitBreaker, createCircuitBreaker, resolveFallback, } from './resilience/circuit-breaker.js';
|
|
2
|
+
export { type CircuitBreakerOptions, type CircuitBreakerState, CircuitBreakerOpenError, CircuitBreakerTimeoutError, } from './resilience/types.js';
|
|
3
|
+
export { composeAggregator } from './composition/aggregator.js';
|
|
4
|
+
export { type TaskDefinition, type TaskDefinitions, type AggregatedResult, type InferTaskOutput, AggregatorError, TaskTimeoutError, } from './composition/types.js';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,eAAe,EACf,gBAAgB,GACjB,MAAM,wBAAwB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TaskTimeoutError = exports.AggregatorError = exports.composeAggregator = exports.CircuitBreakerTimeoutError = exports.CircuitBreakerOpenError = exports.resolveFallback = exports.createCircuitBreaker = exports.CircuitBreaker = void 0;
|
|
4
|
+
var circuit_breaker_js_1 = require("./resilience/circuit-breaker.js");
|
|
5
|
+
Object.defineProperty(exports, "CircuitBreaker", { enumerable: true, get: function () { return circuit_breaker_js_1.CircuitBreaker; } });
|
|
6
|
+
Object.defineProperty(exports, "createCircuitBreaker", { enumerable: true, get: function () { return circuit_breaker_js_1.createCircuitBreaker; } });
|
|
7
|
+
Object.defineProperty(exports, "resolveFallback", { enumerable: true, get: function () { return circuit_breaker_js_1.resolveFallback; } });
|
|
8
|
+
var types_js_1 = require("./resilience/types.js");
|
|
9
|
+
Object.defineProperty(exports, "CircuitBreakerOpenError", { enumerable: true, get: function () { return types_js_1.CircuitBreakerOpenError; } });
|
|
10
|
+
Object.defineProperty(exports, "CircuitBreakerTimeoutError", { enumerable: true, get: function () { return types_js_1.CircuitBreakerTimeoutError; } });
|
|
11
|
+
var aggregator_js_1 = require("./composition/aggregator.js");
|
|
12
|
+
Object.defineProperty(exports, "composeAggregator", { enumerable: true, get: function () { return aggregator_js_1.composeAggregator; } });
|
|
13
|
+
var types_js_2 = require("./composition/types.js");
|
|
14
|
+
Object.defineProperty(exports, "AggregatorError", { enumerable: true, get: function () { return types_js_2.AggregatorError; } });
|
|
15
|
+
Object.defineProperty(exports, "TaskTimeoutError", { enumerable: true, get: function () { return types_js_2.TaskTimeoutError; } });
|
|
16
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,sEAIyC;AAHvC,oHAAA,cAAc,OAAA;AACd,0HAAA,oBAAoB,OAAA;AACpB,qHAAA,eAAe,OAAA;AAGjB,kDAK+B;AAF7B,mHAAA,uBAAuB,OAAA;AACvB,sHAAA,0BAA0B,OAAA;AAG5B,6DAAgE;AAAvD,kHAAA,iBAAiB,OAAA;AAE1B,mDAOgC;AAF9B,2GAAA,eAAe,OAAA;AACf,4GAAA,gBAAgB,OAAA"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { CircuitBreakerOptions, CircuitBreakerState } from './types.js';
|
|
2
|
+
export declare function resolveFallback<T>(fallback: T | (() => Promise<T> | T)): Promise<T>;
|
|
3
|
+
export declare class CircuitBreaker {
|
|
4
|
+
readonly name: string;
|
|
5
|
+
readonly failureThreshold: number;
|
|
6
|
+
readonly resetTimeoutMs: number;
|
|
7
|
+
readonly halfOpenSuccessThreshold: number;
|
|
8
|
+
readonly timeoutMs?: number;
|
|
9
|
+
readonly onStateChange?: (from: CircuitBreakerState, to: CircuitBreakerState) => void;
|
|
10
|
+
private _state;
|
|
11
|
+
private consecutiveFailures;
|
|
12
|
+
private halfOpenSuccesses;
|
|
13
|
+
private lastFailureTime;
|
|
14
|
+
private lastStateChangeTime;
|
|
15
|
+
/**
|
|
16
|
+
* Timestamp of the last state transition.
|
|
17
|
+
*/
|
|
18
|
+
get lastStateChange(): number;
|
|
19
|
+
constructor(options: CircuitBreakerOptions);
|
|
20
|
+
/**
|
|
21
|
+
* Current state of the Circuit Breaker: 'CLOSED' | 'OPEN' | 'HALF_OPEN'.
|
|
22
|
+
*/
|
|
23
|
+
get state(): CircuitBreakerState;
|
|
24
|
+
/**
|
|
25
|
+
* Helper method to read the current state.
|
|
26
|
+
*/
|
|
27
|
+
getState(): CircuitBreakerState;
|
|
28
|
+
/**
|
|
29
|
+
* Number of consecutive failures in CLOSED state.
|
|
30
|
+
*/
|
|
31
|
+
get failures(): number;
|
|
32
|
+
/**
|
|
33
|
+
* Check if circuit breaker is currently open.
|
|
34
|
+
*/
|
|
35
|
+
isOpen(): boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Check if circuit breaker is currently closed.
|
|
38
|
+
*/
|
|
39
|
+
isClosed(): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Check if circuit breaker is currently half-open.
|
|
42
|
+
*/
|
|
43
|
+
isHalfOpen(): boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Resets the circuit breaker state to CLOSED and clears counters.
|
|
46
|
+
*/
|
|
47
|
+
reset(): void;
|
|
48
|
+
/**
|
|
49
|
+
* Manually trips the circuit breaker to OPEN state.
|
|
50
|
+
*/
|
|
51
|
+
trip(): void;
|
|
52
|
+
/**
|
|
53
|
+
* Executes a protected asynchronous function with resilience features (timeout, fallback, state machine).
|
|
54
|
+
*/
|
|
55
|
+
execute<T>(fn: (signal?: AbortSignal) => Promise<T>, fallback?: T | (() => Promise<T> | T)): Promise<T>;
|
|
56
|
+
private checkAutoTransition;
|
|
57
|
+
private handleSuccess;
|
|
58
|
+
private handleFailure;
|
|
59
|
+
private transitionTo;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Factory function to create a new CircuitBreaker instance.
|
|
63
|
+
*/
|
|
64
|
+
export declare function createCircuitBreaker(options: CircuitBreakerOptions): CircuitBreaker;
|
|
65
|
+
//# sourceMappingURL=circuit-breaker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"circuit-breaker.d.ts","sourceRoot":"","sources":["../../src/resilience/circuit-breaker.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AAC,CAAC,EACxC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GACpC,OAAO,CAAC,CAAC,CAAC;IA2Cb,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,aAAa;IAerB,OAAO,CAAC,YAAY;CAarB;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CAEnF"}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CircuitBreaker = void 0;
|
|
4
|
+
exports.resolveFallback = resolveFallback;
|
|
5
|
+
exports.createCircuitBreaker = createCircuitBreaker;
|
|
6
|
+
const types_js_1 = require("./types.js");
|
|
7
|
+
async function resolveFallback(fallback) {
|
|
8
|
+
if (typeof fallback === 'function') {
|
|
9
|
+
return await fallback();
|
|
10
|
+
}
|
|
11
|
+
return fallback;
|
|
12
|
+
}
|
|
13
|
+
class CircuitBreaker {
|
|
14
|
+
name;
|
|
15
|
+
failureThreshold;
|
|
16
|
+
resetTimeoutMs;
|
|
17
|
+
halfOpenSuccessThreshold;
|
|
18
|
+
timeoutMs;
|
|
19
|
+
onStateChange;
|
|
20
|
+
_state = 'CLOSED';
|
|
21
|
+
consecutiveFailures = 0;
|
|
22
|
+
halfOpenSuccesses = 0;
|
|
23
|
+
lastFailureTime = 0;
|
|
24
|
+
lastStateChangeTime = Date.now();
|
|
25
|
+
/**
|
|
26
|
+
* Timestamp of the last state transition.
|
|
27
|
+
*/
|
|
28
|
+
get lastStateChange() {
|
|
29
|
+
return this.lastStateChangeTime;
|
|
30
|
+
}
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.name = options.name;
|
|
33
|
+
this.failureThreshold = options.failureThreshold ?? 5;
|
|
34
|
+
this.resetTimeoutMs = options.resetTimeoutMs ?? 10000;
|
|
35
|
+
this.halfOpenSuccessThreshold = options.halfOpenSuccessThreshold ?? 2;
|
|
36
|
+
this.timeoutMs = options.timeoutMs;
|
|
37
|
+
this.onStateChange = options.onStateChange;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Current state of the Circuit Breaker: 'CLOSED' | 'OPEN' | 'HALF_OPEN'.
|
|
41
|
+
*/
|
|
42
|
+
get state() {
|
|
43
|
+
this.checkAutoTransition();
|
|
44
|
+
return this._state;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Helper method to read the current state.
|
|
48
|
+
*/
|
|
49
|
+
getState() {
|
|
50
|
+
return this.state;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Number of consecutive failures in CLOSED state.
|
|
54
|
+
*/
|
|
55
|
+
get failures() {
|
|
56
|
+
return this.consecutiveFailures;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Check if circuit breaker is currently open.
|
|
60
|
+
*/
|
|
61
|
+
isOpen() {
|
|
62
|
+
return this.state === 'OPEN';
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Check if circuit breaker is currently closed.
|
|
66
|
+
*/
|
|
67
|
+
isClosed() {
|
|
68
|
+
return this.state === 'CLOSED';
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Check if circuit breaker is currently half-open.
|
|
72
|
+
*/
|
|
73
|
+
isHalfOpen() {
|
|
74
|
+
return this.state === 'HALF_OPEN';
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Resets the circuit breaker state to CLOSED and clears counters.
|
|
78
|
+
*/
|
|
79
|
+
reset() {
|
|
80
|
+
const prev = this._state;
|
|
81
|
+
this._state = 'CLOSED';
|
|
82
|
+
this.consecutiveFailures = 0;
|
|
83
|
+
this.halfOpenSuccesses = 0;
|
|
84
|
+
this.lastFailureTime = 0;
|
|
85
|
+
this.lastStateChangeTime = Date.now();
|
|
86
|
+
if (prev !== 'CLOSED' && this.onStateChange) {
|
|
87
|
+
try {
|
|
88
|
+
this.onStateChange(prev, 'CLOSED');
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// Callback safety
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Manually trips the circuit breaker to OPEN state.
|
|
97
|
+
*/
|
|
98
|
+
trip() {
|
|
99
|
+
this.transitionTo('OPEN');
|
|
100
|
+
this.lastFailureTime = Date.now();
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Executes a protected asynchronous function with resilience features (timeout, fallback, state machine).
|
|
104
|
+
*/
|
|
105
|
+
async execute(fn, fallback) {
|
|
106
|
+
this.checkAutoTransition();
|
|
107
|
+
if (this._state === 'OPEN') {
|
|
108
|
+
if (fallback !== undefined) {
|
|
109
|
+
return await resolveFallback(fallback);
|
|
110
|
+
}
|
|
111
|
+
throw new types_js_1.CircuitBreakerOpenError(this.name);
|
|
112
|
+
}
|
|
113
|
+
const controller = this.timeoutMs ? new AbortController() : undefined;
|
|
114
|
+
let timeoutTimer;
|
|
115
|
+
let executionPromise = fn(controller?.signal);
|
|
116
|
+
if (this.timeoutMs && controller) {
|
|
117
|
+
const timeoutLimit = this.timeoutMs;
|
|
118
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
119
|
+
timeoutTimer = setTimeout(() => {
|
|
120
|
+
controller.abort();
|
|
121
|
+
reject(new types_js_1.CircuitBreakerTimeoutError(this.name, timeoutLimit));
|
|
122
|
+
}, timeoutLimit);
|
|
123
|
+
});
|
|
124
|
+
executionPromise = Promise.race([executionPromise, timeoutPromise]);
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
const result = await executionPromise;
|
|
128
|
+
this.handleSuccess();
|
|
129
|
+
return result;
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
this.handleFailure();
|
|
133
|
+
if (fallback !== undefined) {
|
|
134
|
+
return await resolveFallback(fallback);
|
|
135
|
+
}
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
if (timeoutTimer) {
|
|
140
|
+
clearTimeout(timeoutTimer);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
checkAutoTransition() {
|
|
145
|
+
if (this._state === 'OPEN') {
|
|
146
|
+
const now = Date.now();
|
|
147
|
+
if (now - this.lastFailureTime >= this.resetTimeoutMs) {
|
|
148
|
+
this.halfOpenSuccesses = 0;
|
|
149
|
+
this.transitionTo('HALF_OPEN');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
handleSuccess() {
|
|
154
|
+
if (this._state === 'HALF_OPEN') {
|
|
155
|
+
this.halfOpenSuccesses++;
|
|
156
|
+
if (this.halfOpenSuccessThreshold <= this.halfOpenSuccesses) {
|
|
157
|
+
this.consecutiveFailures = 0;
|
|
158
|
+
this.halfOpenSuccesses = 0;
|
|
159
|
+
this.transitionTo('CLOSED');
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else if (this._state === 'CLOSED') {
|
|
163
|
+
this.consecutiveFailures = 0;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
handleFailure() {
|
|
167
|
+
this.lastFailureTime = Date.now();
|
|
168
|
+
if (this._state === 'HALF_OPEN') {
|
|
169
|
+
this.consecutiveFailures = this.failureThreshold;
|
|
170
|
+
this.halfOpenSuccesses = 0;
|
|
171
|
+
this.transitionTo('OPEN');
|
|
172
|
+
}
|
|
173
|
+
else if (this._state === 'CLOSED') {
|
|
174
|
+
this.consecutiveFailures++;
|
|
175
|
+
if (this.consecutiveFailures >= this.failureThreshold) {
|
|
176
|
+
this.transitionTo('OPEN');
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
transitionTo(newState) {
|
|
181
|
+
if (this._state === newState)
|
|
182
|
+
return;
|
|
183
|
+
const oldState = this._state;
|
|
184
|
+
this._state = newState;
|
|
185
|
+
this.lastStateChangeTime = Date.now();
|
|
186
|
+
if (this.onStateChange) {
|
|
187
|
+
try {
|
|
188
|
+
this.onStateChange(oldState, newState);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// Callback safety
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
exports.CircuitBreaker = CircuitBreaker;
|
|
197
|
+
/**
|
|
198
|
+
* Factory function to create a new CircuitBreaker instance.
|
|
199
|
+
*/
|
|
200
|
+
function createCircuitBreaker(options) {
|
|
201
|
+
return new CircuitBreaker(options);
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=circuit-breaker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"circuit-breaker.js","sourceRoot":"","sources":["../../src/resilience/circuit-breaker.ts"],"names":[],"mappings":";;;AAOA,0CAKC;AA+MD,oDAEC;AA7ND,yCAKoB;AAEb,KAAK,UAAU,eAAe,CAAI,QAAoC;IAC3E,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;QACnC,OAAO,MAAO,QAAiC,EAAE,CAAC;IACpD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAa,cAAc;IACT,IAAI,CAAS;IACb,gBAAgB,CAAS;IACzB,cAAc,CAAS;IACvB,wBAAwB,CAAS;IACjC,SAAS,CAAU;IACnB,aAAa,CAAgE;IAErF,MAAM,GAAwB,QAAQ,CAAC;IACvC,mBAAmB,GAAG,CAAC,CAAC;IACxB,iBAAiB,GAAG,CAAC,CAAC;IACtB,eAAe,GAAG,CAAC,CAAC;IACpB,mBAAmB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEzC;;OAEG;IACH,IAAW,eAAe;QACxB,OAAO,IAAI,CAAC,mBAAmB,CAAC;IAClC,CAAC;IAED,YAAY,OAA8B;QACxC,IAAI,CAAC,IAAI,GAAG,OAAO,C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AO,CAAC,CAAC;AACrC,CAAC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type CircuitBreakerState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
2
|
+
export interface CircuitBreakerOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Distinct name identifying this circuit breaker instance.
|
|
5
|
+
*/
|
|
6
|
+
name: string;
|
|
7
|
+
/**
|
|
8
|
+
* Number of consecutive failures required to trip the breaker from CLOSED to OPEN.
|
|
9
|
+
* @default 5
|
|
10
|
+
*/
|
|
11
|
+
failureThreshold?: number;
|
|
12
|
+
/**
|
|
13
|
+
* Duration in milliseconds the breaker stays OPEN before moving to HALF_OPEN for probing.
|
|
14
|
+
* @default 10000
|
|
15
|
+
*/
|
|
16
|
+
resetTimeoutMs?: number;
|
|
17
|
+
/**
|
|
18
|
+
* Number of consecutive successful probe requests in HALF_OPEN to close the breaker.
|
|
19
|
+
* @default 2
|
|
20
|
+
*/
|
|
21
|
+
halfOpenSuccessThreshold?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Optional timeout in milliseconds for individual calls executed through this breaker.
|
|
24
|
+
*/
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
/**
|
|
27
|
+
* Callback fired whenever the state changes.
|
|
28
|
+
*/
|
|
29
|
+
onStateChange?: (from: CircuitBreakerState, to: CircuitBreakerState) => void;
|
|
30
|
+
}
|
|
31
|
+
export declare class CircuitBreakerOpenError extends Error {
|
|
32
|
+
readonly circuitBreakerName: string;
|
|
33
|
+
constructor(circuitBreakerName: string);
|
|
34
|
+
}
|
|
35
|
+
export declare class CircuitBreakerTimeoutError extends Error {
|
|
36
|
+
readonly circuitBreakerName: string;
|
|
37
|
+
readonly timeoutMs: number;
|
|
38
|
+
constructor(circuitBreakerName: string, timeoutMs: number);
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/resilience/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,mBAAmB,GAAG,QAAQ,GAAG,MAAM,GAAG,WAAW,CAAC;AAElE,MAAM,WAAW,qBAAqB;IACpC;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IAExB;;;OAGG;IACH,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAElC;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,mBAAmB,EAAE,EAAE,EAAE,mBAAmB,KAAK,IAAI,CAAC;CAC9E;AAED,qBAAa,uBAAwB,SAAQ,KAAK;IAChD,SAAgB,kBAAkB,EAAE,MAAM,CAAC;gBAE/B,kBAAkB,EAAE,MAAM;CAKvC;AAED,qBAAa,0BAA2B,SAAQ,KAAK;IACnD,SAAgB,kBAAkB,EAAE,MAAM,CAAC;IAC3C,SAAgB,SAAS,EAAE,MAAM,CAAC;gBAEtB,kBAAkB,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM;CAM1D"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CircuitBreakerTimeoutError = exports.CircuitBreakerOpenError = void 0;
|
|
4
|
+
class CircuitBreakerOpenError extends Error {
|
|
5
|
+
circuitBreakerName;
|
|
6
|
+
constructor(circuitBreakerName) {
|
|
7
|
+
super(`[CircuitBreaker] "${circuitBreakerName}" is OPEN. Immediate rejection without network execution.`);
|
|
8
|
+
this.name = 'CircuitBreakerOpenError';
|
|
9
|
+
this.circuitBreakerName = circuitBreakerName;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
exports.CircuitBreakerOpenError = CircuitBreakerOpenError;
|
|
13
|
+
class CircuitBreakerTimeoutError extends Error {
|
|
14
|
+
circuitBreakerName;
|
|
15
|
+
timeoutMs;
|
|
16
|
+
constructor(circuitBreakerName, timeoutMs) {
|
|
17
|
+
super(`[CircuitBreaker] "${circuitBreakerName}" execution timed out after ${timeoutMs}ms.`);
|
|
18
|
+
this.name = 'CircuitBreakerTimeoutError';
|
|
19
|
+
this.circuitBreakerName = circuitBreakerName;
|
|
20
|
+
this.timeoutMs = timeoutMs;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.CircuitBreakerTimeoutError = CircuitBreakerTimeoutError;
|
|
24
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/resilience/types.ts"],"names":[],"mappings":";;;AAqCA,MAAa,uBAAwB,SAAQ,KAAK;IAChC,kBAAkB,CAAS;IAE3C,YAAY,kBAA0B;QACpC,KAAK,CAAC,qBAAqB,kBAAkB,2DAA2D,CAAC,CAAC;QAC1G,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,kBAAkB,GAAG,kBAAkB,CAAC;IAC/C,CAAC;CACF;AARD,0DAQC;AAED,MAAa,0BAA2B,SAAQ,KAAK;IACnC,kBAAkB,CAAS;IAC3B,SAAS,CAAS;IAElC,YAAY,kBAA0B,EAAE,SAAiB;QACvD,KAAK,CAAC,qBAAqB,kBAAkB,+BAA+B,SAAS,KAAK,CAAC,CAAC;QAC5F,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;QACzC,IAAI,CAAC,kBAAkB,GAAG,kBAAkB,CAAC;QAC7C,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAVD,gEAUC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@argos-js/bff",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "API Composition, Data Aggregation, and Resilience (Circuit Breaker & Scatter-Gather) for Argos-JS",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"import": "./dist/index.js",
|
|
10
|
+
"require": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@argos-js/core": "0.1.1"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@types/node": "^20.11.0",
|
|
19
|
+
"tsx": "^4.7.0",
|
|
20
|
+
"typescript": "^5.4.0"
|
|
21
|
+
},
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc",
|
|
30
|
+
"dev": "tsc --watch",
|
|
31
|
+
"test": "tsx test/bff.spec.ts"
|
|
32
|
+
}
|
|
6
33
|
}
|