@gravito/ripple 4.0.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 (91) hide show
  1. package/dist/atlas/src/DB.d.ts +51 -4
  2. package/dist/atlas/src/config/index.d.ts +1 -1
  3. package/dist/atlas/src/config/loadConfig.d.ts +0 -7
  4. package/dist/atlas/src/connection/Connection.d.ts +4 -0
  5. package/dist/atlas/src/connection/ConnectionManager.d.ts +75 -6
  6. package/dist/atlas/src/connection/ReplicaConnectionPool.d.ts +54 -0
  7. package/dist/atlas/src/drivers/MySQLDriver.d.ts +16 -3
  8. package/dist/atlas/src/drivers/PostgresDriver.d.ts +15 -2
  9. package/dist/atlas/src/index.d.ts +15 -3
  10. package/dist/atlas/src/observability/AtlasMetrics.d.ts +22 -0
  11. package/dist/atlas/src/orm/Repository.d.ts +247 -0
  12. package/dist/atlas/src/orm/index.d.ts +1 -0
  13. package/dist/atlas/src/orm/model/Model.d.ts +11 -2
  14. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +14 -0
  15. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +5 -0
  16. package/dist/atlas/src/orm/model/decorators.d.ts +29 -0
  17. package/dist/atlas/src/orm/model/index.d.ts +1 -1
  18. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +1 -0
  19. package/dist/atlas/src/pool/AdaptivePoolManager.d.ts +98 -0
  20. package/dist/atlas/src/pool/PoolHealthChecker.d.ts +91 -0
  21. package/dist/atlas/src/pool/PoolStrategy.d.ts +129 -0
  22. package/dist/atlas/src/pool/PoolWarmer.d.ts +92 -0
  23. package/dist/atlas/src/query/QueryBuilder.d.ts +71 -1
  24. package/dist/atlas/src/query/RelationshipResolver.d.ts +23 -0
  25. package/dist/atlas/src/schema/MigrationGenerator.d.ts +45 -0
  26. package/dist/atlas/src/schema/SchemaDiff.d.ts +73 -0
  27. package/dist/atlas/src/schema/TypeGenerator.d.ts +57 -0
  28. package/dist/atlas/src/schema/TypeWriter.d.ts +42 -0
  29. package/dist/atlas/src/sharding/ShardingManager.d.ts +59 -0
  30. package/dist/atlas/src/types/index.d.ts +83 -1
  31. package/dist/atlas/src/utils/CursorEncoding.d.ts +63 -0
  32. package/dist/core/src/ConfigManager.d.ts +39 -0
  33. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  34. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  35. package/dist/core/src/Container.d.ts +45 -0
  36. package/dist/core/src/ErrorHandler.d.ts +3 -0
  37. package/dist/core/src/HookManager.d.ts +95 -0
  38. package/dist/core/src/PlanetCore.d.ts +89 -0
  39. package/dist/core/src/RequestContext.d.ts +97 -0
  40. package/dist/core/src/ServiceProvider.d.ts +22 -0
  41. package/dist/core/src/adapters/PhotonAdapter.d.ts +4 -0
  42. package/dist/core/src/adapters/bun/BunContext.d.ts +4 -0
  43. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  44. package/dist/core/src/engine/AOTRouter.d.ts +6 -1
  45. package/dist/core/src/engine/FastContext.d.ts +23 -0
  46. package/dist/core/src/engine/Gravito.d.ts +0 -1
  47. package/dist/core/src/engine/MinimalContext.d.ts +21 -0
  48. package/dist/core/src/engine/types.d.ts +3 -0
  49. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  50. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  51. package/dist/core/src/events/DeadLetterQueue.d.ts +75 -1
  52. package/dist/core/src/events/EventBackend.d.ts +2 -1
  53. package/dist/core/src/events/EventOptions.d.ts +99 -4
  54. package/dist/core/src/events/EventPriorityQueue.d.ts +105 -6
  55. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  56. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  57. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  58. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  59. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  60. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  61. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  62. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  63. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  64. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  65. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  66. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  67. package/dist/core/src/events/index.d.ts +11 -0
  68. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +92 -0
  69. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  70. package/dist/core/src/events/observability/index.d.ts +4 -0
  71. package/dist/core/src/events/types.d.ts +59 -0
  72. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  73. package/dist/core/src/http/types.d.ts +19 -0
  74. package/dist/core/src/index.d.ts +13 -1
  75. package/dist/core/src/observability/Metrics.d.ts +244 -0
  76. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  77. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +34 -0
  78. package/dist/index.js +403 -40
  79. package/dist/index.js.map +11 -9
  80. package/dist/photon/src/index.d.ts +5 -0
  81. package/dist/photon/src/middleware/ratelimit-redis.d.ts +50 -0
  82. package/dist/photon/src/middleware/ratelimit.d.ts +4 -0
  83. package/dist/ripple/src/RippleServer.d.ts +0 -1
  84. package/dist/ripple/src/engines/UWebSocketsEngine.d.ts +97 -0
  85. package/dist/ripple/src/engines/WsEngine.d.ts +69 -0
  86. package/dist/ripple/src/engines/index.d.ts +4 -0
  87. package/dist/ripple/src/serializers/ISerializer.d.ts +1 -1
  88. package/dist/ripple/src/serializers/JsonSerializer.d.ts +1 -1
  89. package/dist/ripple/src/serializers/ProtobufSerializer.d.ts +6 -3
  90. package/dist/ripple/src/types.d.ts +11 -0
  91. package/package.json +3 -2
