@gravito/core 1.6.1 → 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 (173) 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 +576 -647
  53. package/dist/engine/index.cjs.map +22 -0
  54. package/dist/engine/index.d.ts +14 -910
  55. package/dist/engine/index.js +576 -623
  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-CI8hiulX.d.cts → http/types.d.ts} +29 -16
  129. package/dist/index.browser.d.ts +34 -0
  130. package/dist/index.cjs +10525 -11171
  131. package/dist/index.cjs.map +168 -0
  132. package/dist/index.d.ts +58 -10981
  133. package/dist/index.js +10861 -10997
  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 +21 -52
  167. package/src/ffi/native/cbor.c +1148 -0
  168. package/dist/Metrics-VOWWRNNR.js +0 -219
  169. package/dist/chunk-R5U7XKVJ.js +0 -16
  170. package/dist/compat-CI8hiulX.d.ts +0 -376
  171. package/dist/compat.d.cts +0 -1
  172. package/dist/engine/index.d.cts +0 -922
  173. package/dist/index.d.cts +0 -11008
@@ -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
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Event dispatch options for async event handling.
3
+ * @public
4
+ */
5
+ export interface EventOptions {
6
+ /**
7
+ * Whether to dispatch the event asynchronously.
8
+ * @default false
9
+ */
10
+ async?: boolean;
11
+ /**
12
+ * Priority level for event processing.
13
+ * - 'critical': Immediate processing, bypass queue (< 1ms)
14
+ * - 'high': High priority events (< 50ms)
15
+ * - 'normal': Standard events (< 200ms)
16
+ * - 'low': Non-critical events (< 500ms)
17
+ * @default 'normal'
18
+ */
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
+ };
57
+ /**
58
+ * Execution timeout in milliseconds.
59
+ * If a listener exceeds this timeout, it will be terminated.
60
+ * @default 5000
61
+ */
62
+ timeout?: number;
63
+ /**
64
+ * Ordering guarantee strategy.
65
+ * - 'strict': Global strict ordering (slow, serialized)
66
+ * - 'partition': Partition-based ordering (recommended, balanced)
67
+ * - 'none': No ordering guarantee (fastest, parallel)
68
+ * @default 'none'
69
+ */
70
+ ordering?: 'strict' | 'partition' | 'none';
71
+ /**
72
+ * Partition key for partition-based ordering.
73
+ * Events with the same partition key are processed in order.
74
+ * Only used when ordering is 'partition'.
75
+ * @example 'order:123' or 'user:456'
76
+ */
77
+ partitionKey?: string;
78
+ /**
79
+ * Idempotency key for deduplication.
80
+ * Events with the same idempotency key within the TTL window
81
+ * will be processed only once.
82
+ * @example 'order:123:created'
83
+ */
84
+ idempotencyKey?: string;
85
+ /**
86
+ * Time-to-live for idempotency key in milliseconds.
87
+ * @default 3600000 (1 hour)
88
+ */
89
+ ttl?: number;
90
+ /**
91
+ * Retry policy for failed event processing.
92
+ */
93
+ retry?: {
94
+ /**
95
+ * Maximum number of retry attempts.
96
+ * @default 0
97
+ */
98
+ maxRetries?: number;
99
+ /**
100
+ * Backoff strategy for retries.
101
+ * - 'exponential': Delay doubles with each retry (1s, 2s, 4s, 8s...)
102
+ * - 'linear': Fixed delay between retries
103
+ * @default 'exponential'
104
+ */
105
+ backoff?: 'exponential' | 'linear';
106
+ /**
107
+ * Initial delay in milliseconds before first retry.
108
+ * @default 1000
109
+ */
110
+ initialDelayMs?: number;
111
+ /**
112
+ * Maximum delay in milliseconds between retries.
113
+ * @default 30000
114
+ */
115
+ maxDelayMs?: number;
116
+ /**
117
+ * Whether to send failed events to Dead Letter Queue after max retries.
118
+ * @default false
119
+ */
120
+ dlqAfterMaxRetries?: boolean;
121
+ };
122
+ /**
123
+ * Circuit breaker options for this event.
124
+ */
125
+ circuitBreaker?: {
126
+ /**
127
+ * Number of consecutive failures before opening the circuit.
128
+ * @default 5
129
+ */
130
+ failureThreshold?: number;
131
+ /**
132
+ * Time in milliseconds to wait before attempting to close the circuit.
133
+ * @default 30000
134
+ */
135
+ resetTimeout?: number;
136
+ /**
137
+ * Number of test requests to allow in half-open state.
138
+ * @default 3
139
+ */
140
+ halfOpenRequests?: number;
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
+ };
199
+ }
200
+ /**
201
+ * Default event options.
202
+ * @internal
203
+ */
204
+ export declare const DEFAULT_EVENT_OPTIONS: Required<EventOptions>;
@@ -0,0 +1,63 @@
1
+ import type { Span } from '@opentelemetry/api';
2
+ import type { ActionCallback } from '../HookManager';
3
+ import type { BackpressureManager } from './BackpressureManager';
4
+ import type { DeadLetterQueue } from './DeadLetterQueue';
5
+ import type { EventBackend } from './EventBackend';
6
+ import type { EventOptions } from './EventOptions';
7
+ import type { EventMetrics } from './observability/EventMetrics';
8
+ import type { EventTracing } from './observability/EventTracing';
9
+ import type { OTelEventMetrics } from './observability/OTelEventMetrics';
10
+ import type { PriorityStatistics } from './PriorityEscalationManager';
11
+ import type { RetryScheduler } from './RetryScheduler';
12
+ import type { BackpressureStrategy, EventQueueConfig, EventTask, MultiPriorityQueueDepth } from './types';
13
+ import type { WorkerPool } from './WorkerPool';
14
+ export type { EventTask, EventQueueConfig, BackpressureStrategy };
15
+ /**
16
+ * Priority queue for event processing.
17
+ * Events are processed based on their priority level:
18
+ * - Critical priority events are processed first (< 1ms)
19
+ * - High priority events are processed second (< 50ms)
20
+ * - Normal priority events are processed third (< 200ms)
21
+ * - Low priority events are processed last (< 500ms)
22
+ *
23
+ * Supports automatic priority escalation based on wait time.
24
+ *
25
+ * Composed of:
26
+ * - {@link QueueCore}: queue data structures and backpressure logic
27
+ * - {@link TaskExecutor}: task execution, retry, circuit breaker, DLQ
28
+ *
29
+ * @internal
30
+ */
31
+ export declare class EventPriorityQueue implements EventBackend {
32
+ private queueCore;
33
+ private taskExecutor;
34
+ private processing;
35
+ private workerPool?;
36
+ constructor(config?: EventQueueConfig);
37
+ setDeadLetterQueue(dlq: DeadLetterQueue): void;
38
+ setPersistentDLQHandler(handler: (hook: string, args: unknown, options: EventOptions, error: Error, retryCount: number, firstFailedAt: number) => Promise<void>): void;
39
+ setEventMetrics(metrics: EventMetrics): void;
40
+ setOTelEventMetrics(metrics: OTelEventMetrics): void;
41
+ setPriorityStatistics(stats: PriorityStatistics): void;
42
+ getPriorityStatistics(): PriorityStatistics | undefined;
43
+ setEventTracing(tracing: EventTracing): void;
44
+ setCurrentDispatchSpan(span: Span | undefined): void;
45
+ getCurrentDispatchSpan(): Span | undefined;
46
+ setRetryScheduler(scheduler: RetryScheduler): void;
47
+ getRetryScheduler(): RetryScheduler | undefined;
48
+ getCircuitBreaker(hook: string): import("./CircuitBreaker").CircuitBreaker;
49
+ getCircuitBreakers(): Map<string, import("./CircuitBreaker").CircuitBreaker>;
50
+ resetCircuitBreaker(hook: string): boolean;
51
+ setWorkerPool(pool: WorkerPool): void;
52
+ getWorkerPool(): WorkerPool | undefined;
53
+ getBackpressureManager(): BackpressureManager | undefined;
54
+ enqueue(task: EventTask): string;
55
+ enqueue(hook: string, args: unknown, callbacks: ActionCallback[], options: EventOptions): string;
56
+ enqueueBatch(tasks: EventTask[]): string[];
57
+ getDepth(): number;
58
+ getDepthByPriority(priority: 'critical' | 'high' | 'normal' | 'low'): number;
59
+ getQueueDepthByPriority(): MultiPriorityQueueDepth;
60
+ clear(): void;
61
+ dequeue(): EventTask | undefined;
62
+ private processNext;
63
+ }
@@ -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,60 @@
1
+ /**
2
+ * Idempotency cache for deduplicating events.
3
+ * Prevents duplicate events from being processed within a configurable TTL window.
4
+ * @internal
5
+ */
6
+ export declare class IdempotencyCache {
7
+ private cache;
8
+ private cleanupInterval;
9
+ private readonly defaultCleanupIntervalMs;
10
+ constructor();
11
+ /**
12
+ * Check if an event with the given idempotency key is a duplicate.
13
+ * @param key - Idempotency key
14
+ * @param ttlMs - Time-to-live in milliseconds
15
+ * @returns True if this is a duplicate, false if it's a new event
16
+ */
17
+ isDuplicate(key: string, ttlMs: number): boolean;
18
+ /**
19
+ * Record an event in the cache.
20
+ * @param key - Idempotency key
21
+ */
22
+ recordEvent(key: string): void;
23
+ /**
24
+ * Remove an entry from the cache.
25
+ * @param key - Idempotency key
26
+ * @returns True if entry was removed, false if not found
27
+ */
28
+ remove(key: string): boolean;
29
+ /**
30
+ * Clear all entries from the cache.
31
+ */
32
+ clear(): void;
33
+ /**
34
+ * Get the current cache size.
35
+ * @returns Number of entries in cache
36
+ */
37
+ getSize(): number;
38
+ /**
39
+ * Start periodic cleanup of expired entries.
40
+ * @internal
41
+ */
42
+ private startCleanup;
43
+ /**
44
+ * Stop the periodic cleanup.
45
+ * @internal
46
+ */
47
+ stopCleanup(): void;
48
+ /**
49
+ * Clean up expired entries from the cache.
50
+ * This is called periodically and doesn't use strict TTL checking,
51
+ * so entries older than a reasonable default (24 hours) are removed.
52
+ * @internal
53
+ */
54
+ private cleanup;
55
+ /**
56
+ * Destructor to clean up resources.
57
+ * @internal
58
+ */
59
+ destroy(): void;
60
+ }