@gravito/radiance 1.0.3 → 1.0.5

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 (149) hide show
  1. package/README.md +30 -7
  2. package/README.zh-TW.md +238 -3
  3. package/dist/core/src/Application.d.ts +256 -0
  4. package/dist/core/src/CommandKernel.d.ts +33 -0
  5. package/dist/core/src/ConfigManager.d.ts +65 -0
  6. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  7. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  8. package/dist/core/src/Container.d.ts +153 -0
  9. package/dist/core/src/ErrorHandler.d.ts +66 -0
  10. package/dist/core/src/Event.d.ts +5 -0
  11. package/dist/core/src/EventManager.d.ts +123 -0
  12. package/dist/core/src/GlobalErrorHandlers.d.ts +47 -0
  13. package/dist/core/src/GravitoServer.d.ts +28 -0
  14. package/dist/core/src/HookManager.d.ts +435 -0
  15. package/dist/core/src/Listener.d.ts +4 -0
  16. package/dist/core/src/Logger.d.ts +20 -0
  17. package/dist/core/src/PlanetCore.d.ts +402 -0
  18. package/dist/core/src/RequestContext.d.ts +97 -0
  19. package/dist/core/src/Route.d.ts +36 -0
  20. package/dist/core/src/Router.d.ts +270 -0
  21. package/dist/core/src/ServiceProvider.d.ts +178 -0
  22. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +27 -0
  23. package/dist/core/src/adapters/bun/BunContext.d.ts +54 -0
  24. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +66 -0
  25. package/dist/core/src/adapters/bun/BunRequest.d.ts +31 -0
  26. package/dist/core/src/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  27. package/dist/core/src/adapters/bun/RadixNode.d.ts +19 -0
  28. package/dist/core/src/adapters/bun/RadixRouter.d.ts +32 -0
  29. package/dist/core/src/adapters/bun/index.d.ts +7 -0
  30. package/dist/core/src/adapters/bun/types.d.ts +20 -0
  31. package/dist/core/src/adapters/types.d.ts +235 -0
  32. package/dist/core/src/binary/BinaryUtils.d.ts +105 -0
  33. package/dist/core/src/binary/index.d.ts +5 -0
  34. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  35. package/dist/core/src/compat/async-local-storage.d.ts +7 -0
  36. package/dist/core/src/compat/crypto.d.ts +6 -0
  37. package/dist/core/src/engine/AOTRouter.d.ts +139 -0
  38. package/dist/core/src/engine/FastContext.d.ts +141 -0
  39. package/dist/core/src/engine/Gravito.d.ts +131 -0
  40. package/dist/core/src/engine/MinimalContext.d.ts +102 -0
  41. package/dist/core/src/engine/analyzer.d.ts +113 -0
  42. package/dist/core/src/engine/constants.d.ts +23 -0
  43. package/dist/core/src/engine/index.d.ts +26 -0
  44. package/dist/core/src/engine/path.d.ts +26 -0
  45. package/dist/core/src/engine/pool.d.ts +83 -0
  46. package/dist/core/src/engine/types.d.ts +149 -0
  47. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  48. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  49. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  50. package/dist/core/src/events/DeadLetterQueue.d.ts +219 -0
  51. package/dist/core/src/events/EventBackend.d.ts +12 -0
  52. package/dist/core/src/events/EventOptions.d.ts +204 -0
  53. package/dist/core/src/events/EventPriorityQueue.d.ts +63 -0
  54. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  55. package/dist/core/src/events/IdempotencyCache.d.ts +60 -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 +26 -0
  68. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  69. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  70. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  71. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +332 -0
  72. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  73. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  74. package/dist/core/src/events/observability/index.d.ts +24 -0
  75. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  76. package/dist/core/src/events/queue-core.d.ts +77 -0
  77. package/dist/core/src/events/task-executor.d.ts +51 -0
  78. package/dist/core/src/events/types.d.ts +134 -0
  79. package/dist/core/src/exceptions/AuthenticationException.d.ts +8 -0
  80. package/dist/core/src/exceptions/AuthorizationException.d.ts +8 -0
  81. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  82. package/dist/core/src/exceptions/GravitoException.d.ts +23 -0
  83. package/dist/core/src/exceptions/HttpException.d.ts +9 -0
  84. package/dist/core/src/exceptions/ModelNotFoundException.d.ts +10 -0
  85. package/dist/core/src/exceptions/ValidationException.d.ts +22 -0
  86. package/dist/core/src/exceptions/index.d.ts +7 -0
  87. package/dist/core/src/ffi/NativeAccelerator.d.ts +62 -0
  88. package/dist/core/src/ffi/NativeHasher.d.ts +139 -0
  89. package/dist/core/src/ffi/cbor-fallback.d.ts +96 -0
  90. package/dist/core/src/ffi/hash-fallback.d.ts +33 -0
  91. package/dist/core/src/ffi/index.d.ts +10 -0
  92. package/dist/core/src/ffi/types.d.ts +135 -0
  93. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  94. package/dist/core/src/helpers/Arr.d.ts +19 -0
  95. package/dist/core/src/helpers/Str.d.ts +38 -0
  96. package/dist/core/src/helpers/data.d.ts +25 -0
  97. package/dist/core/src/helpers/errors.d.ts +34 -0
  98. package/dist/core/src/helpers/response.d.ts +41 -0
  99. package/dist/core/src/helpers.d.ts +338 -0
  100. package/dist/core/src/hooks/ActionManager.d.ts +132 -0
  101. package/dist/core/src/hooks/AsyncDetector.d.ts +84 -0
  102. package/dist/core/src/hooks/FilterManager.d.ts +71 -0
  103. package/dist/core/src/hooks/MigrationWarner.d.ts +24 -0
  104. package/dist/core/src/hooks/dlq-operations.d.ts +60 -0
  105. package/dist/core/src/hooks/types.d.ts +107 -0
  106. package/dist/core/src/http/CookieJar.d.ts +51 -0
  107. package/dist/core/src/http/cookie.d.ts +29 -0
  108. package/dist/core/src/http/types.d.ts +395 -0
  109. package/dist/core/src/index.d.ts +565 -0
  110. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  111. package/dist/core/src/observability/contracts.d.ts +137 -0
  112. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +349 -0
  113. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  114. package/dist/core/src/reliability/index.d.ts +6 -0
  115. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  116. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  117. package/dist/core/src/runtime/adapter-bun.d.ts +12 -0
  118. package/dist/core/src/runtime/adapter-deno.d.ts +12 -0
  119. package/dist/core/src/runtime/adapter-node.d.ts +12 -0
  120. package/dist/core/src/runtime/adapter-unknown.d.ts +13 -0
  121. package/dist/core/src/runtime/archive.d.ts +17 -0
  122. package/dist/core/src/runtime/compression.d.ts +21 -0
  123. package/dist/core/src/runtime/deep-equals.d.ts +56 -0
  124. package/dist/core/src/runtime/detection.d.ts +22 -0
  125. package/dist/core/src/runtime/escape.d.ts +34 -0
  126. package/dist/core/src/runtime/index.d.ts +44 -0
  127. package/dist/core/src/runtime/markdown.d.ts +44 -0
  128. package/dist/core/src/runtime/types.d.ts +436 -0
  129. package/dist/core/src/runtime-helpers.d.ts +67 -0
  130. package/dist/core/src/runtime.d.ts +11 -0
  131. package/dist/core/src/security/Encrypter.d.ts +33 -0
  132. package/dist/core/src/security/Hasher.d.ts +29 -0
  133. package/dist/core/src/testing/HttpTester.d.ts +40 -0
  134. package/dist/core/src/testing/TestResponse.d.ts +78 -0
  135. package/dist/core/src/testing/index.d.ts +2 -0
  136. package/dist/core/src/transpiler-utils.d.ts +170 -0
  137. package/dist/core/src/types/events.d.ts +94 -0
  138. package/dist/index.js +1 -274
  139. package/dist/index.js.map +3 -10
  140. package/dist/radiance/src/BroadcastManager.d.ts +124 -0
  141. package/dist/radiance/src/OrbitRadiance.d.ts +98 -0
  142. package/dist/radiance/src/channels/Channel.d.ts +86 -0
  143. package/dist/radiance/src/drivers/AblyDriver.d.ts +73 -0
  144. package/dist/radiance/src/drivers/BroadcastDriver.d.ts +50 -0
  145. package/dist/radiance/src/drivers/PusherDriver.d.ts +95 -0
  146. package/dist/radiance/src/drivers/RedisDriver.d.ts +83 -0
  147. package/dist/radiance/src/drivers/WebSocketDriver.d.ts +89 -0
  148. package/dist/radiance/src/index.d.ts +39 -0
  149. package/package.json +10 -6