@@ -10,12 +10,50 @@ export interface EventOptions {
10
10
  async?: boolean;
11
11
  /**
12
12
  * Priority level for event processing.
13
- * - 'high': Critical events (e.g., order:created, payment:succeeded)
14
- * - 'normal': Standard events (e.g., order:confirmed)
15
- * - 'low': Non-critical events (e.g., analytics, logging)
13
+ * - 'critical': Immediate processing, bypass queue (< 1ms)
14
+ * - 'high': High priority events (< 50ms)
15
+ * - 'normal': Standard events (< 200ms)
16
+ * - 'low': Non-critical events (< 500ms)
16
17
  * @default 'normal'
17
18
  */
18
- priority?: 'high' | 'normal' | 'low';
19
+ priority?: 'critical' | 'high' | 'normal' | 'low';
20
+ /**
21
+ * Automatic priority escalation configuration.
22
+ * Events can be automatically upgraded to higher priority based on wait time.
23
+ */
24
+ escalation?: {
25
+ /**
26
+ * Whether to enable automatic priority escalation.
27
+ * @default true
28
+ */
29
+ enabled?: boolean;
30
+ /**
31
+ * Escalation thresholds in milliseconds.
32
+ * Events exceeding these wait times are promoted.
33
+ */
34
+ thresholds?: {
35
+ /**
36
+ * Wait time before LOW events are promoted to NORMAL.
37
+ * @default 200
38
+ */
39
+ lowToNormal?: number;
40
+ /**
41
+ * Wait time before NORMAL events are promoted to HIGH.
42
+ * @default 100
43
+ */
44
+ normalToHigh?: number;
45
+ /**
46
+ * Wait time before HIGH events are promoted to CRITICAL.
47
+ * @default 50
48
+ */
49
+ highToCritical?: number;
50
+ };
51
+ /**
52
+ * Maximum wait time before forcing CRITICAL priority.
53
+ * @default 500
54
+ */
55
+ maxWaitTimeMs?: number;
56
+ };
19
57
  /**
20
58
  * Execution timeout in milliseconds.
21
59
  * If a listener exceeds this timeout, it will be terminated.
@@ -101,6 +139,63 @@ export interface EventOptions {
101
139
  */
102
140
  halfOpenRequests?: number;
103
141
  };
