@gravito/ripple 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/README.md +260 -19
  2. package/dist/atlas/src/DB.d.ts +348 -0
  3. package/dist/atlas/src/OrbitAtlas.d.ts +9 -0
  4. package/dist/atlas/src/config/defineConfig.d.ts +14 -0
  5. package/dist/atlas/src/config/index.d.ts +7 -0
  6. package/dist/atlas/src/config/loadConfig.d.ts +41 -0
  7. package/dist/atlas/src/connection/Connection.d.ts +112 -0
  8. package/dist/atlas/src/connection/ConnectionManager.d.ts +180 -0
  9. package/dist/atlas/src/connection/ReplicaConnectionPool.d.ts +54 -0
  10. package/dist/atlas/src/drivers/BunSQLDriver.d.ts +32 -0
  11. package/dist/atlas/src/drivers/BunSQLPreparedStatement.d.ts +118 -0
  12. package/dist/atlas/src/drivers/MongoDBDriver.d.ts +36 -0
  13. package/dist/atlas/src/drivers/MySQLDriver.d.ts +79 -0
  14. package/dist/atlas/src/drivers/PostgresDriver.d.ts +96 -0
  15. package/dist/atlas/src/drivers/RedisDriver.d.ts +43 -0
  16. package/dist/atlas/src/drivers/SQLiteDriver.d.ts +45 -0
  17. package/dist/atlas/src/drivers/types.d.ts +260 -0
  18. package/dist/atlas/src/errors/index.d.ts +45 -0
  19. package/dist/atlas/src/grammar/Grammar.d.ts +342 -0
  20. package/dist/atlas/src/grammar/MongoGrammar.d.ts +47 -0
  21. package/dist/atlas/src/grammar/MySQLGrammar.d.ts +54 -0
  22. package/dist/atlas/src/grammar/NullGrammar.d.ts +35 -0
  23. package/dist/atlas/src/grammar/PostgresGrammar.d.ts +62 -0
  24. package/dist/atlas/src/grammar/SQLiteGrammar.d.ts +32 -0
  25. package/dist/atlas/src/index.d.ts +79 -0
  26. package/dist/atlas/src/migration/Migration.d.ts +64 -0
  27. package/dist/atlas/src/migration/MigrationRepository.d.ts +65 -0
  28. package/dist/atlas/src/migration/Migrator.d.ts +110 -0
  29. package/dist/atlas/src/migration/index.d.ts +6 -0
  30. package/dist/atlas/src/observability/AtlasMetrics.d.ts +33 -0
  31. package/dist/atlas/src/observability/AtlasObservability.d.ts +15 -0
  32. package/dist/atlas/src/observability/AtlasTracer.d.ts +12 -0
  33. package/dist/atlas/src/observability/index.d.ts +9 -0
  34. package/dist/atlas/src/orm/Repository.d.ts +247 -0
  35. package/dist/atlas/src/orm/index.d.ts +6 -0
  36. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +121 -0
  37. package/dist/atlas/src/orm/model/Model.d.ts +458 -0
  38. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +20 -0
  39. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +150 -0
  40. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +36 -0
  41. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +92 -0
  42. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +117 -0
  43. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +64 -0
  44. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +15 -0
  45. package/dist/atlas/src/orm/model/concerns/index.d.ts +12 -0
  46. package/dist/atlas/src/orm/model/decorators.d.ts +138 -0
  47. package/dist/atlas/src/orm/model/errors.d.ts +52 -0
  48. package/dist/atlas/src/orm/model/index.d.ts +10 -0
  49. package/dist/atlas/src/orm/model/relationships.d.ts +207 -0
  50. package/dist/atlas/src/orm/model/types.d.ts +12 -0
  51. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +124 -0
  52. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +54 -0
  53. package/dist/atlas/src/orm/schema/index.d.ts +6 -0
  54. package/dist/atlas/src/orm/schema/types.d.ts +85 -0
  55. package/dist/atlas/src/pool/AdaptivePoolManager.d.ts +98 -0
  56. package/dist/atlas/src/pool/PoolHealthChecker.d.ts +91 -0
  57. package/dist/atlas/src/pool/PoolStrategy.d.ts +129 -0
  58. package/dist/atlas/src/pool/PoolWarmer.d.ts +92 -0
  59. package/dist/atlas/src/query/Expression.d.ts +60 -0
  60. package/dist/atlas/src/query/NPlusOneDetector.d.ts +10 -0
  61. package/dist/atlas/src/query/QueryBuilder.d.ts +643 -0
  62. package/dist/atlas/src/query/RelationshipResolver.d.ts +23 -0
  63. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +51 -0
  64. package/dist/atlas/src/query/clauses/HavingClause.d.ts +70 -0
  65. package/dist/atlas/src/query/clauses/JoinClause.d.ts +87 -0
  66. package/dist/atlas/src/query/clauses/LimitClause.d.ts +82 -0
  67. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +69 -0
  68. package/dist/atlas/src/query/clauses/SelectClause.d.ts +71 -0
  69. package/dist/atlas/src/query/clauses/WhereClause.d.ts +167 -0
  70. package/dist/atlas/src/query/clauses/index.d.ts +11 -0
  71. package/dist/atlas/src/schema/Blueprint.d.ts +276 -0
  72. package/dist/atlas/src/schema/ColumnDefinition.d.ts +154 -0
  73. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +37 -0
  74. package/dist/atlas/src/schema/MigrationGenerator.d.ts +45 -0
  75. package/dist/atlas/src/schema/Schema.d.ts +131 -0
  76. package/dist/atlas/src/schema/SchemaDiff.d.ts +73 -0
  77. package/dist/atlas/src/schema/TypeGenerator.d.ts +57 -0
  78. package/dist/atlas/src/schema/TypeWriter.d.ts +42 -0
  79. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +23 -0
  80. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +26 -0
  81. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +28 -0
  82. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +97 -0
  83. package/dist/atlas/src/schema/grammars/index.d.ts +7 -0
  84. package/dist/atlas/src/schema/index.d.ts +8 -0
  85. package/dist/atlas/src/seed/Factory.d.ts +90 -0
  86. package/dist/atlas/src/seed/Seeder.d.ts +28 -0
  87. package/dist/atlas/src/seed/SeederRunner.d.ts +74 -0
  88. package/dist/atlas/src/seed/index.d.ts +6 -0
  89. package/dist/atlas/src/sharding/ShardingManager.d.ts +59 -0
  90. package/dist/atlas/src/types/index.d.ts +1182 -0
  91. package/dist/atlas/src/utils/CursorEncoding.d.ts +63 -0
  92. package/dist/atlas/src/utils/levenshtein.d.ts +9 -0
  93. package/dist/core/src/CommandKernel.d.ts +33 -0
  94. package/dist/core/src/ConfigManager.d.ts +39 -0
  95. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  96. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  97. package/dist/core/src/Container.d.ts +86 -11
  98. package/dist/core/src/ErrorHandler.d.ts +3 -0
  99. package/dist/core/src/HookManager.d.ts +511 -4
  100. package/dist/core/src/PlanetCore.d.ts +89 -0
  101. package/dist/core/src/RequestContext.d.ts +97 -0
  102. package/dist/core/src/Router.d.ts +1 -5
  103. package/dist/core/src/ServiceProvider.d.ts +22 -0
  104. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +1 -0
  105. package/dist/core/src/adapters/PhotonAdapter.d.ts +5 -0
  106. package/dist/core/src/adapters/bun/BunContext.d.ts +4 -0
  107. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +1 -0
  108. package/dist/core/src/adapters/types.d.ts +27 -0
  109. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  110. package/dist/core/src/engine/AOTRouter.d.ts +7 -12
  111. package/dist/core/src/engine/FastContext.d.ts +27 -2
  112. package/dist/core/src/engine/Gravito.d.ts +0 -1
  113. package/dist/core/src/engine/MinimalContext.d.ts +25 -2
  114. package/dist/core/src/engine/types.d.ts +9 -1
  115. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  116. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  117. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  118. package/dist/core/src/events/DeadLetterQueue.d.ts +219 -0
  119. package/dist/core/src/events/EventBackend.d.ts +12 -0
  120. package/dist/core/src/events/EventOptions.d.ts +204 -0
  121. package/dist/core/src/events/EventPriorityQueue.d.ts +301 -0
  122. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  123. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  124. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  125. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  126. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  127. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  128. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  129. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  130. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  131. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  132. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  133. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  134. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  135. package/dist/core/src/events/index.d.ts +25 -0
  136. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  137. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  138. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  139. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +332 -0
  140. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  141. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  142. package/dist/core/src/events/observability/index.d.ts +24 -0
  143. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  144. package/dist/core/src/events/types.d.ts +134 -0
  145. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  146. package/dist/core/src/exceptions/index.d.ts +1 -0
  147. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  148. package/dist/core/src/http/types.d.ts +40 -0
  149. package/dist/core/src/index.d.ts +25 -4
  150. package/dist/core/src/instrumentation/index.d.ts +35 -0
  151. package/dist/core/src/instrumentation/opentelemetry.d.ts +178 -0
  152. package/dist/core/src/instrumentation/types.d.ts +182 -0
  153. package/dist/core/src/observability/Metrics.d.ts +244 -0
  154. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  155. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +350 -0
  156. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  157. package/dist/core/src/reliability/index.d.ts +6 -0
  158. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  159. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  160. package/dist/index.js +6709 -9888
  161. package/dist/index.js.map +64 -62
  162. package/dist/photon/src/index.d.ts +19 -0
  163. package/dist/photon/src/middleware/ratelimit-redis.d.ts +50 -0
  164. package/dist/photon/src/middleware/ratelimit.d.ts +161 -0
  165. package/dist/photon/src/openapi.d.ts +19 -0
  166. package/dist/proto/ripple.proto +120 -0
  167. package/dist/ripple/src/RippleServer.d.ts +64 -445
  168. package/dist/ripple/src/channels/ChannelManager.d.ts +25 -10
  169. package/dist/ripple/src/drivers/NATSDriver.d.ts +87 -0
  170. package/dist/ripple/src/drivers/RedisDriver.d.ts +30 -1
  171. package/dist/ripple/src/drivers/index.d.ts +1 -0
  172. package/dist/ripple/src/engines/BunEngine.d.ts +98 -0
  173. package/dist/ripple/src/engines/IRippleEngine.d.ts +205 -0
  174. package/dist/ripple/src/engines/UWebSocketsEngine.d.ts +97 -0
  175. package/dist/ripple/src/engines/WsEngine.d.ts +69 -0
  176. package/dist/ripple/src/engines/index.d.ts +15 -0
  177. package/dist/ripple/src/index.d.ts +2 -0
  178. package/dist/ripple/src/middleware/InterceptorManager.d.ts +21 -0
  179. package/dist/ripple/src/observability/RippleMetrics.d.ts +24 -0
  180. package/dist/ripple/src/reliability/AckManager.d.ts +48 -0
  181. package/dist/ripple/src/serializers/ISerializer.d.ts +39 -0
  182. package/dist/ripple/src/serializers/JsonSerializer.d.ts +19 -0
  183. package/dist/ripple/src/serializers/ProtobufSerializer.d.ts +41 -0
  184. package/dist/ripple/src/serializers/index.d.ts +3 -0
  185. package/dist/ripple/src/tracking/SessionManager.d.ts +104 -0
  186. package/dist/ripple/src/tracking/index.d.ts +1 -0
  187. package/dist/ripple/src/types.d.ts +188 -12
  188. package/dist/ripple/src/utils/MessageSerializer.d.ts +33 -23
  189. package/dist/ripple/src/utils/TokenBucket.d.ts +25 -0
  190. package/package.json +25 -8
