@gravito/core 1.6.0 → 2.0.0

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 (171) hide show
  1. package/README.md +100 -6
  2. package/README.zh-TW.md +101 -6
  3. package/dist/Application.d.ts +256 -0
  4. package/dist/CommandKernel.d.ts +33 -0
  5. package/dist/ConfigManager.d.ts +65 -0
  6. package/dist/Container/RequestScopeManager.d.ts +62 -0
  7. package/dist/Container/RequestScopeMetrics.d.ts +144 -0
  8. package/dist/Container.d.ts +153 -0
  9. package/dist/ErrorHandler.d.ts +66 -0
  10. package/dist/Event.d.ts +5 -0
  11. package/dist/EventManager.d.ts +123 -0
  12. package/dist/GlobalErrorHandlers.d.ts +47 -0
  13. package/dist/GravitoServer.d.ts +28 -0
  14. package/dist/HookManager.d.ts +435 -0
  15. package/dist/Listener.d.ts +4 -0
  16. package/dist/Logger.d.ts +20 -0
  17. package/dist/PlanetCore.d.ts +402 -0
  18. package/dist/RequestContext.d.ts +97 -0
  19. package/dist/Route.d.ts +36 -0
  20. package/dist/Router.d.ts +270 -0
  21. package/dist/ServiceProvider.d.ts +178 -0
  22. package/dist/adapters/GravitoEngineAdapter.d.ts +27 -0
  23. package/dist/adapters/bun/AdaptiveAdapter.d.ts +99 -0
  24. package/dist/adapters/bun/BunContext.d.ts +54 -0
  25. package/dist/adapters/bun/BunNativeAdapter.d.ts +66 -0
  26. package/dist/adapters/bun/BunRequest.d.ts +31 -0
  27. package/dist/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  28. package/dist/adapters/bun/RadixNode.d.ts +19 -0
  29. package/dist/adapters/bun/RadixRouter.d.ts +32 -0
  30. package/dist/adapters/bun/index.d.ts +7 -0
  31. package/dist/adapters/bun/types.d.ts +20 -0
  32. package/dist/adapters/index.d.ts +12 -0
  33. package/dist/adapters/types.d.ts +235 -0
  34. package/dist/binary/BinaryUtils.d.ts +105 -0
  35. package/dist/binary/index.d.ts +5 -0
  36. package/dist/cli/queue-commands.d.ts +6 -0
  37. package/dist/compat/async-local-storage.browser.d.ts +9 -0
  38. package/dist/compat/async-local-storage.d.ts +7 -0
  39. package/dist/compat/crypto.browser.d.ts +5 -0
  40. package/dist/compat/crypto.d.ts +6 -0
  41. package/dist/compat.cjs +42 -11
  42. package/dist/compat.cjs.map +9 -0
  43. package/dist/compat.d.ts +23 -1
  44. package/dist/compat.js +3 -0
  45. package/dist/compat.js.map +9 -0
  46. package/dist/engine/AOTRouter.d.ts +139 -0
  47. package/dist/engine/FastContext.d.ts +141 -0
  48. package/dist/engine/Gravito.d.ts +131 -0
  49. package/dist/engine/MinimalContext.d.ts +102 -0
  50. package/dist/engine/analyzer.d.ts +113 -0
  51. package/dist/engine/constants.d.ts +23 -0
  52. package/dist/engine/index.cjs +758 -532
  53. package/dist/engine/index.cjs.map +22 -0
  54. package/dist/engine/index.d.ts +14 -690
  55. package/dist/engine/index.js +758 -508
  56. package/dist/engine/index.js.map +22 -0
  57. package/dist/engine/path.d.ts +26 -0
  58. package/dist/engine/pool.d.ts +83 -0
  59. package/dist/engine/types.d.ts +149 -0
  60. package/dist/error-handling/RequestScopeErrorContext.d.ts +126 -0
  61. package/dist/events/BackpressureManager.d.ts +215 -0
  62. package/dist/events/CircuitBreaker.d.ts +229 -0
  63. package/dist/events/DeadLetterQueue.d.ts +219 -0
  64. package/dist/events/EventBackend.d.ts +12 -0
  65. package/dist/events/EventOptions.d.ts +204 -0
  66. package/dist/events/EventPriorityQueue.d.ts +63 -0
  67. package/dist/events/FlowControlStrategy.d.ts +109 -0
  68. package/dist/events/IdempotencyCache.d.ts +60 -0
  69. package/dist/events/MessageQueueBridge.d.ts +184 -0
  70. package/dist/events/PriorityEscalationManager.d.ts +82 -0
  71. package/dist/events/RetryScheduler.d.ts +104 -0
  72. package/dist/events/WorkerPool.d.ts +98 -0
  73. package/dist/events/WorkerPoolConfig.d.ts +153 -0
  74. package/dist/events/WorkerPoolMetrics.d.ts +65 -0
  75. package/dist/events/aggregation/AggregationWindow.d.ts +77 -0
  76. package/dist/events/aggregation/DeduplicationManager.d.ts +135 -0
  77. package/dist/events/aggregation/EventAggregationManager.d.ts +108 -0
  78. package/dist/events/aggregation/EventBatcher.d.ts +99 -0
  79. package/dist/events/aggregation/index.d.ts +10 -0
  80. package/dist/events/aggregation/types.d.ts +117 -0
  81. package/dist/events/index.d.ts +26 -0
  82. package/dist/events/observability/EventMetrics.d.ts +132 -0
  83. package/dist/events/observability/EventTracer.d.ts +68 -0
  84. package/dist/events/observability/EventTracing.d.ts +161 -0
  85. package/dist/events/observability/OTelEventMetrics.d.ts +332 -0
  86. package/dist/events/observability/ObservableHookManager.d.ts +108 -0
  87. package/dist/events/observability/StreamWorkerMetrics.d.ts +76 -0
  88. package/dist/events/observability/index.d.ts +24 -0
  89. package/dist/events/observability/metrics-types.d.ts +16 -0
  90. package/dist/events/queue-core.d.ts +77 -0
  91. package/dist/events/task-executor.d.ts +51 -0
  92. package/dist/events/types.d.ts +134 -0
  93. package/dist/exceptions/AuthenticationException.d.ts +8 -0
  94. package/dist/exceptions/AuthorizationException.d.ts +8 -0
  95. package/dist/exceptions/CircularDependencyException.d.ts +9 -0
  96. package/dist/exceptions/GravitoException.d.ts +23 -0
  97. package/dist/exceptions/HttpException.d.ts +9 -0
  98. package/dist/exceptions/ModelNotFoundException.d.ts +10 -0
  99. package/dist/exceptions/ValidationException.d.ts +22 -0
  100. package/dist/exceptions/index.d.ts +7 -0
  101. package/dist/ffi/NativeAccelerator.d.ts +69 -0
  102. package/dist/ffi/NativeHasher.d.ts +139 -0
  103. package/dist/ffi/cbor-fallback.d.ts +96 -0
  104. package/dist/ffi/hash-fallback.d.ts +33 -0
  105. package/dist/ffi/index.cjs +621 -0
  106. package/dist/ffi/index.cjs.map +14 -0
  107. package/dist/ffi/index.d.ts +10 -0
  108. package/dist/ffi/index.js +602 -0
  109. package/dist/ffi/index.js.map +14 -0
  110. package/dist/ffi/types.d.ts +135 -0
  111. package/dist/health/HealthProvider.d.ts +67 -0
  112. package/dist/helpers/Arr.d.ts +19 -0
  113. package/dist/helpers/Str.d.ts +38 -0
  114. package/dist/helpers/data.d.ts +25 -0
  115. package/dist/helpers/errors.d.ts +34 -0
  116. package/dist/helpers/response.d.ts +41 -0
  117. package/dist/helpers.d.ts +338 -0
  118. package/dist/hooks/ActionManager.d.ts +132 -0
  119. package/dist/hooks/AsyncDetector.d.ts +84 -0
  120. package/dist/hooks/FilterManager.d.ts +71 -0
  121. package/dist/hooks/MigrationWarner.d.ts +24 -0
  122. package/dist/hooks/dlq-operations.d.ts +60 -0
  123. package/dist/hooks/index.d.ts +11 -0
  124. package/dist/hooks/types.d.ts +107 -0
  125. package/dist/http/CookieJar.d.ts +51 -0
  126. package/dist/http/cookie.d.ts +29 -0
  127. package/dist/http/index.d.ts +12 -0
  128. package/dist/{compat-C4Src6NN.d.cts → http/types.d.ts} +48 -16
  129. package/dist/index.browser.d.ts +34 -0
  130. package/dist/index.cjs +12909 -9492
  131. package/dist/index.cjs.map +168 -0
  132. package/dist/index.d.ts +58 -8707
  133. package/dist/index.js +12906 -9381
  134. package/dist/index.js.map +168 -0
  135. package/dist/observability/QueueDashboard.d.ts +136 -0
  136. package/dist/observability/contracts.d.ts +137 -0
  137. package/dist/observability/index.d.ts +13 -0
  138. package/dist/reliability/DeadLetterQueueManager.d.ts +349 -0
  139. package/dist/reliability/RetryPolicy.d.ts +217 -0
  140. package/dist/reliability/index.d.ts +6 -0
  141. package/dist/router/ControllerDispatcher.d.ts +12 -0
  142. package/dist/router/RequestValidator.d.ts +20 -0
  143. package/dist/runtime/adapter-bun.d.ts +12 -0
  144. package/dist/runtime/adapter-deno.d.ts +12 -0
  145. package/dist/runtime/adapter-node.d.ts +12 -0
  146. package/dist/runtime/adapter-unknown.d.ts +13 -0
  147. package/dist/runtime/archive.d.ts +17 -0
  148. package/dist/runtime/compression.d.ts +21 -0
  149. package/dist/runtime/deep-equals.d.ts +56 -0
  150. package/dist/runtime/detection.d.ts +22 -0
  151. package/dist/runtime/escape.d.ts +34 -0
  152. package/dist/runtime/index.browser.d.ts +20 -0
  153. package/dist/runtime/index.d.ts +44 -0
  154. package/dist/runtime/markdown.d.ts +44 -0
  155. package/dist/runtime/types.d.ts +436 -0
  156. package/dist/runtime-helpers.d.ts +67 -0
  157. package/dist/runtime.d.ts +11 -0
  158. package/dist/security/Encrypter.d.ts +33 -0
  159. package/dist/security/Hasher.d.ts +29 -0
  160. package/dist/testing/HttpTester.d.ts +39 -0
  161. package/dist/testing/TestResponse.d.ts +78 -0
  162. package/dist/testing/index.d.ts +2 -0
  163. package/dist/transpiler-utils.d.ts +170 -0
  164. package/dist/types/events.d.ts +94 -0
  165. package/dist/types.d.ts +13 -0
  166. package/package.json +23 -53
  167. package/src/ffi/native/cbor.c +1148 -0
  168. package/dist/compat-C4Src6NN.d.ts +0 -357
  169. package/dist/compat.d.cts +0 -1
  170. package/dist/engine/index.d.cts +0 -702
  171. package/dist/index.d.cts +0 -8734