142
+ /**
143
+ * Event aggregation configuration (FS-102).
144
+ * Enables deduplication and micro-batching for improved throughput.
145
+ * @default undefined (disabled)
146
+ */
147
+ aggregation?: {
148
+ /**
149
+ * Enable event aggregation.
150
+ * @default false
151
+ */
152
+ enabled?: boolean;
153
+ /**
154
+ * Aggregation window size in milliseconds.
155
+ * Backpressure-aware adjustment: 50-500ms
156
+ * @default 200
157
+ */
158
+ windowMs?: number;
159
+ /**
160
+ * Batch size threshold for auto-flush.
161
+ * @default 50
162
+ */
163
+ batchSize?: number;
164
+ /**
165
+ * Deduplication strategy.
166
+ * @default 'pattern'
167
+ */
168
+ deduplication?: 'pattern' | 'idempotencyKey' | 'off';
169
+ /**
170
+ * Deduplication pattern (string or function).
171
+ * String: hook-based pattern
172
+ * Function: custom pattern from event args
173
+ */
174
+ pattern?: string | ((args: unknown) => string);
175
+ /**
176
+ * Priority merge strategy.
177
+ * - 'highest': keep highest priority event
178
+ * - 'earliest': keep earliest event
179
+ * - 'latest': keep latest event
180
+ * @default 'highest'
181
+ */
182
+ mergePriority?: 'highest' | 'earliest' | 'latest';
183
+ /**
184
+ * Enable automatic cleanup of expired entries.
185
+ * @default true
186
+ */
187
+ enableCleanup?: boolean;
188
+ /**
189
+ * Cleanup interval in milliseconds.
190
+ * @default 300000 (5 minutes)
191
+ */
192
+ cleanupIntervalMs?: number;
193
+ /**
194
+ * TTL for entries in milliseconds.
195
+ * @default 600000 (10 minutes)
196
+ */
197
+ ttlMs?: number;
198
+ };
104
199
  }
105
200
  /**
106
201
  * Default event options.
@@ -1,23 +1,32 @@
1
1
  import type { Span } from '@opentelemetry/api';
2
2
  import type { ActionCallback } from '../HookManager';
3
+ import { BackpressureManager } from './BackpressureManager';
3
4
  import { CircuitBreaker } from './CircuitBreaker';
4
5
  import type { DeadLetterQueue } from './DeadLetterQueue';
5
6
  import type { EventBackend } from './EventBackend';
6
7
  import type { EventOptions } from './EventOptions';
7
8
  import type { EventMetrics } from './observability/EventMetrics';
8
9
  import type { EventTracing } from './observability/EventTracing';
9
- import type { BackpressureStrategy, EventQueueConfig, EventTask } from './types';
10
+ import type { OTelEventMetrics } from './observability/OTelEventMetrics';
11
+ import { type PriorityStatistics } from './PriorityEscalationManager';
12
+ import type { RetryScheduler } from './RetryScheduler';
13
+ import type { BackpressureStrategy, EventQueueConfig, EventTask, MultiPriorityQueueDepth } from './types';
14
+ import type { WorkerPool } from './WorkerPool';
10
15
  export type { EventTask, EventQueueConfig, BackpressureStrategy };
11
16
  /**
12
17
  * Priority queue for event processing.
13
18
  * Events are processed based on their priority level:
14
- * - High priority events are processed first
15
- * - Normal priority events are processed second
16
- * - Low priority events are processed last
19
+ * - Critical priority events are processed first (< 1ms)
20
+ * - High priority events are processed second (< 50ms)
21
+ * - Normal priority events are processed third (< 200ms)
22
+ * - Low priority events are processed last (< 500ms)
23
+ *
24
+ * Supports automatic priority escalation based on wait time.
17
25
  *
18
26
  * @internal
19
27
  */
