@hazeljs/resilience 0.2.0-beta.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +192 -0
  2. package/README.md +95 -0
  3. package/dist/__tests__/bulkhead-timeout.test.d.ts +2 -0
  4. package/dist/__tests__/bulkhead-timeout.test.d.ts.map +1 -0
  5. package/dist/__tests__/bulkhead-timeout.test.js +74 -0
  6. package/dist/__tests__/circuit-breaker.test.d.ts +2 -0
  7. package/dist/__tests__/circuit-breaker.test.d.ts.map +1 -0
  8. package/dist/__tests__/circuit-breaker.test.js +160 -0
  9. package/dist/__tests__/decorators.test.d.ts +2 -0
  10. package/dist/__tests__/decorators.test.d.ts.map +1 -0
  11. package/dist/__tests__/decorators.test.js +288 -0
  12. package/dist/__tests__/index.test.d.ts +2 -0
  13. package/dist/__tests__/index.test.d.ts.map +1 -0
  14. package/dist/__tests__/index.test.js +50 -0
  15. package/dist/__tests__/metrics.test.d.ts +2 -0
  16. package/dist/__tests__/metrics.test.d.ts.map +1 -0
  17. package/dist/__tests__/metrics.test.js +83 -0
  18. package/dist/__tests__/rate-limiter.test.d.ts +2 -0
  19. package/dist/__tests__/rate-limiter.test.d.ts.map +1 -0
  20. package/dist/__tests__/rate-limiter.test.js +143 -0
  21. package/dist/__tests__/retry-policy.test.d.ts +2 -0
  22. package/dist/__tests__/retry-policy.test.d.ts.map +1 -0
  23. package/dist/__tests__/retry-policy.test.js +84 -0
  24. package/dist/__tests__/sliding-window.test.d.ts +2 -0
  25. package/dist/__tests__/sliding-window.test.d.ts.map +1 -0
  26. package/dist/__tests__/sliding-window.test.js +93 -0
  27. package/dist/bulkhead/bulkhead.d.ts +34 -0
  28. package/dist/bulkhead/bulkhead.d.ts.map +1 -0
  29. package/dist/bulkhead/bulkhead.js +97 -0
  30. package/dist/circuit-breaker/circuit-breaker-registry.d.ts +38 -0
  31. package/dist/circuit-breaker/circuit-breaker-registry.d.ts.map +1 -0
  32. package/dist/circuit-breaker/circuit-breaker-registry.js +61 -0
  33. package/dist/circuit-breaker/circuit-breaker.d.ts +51 -0
  34. package/dist/circuit-breaker/circuit-breaker.d.ts.map +1 -0
  35. package/dist/circuit-breaker/circuit-breaker.js +182 -0
  36. package/dist/circuit-breaker/sliding-window.d.ts +49 -0
  37. package/dist/circuit-breaker/sliding-window.d.ts.map +1 -0
  38. package/dist/circuit-breaker/sliding-window.js +89 -0
  39. package/dist/decorators/index.d.ts +51 -0
  40. package/dist/decorators/index.d.ts.map +1 -0
  41. package/dist/decorators/index.js +133 -0
  42. package/dist/index.d.ts +18 -0
  43. package/dist/index.d.ts.map +1 -0
  44. package/dist/index.js +55 -0
  45. package/dist/metrics/metrics-collector.d.ts +69 -0
  46. package/dist/metrics/metrics-collector.d.ts.map +1 -0
  47. package/dist/metrics/metrics-collector.js +180 -0
  48. package/dist/rate-limiter/rate-limiter.d.ts +72 -0
  49. package/dist/rate-limiter/rate-limiter.d.ts.map +1 -0
  50. package/dist/rate-limiter/rate-limiter.js +147 -0
  51. package/dist/retry/retry-policy.d.ts +19 -0
  52. package/dist/retry/retry-policy.d.ts.map +1 -0
  53. package/dist/retry/retry-policy.js +87 -0
  54. package/dist/timeout/timeout.d.ts +23 -0
  55. package/dist/timeout/timeout.d.ts.map +1 -0
  56. package/dist/timeout/timeout.js +55 -0
  57. package/dist/types/index.d.ts +135 -0
  58. package/dist/types/index.d.ts.map +1 -0
  59. package/dist/types/index.js +61 -0
  60. package/package.json +63 -0
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024 HazelJS Team
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ---
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,95 @@
1
+ # @hazeljs/resilience
2
+
3
+ Fault-tolerance and resilience patterns for HazelJS. Provides circuit breaker, retry, timeout, bulkhead, rate limiter, and metrics collection — all usable via decorators or programmatic API.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/resilience.svg)](https://www.npmjs.com/package/@hazeljs/resilience)
6
+ [![npm downloads](https://img.shields.io/npm/dm/@hazeljs/resilience)](https://www.npmjs.com/package/@hazeljs/resilience)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @hazeljs/resilience
13
+ ```
14
+
15
+ ## Features
16
+
17
+ - **Circuit Breaker** — Prevents cascading failures with sliding window metrics, configurable failure predicates, fallback support, and event-driven state transitions
18
+ - **Retry** — Configurable retry with exponential/linear/fixed backoff, jitter, and retryable-error predicates
19
+ - **Timeout** — Promise-based timeout wrapper with cancellation
20
+ - **Bulkhead** — Concurrency limiter with queue support to isolate failures
21
+ - **Rate Limiter** — Token bucket and sliding window strategies
22
+ - **Metrics** — Tracks success/failure/latency per target, feeds into gateway canary decisions
23
+
24
+ ## Quick Start
25
+
26
+ ### Decorator API
27
+
28
+ ```typescript
29
+ import { Injectable } from '@hazeljs/core';
30
+ import { WithCircuitBreaker, WithRetry, WithTimeout, WithBulkhead, Fallback } from '@hazeljs/resilience';
31
+
32
+ @Injectable()
33
+ class PaymentService {
34
+ @WithCircuitBreaker({
35
+ failureThreshold: 5,
36
+ slidingWindow: { type: 'count', size: 20 },
37
+ resetTimeout: 30_000,
38
+ fallback: 'processPaymentFallback',
39
+ })
40
+ @WithRetry({ maxAttempts: 3, backoff: 'exponential', baseDelay: 500 })
41
+ @WithTimeout(5000)
42
+ @WithBulkhead({ maxConcurrent: 10, maxQueue: 50 })
43
+ async processPayment(order: Order): Promise<PaymentResult> {
44
+ return await this.paymentGateway.charge(order);
45
+ }
46
+
47
+ @Fallback('processPayment')
48
+ async processPaymentFallback(order: Order): Promise<PaymentResult> {
49
+ return { status: 'queued', message: 'Payment will be processed later' };
50
+ }
51
+ }
52
+ ```
53
+
54
+ ### Programmatic API
55
+
56
+ ```typescript
57
+ import { CircuitBreaker, RetryPolicy, Timeout, Bulkhead } from '@hazeljs/resilience';
58
+
59
+ // Circuit Breaker
60
+ const breaker = new CircuitBreaker({ failureThreshold: 5 });
61
+ const result = await breaker.execute(() => fetch('/api/data'));
62
+
63
+ breaker.on('stateChange', (from, to) => console.log(`${from} -> ${to}`));
64
+ breaker.getMetrics(); // { totalRequests, failureRate, p99Latency, ... }
65
+
66
+ // Retry
67
+ const retry = new RetryPolicy({ maxAttempts: 3, backoff: 'exponential', baseDelay: 1000 });
68
+ const data = await retry.execute(() => fetch('/api/unstable'));
69
+
70
+ // Timeout
71
+ const timeout = new Timeout(5000);
72
+ const response = await timeout.execute(() => fetch('/api/slow'));
73
+
74
+ // Bulkhead
75
+ const bulkhead = new Bulkhead({ maxConcurrent: 10, maxQueue: 50 });
76
+ const result = await bulkhead.execute(() => intensiveOperation());
77
+ ```
78
+
79
+ ## Circuit Breaker States
80
+
81
+ ```
82
+ CLOSED ──(failures >= threshold)──> OPEN
83
+ ^ |
84
+ | | (reset timeout)
85
+ | v
86
+ └──(successes >= threshold)── HALF_OPEN
87
+ ```
88
+
89
+ ## API Reference
90
+
91
+ See the [full documentation](https://hazeljs.com/docs/packages/resilience) for complete API reference.
92
+
93
+ ## License
94
+
95
+ MIT
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=bulkhead-timeout.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bulkhead-timeout.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/bulkhead-timeout.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const bulkhead_1 = require("../bulkhead/bulkhead");
4
+ const timeout_1 = require("../timeout/timeout");
5
+ const types_1 = require("../types");
6
+ describe('Bulkhead', () => {
7
+ it('should allow calls within concurrency limit', async () => {
8
+ const bulkhead = new bulkhead_1.Bulkhead({ maxConcurrent: 2, maxQueue: 0 });
9
+ const results = await Promise.all([
10
+ bulkhead.execute(() => Promise.resolve('a')),
11
+ bulkhead.execute(() => Promise.resolve('b')),
12
+ ]);
13
+ expect(results).toEqual(['a', 'b']);
14
+ });
15
+ it('should reject when concurrency and queue are full', async () => {
16
+ const bulkhead = new bulkhead_1.Bulkhead({ maxConcurrent: 1, maxQueue: 0 });
17
+ // Start a slow call that holds the slot
18
+ const slowCall = bulkhead.execute(() => new Promise((resolve) => setTimeout(() => resolve('slow'), 100)));
19
+ // This should be rejected immediately
20
+ await expect(bulkhead.execute(() => Promise.resolve('should-not-run'))).rejects.toThrow(types_1.BulkheadError);
21
+ await slowCall;
22
+ });
23
+ it('should queue calls when concurrency is full', async () => {
24
+ const bulkhead = new bulkhead_1.Bulkhead({ maxConcurrent: 1, maxQueue: 1 });
25
+ const order = [];
26
+ const call1 = bulkhead.execute(async () => {
27
+ await new Promise((resolve) => setTimeout(resolve, 50));
28
+ order.push('first');
29
+ return 'first';
30
+ });
31
+ const call2 = bulkhead.execute(async () => {
32
+ order.push('second');
33
+ return 'second';
34
+ });
35
+ const [r1, r2] = await Promise.all([call1, call2]);
36
+ expect(r1).toBe('first');
37
+ expect(r2).toBe('second');
38
+ expect(order).toEqual(['first', 'second']);
39
+ });
40
+ it('should track metrics', async () => {
41
+ const bulkhead = new bulkhead_1.Bulkhead({ maxConcurrent: 2, maxQueue: 5 });
42
+ const metrics = bulkhead.getMetrics();
43
+ expect(metrics.activeCalls).toBe(0);
44
+ expect(metrics.queueLength).toBe(0);
45
+ expect(metrics.maxConcurrent).toBe(2);
46
+ expect(metrics.maxQueue).toBe(5);
47
+ });
48
+ });
49
+ describe('Timeout', () => {
50
+ it('should resolve if function completes in time', async () => {
51
+ const timeout = new timeout_1.Timeout(1000);
52
+ const result = await timeout.execute(() => Promise.resolve('fast'));
53
+ expect(result).toBe('fast');
54
+ });
55
+ it('should reject with TimeoutError if too slow', async () => {
56
+ const timeout = new timeout_1.Timeout(50);
57
+ await expect(timeout.execute(() => new Promise((resolve) => setTimeout(() => resolve('slow'), 200)))).rejects.toThrow(types_1.TimeoutError);
58
+ });
59
+ it('should work with withTimeout helper', async () => {
60
+ const result = await (0, timeout_1.withTimeout)(() => Promise.resolve('quick'), 1000);
61
+ expect(result).toBe('quick');
62
+ });
63
+ it('should include duration in error message', async () => {
64
+ const timeout = new timeout_1.Timeout({ duration: 50, message: 'Custom timeout' });
65
+ try {
66
+ await timeout.execute(() => new Promise((resolve) => setTimeout(() => resolve('slow'), 200)));
67
+ fail('should have thrown');
68
+ }
69
+ catch (error) {
70
+ expect(error.message).toContain('Custom timeout');
71
+ expect(error.message).toContain('50ms');
72
+ }
73
+ });
74
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=circuit-breaker.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuit-breaker.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/circuit-breaker.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const circuit_breaker_1 = require("../circuit-breaker/circuit-breaker");
4
+ const circuit_breaker_registry_1 = require("../circuit-breaker/circuit-breaker-registry");
5
+ const types_1 = require("../types");
6
+ describe('CircuitBreaker', () => {
7
+ let breaker;
8
+ beforeEach(() => {
9
+ breaker = new circuit_breaker_1.CircuitBreaker({
10
+ failureThreshold: 3,
11
+ successThreshold: 2,
12
+ timeout: 5000,
13
+ resetTimeout: 100, // Short for tests
14
+ });
15
+ });
16
+ describe('CLOSED state', () => {
17
+ it('should start in CLOSED state', () => {
18
+ expect(breaker.getState()).toBe(types_1.CircuitState.CLOSED);
19
+ expect(breaker.isClosed()).toBe(true);
20
+ });
21
+ it('should pass through successful calls', async () => {
22
+ const result = await breaker.execute(() => Promise.resolve('success'));
23
+ expect(result).toBe('success');
24
+ expect(breaker.getState()).toBe(types_1.CircuitState.CLOSED);
25
+ });
26
+ it('should pass through failing calls and count failures', async () => {
27
+ await expect(breaker.execute(() => Promise.reject(new Error('fail')))).rejects.toThrow('fail');
28
+ expect(breaker.getFailureCount()).toBe(1);
29
+ });
30
+ it('should transition to OPEN after failure threshold', async () => {
31
+ for (let i = 0; i < 3; i++) {
32
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
33
+ }
34
+ expect(breaker.getState()).toBe(types_1.CircuitState.OPEN);
35
+ expect(breaker.isOpen()).toBe(true);
36
+ });
37
+ });
38
+ describe('OPEN state', () => {
39
+ beforeEach(async () => {
40
+ // Trip the breaker
41
+ for (let i = 0; i < 3; i++) {
42
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
43
+ }
44
+ });
45
+ it('should reject calls immediately when OPEN', async () => {
46
+ await expect(breaker.execute(() => Promise.resolve('should not reach'))).rejects.toThrow(types_1.CircuitBreakerError);
47
+ });
48
+ it('should transition to HALF_OPEN after reset timeout', async () => {
49
+ // Wait for reset timeout
50
+ await new Promise((resolve) => setTimeout(resolve, 150));
51
+ // Next call should be allowed (transitions to HALF_OPEN)
52
+ const result = await breaker.execute(() => Promise.resolve('trial'));
53
+ expect(result).toBe('trial');
54
+ });
55
+ });
56
+ describe('HALF_OPEN state', () => {
57
+ beforeEach(async () => {
58
+ // Trip the breaker, then wait for reset
59
+ for (let i = 0; i < 3; i++) {
60
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
61
+ }
62
+ await new Promise((resolve) => setTimeout(resolve, 150));
63
+ });
64
+ it('should transition back to CLOSED after success threshold', async () => {
65
+ // successThreshold = 2
66
+ await breaker.execute(() => Promise.resolve('ok'));
67
+ expect(breaker.getState()).toBe(types_1.CircuitState.HALF_OPEN);
68
+ await breaker.execute(() => Promise.resolve('ok'));
69
+ expect(breaker.getState()).toBe(types_1.CircuitState.CLOSED);
70
+ });
71
+ it('should transition back to OPEN on failure in HALF_OPEN', async () => {
72
+ await breaker.execute(() => Promise.resolve('ok')); // first trial success
73
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { }); // failure -> back to OPEN
74
+ expect(breaker.getState()).toBe(types_1.CircuitState.OPEN);
75
+ });
76
+ });
77
+ describe('events', () => {
78
+ it('should emit stateChange events', async () => {
79
+ const transitions = [];
80
+ breaker.on('stateChange', (from, to) => transitions.push([from, to]));
81
+ // Trip the breaker
82
+ for (let i = 0; i < 3; i++) {
83
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
84
+ }
85
+ expect(transitions).toContainEqual([types_1.CircuitState.CLOSED, types_1.CircuitState.OPEN]);
86
+ });
87
+ it('should emit success and failure events', async () => {
88
+ let successCount = 0;
89
+ let failureCount = 0;
90
+ breaker.on('success', () => successCount++);
91
+ breaker.on('failure', () => failureCount++);
92
+ await breaker.execute(() => Promise.resolve('ok'));
93
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
94
+ expect(successCount).toBe(1);
95
+ expect(failureCount).toBe(1);
96
+ });
97
+ });
98
+ describe('metrics', () => {
99
+ it('should track metrics', async () => {
100
+ await breaker.execute(() => Promise.resolve('ok'));
101
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
102
+ const metrics = breaker.getMetrics();
103
+ expect(metrics.totalRequests).toBe(2);
104
+ expect(metrics.successCount).toBe(1);
105
+ expect(metrics.failureCount).toBe(1);
106
+ expect(metrics.failureRate).toBe(50);
107
+ });
108
+ });
109
+ describe('reset', () => {
110
+ it('should reset to CLOSED state', async () => {
111
+ // Trip the breaker
112
+ for (let i = 0; i < 3; i++) {
113
+ await breaker.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
114
+ }
115
+ expect(breaker.getState()).toBe(types_1.CircuitState.OPEN);
116
+ breaker.reset();
117
+ expect(breaker.getState()).toBe(types_1.CircuitState.CLOSED);
118
+ expect(breaker.getFailureCount()).toBe(0);
119
+ });
120
+ });
121
+ describe('failure predicate', () => {
122
+ it('should ignore errors that do not match the predicate', async () => {
123
+ const selectiveBreaker = new circuit_breaker_1.CircuitBreaker({
124
+ failureThreshold: 1,
125
+ failurePredicate: (error) => error instanceof Error && error.message !== 'ignore-me',
126
+ });
127
+ // This error should NOT count as failure
128
+ await selectiveBreaker.execute(() => Promise.reject(new Error('ignore-me'))).catch(() => { });
129
+ expect(selectiveBreaker.getState()).toBe(types_1.CircuitState.CLOSED);
130
+ // This error SHOULD count
131
+ await selectiveBreaker.execute(() => Promise.reject(new Error('count-me'))).catch(() => { });
132
+ expect(selectiveBreaker.getState()).toBe(types_1.CircuitState.OPEN);
133
+ });
134
+ });
135
+ });
136
+ describe('CircuitBreakerRegistry', () => {
137
+ beforeEach(() => {
138
+ circuit_breaker_registry_1.CircuitBreakerRegistry.clear();
139
+ });
140
+ it('should create and cache circuit breakers', () => {
141
+ const b1 = circuit_breaker_registry_1.CircuitBreakerRegistry.getOrCreate('test');
142
+ const b2 = circuit_breaker_registry_1.CircuitBreakerRegistry.getOrCreate('test');
143
+ expect(b1).toBe(b2);
144
+ });
145
+ it('should return different breakers for different names', () => {
146
+ const b1 = circuit_breaker_registry_1.CircuitBreakerRegistry.getOrCreate('a');
147
+ const b2 = circuit_breaker_registry_1.CircuitBreakerRegistry.getOrCreate('b');
148
+ expect(b1).not.toBe(b2);
149
+ });
150
+ it('should reset all breakers', async () => {
151
+ const b = circuit_breaker_registry_1.CircuitBreakerRegistry.getOrCreate('test', {
152
+ failureThreshold: 1,
153
+ resetTimeout: 100,
154
+ });
155
+ await b.execute(() => Promise.reject(new Error('fail'))).catch(() => { });
156
+ expect(b.getState()).toBe(types_1.CircuitState.OPEN);
157
+ circuit_breaker_registry_1.CircuitBreakerRegistry.resetAll();
158
+ expect(b.getState()).toBe(types_1.CircuitState.CLOSED);
159
+ });
160
+ });
@@ -0,0 +1,2 @@
1
+ import 'reflect-metadata';
2
+ //# sourceMappingURL=decorators.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/decorators.test.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC"}