@@ -0,0 +1,126 @@
1
+ /**
2
+ * RequestScope-Aware Error Handling
3
+ *
4
+ * Integrates RequestScope lifecycle with error handling to provide:
5
+ * - Error context with request-scoped resources
6
+ * - Automatic cleanup of scoped services on error
7
+ * - Request tracing and diagnostics
8
+ * - Resource leak detection
9
+ */
10
+ import type { RequestScopeManager } from '../Container/RequestScopeManager';
11
+ import type { RequestScopeMetrics } from '../Container/RequestScopeMetrics';
12
+ import type { GravitoContext } from '../http/types';
13
+ /**
14
+ * Extended error context with RequestScope information
15
+ *
16
+ * Provides error handlers access to request-scoped resources
17
+ * for proper resource cleanup and error diagnostics.
18
+ */
19
+ export interface RequestScopeErrorContext {
20
+ /**
21
+ * The original error that was thrown
22
+ */
23
+ error: unknown;
24
+ /**
25
+ * HTTP context where error occurred
26
+ */
27
+ context: GravitoContext;
28
+ /**
29
+ * RequestScope manager for this request
30
+ * Allows error handlers to access or clean up scoped resources
31
+ */
32
+ scope?: RequestScopeManager;
33
+ /**
34
+ * Metrics about the request scope state
35
+ * Useful for diagnostics and understanding resource usage
36
+ */
37
+ scopeMetrics?: RequestScopeMetrics;
38
+ /**
39
+ * Number of scoped services at time of error
40
+ * High numbers might indicate resource leaks
41
+ */
42
+ scopeSize?: number;
43
+ /**
44
+ * Request processing time in milliseconds
45
+ * Useful for timeout errors
46
+ */
47
+ duration?: number;
48
+ /**
49
+ * Additional diagnostic information
50
+ */
51
+ diagnostics?: {
52
+ servicesCleanedUp?: string[];
53
+ cleanupErrors?: Array<{
54
+ service: string;
55
+ error: unknown;
56
+ }>;
57
+ peakMemoryMb?: number;
58
+ };
59
+ }
60
+ /**
61
+ * Error that occurred during RequestScope cleanup
62
+ *
63
+ * Wraps original error with cleanup context for proper error reporting
64
+ */
65
+ export declare class RequestScopeCleanupError extends Error {
66
+ originalError: unknown;
67
+ cleanupErrors: Array<{
68
+ service: string;
69
+ error: unknown;
70
+ }>;
71
+ constructor(message: string, originalError: unknown, cleanupErrors: Array<{
72
+ service: string;
73
+ error: unknown;
74
+ }>);
75
+ }
76
+ /**
77
+ * Helper to extract RequestScope context from GravitoContext
78
+ *
79
+ * @param ctx - Gravito context
80
+ * @returns RequestScope error context with available information
81
+ */
82
+ export declare function extractRequestScopeErrorContext(ctx: GravitoContext, error: unknown): RequestScopeErrorContext;
83
+ /**
84
+ * Cleanup scoped services safely during error handling
85
+ *
86
+ * Ensures all scoped services are cleaned up even if some fail,
87
+ * and collects cleanup errors for diagnostics.
88
+ *
89
+ * @param scope - RequestScope manager
90
+ * @returns Array of cleanup errors if any occurred
91
+ */
92
+ export declare function cleanupRequestScopeOnError(scope?: RequestScopeManager): Promise<Array<{
93
+ service: string;
94
+ error: unknown;
95
+ }>>;
96
+ /**
97
+ * Safe error handler wrapper that manages RequestScope cleanup
98
+ *
99
+ * Ensures scoped services are properly cleaned up before returning error response.
100
+ * Use this to wrap error handlers to make them RequestScope-aware.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * const errorHandler = withRequestScopeCleanup(async (ctx, error) => {
105
+ * // Handle error...
106
+ * return ctx.json({ error: error.message }, 500)
107
+ * })
108
+ *
109
+ * // In your app:
110
+ * try {
111
+ * // Handle request...
112
+ * } catch (error) {
113
+ * return errorHandler(ctx, error)
114
+ * }
115
+ * ```
116
+ */
117
+ export declare function withRequestScopeCleanup<T extends (ctx: GravitoContext, error: unknown) => Promise<Response>>(handler: T): T;
118
+ /**
119
+ * Detect potential resource leaks in RequestScope
120
+ *
121
+ * Returns diagnostic information about suspicious resource usage patterns
122
+ */
123
+ export declare function detectRequestScopeLeaks(context: RequestScopeErrorContext): {
124
+ potentialLeaks: boolean;
125
+ warnings: string[];
126
+ };
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @gravito/core - Event System Backpressure Management
3
+ *
4
+ * Implements a backpressure management system to prevent high-priority events
5
+ * from starving low-priority events when the queue is under resource constraints.
6
+ *
7
+ * 背壓管理器:在資源受限時進行智慧型流量控制,防止優先級飢餓。
8
+ *
9
+ * FS-103 增強:
10
+ * - 多優先級隊列深度監控
11
+ * - 背壓反饋迴路支持
12
+ * - 智能 DLQ 路由決策
13
+ */
14
+ import type { DeadLetterDecision, MultiPriorityQueueDepth } from './types';
15
+ /**
16
+ * 背壓狀態枚舉。
17
+ *
18
+ * 狀態轉換:Normal → Warning → Critical → Overflow
19
+ * 恢復方向:遲滯設計(需降至觸發閾值的 80%)
20
+ *
21
+ * @public
22
+ */
23
+ export declare enum BackpressureState {
24
+ /** 正常運作,無背壓 */
25
+ NORMAL = "NORMAL",
26
+ /** 警告狀態,開始限制低優先級事件 */
27
+ WARNING = "WARNING",
28
+ /** 危急狀態,僅允許高優先級事件 */
29
+ CRITICAL = "CRITICAL",
30
+ /** 溢位狀態,全部拒絕 */
31
+ OVERFLOW = "OVERFLOW"
32
+ }
33
+ /**
34
+ * 背壓配置選項。
35
+ *
36
+ * @public
37
+ */
38
+ export interface BackpressureConfig {
39
+ /** 是否啟用背壓管理器(預設 true) */
40
+ enabled?: boolean;
41
+ /** 總隊列深度限制(預設無限) */
42
+ maxQueueSize?: number;
43
+ /** 分優先級隊列深度限制 */
44
+ maxSizeByPriority?: {
45
+ critical?: number;
46
+ high?: number;
47
+ normal?: number;
48
+ low?: number;
49
+ };
50
+ /** 每秒最大入隊速率(events/sec,預設無限) */
51
+ maxEnqueueRate?: number;
52
+ /** 速率限制滑動視窗大小(ms,預設 1000) */
53
+ rateLimitWindowMs?: number;
54
+ /** 背壓狀態閾值(佔 maxQueueSize 的百分比) */
55
+ thresholds?: {
56
+ /** WARNING 觸發百分比(預設 0.6 = 60%) */
57
+ warning?: number;
58
+ /** CRITICAL 觸發百分比(預設 0.85 = 85%) */
59
+ critical?: number;
60
+ /** OVERFLOW 觸發百分比(預設 1.0 = 100%) */
61
+ overflow?: number;
62
+ };
63
+ /** 被拒絕事件的處理策略(預設 'drop-with-callback') */
64
+ rejectionPolicy?: 'throw' | 'drop-silent' | 'drop-with-callback';
65
+ /** 當 rejectionPolicy 為 'drop-with-callback' 時的回呼 */
66
+ onRejected?: (eventName: string, priority: string, reason: string) => void;
67
+ /** 背壓狀態變更回呼 */
68
+ onStateChange?: (from: BackpressureState, to: BackpressureState) => void;
69
+ /** 低優先級事件在 WARNING 狀態下的延遲入隊時間(ms,預設 100) */
70
+ lowPriorityDelayMs?: number;
71
+ /** 是否啟用優先級反轉防護(預設 true) */
72
+ enableStarvationProtection?: boolean;
73
+ /** 低優先級事件最大等待時間,超過則提升優先級(ms,預設 5000) */
74
+ starvationTimeoutMs?: number;
75
+ /** 當進入 OVERFLOW 狀態時,是否將被拒絕事件路由到 DLQ(預設 false) */
76
+ dlqOnOverflow?: boolean;
77
+ /** OVERFLOW 時的重試策略(預設 'dlq-only') */
78
+ overflowRetryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
79
+ /** OVERFLOW 延遲重試的基礎延遲時間(ms,預設 5000) */
80
+ overflowRetryDelayMs?: number;
81
+ }
82
+ /**
83
+ * 背壓決策結果。
84
+ *
85
+ * @public
86
+ */
87
+ export interface BackpressureDecision {
88
+ /** 是否允許入隊 */
89
+ allowed: boolean;
90
+ /** 拒絕原因(若不允許) */
91
+ reason?: string;
92
+ /** 是否需要延遲入隊 */
93
+ delayed?: boolean;
94
+ /** 延遲時間(ms) */
95
+ delayMs?: number;
96
+ /** 建議降級後的優先級(若降級) */
97
+ degradedPriority?: 'high' | 'normal' | 'low';
98
+ /** 是否是由於 OVERFLOW 狀態被拒絕 */
99
+ isOverflow?: boolean;
100
+ /** OVERFLOW 時的重試策略建議('immediate'、'delayed'、'dlq-only') */
101
+ retryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
102
+ }
103
+ /**
104
+ * 背壓指標快照。
105
+ *
106
+ * @public
107
+ */
108
+ export interface BackpressureMetricsSnapshot {
109
+ state: BackpressureState;
110
+ totalDepth: number;
111
+ depthByPriority: {
112
+ critical: number;
113
+ high: number;
114
+ normal: number;
115
+ low: number;
116
+ };
117
+ enqueueRate: number;
118
+ rejectedCount: number;
119
+ degradedCount: number;
120
+ stateTransitions: number;
121
+ dlqRouteCount?: number;
122
+ windowAdjustmentCount?: number;
123
+ }
124
+ /**
125
+ * 背壓管理器。
126
+ *
127
+ * 根據隊列深度、速率、優先級等因素,決定是否允許新事件入隊,
128
+ * 以及是否需要降級優先級或延遲入隊。
129
+ *
130
+ * @public
131
+ */
132
+ export declare class BackpressureManager {
133
+ private enabled;
134
+ private config;
135
+ private onRejected?;
136
+ private onStateChange?;
137
+ private state;
138
+ private rejectedCount;
139
+ private degradedCount;
140
+ private stateTransitions;
141
+ private rateCounter;
142
+ private depthByPriority;
143
+ private windowAdjustmentHistory;
144
+ private dlqRouteCount;
145
+ constructor(config?: BackpressureConfig);
146
+ /**
147
+ * 評估是否允許新事件入隊。
148
+ *
149
+ * @param eventName 事件名稱
150
+ * @param priority 事件優先級
151
+ * @param queueDepth 當前隊列深度
152
+ * @param depthByPriority 分優先級隊列深度
153
+ * @returns 背壓決策結果
154
+ */
155
+ evaluate(eventName: string, priority: 'critical' | 'high' | 'normal' | 'low', queueDepth: number, depthByPriority: {
156
+ critical: number;
157
+ high: number;
158
+ normal: number;
159
+ low: number;
160
+ }): BackpressureDecision;
161
+ /**
162
+ * 獲取當前背壓狀態。
163
+ */
164
+ getState(): BackpressureState;
165
+ /**
166
+ * 獲取背壓指標快照。
167
+ */
168
+ getMetrics(): BackpressureMetricsSnapshot;
169
+ /**
170
+ * 重置背壓管理器狀態。
171
+ */
172
+ reset(): void;
173
+ /**
174
+ * 同步隊列深度(由 EventPriorityQueue 調用)。
175
+ * FS-103:多優先級隊列深度監控
176
+ */
177
+ updateQueueDepth(depths: MultiPriorityQueueDepth): void;
178
+ /**
179
+ * 獲取各優先級的隊列深度。
180
+ * FS-103:提供實時隊列深度快照
181
+ */
182
+ getQueueDepthByPriority(): MultiPriorityQueueDepth;
183
+ /**
184
+ * 獲取總隊列深度。
185
+ */
186
+ getTotalQueueDepth(): number;
187
+ /**
188
+ * 接收來自 AggregationWindow 的窗口調整通知。
189
+ * FS-103:背壓反饋迴路
190
+ */
191
+ notifyWindowAdjustment(oldWindowMs: number, newWindowMs: number): void;
192
+ /**
193
+ * 檢查是否可以從 CRITICAL 或更高級別降級。
194
+ * FS-103:自動狀態恢復機制
195
+ */
196
+ private checkStateRecovery;
197
+ /**
198
+ * 決定是否應該將事件路由到死信隊列。
199
+ * FS-103:智能 DLQ 路由決策
200
+ */
201
+ makeDeadLetterDecision(_eventName: string, priority: 'critical' | 'high' | 'normal' | 'low'): DeadLetterDecision;
202
+ /**
203
+ * 更新背壓狀態。
204
+ * 使用遲滯設計(80% 回復比例)避免邊界震盪。
205
+ */
206
+ private updateState;
207
+ /**
208
+ * 執行狀態轉換。
209
+ */
210
+ private transitionTo;
211
+ /**
212
+ * 建立決策結果並記錄拒絕。
213
+ */
214
+ private createDecision;
215
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Circuit Breaker state enum.
3
+ * @public
4
+ */
5
+ export declare enum CircuitBreakerState {
6
+ CLOSED = "CLOSED",
7
+ OPEN = "OPEN",
8
+ HALF_OPEN = "HALF_OPEN"
9
+ }
10
+ /**
11
+ * Circuit Breaker metrics snapshot.
12
+ * @public
13
+ */
14
+ export interface CircuitBreakerMetrics {
15
+ /**
16
+ * Current state of the circuit breaker
17
+ */
18
+ state: CircuitBreakerState;
19
+ /**
20
+ * Number of failures in the current window
21
+ */
22
+ failures: number;
23
+ /**
24
+ * Number of successes in the current window
25
+ */
26
+ successes: number;
27
+ /**
28
+ * Timestamp of the last failure
29
+ */
30
+ lastFailureAt?: Date;
31
+ /**
32
+ * Timestamp of the last success
33
+ */
34
+ lastSuccessAt?: Date;
35
+ /**
36
+ * Timestamp when the circuit was opened
37
+ */
38
+ openedAt?: Date;
39
+ /**
40
+ * Total requests processed
41
+ */
42
+ totalRequests: number;
43
+ /**
44
+ * Total failures recorded
45
+ */
46
+ totalFailures: number;
47
+ /**
48
+ * Total successes recorded
49
+ */
50
+ totalSuccesses: number;
51
+ }
52
+ /**
53
+ * Circuit Breaker metrics recorder interface.
54
+ * @public
55
+ */
56
+ export interface CircuitBreakerMetricsRecorder {
57
+ /**
58
+ * Record current state of the circuit breaker.
59
+ * @param eventName - Name of the event
60
+ * @param state - State as number (0=CLOSED, 1=HALF_OPEN, 2=OPEN)
61
+ */
62
+ recordState: (eventName: string, state: number) => void;
63
+ /**
64
+ * Record state transition.
65
+ */
66
+ recordTransition: (eventName: string, fromState: string, toState: string) => void;
67
+ /**
68
+ * Record a failure.
69
+ */
70
+ recordFailure: (eventName: string) => void;
71
+ /**
72
+ * Record a success.
73
+ */
74
+ recordSuccess: (eventName: string) => void;
75
+ /**
76
+ * Record OPEN state duration.
77
+ */
78
+ recordOpenDuration: (eventName: string, seconds: number) => void;
79
+ }
80
+ /**
81
+ * Circuit Breaker configuration options.
82
+ * @public
83
+ */
84
+ export interface CircuitBreakerOptions {
85
+ /**
86
+ * Number of consecutive failures before opening the circuit.
87
+ * @default 5
88
+ */
89
+ failureThreshold?: number;
90
+ /**
91
+ * Time in milliseconds to wait before attempting to close the circuit (move to HALF_OPEN).
92
+ * @default 30000
93
+ */
94
+ resetTimeout?: number;
95
+ /**
96
+ * Number of test requests to allow given the circuit is in HALF_OPEN state.
97
+ * If these succeed, the circuit closes. If any fail, it opens again.
98
+ * @default 3
99
+ */
100
+ halfOpenRequests?: number;
101
+ /**
102
+ * Number of successes required in HALF_OPEN state to close the circuit.
103
+ * @default 2
104
+ */
105
+ successThreshold?: number;
106
+ /**
107
+ * Time in milliseconds for the sliding window to track failures.
108
+ * Failures outside this window are not counted.
109
+ * @default 60000
110
+ */
111
+ windowSize?: number;
112
+ /**
113
+ * Enable or disable the circuit breaker.
114
+ * @default true
115
+ */
116
+ enabled?: boolean;
117
+ /**
118
+ * Callback when circuit opens.
119
+ */
120
+ onOpen?: (name?: string) => void;
121
+ /**
122
+ * Callback when circuit moves to half-open.
123
+ */
124
+ onHalfOpen?: (name?: string) => void;
125
+ /**
126
+ * Callback when circuit closes.
127
+ */
128
+ onClose?: (name?: string) => void;
129
+ /**
130
+ * Metrics recorder for recording circuit breaker events.
131
+ * Optional - if not provided, metrics will not be recorded.
132
+ */
133
+ metricsRecorder?: CircuitBreakerMetricsRecorder | undefined;
134
+ }
135
+ /**
136
+ * Required Circuit Breaker configuration (with defaults applied).
137
+ * @internal
138
+ */
139
+ export interface RequiredCircuitBreakerOptions extends Required<Omit<CircuitBreakerOptions, 'metricsRecorder'>> {
140
+ metricsRecorder?: CircuitBreakerMetricsRecorder;
141
+ }
142
+ /**
143
+ * Circuit Breaker implementation for fault tolerance.
144
+ *
145
+ * Prevents cascading failures by stopping execution of a failing operation
146
+ * for a specified period after a threshold of failures is reached.
147
+ *
148
+ * Supports sliding window algorithm, enabling/disabling, and detailed metrics.
149
+ *
150
+ * @public
151
+ */
152
+ export declare class CircuitBreaker {
153
+ private state;
154
+ private failureCount;
155
+ private successCount;
156
+ private name;
157
+ private config;
158
+ private metricsRecorder?;
159
+ private lastFailureAt?;
160
+ private lastSuccessAt?;
161
+ private openedAt?;
162
+ private totalRequests;
163
+ private totalFailures;
164
+ private totalSuccesses;
165
+ private halfOpenAttempts;
166
+ /**
167
+ * Create a new Circuit Breaker.
168
+ *
169
+ * Supports two signatures for backward compatibility:
170
+ * - CircuitBreaker(options?: CircuitBreakerOptions) - anonymous breaker
171
+ * - CircuitBreaker(name: string, options?: CircuitBreakerOptions) - named breaker
172
+ *
173
+ * @param nameOrOptions - Circuit breaker name or options
174
+ * @param maybeOptions - Options (used when first param is a string)
175
+ */
176
+ constructor(nameOrOptions?: string | CircuitBreakerOptions, maybeOptions?: CircuitBreakerOptions);
177
+ /**
178
+ * Execute an operation through the circuit breaker.
179
+ *
180
+ * @param operation - Async operation to execute
181
+ * @returns Operation result
182
+ * @throws Error if circuit is open or operation fails
183
+ */
184
+ execute<T>(operation: () => Promise<T>): Promise<T>;
185
+ /**
186
+ * Check if the circuit breaker is currently OPEN.
187
+ */
188
+ isOpen(): boolean;
189
+ /**
190
+ * Check if the circuit breaker is currently HALF_OPEN.
191
+ */
192
+ isHalfOpen(): boolean;
193
+ /**
194
+ * Check if the circuit breaker is currently CLOSED.
195
+ */
196
+ isClosed(): boolean;
197
+ /**
198
+ * Get current state of the circuit breaker.
199
+ */
200
+ getState(): CircuitBreakerState;
201
+ /**
202
+ * Get failure count (deprecated, use getMetrics for complete information).
203
+ */
204
+ getFailureCount(): number;
205
+ /**
206
+ * Get the name of this circuit breaker.
207
+ */
208
+ getName(): string;
209
+ /**
210
+ * Get detailed metrics snapshot of the circuit breaker.
211
+ */
212
+ getMetrics(): CircuitBreakerMetrics;
213
+ /**
214
+ * Manually reset the circuit breaker to CLOSED state.
215
+ */
216
+ reset(): void;
217
+ /**
218
+ * Forcefully reset the circuit breaker (alias for reset).
219
+ */
220
+ manualReset(): void;
221
+ /**
222
+ * Check for automatic state transitions based on time and sliding window.
223
+ */
224
+ checkStateTransition(): void;
225
+ private onSuccess;
226
+ private onFailure;
227
+ private transitionTo;
228
+ private stateToNumber;
229
+ }