20
28
  export declare class EventPriorityQueue implements EventBackend {
29
+ private criticalPriority;
21
30
  private highPriority;
22
31
  private normalPriority;
23
32
  private lowPriority;
@@ -29,8 +38,13 @@ export declare class EventPriorityQueue implements EventBackend {
29
38
  private processingPartitions;
30
39
  private eventCircuitBreakers;
31
40
  private eventMetrics?;
41
+ private otelEventMetrics?;
32
42
  private eventTracing?;
33
43
  private currentDispatchSpan?;
44
+ private backpressureManager?;
45
+ private workerPool?;
46
+ private retryScheduler?;
47
+ private priorityStats?;
34
48
  constructor(config?: EventQueueConfig);
35
49
  /**
36
50
  * Set the Dead Letter Queue for failed events.
@@ -51,6 +65,27 @@ export declare class EventPriorityQueue implements EventBackend {
51
65
  * @internal
52
66
  */
53
67
  setEventMetrics(metrics: EventMetrics): void;
68
+ /**
69
+ * Set the OTelEventMetrics instance for recording DLQ and backpressure metrics.
70
+ *
71
+ * @param metrics - OTelEventMetrics instance
72
+ * @internal
73
+ */
74
+ setOTelEventMetrics(metrics: OTelEventMetrics): void;
75
+ /**
76
+ * Set the PriorityStatistics instance for tracking priority distribution.
77
+ *
78
+ * @param stats - PriorityStatistics instance
79
+ * @internal
80
+ */
81
+ setPriorityStatistics(stats: PriorityStatistics): void;
82
+ /**
83
+ * Get the PriorityStatistics instance.
84
+ *
85
+ * @returns PriorityStatistics instance or undefined
86
+ * @internal
87
+ */
88
+ getPriorityStatistics(): PriorityStatistics | undefined;
54
89
  /**
55
90
  * Set the EventTracing instance for distributed tracing.
56
91
  *
@@ -72,6 +107,20 @@ export declare class EventPriorityQueue implements EventBackend {
72
107
  * @internal
73
108
  */
74
109
  getCurrentDispatchSpan(): Span | undefined;
110
+ /**
111
+ * Set the RetryScheduler for async distributed retries.
112
+ *
113
+ * @param scheduler - RetryScheduler instance
114
+ * @internal
115
+ */
116
+ setRetryScheduler(scheduler: RetryScheduler): void;
117
+ /**
118
+ * Get the RetryScheduler instance.
119
+ *
120
+ * @returns RetryScheduler instance or undefined
121
+ * @internal
122
+ */
123
+ getRetryScheduler(): RetryScheduler | undefined;
75
124
  /**
76
125
  * Get or create a circuit breaker for an event hook.
77
126
  *
@@ -90,7 +139,7 @@ export declare class EventPriorityQueue implements EventBackend {
90
139
  * @param options - Event options
91
140
  * @returns Task ID
92
141
  */
93
- enqueue(task: EventTask): void;
142
+ enqueue(task: EventTask): string;
94
143
  enqueue(hook: string, args: unknown, callbacks: ActionCallback[], options: EventOptions): string;
95
144
  /**
96
145
  * Handle backpressure when queue is full.
@@ -99,17 +148,20 @@ export declare class EventPriorityQueue implements EventBackend {
99
148
  private handleBackpressure;
100
149
  /**
101
150
  * Drop the oldest event from the queue, prioritizing low priority events.
151
+ * Drops in order: LOW → NORMAL → HIGH → CRITICAL
102
152
  */
103
153
  private dropOldest;
104
154
  /**
105
155
  * Process the next task in the queue.
106
156
  * Tasks are processed in priority order: high > normal > low
157
+ * If WorkerPool is configured, tasks are submitted to the pool for concurrent execution.
107
158
  *
108
159
  * @internal
109
160
  */
110
161
  private processNext;
111
162
  /**
112
163
  * Dequeue the next task based on priority and partition ordering.
164
+ * Priority order: CRITICAL > HIGH > NORMAL > LOW
113
165
  *
114
166
  * @returns Next task to process, or undefined if queue is empty
115
167
  * @internal
@@ -171,7 +223,28 @@ export declare class EventPriorityQueue implements EventBackend {
171
223
  * @param priority - Priority level
172
224
  * @returns Number of tasks in the specified priority queue
173
225
  */
174
- getDepthByPriority(priority: 'high' | 'normal' | 'low'): number;
226
+ getDepthByPriority(priority: 'critical' | 'high' | 'normal' | 'low'): number;
227
+ /**
228
+ * Get the BackpressureManager instance if enabled.
229
+ *
230
+ * @returns BackpressureManager instance or undefined if not enabled
231
+ * @internal
232
+ */
233
+ getBackpressureManager(): BackpressureManager | undefined;
234
+ /**
235
+ * Set the WorkerPool for concurrent task execution.
236
+ *
237
+ * @param pool - WorkerPool instance
238
+ * @internal
239
+ */
240
+ setWorkerPool(pool: WorkerPool): void;
241
+ /**
242
+ * Get the WorkerPool instance if set.
243
+ *
244
+ * @returns WorkerPool instance or undefined if not set
245
+ * @internal
246
+ */
247
+ getWorkerPool(): WorkerPool | undefined;
175
248
  /**
176
249
  * Clear all tasks from the queue.
177
250
  */
@@ -199,4 +272,30 @@ export declare class EventPriorityQueue implements EventBackend {
199
272
  * @internal
200
273
  */
201
274
  resetCircuitBreaker(hook: string): boolean;
275
+ /**
276
+ * Batch enqueue multiple tasks (FS-102).
277
+ * Supports aggregation layer batch submission.
278
+ *
279
+ * @param tasks - Array of tasks to enqueue
280
+ * @returns Array of task IDs
281
+ * @internal
282
+ */
283
+ enqueueBatch(tasks: EventTask[]): string[];
284
+ /**
285
+ * Get queue depth for each priority level (FS-103).
286
+ * Used by BackpressureManager for multi-priority depth monitoring.
287
+ *
288
+ * @returns Queue depth snapshot with depths for each priority
289
+ * @internal
290
+ */
291
+ getQueueDepthByPriority(): MultiPriorityQueueDepth;
292
+ /**
293
+ * Sync queue depth to BackpressureManager (FS-103).
294
+ * Called whenever queue depth changes to keep BackpressureManager
295
+ * synchronized with real-time queue state.
296
+ *
297
+ * @private
298
+ * @internal
299
+ */
300
+ private syncBackpressure;
202
301
  }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * @gravito/core - Flow Control Strategies
3
+ *
4
+ * Implements various flow control strategies for backpressure management.
5
+ * Strategies can be composed to create flexible backpressure policies.
6
+ *
7
+ * 流控策略:支援多種組合策略進行靈活的背壓管理。
8
+ */
9
+ import { type BackpressureConfig, type BackpressureDecision, BackpressureState } from './BackpressureManager';
10
+ /**
11
+ * 流控評估上下文。
12
+ *
13
+ * @public
14
+ */
15
+ export interface FlowControlContext {
16
+ /** 當前背壓狀態 */
17
+ state: BackpressureState;
18
+ /** 事件優先級 */
19
+ priority: 'high' | 'normal' | 'low';
20
+ /** 總隊列深度 */
21
+ totalDepth: number;
22
+ /** 分優先級隊列深度 */
23
+ depthByPriority: {
24
+ high: number;
25
+ normal: number;
26
+ low: number;
27
+ };
28
+ /** 當前入隊速率(events/sec) */
29
+ currentRate: number;
30
+ /** 配置 */
31
+ config: Omit<BackpressureConfig, 'onRejected' | 'onStateChange'>;
32
+ }
33
+ /**
34
+ * 流控策略介面。
35
+ *
36
+ * @public
37
+ */
38
+ export interface FlowControlStrategy {
39
+ /** 策略名稱 */
40
+ readonly name: string;
41
+ /** 評估是否應該限制此事件 */
42
+ evaluate(context: FlowControlContext): BackpressureDecision;
43
+ }
44
+ /**
45
+ * 隊列深度策略。
46
+ *
47
+ * 根據總隊列深度和分優先級隊列深度決定是否限制事件入隊。
48
+ */
49
+ export declare class QueueDepthStrategy implements FlowControlStrategy {
50
+ readonly name = "queue-depth";
51
+ evaluate(context: FlowControlContext): BackpressureDecision;
52
+ }
53
+ /**
54
+ * 速率限制策略。
55
+ *
56
+ * 根據每秒入隊速率限制事件入隊。
57
+ */
58
+ export declare class RateLimitStrategy implements FlowControlStrategy {
59
+ readonly name = "rate-limit";
60
+ evaluate(context: FlowControlContext): BackpressureDecision;
61
+ }
62
+ /**
63
+ * 優先級平衡策略。
64
+ *
65
+ * 在 WARNING 和 CRITICAL 狀態下降級低優先級事件,防止高優先級飢餓。
66
+ */
67
+ export declare class PriorityRebalanceStrategy implements FlowControlStrategy {
68
+ readonly name = "priority-rebalance";
69
+ evaluate(context: FlowControlContext): BackpressureDecision;
70
+ }
71
+ /**
72
+ * 反飢餓保護策略。
73
+ *
74
+ * 防止低優先級事件被長期壓制。
75
+ * 當事件等待超過 starvationTimeoutMs 時,自動提升其優先級。
76
+ */
77
+ export declare class StarvationProtectionStrategy implements FlowControlStrategy {
78
+ readonly name = "starvation-protection";
79
+ evaluate(_context: FlowControlContext): BackpressureDecision;
80
+ }
81
+ /**
82
+ * 組合策略。
83
+ *
84
+ * 組合多個策略。評估時所有子策略必須允許,否則拒絕。
85
+ * 取最嚴格的決策(拒絕 > 延遲 > 允許)。
86
+ */
87
+ export declare class CompositeStrategy implements FlowControlStrategy {
88
+ readonly name: string;
89
+ private strategies;
90
+ constructor(name: string, strategies: FlowControlStrategy[]);
91
+ evaluate(context: FlowControlContext): BackpressureDecision;
92
+ /**
93
+ * 新增子策略。
94
+ */
95
+ addStrategy(strategy: FlowControlStrategy): void;
96
+ /**
97
+ * 移除指定名稱的子策略。
98
+ */
99
+ removeStrategy(name: string): boolean;
100
+ }
101
+ /**
102
+ * 工廠方法:建立預設流控策略組合。
103
+ *
104
+ * @param config 背壓配置
105
+ * @returns 組合策略實例
106
+ *
107
+ * @public
108
+ */
109
+ export declare function createDefaultStrategies(_config: Omit<BackpressureConfig, 'onRejected' | 'onStateChange'>): FlowControlStrategy[];
@@ -0,0 +1,184 @@
1
+ /**
2
+ * @gravito/core - Message Queue Bridge
3
+ *
4
+ * 橋接層,連接 HookManager 與 Bull Queue (via StreamEventBackend)
5
+ * 支持分佈式事件流:HookManager → Bull Queue → Worker → 完成/DLQ
6
+ */
7
+ import type { HookManager } from '../HookManager';
8
+ import type { DeadLetterQueueManager } from '../reliability/DeadLetterQueueManager';
9
+ import type { EventBackend } from './EventBackend';
10
+ import type { EventTask } from './types';
11
+ import type { WorkerPool } from './WorkerPool';
12
+ /**
13
+ * 事件執行狀態
14
+ */
15
+ export interface EventStatus {
16
+ eventId: string;
17
+ status: 'pending' | 'processing' | 'completed' | 'failed' | 'in_dlq';
18
+ attempts: number;
19
+ lastError?: string;
20
+ createdAt: number;
21
+ processedAt?: number;
22
+ }
23
+ /**
24
+ * MessageQueueBridge 配置
25
+ */
26
+ export interface MessageQueueBridgeConfig {
27
+ /**
28
+ * HookManager 實例
29
+ */
30
+ hookManager: HookManager;
31
+ /**
32
+ * Worker 線程池(可選)
33
+ */
34
+ workerPool?: WorkerPool;
35
+ /**
36
+ * 分佈式事件後端(Bull Queue)
37
+ */
38
+ eventBackend: EventBackend;
39
+ /**
40
+ * Dead Letter Queue 管理器
41
+ */
42
+ dlqManager: DeadLetterQueueManager;
43
+ /**
44
+ * 是否啟用 CircuitBreaker 檢查
45
+ * @default false
46
+ */
47
+ enableCircuitBreaker?: boolean;
48
+ }
49
+ /**
50
+ * MessageQueueBridge - 連接 HookManager 與 Bull Queue 的橋接層
51
+ *
52
+ * 功能:
53
+ * 1. 通過 Bull Queue 分發事件(dispatchWithQueue)
54
+ * 2. Worker 中處理隊列事件(processQueuedEvent)
55
+ * 3. 失敗任務轉移至 DLQ(handleJobFailure)
56
+ * 4. 查詢事件執行狀態(getEventStatus)
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const bridge = new MessageQueueBridge({
61
+ * hookManager,
62
+ * eventBackend: streamEventBackend,
63
+ * dlqManager,
64
+ * enableCircuitBreaker: true
65
+ * })
66
+ *
67
+ * // 分發事件至 Bull Queue
68
+ * const jobId = await bridge.dispatchWithQueue('order:created', { orderId: 123 })
69
+ *
70
+ * // Worker 處理事件
71
+ * await bridge.processQueuedEvent(jobId, task)
72
+ * ```
73
+ */
74
+ export declare class MessageQueueBridge {
75
+ private config;
76
+ constructor(config: MessageQueueBridgeConfig);
77
+ /**
78
+ * 通過 Bull Queue 分發事件(分佈式異步處理)
79
+ *
80
+ * 流程:
81
+ * 1. 驗證事件 listeners 存在
82
+ * 2. 檢查 CircuitBreaker 狀態(如果啟用)
83
+ * 3. 構建 EventTask
84
+ * 4. 入隊到 eventBackend (Bull Queue)
85
+ *
86
+ * @param eventName - 事件名稱
87
+ * @param args - 事件參數
88
+ * @param options - 事件選項(可選)
89
+ * @returns Job ID
90
+ * @throws 如果沒有 listeners 或 CircuitBreaker 打開
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const jobId = await bridge.dispatchWithQueue('order:created', {
95
+ * orderId: 'ORD-123',
96
+ * amount: 999.99
97
+ * })
98
+ * ```
99
+ */
100
+ dispatchWithQueue<TArgs = unknown>(eventName: string, args: TArgs, options?: any): Promise<string>;
101
+ /**
102
+ * 處理隊列事件(由 Bull Queue Worker 調用)
103
+ *
104
+ * 重要:使用 doActionSync() 避免遞迴
105
+ * - 不能使用 doActionAsync()(會導致事件再次入隊)
106
+ * - Worker 中直接同步執行 callbacks
107
+ *
108
+ * 流程:
109
+ * 1. 直接執行 callbacks(不使用 doActionSync,避免吞掉錯誤)
110
+ * 2. 記錄成功或失敗
111
+ * 3. 拋出錯誤讓 Bull Queue 處理重試
112
+ *
113
+ * @param jobId - Bull Queue Job ID
114
+ * @param task - 事件任務
115
+ * @throws 如果 callback 執行失敗,讓 Bull Queue 處理重試
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * // 在 Bull Queue Worker 中:
120
+ * await bridge.processQueuedEvent(jobId, task)
121
+ * ```
122
+ */
123
+ processQueuedEvent(jobId: string, task: EventTask): Promise<void>;
124
+ /**
125
+ * 處理 Bull Queue 任務失敗(由 onFailed callback 調用)
126
+ *
127
+ * 流程:
128
+ * 1. 記錄警告日誌
129
+ * 2. 移至 persistent DLQ(DeadLetterQueueManager)
130
+ * 3. 持久化到 event_dlq 表,支持延遲重試
131
+ *
132
+ * @param jobId - Bull Queue Job ID
133
+ * @param task - 事件任務
134
+ * @param error - 導致失敗的錯誤
135
+ * @param retryCount - 已重試次數(可選)
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * // 在 Bull Queue onFailed callback 中:
140
+ * await bridge.handleJobFailure(jobId, task, error, 3)
141
+ * ```
142
+ */
143
+ handleJobFailure(jobId: string, task: EventTask, error: Error, retryCount?: number): Promise<void>;
144
+ /**
145
+ * 查詢事件執行狀態
146
+ *
147
+ * 支持查詢:
148
+ * 1. 待處理事件
149
+ * 2. 正在處理的事件
150
+ * 3. 已完成事件
151
+ * 4. 失敗事件(在 DLQ 中)
152
+ *
153
+ * @param eventId - 事件 ID(task.id 或 jobId)
154
+ * @returns 事件狀態
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * const status = await bridge.getEventStatus('queue-1707000000000-abc123')
159
+ * console.log(status) // { eventId, status, attempts, ... }
160
+ * ```
161
+ */
162
+ getEventStatus(eventId: string): Promise<EventStatus>;
163
+ /**
164
+ * 獲取 EventBackend 實例(用於高級操作)
165
+ *
166
+ * @returns EventBackend 實例
167
+ * @internal
168
+ */
169
+ getEventBackend(): EventBackend;
170
+ /**
171
+ * 獲取 DLQ 管理器實例(用於高級操作)
172
+ *
173
+ * @returns DeadLetterQueueManager 實例
174
+ * @internal
175
+ */
176
+ getDLQManager(): DeadLetterQueueManager;
177
+ /**
178
+ * 獲取 HookManager 實例(用於高級操作)
179
+ *
180
+ * @returns HookManager 實例
181
+ * @internal
182
+ */
183
+ getHookManager(): HookManager;
184
+ }
@@ -0,0 +1,82 @@
1
+ import type { EventOptions } from './EventOptions';
2
+ import type { EventTask } from './types';
3
+ /**
4
+ * 優先級升級管理器
5
+ *
6
+ * 根據事件等待時間動態調整優先級,實施優先級提升機制。
7
+ * 確保關鍵事件不會因為隊列深度而長時間等待。
8
+ *
9
+ * 升級規則(可配置):
10
+ * - LOW 等待 > 200ms → NORMAL
11
+ * - NORMAL 等待 > 100ms → HIGH
12
+ * - HIGH 等待 > 50ms → CRITICAL
13
+ * - 超過 maxWaitTimeMs → 強制 CRITICAL
14
+ *
15
+ * @internal
16
+ */
17
+ export declare class PriorityEscalationManager {
18
+ /**
19
+ * 計算事件當前應該的優先級
20
+ * 根據等待時間動態調整
21
+ */
22
+ static calculateCurrentPriority(task: EventTask, config?: EventOptions['escalation']): 'critical' | 'high' | 'normal' | 'low';
23
+ /**
24
+ * 比較兩個事件的優先級
25
+ * @returns 負數表示 task1 優先級更高,正數表示 task2 優先級更高
26
+ */
27
+ static comparePriority(task1: EventTask, task2: EventTask): number;
28
+ /**
29
+ * 判斷事件是否應該立即處理(跳過隊列)
30
+ */
31
+ static shouldProcessImmediately(task: EventTask, config?: EventOptions['escalation']): boolean;
32
+ /**
33
+ * 獲取事件當前的超期時間(毫秒)
34
+ * 正數表示已超期,0 表示未超期
35
+ */
36
+ static calculateOverdueTime(task: EventTask, config?: EventOptions['escalation']): number;
37
+ }
38
+ /**
39
+ * 優先級統計器
40
+ * 追蹤優先級分布和升級事件
41
+ *
42
+ * @internal
43
+ */
44
+ export declare class PriorityStatistics {
45
+ private eventCounts;
46
+ private escalationCounts;
47
+ private totalEscalations;
48
+ /**
49
+ * 記錄一個優先級的事件
50
+ */
51
+ recordEvent(priority: 'critical' | 'high' | 'normal' | 'low'): void;
52
+ /**
53
+ * 記錄優先級升級
54
+ */
55
+ recordEscalation(fromPriority: 'critical' | 'high' | 'normal' | 'low', toPriority: 'critical' | 'high' | 'normal' | 'low'): void;
56
+ /**
57
+ * 獲取優先級分布
58
+ */
59
+ getDistribution(): Record<'critical' | 'high' | 'normal' | 'low', string>;
60
+ /**
61
+ * 獲取升級統計
62
+ */
63
+ getEscalationStats(): {
64
+ total: number;
65
+ byTransition: Record<string, number>;
66
+ };
67
+ /**
68
+ * 重置統計信息
69
+ */
70
+ reset(): void;
71
+ /**
72
+ * 獲取所有統計信息
73
+ */
74
+ getStats(): {
75
+ eventCounts: Record<'critical' | 'high' | 'normal' | 'low', number>;
76
+ escalationStats: {
77
+ total: number;
78
+ byTransition: Record<string, number>;
79
+ };
80
+ distribution: Record<'critical' | 'high' | 'normal' | 'low', string>;
81
+ };
82
+ }