@@ -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
+ }
@@ -0,0 +1,219 @@
1
+ import type { EventOptions } from './EventOptions';
2
+ /**
3
+ * Source of DLQ entry - reason why event entered the DLQ.
4
+ * @public
5
+ */
6
+ export type DLQEntrySource = 'retry_exhausted' | 'circuit_breaker' | 'backpressure_overflow' | 'manual';
7
+ /**
8
+ * Dead Letter Queue entry representing a failed event.
9
+ * @public
10
+ */
11
+ export interface DLQEntry {
12
+ /**
13
+ * Unique identifier for this DLQ entry.
14
+ */
15
+ id: string;
16
+ /**
17
+ * Event hook name.
18
+ */
19
+ eventName: string;
20
+ /**
21
+ * Event payload.
22
+ */
23
+ payload: unknown;
24
+ /**
25
+ * Event options used when dispatching.
26
+ */
27
+ options: EventOptions;
28
+ /**
29
+ * Error that caused the event to fail.
30
+ */
31
+ error: {
32
+ message: string;
33
+ stack?: string;
34
+ code?: string;
35
+ };
36
+ /**
37
+ * Number of retry attempts made.
38
+ */
39
+ retryCount: number;
40
+ /**
41
+ * Timestamp when the event first failed.
42
+ */
43
+ firstFailedAt: number;
44
+ /**
45
+ * Timestamp when the event was added to DLQ.
46
+ */
47
+ failedAt: number;
48
+ /**
49
+ * Timestamp when the event was last retried (if any).
50
+ */
51
+ lastRetriedAt?: number;
52
+ /**
53
+ * Source of the DLQ entry - reason why event entered the DLQ.
54
+ */
55
+ source: DLQEntrySource;
56
+ }
57
+ /**
58
+ * Filter options for querying DLQ entries.
59
+ * @public
60
+ */
61
+ export interface DLQFilter {
62
+ /**
63
+ * Filter by event name.
64
+ */
65
+ eventName?: string;
66
+ /**
67
+ * Filter by entries failed after this timestamp.
68
+ */
69
+ from?: number;
70
+ /**
71
+ * Filter by entries failed before this timestamp.
72
+ */
73
+ to?: number;
74
+ /**
75
+ * Maximum number of entries to return.
76
+ */
77
+ limit?: number;
78
+ }
79
+ /**
80
+ * Callback type for DLQ entry events.
81
+ * @public
82
+ */
83
+ export type DLQEntryCallback = (entry: DLQEntry) => void;
84
+ /**
85
+ * Dead Letter Queue Manager for handling failed events.
86
+ *
87
+ * The DLQ stores events that have exceeded their retry limit,
88
+ * allowing for manual inspection, reprocessing, or analysis.
89
+ *
90
+ * @public
91
+ */
92
+ export declare class DeadLetterQueue {
93
+ private entries;
94
+ private entryIdCounter;
95
+ private maxEntries?;
96
+ private onEntryAdded?;
97
+ private onEntryRemoved?;
98
+ /**
99
+ * Create a new DeadLetterQueue instance.
100
+ *
101
+ * @param maxEntries - Maximum number of entries to keep (optional, no limit if not set)
102
+ */
103
+ constructor(maxEntries?: number);
104
+ /**
105
+ * Add a failed event to the Dead Letter Queue.
106
+ *
107
+ * @param eventName - Name of the failed event
108
+ * @param payload - Event payload
109
+ * @param options - Event options
110
+ * @param error - Error that caused the failure
111
+ * @param retryCount - Number of retry attempts made
112
+ * @param firstFailedAt - Timestamp of first failure
113
+ * @param source - Source of the DLQ entry (default: 'retry_exhausted')
114
+ * @returns DLQ entry ID
115
+ */
116
+ add(eventName: string, payload: unknown, options: EventOptions, error: Error, retryCount: number, firstFailedAt: number, source?: DLQEntrySource): string;
117
+ /**
118
+ * Get a specific DLQ entry by ID.
119
+ *
120
+ * @param entryId - DLQ entry ID
121
+ * @returns DLQ entry or undefined if not found
122
+ */
123
+ get(entryId: string): DLQEntry | undefined;
124
+ /**
125
+ * List DLQ entries with optional filtering.
126
+ *
127
+ * @param filter - Filter options
128
+ * @returns Array of DLQ entries
129
+ */
130
+ list(filter?: DLQFilter): DLQEntry[];
131
+ /**
132
+ * Delete a DLQ entry.
133
+ *
134
+ * @param entryId - DLQ entry ID
135
+ * @returns True if entry was deleted, false if not found
136
+ */
137
+ delete(entryId: string): boolean;
138
+ /**
139
+ * Delete all DLQ entries matching the filter.
140
+ *
141
+ * @param filter - Filter options
142
+ * @returns Number of entries deleted
143
+ */
144
+ deleteAll(filter?: DLQFilter): number;
145
+ /**
146
+ * Get the total number of entries in the DLQ.
147
+ *
148
+ * @returns Total entry count
149
+ */
150
+ getCount(): number;
151
+ /**
152
+ * Get the count of entries for a specific event.
153
+ *
154
+ * @param eventName - Event name
155
+ * @returns Entry count for the event
156
+ */
157
+ getCountByEvent(eventName: string): number;
158
+ /**
159
+ * Clear all entries from the DLQ.
160
+ */
161
+ clear(): void;
162
+ /**
163
+ * Update the last retried timestamp for an entry.
164
+ *
165
+ * @param entryId - DLQ entry ID
166
+ * @internal
167
+ */
168
+ updateLastRetried(entryId: string): void;
169
+ /**
170
+ * Evict the oldest entry from the DLQ.
171
+ * Used when capacity limit is reached.
172
+ *
173
+ * @private
174
+ */
175
+ private evictOldest;
176
+ /**
177
+ * Get the oldest entry in the DLQ.
178
+ *
179
+ * @returns Oldest DLQ entry or undefined if empty
180
+ */
181
+ getOldestEntry(): DLQEntry | undefined;
182
+ /**
183
+ * Get the newest entry in the DLQ.
184
+ *
185
+ * @returns Newest DLQ entry or undefined if empty
186
+ */
187
+ getNewestEntry(): DLQEntry | undefined;
188
+ /**
189
+ * Get all entries grouped by source.
190
+ *
191
+ * @param source - Source to filter by
192
+ * @returns Array of entries matching the source
193
+ */
194
+ getEntriesBySource(source: DLQEntrySource): DLQEntry[];
195
+ /**
196
+ * Set callback for when an entry is added to the DLQ.
197
+ *
198
+ * @param callback - Callback function or undefined to clear
199
+ */
200
+ setOnEntryAdded(callback?: DLQEntryCallback): void;
201
+ /**
202
+ * Set callback for when an entry is removed from the DLQ.
203
+ *
204
+ * @param callback - Callback function or undefined to clear
205
+ */
206
+ setOnEntryRemoved(callback?: DLQEntryCallback): void;
207
+ /**
208
+ * Get the maximum number of entries allowed in the DLQ.
209
+ *
210
+ * @returns Max entries limit or undefined if no limit
211
+ */
212
+ getMaxEntries(): number | undefined;
213
+ /**
214
+ * Set the maximum number of entries allowed in the DLQ.
215
+ *
216
+ * @param maxEntries - Maximum entries or undefined to remove limit
217
+ */
218
+ setMaxEntries(maxEntries?: number): void;
219
+ }
@@ -0,0 +1,12 @@
1
+ import type { EventTask } from './types';
2
+ /**
3
+ * Interface for event dispatch backends.
4
+ */
5
+ export interface EventBackend {
6
+ /**
7
+ * Enqueue an event for processing.
8
+ * @param task - The event task to process
9
+ * @returns Task ID or 'dropped' if event was rejected (can be async for some backends)
10
+ */
11
+ enqueue(task: EventTask): string | Promise<void>;
12
+ }