@@ -0,0 +1,137 @@
1
+ /**
2
+ * @gravito/core - Observability Contracts
3
+ *
4
+ * Abstract interfaces for observability providers, decoupling core from OpenTelemetry.
5
+ * This allows @gravito/monitor to provide complete OTel implementations while core
6
+ * remains dependency-free.
7
+ */
8
+ /**
9
+ * Represents a tracing span for distributed tracing.
10
+ * @public
11
+ */
12
+ export interface TracingSpan {
13
+ /**
14
+ * Add an event to the span.
15
+ *
16
+ * @param name - Event name
17
+ * @param attributes - Optional event attributes
18
+ */
19
+ addEvent(name: string, attributes?: Record<string, string | number>): void;
20
+ /**
21
+ * Set the span status.
22
+ *
23
+ * @param code - Status code: 'OK' or 'ERROR'
24
+ * @param message - Optional error message
25
+ */
26
+ setStatus(code: 'OK' | 'ERROR', message?: string): void;
27
+ /**
28
+ * End the span.
29
+ */
30
+ end(): void;
31
+ }
32
+ /**
33
+ * Event tracing provider for distributed tracing of events.
34
+ * @public
35
+ */
36
+ export interface EventTracingProvider {
37
+ /**
38
+ * Start a new tracing span for an event.
39
+ *
40
+ * @param name - Span name
41
+ * @returns A TracingSpan instance
42
+ */
43
+ startSpan(name: string): TracingSpan;
44
+ /**
45
+ * Record custom metrics for an event.
46
+ *
47
+ * @param eventName - Name of the event
48
+ * @param metrics - Metrics to record (e.g., duration, count)
49
+ */
50
+ recordMetrics(eventName: string, metrics: Record<string, number>): void;
51
+ }
52
+ /**
53
+ * Event metrics recorder for monitoring event processing.
54
+ * @public
55
+ */
56
+ export interface EventMetricsRecorder {
57
+ /**
58
+ * Record event processing completion.
59
+ *
60
+ * @param eventName - Name of the event
61
+ * @param duration - Processing duration in milliseconds
62
+ * @param success - Whether processing was successful
63
+ */
64
+ recordEventProcessed(eventName: string, duration: number, success: boolean): void;
65
+ /**
66
+ * Record event publication.
67
+ *
68
+ * @param eventName - Name of the event
69
+ */
70
+ recordEventPublished(eventName: string): void;
71
+ /**
72
+ * Record event processing error.
73
+ *
74
+ * @param eventName - Name of the event
75
+ * @param error - The error that occurred
76
+ */
77
+ recordEventError(eventName: string, error: Error): void;
78
+ }
79
+ /**
80
+ * Worker metrics provider for monitoring worker pool operations.
81
+ * @public
82
+ */
83
+ export interface WorkerMetricsProvider {
84
+ /**
85
+ * Record worker pool startup.
86
+ *
87
+ * @param poolId - ID of the worker pool
88
+ */
89
+ recordWorkerStartup(poolId: string): void;
90
+ /**
91
+ * Record task execution in a worker pool.
92
+ *
93
+ * @param poolId - ID of the worker pool
94
+ * @param duration - Task duration in milliseconds
95
+ * @param success - Whether task execution was successful
96
+ */
97
+ recordTaskExecution(poolId: string, duration: number, success: boolean): void;
98
+ /**
99
+ * Record worker pool error.
100
+ *
101
+ * @param poolId - ID of the worker pool
102
+ * @param error - The error that occurred
103
+ */
104
+ recordWorkerError(poolId: string, error: Error): void;
105
+ }
106
+ /**
107
+ * Main observability provider interface combining all observability capabilities.
108
+ * @public
109
+ */
110
+ export interface ObservabilityProvider {
111
+ /**
112
+ * Event tracing provider (optional).
113
+ */
114
+ eventTracing?: EventTracingProvider;
115
+ /**
116
+ * Event metrics recorder (optional).
117
+ */
118
+ eventMetrics?: EventMetricsRecorder;
119
+ /**
120
+ * Worker metrics provider (optional).
121
+ */
122
+ workerMetrics?: WorkerMetricsProvider;
123
+ /**
124
+ * General tracing provider (optional).
125
+ */
126
+ tracing?: {
127
+ startSpan(name: string): TracingSpan;
128
+ };
129
+ }
130
+ /**
131
+ * Create a no-op observability provider.
132
+ * Used by default when no observability implementation is provided.
133
+ *
134
+ * @returns An ObservabilityProvider with all no-op implementations
135
+ * @internal
136
+ */
137
+ export declare function createNoOpObservabilityProvider(): ObservabilityProvider;
@@ -0,0 +1,349 @@
1
+ /**
2
+ * @gravito/core - Dead Letter Queue Manager
3
+ *
4
+ * 管理失敗事件的持久化存儲
5
+ * 支持 CRUD、重新入隊、批量重試和統計功能
6
+ */
7
+ import type { EventOptions } from '../events/EventOptions';
8
+ import type { RetryPolicy } from './RetryPolicy';
9
+ /**
10
+ * DLQ 事件的數據庫記錄
11
+ */
12
+ export interface DLQRecord {
13
+ id: number;
14
+ dlq_id: string;
15
+ event_name: string;
16
+ event_payload: unknown;
17
+ event_options: unknown;
18
+ attempt_count: number;
19
+ max_retries: number;
20
+ next_retry_at: string | null;
21
+ last_error: unknown;
22
+ status: 'pending' | 'requeued' | 'resolved' | 'abandoned';
23
+ resolution_notes: string | null;
24
+ failed_at: string;
25
+ created_at: string;
26
+ updated_at: string;
27
+ }
28
+ /**
29
+ * DLQ 事件查詢過濾選項(for DeadLetterQueueManager)
30
+ */
31
+ export interface DLQManagerFilter {
32
+ /** 按事件名稱篩選 */
33
+ eventName?: string;
34
+ /** 按狀態篩選 */
35
+ status?: 'pending' | 'requeued' | 'resolved' | 'abandoned';
36
+ /** 開始時間 */
37
+ from?: Date;
38
+ /** 結束時間 */
39
+ to?: Date;
40
+ /** 結果數量限制 */
41
+ limit?: number;
42
+ /** 分頁偏移 */
43
+ offset?: number;
44
+ }
45
+ /**
46
+ * DLQ 統計信息
47
+ */
48
+ export interface DLQStats {
49
+ /** 事件總數 */
50
+ total: number;
51
+ /** 按事件名稱的統計 */
52
+ byEvent: Record<string, number>;
53
+ /** 按狀態的統計 */
54
+ byStatus: Record<string, number>;
55
+ }
56
+ /**
57
+ * Dead Letter Queue 管理器
58
+ *
59
+ * 負責管理失敗事件的持久化存儲,支持:
60
+ * - 自動將失敗事件移至 DLQ
61
+ * - 查詢和篩選 DLQ 事件
62
+ * - 重新入隊單個或批量事件
63
+ * - 標記事件為已解決或已放棄
64
+ * - 查看統計信息
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * const db = container.make('db') as any
69
+ * const dlqManager = new DeadLetterQueueManager(db)
70
+ *
71
+ * // 將失敗事件移至 DLQ
72
+ * const dlqId = await dlqManager.moveToDlq(
73
+ * 'order:created',
74
+ * { orderId: '123' },
75
+ * { retry: {...} },
76
+ * error,
77
+ * 3
78
+ * )
79
+ *
80
+ * // 查詢 DLQ 事件
81
+ * const events = await dlqManager.list({ event: 'order:created', status: 'pending' })
82
+ *
83
+ * // 重新入隊
84
+ * await dlqManager.requeue(dlqId)
85
+ *
86
+ * // 批量重試
87
+ * const result = await dlqManager.retryBatch({ eventName: 'order:created' })
88
+ *
89
+ * // 統計
90
+ * const stats = await dlqManager.getStats()
91
+ * ```
92
+ */
93
+ export declare class DeadLetterQueueManager {
94
+ private db;
95
+ private retryEngine;
96
+ constructor(db: any);
97
+ /**
98
+ * 將失敗事件移至死信隊列
99
+ *
100
+ * @param eventName - 事件名稱
101
+ * @param payload - 事件負載
102
+ * @param options - 事件選項
103
+ * @param error - 導致失敗的錯誤
104
+ * @param attemptCount - 當前嘗試次數
105
+ * @param retryPolicy - 重試策略配置
106
+ * @returns DLQ 記錄的 UUID
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const dlqId = await dlqManager.moveToDlq(
111
+ * 'order:created',
112
+ * { orderId: 'ORD-123' },
113
+ * { retry: { maxRetries: 3, backoff: 'exponential' } },
114
+ * new Error('Service unavailable'),
115
+ * 3,
116
+ * { maxRetries: 3, backoff: 'exponential', initialDelayMs: 1000, maxDelayMs: 30000 }
117
+ * )
118
+ * ```
119
+ */
120
+ moveToDlq(eventName: string, payload: unknown, options: EventOptions, error: Error, attemptCount: number, retryPolicy?: RetryPolicy): Promise<string>;
121
+ /**
122
+ * 按 DLQ ID 獲取單個事件
123
+ *
124
+ * @param dlqId - DLQ 事件的 UUID
125
+ * @returns DLQ 記錄,若不存在則返回 undefined
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * const event = await dlqManager.getById('550e8400-e29b-41d4-a716-446655440000')
130
+ * if (event) {
131
+ * console.log(event.event_name, event.status)
132
+ * }
133
+ * ```
134
+ */
135
+ getById(dlqId: string): Promise<DLQRecord | undefined>;
136
+ /**
137
+ * 查詢 DLQ 事件
138
+ *
139
+ * @param filter - 查詢過濾條件
140
+ * @returns DLQ 記錄列表(按失敗時間倒序)
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * // 查詢特定事件的待處理事件
145
+ * const events = await dlqManager.list({
146
+ * eventName: 'order:created',
147
+ * status: 'pending',
148
+ * limit: 50
149
+ * })
150
+ *
151
+ * // 查詢時間範圍內的所有失敗事件
152
+ * const eventsInRange = await dlqManager.list({
153
+ * from: new Date('2026-02-01'),
154
+ * to: new Date('2026-02-03'),
155
+ * limit: 100
156
+ * })
157
+ * ```
158
+ */
159
+ list(filter?: DLQManagerFilter): Promise<DLQRecord[]>;
160
+ /**
161
+ * 重新入隊單個 DLQ 事件
162
+ *
163
+ * 重新入隊不會自動派發事件,而是標記狀態為 'requeued'
164
+ * 實際的事件派發應由調用者負責處理
165
+ *
166
+ * @param dlqId - DLQ 事件的 UUID
167
+ * @throws 如果事件不存在
168
+ *
169
+ * @example
170
+ * ```typescript
171
+ * const event = await dlqManager.getById(dlqId)
172
+ * if (event) {
173
+ * // 由調用者決定如何派發事件
174
+ * await eventSystem.doActionAsync(
175
+ * event.event_name,
176
+ * event.event_payload,
177
+ * event.event_options
178
+ * )
179
+ *
180
+ * // 標記為已重新入隊
181
+ * await dlqManager.requeue(dlqId)
182
+ * }
183
+ * ```
184
+ */
185
+ requeue(dlqId: string): Promise<void>;
186
+ /**
187
+ * 批量重新入隊 DLQ 事件
188
+ *
189
+ * @param filter - 查詢過濾條件
190
+ * @returns 包含處理結果的統計對象
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * const result = await dlqManager.retryBatch({
195
+ * eventName: 'order:created',
196
+ * status: 'pending'
197
+ * })
198
+ *
199
+ * console.log(`Success: ${result.succeeded}, Failed: ${result.failed}`)
200
+ * ```
201
+ */
202
+ retryBatch(filter?: DLQManagerFilter): Promise<{
203
+ total: number;
204
+ succeeded: number;
205
+ failed: number;
206
+ }>;
207
+ /**
208
+ * 標記 DLQ 事件為已解決
209
+ *
210
+ * @param dlqId - DLQ 事件的 UUID
211
+ * @param notes - 解決說明
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * await dlqManager.resolve(dlqId, 'Manual fix applied: Database issue resolved')
216
+ * ```
217
+ */
218
+ resolve(dlqId: string, notes?: string): Promise<void>;
219
+ /**
220
+ * 放棄 DLQ 事件(不再重試)
221
+ *
222
+ * @param dlqId - DLQ 事件的 UUID
223
+ * @param reason - 放棄原因
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * await dlqManager.abandon(dlqId, 'Data corrupted, cannot recover')
228
+ * ```
229
+ */
230
+ abandon(dlqId: string, reason?: string): Promise<void>;
231
+ /**
232
+ * 更新 DLQ 事件狀態
233
+ *
234
+ * @param dlqId - DLQ 事件的 UUID
235
+ * @param status - 新狀態
236
+ * @param notes - 狀態變更說明
237
+ * @throws 如果事件不存在
238
+ *
239
+ * @internal
240
+ */
241
+ updateStatus(dlqId: string, status: 'pending' | 'requeued' | 'resolved' | 'abandoned', notes?: string): Promise<void>;
242
+ /**
243
+ * 刪除單個 DLQ 事件
244
+ *
245
+ * @param dlqId - DLQ 事件的 UUID
246
+ * @returns true 如果刪除成功,false 如果事件不存在
247
+ *
248
+ * @example
249
+ * ```typescript
250
+ * const deleted = await dlqManager.deleteEntry(dlqId)
251
+ * if (deleted) {
252
+ * console.log('Event deleted')
253
+ * }
254
+ * ```
255
+ */
256
+ deleteEntry(dlqId: string): Promise<boolean>;
257
+ /**
258
+ * 刪除多個 DLQ 事件
259
+ *
260
+ * @param dlqIds - DLQ 事件 UUID 列表
261
+ * @returns 刪除的事件數量
262
+ *
263
+ * @example
264
+ * ```typescript
265
+ * const deletedCount = await dlqManager.deleteEntries([id1, id2, id3])
266
+ * ```
267
+ */
268
+ deleteEntries(dlqIds: string[]): Promise<number>;
269
+ /**
270
+ * 獲取 DLQ 統計信息
271
+ *
272
+ * @returns 包含總數、按事件名稱和狀態的統計信息
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * const stats = await dlqManager.getStats()
277
+ *
278
+ * console.log(`Total events: ${stats.total}`)
279
+ * console.log('By event:', stats.byEvent)
280
+ * // Output: { 'order:created': 145, 'payment:succeeded': 23 }
281
+ *
282
+ * console.log('By status:', stats.byStatus)
283
+ * // Output: { pending: 120, requeued: 15, resolved: 8, abandoned: 2 }
284
+ * ```
285
+ */
286
+ getStats(): Promise<DLQStats>;
287
+ /**
288
+ * 獲取某個事件名稱的 DLQ 事件數
289
+ *
290
+ * @param eventName - 事件名稱
291
+ * @returns 事件數量
292
+ *
293
+ * @example
294
+ * ```typescript
295
+ * const count = await dlqManager.getCountByEvent('order:created')
296
+ * ```
297
+ */
298
+ getCountByEvent(eventName: string): Promise<number>;
299
+ /**
300
+ * 清空所有 DLQ 事件(慎用!)
301
+ *
302
+ * @param includeResolved - 是否包含已解決的事件
303
+ * @returns 清空的事件數量
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * // 只清空待處理的事件
308
+ * const count = await dlqManager.clear(false)
309
+ *
310
+ * // 清空所有事件(包括已解決和已放棄)
311
+ * const countAll = await dlqManager.clear(true)
312
+ * ```
313
+ */
314
+ clear(includeResolved?: boolean): Promise<number>;
315
+ /**
316
+ * 通過 Bull Job ID 查找 DLQ 記錄
317
+ *
318
+ * 用於 MessageQueueBridge 集成:當 Bull Queue job 失敗時,
319
+ * 通過 Job ID 查找相應的 DLQ 記錄。
320
+ *
321
+ * @param bullJobId - Bull Queue Job ID
322
+ * @returns DLQ 記錄或 undefined
323
+ *
324
+ * @example
325
+ * ```typescript
326
+ * const record = await dlqManager.findByBullJobId('job-abc123')
327
+ * if (record) {
328
+ * console.log(`Event ${record.event_name} is in DLQ`)
329
+ * }
330
+ * ```
331
+ */
332
+ findByBullJobId(bullJobId: string): Promise<DLQRecord | undefined>;
333
+ /**
334
+ * 調度延遲重試(整合 Bull Queue delayed jobs)
335
+ *
336
+ * 從 DLQ 中提取事件,通過 Bull Queue 的延遲 job 功能進行重試。
337
+ *
338
+ * @param dlqId - DLQ 記錄 ID
339
+ * @param delayMs - 延遲時間(毫秒)
340
+ * @throws 如果記錄不存在
341
+ *
342
+ * @example
343
+ * ```typescript
344
+ * // 延遲 1 小時後重試
345
+ * await dlqManager.scheduleRetry('dlq-uuid-123', 3600000)
346
+ * ```
347
+ */
348
+ scheduleRetry(dlqId: string, delayMs: number): Promise<void>;
349
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * @gravito/core - Retry Policy
3
+ *
4
+ * 重試策略和退避算法的實現
5
+ * 支持指數和線性退避,包含 Jitter 防止雷鳴羊群
6
+ */
7
+ /**
8
+ * 重試策略配置接口
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const policy: RetryPolicy = {
13
+ * maxRetries: 3,
14
+ * backoff: 'exponential',
15
+ * initialDelayMs: 1000,
16
+ * maxDelayMs: 30000,
17
+ * dlqAfterMaxRetries: true
18
+ * }
19
+ * ```
20
+ */
21
+ export interface RetryPolicy {
22
+ /** 最大重試次數 */
23
+ maxRetries: number;
24
+ /** 退避策略:指數或線性 */
25
+ backoff: 'exponential' | 'linear';
26
+ /** 初始延遲時間(毫秒) */
27
+ initialDelayMs: number;
28
+ /** 最大延遲時間(毫秒) */
29
+ maxDelayMs: number;
30
+ /** 超過最大重試次數後是否發送到死信隊列 */
31
+ dlqAfterMaxRetries?: boolean;
32
+ }
33
+ /**
34
+ * 重試引擎
35
+ *
36
+ * 負責計算重試延遲、判斷是否應該重試等邏輯
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const engine = new RetryEngine()
41
+ * const delay = engine.calculateDelay(1, policy)
42
+ * const shouldRetry = engine.shouldRetry(3, policy)
43
+ * ```
44
+ */
45
+ export declare class RetryEngine {
46
+ /**
47
+ * 計算下次重試的延遲時間(毫秒)
48
+ *
49
+ * @param attemptCount - 當前嘗試次數(從 1 開始)
50
+ * @param policy - 重試策略配置
51
+ * @returns 延遲時間(毫秒)
52
+ *
53
+ * @description
54
+ * - 指數退避:delay = initialDelay * 2^(attemptCount - 1)
55
+ * - 線性退避:delay = initialDelay * attemptCount
56
+ * - 添加隨機抖動(Jitter),防止雷鳴羊群問題
57
+ * - 結果不超過 maxDelayMs
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const policy: RetryPolicy = {
62
+ * maxRetries: 3,
63
+ * backoff: 'exponential',
64
+ * initialDelayMs: 1000,
65
+ * maxDelayMs: 30000
66
+ * }
67
+ *
68
+ * // 第 1 次重試:1000ms * 2^0 = 1000ms (加抖動)
69
+ * const delay1 = engine.calculateDelay(1, policy) // ~1100ms
70
+ *
71
+ * // 第 2 次重試:1000ms * 2^1 = 2000ms (加抖動)
72
+ * const delay2 = engine.calculateDelay(2, policy) // ~2200ms
73
+ *
74
+ * // 第 3 次重試:1000ms * 2^2 = 4000ms (加抖動)
75
+ * const delay3 = engine.calculateDelay(3, policy) // ~4400ms
76
+ * ```
77
+ */
78
+ calculateDelay(attemptCount: number, policy: RetryPolicy): number;
79
+ /**
80
+ * 判斷是否應該重試
81
+ *
82
+ * @param attemptCount - 當前嘗試次數(從 1 開始)
83
+ * @param policy - 重試策略配置
84
+ * @returns 是否應該重試
85
+ *
86
+ * @description
87
+ * 當 attemptCount < maxRetries 時返回 true
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const policy = { maxRetries: 3, ... }
92
+ *
93
+ * engine.shouldRetry(1, policy) // true(1 < 3)
94
+ * engine.shouldRetry(3, policy) // false(3 >= 3)
95
+ * engine.shouldRetry(4, policy) // false(4 >= 3)
96
+ * ```
97
+ */
98
+ shouldRetry(attemptCount: number, policy: RetryPolicy): boolean;
99
+ /**
100
+ * 獲取退避時間(包含延遲計算和 Jitter)
101
+ *
102
+ * @param retryCount - 重試次數(從 0 開始)
103
+ * @param policy - 重試策略配置
104
+ * @returns 退避時間(毫秒)
105
+ *
106
+ * @description
107
+ * 這是 calculateDelay 的別名,但接收的是從 0 開始的重試計數
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * const policy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
112
+ *
113
+ * // 第 0 次重試(第 1 次嘗試失敗)
114
+ * const time1 = engine.getBackoffTime(0, policy) // ~1100ms
115
+ *
116
+ * // 第 1 次重試(第 2 次嘗試失敗)
117
+ * const time2 = engine.getBackoffTime(1, policy) // ~2200ms
118
+ * ```
119
+ */
120
+ getBackoffTime(retryCount: number, policy: RetryPolicy): number;
121
+ /**
122
+ * 計算下次重試的絕對時間
123
+ *
124
+ * @param retryCount - 重試次數(從 0 開始)
125
+ * @param policy - 重試策略配置
126
+ * @param baseTime - 基礎時間戳(默認為當前時間)
127
+ * @returns 下次重試的時間戳(毫秒)
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const policy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
132
+ *
133
+ * const now = Date.now()
134
+ * const nextRetryTime = engine.getNextRetryTime(0, policy, now)
135
+ * // 返回大約 now + 1000 + jitter
136
+ * ```
137
+ */
138
+ getNextRetryTime(retryCount: number, policy: RetryPolicy, baseTime?: number): number;
139
+ /**
140
+ * 驗證重試策略配置
141
+ *
142
+ * @param policy - 重試策略配置
143
+ * @returns 是否有效
144
+ *
145
+ * @description
146
+ * 檢查配置是否合理:
147
+ * - maxRetries >= 0
148
+ * - initialDelayMs > 0
149
+ * - maxDelayMs >= initialDelayMs
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * const validPolicy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
154
+ * engine.isValidPolicy(validPolicy) // true
155
+ *
156
+ * const invalidPolicy = { maxRetries: 3, initialDelayMs: 5000, maxDelayMs: 1000, backoff: 'exponential' }
157
+ * engine.isValidPolicy(invalidPolicy) // false (maxDelayMs < initialDelayMs)
158
+ * ```
159
+ */
160
+ isValidPolicy(policy: RetryPolicy): boolean;
161
+ /**
162
+ * 獲取人類可讀的重試信息
163
+ *
164
+ * @param attemptCount - 當前嘗試次數(從 1 開始)
165
+ * @param policy - 重試策略配置
166
+ * @returns 描述性文本
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const policy = { maxRetries: 3, initialDelayMs: 1000, maxDelayMs: 30000, backoff: 'exponential' }
171
+ *
172
+ * engine.getRetryInfo(1, policy) // "Retry 1 of 3, will retry in ~1100ms"
173
+ * engine.getRetryInfo(3, policy) // "Retry 3 of 3 (final attempt), will retry in ~4400ms"
174
+ * engine.getRetryInfo(4, policy) // "Max retries exceeded (4 >= 3)"
175
+ * ```
176
+ */
177
+ getRetryInfo(attemptCount: number, policy: RetryPolicy): string;
178
+ }
179
+ /**
180
+ * 創建默認的重試策略
181
+ *
182
+ * @returns 默認重試策略
183
+ *
184
+ * @description
185
+ * 默認配置:
186
+ * - 最多重試 3 次
187
+ * - 指數退避
188
+ * - 初始延遲 1 秒
189
+ * - 最大延遲 30 秒
190
+ * - 超過最大重試後發送 DLQ
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * const policy = getDefaultRetryPolicy()
195
+ * // { maxRetries: 3, backoff: 'exponential', initialDelayMs: 1000, maxDelayMs: 30000, dlqAfterMaxRetries: true }
196
+ * ```
197
+ */
198
+ export declare function getDefaultRetryPolicy(): RetryPolicy;
199
+ /**
200
+ * 為不同類型的操作獲取預設的重試策略
201
+ *
202
+ * @param type - 操作類型
203
+ * @returns 推薦的重試策略
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * // 外部 API 調用:更多重試,更長延遲
208
+ * const apiPolicy = getPresetRetryPolicy('external-api')
209
+ *
210
+ * // 數據庫操作:較少重試,短延遲
211
+ * const dbPolicy = getPresetRetryPolicy('database')
212
+ *
213
+ * // 消息隊列:適中重試
214
+ * const mqPolicy = getPresetRetryPolicy('message-queue')
215
+ * ```
216
+ */
217
+ export declare function getPresetRetryPolicy(type: 'external-api' | 'database' | 'message-queue' | 'default'): RetryPolicy;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Reliability and retry exports.
3
+ * @packageDocumentation
4
+ */
5
+ export { DeadLetterQueueManager, type DLQManagerFilter, type DLQRecord, type DLQStats, } from './DeadLetterQueueManager';
6
+ export { getDefaultRetryPolicy, getPresetRetryPolicy, RetryEngine, type RetryPolicy, } from './RetryPolicy';