@gravito/ripple 4.0.0 → 4.0.3

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 (225) hide show
  1. package/README.md +26 -10
  2. package/dist/{ripple/src/OrbitRipple.d.ts → OrbitRipple.d.ts} +1 -0
  3. package/dist/{ripple/src/RippleServer.d.ts → RippleServer.d.ts} +32 -2
  4. package/dist/core/src/Application.d.ts +41 -0
  5. package/dist/core/src/ConfigManager.d.ts +39 -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 +45 -0
  9. package/dist/core/src/ErrorHandler.d.ts +3 -0
  10. package/dist/core/src/HookManager.d.ts +104 -165
  11. package/dist/core/src/PlanetCore.d.ts +114 -1
  12. package/dist/core/src/RequestContext.d.ts +97 -0
  13. package/dist/core/src/Router.d.ts +32 -46
  14. package/dist/core/src/ServiceProvider.d.ts +22 -0
  15. package/dist/core/src/adapters/bun/BunContext.d.ts +10 -1
  16. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +35 -0
  17. package/dist/core/src/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  18. package/dist/core/src/adapters/bun/RadixRouter.d.ts +1 -0
  19. package/dist/core/src/adapters/bun/index.d.ts +7 -0
  20. package/dist/core/src/binary/BinaryUtils.d.ts +105 -0
  21. package/dist/core/src/binary/index.d.ts +5 -0
  22. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  23. package/dist/core/src/compat/async-local-storage.d.ts +7 -0
  24. package/dist/core/src/compat/crypto.d.ts +6 -0
  25. package/dist/core/src/engine/AOTRouter.d.ts +16 -1
  26. package/dist/core/src/engine/FastContext.d.ts +42 -1
  27. package/dist/core/src/engine/Gravito.d.ts +13 -19
  28. package/dist/core/src/engine/MinimalContext.d.ts +23 -0
  29. package/dist/core/src/engine/analyzer.d.ts +92 -6
  30. package/dist/core/src/engine/types.d.ts +6 -0
  31. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  32. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  33. package/dist/core/src/events/DeadLetterQueue.d.ts +75 -1
  34. package/dist/core/src/events/EventBackend.d.ts +2 -1
  35. package/dist/core/src/events/EventOptions.d.ts +99 -4
  36. package/dist/core/src/events/EventPriorityQueue.d.ts +36 -175
  37. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  38. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  39. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  40. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  41. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  42. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  43. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  44. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  45. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  46. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  47. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  48. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  49. package/dist/core/src/events/index.d.ts +18 -6
  50. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +92 -0
  51. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  52. package/dist/core/src/events/observability/index.d.ts +4 -0
  53. package/dist/core/src/events/queue-core.d.ts +77 -0
  54. package/dist/core/src/events/task-executor.d.ts +51 -0
  55. package/dist/core/src/events/types.d.ts +59 -0
  56. package/dist/core/src/ffi/NativeAccelerator.d.ts +62 -0
  57. package/dist/core/src/ffi/NativeHasher.d.ts +139 -0
  58. package/dist/core/src/ffi/cbor-fallback.d.ts +96 -0
  59. package/dist/core/src/ffi/hash-fallback.d.ts +33 -0
  60. package/dist/core/src/ffi/index.d.ts +10 -0
  61. package/dist/core/src/ffi/types.d.ts +135 -0
  62. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  63. package/dist/core/src/helpers/Str.d.ts +15 -0
  64. package/dist/core/src/hooks/ActionManager.d.ts +132 -0
  65. package/dist/core/src/hooks/AsyncDetector.d.ts +84 -0
  66. package/dist/core/src/hooks/FilterManager.d.ts +71 -0
  67. package/dist/core/src/hooks/MigrationWarner.d.ts +24 -0
  68. package/dist/core/src/hooks/dlq-operations.d.ts +60 -0
  69. package/dist/core/src/hooks/types.d.ts +107 -0
  70. package/dist/core/src/http/CookieJar.d.ts +2 -2
  71. package/dist/core/src/http/types.d.ts +43 -3
  72. package/dist/core/src/index.d.ts +504 -15
  73. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  74. package/dist/core/src/observability/contracts.d.ts +137 -0
  75. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +36 -3
  76. package/dist/core/src/runtime/adapter-bun.d.ts +12 -0
  77. package/dist/core/src/runtime/adapter-deno.d.ts +12 -0
  78. package/dist/core/src/runtime/adapter-node.d.ts +12 -0
  79. package/dist/core/src/runtime/adapter-unknown.d.ts +13 -0
  80. package/dist/core/src/runtime/archive.d.ts +17 -0
  81. package/dist/core/src/runtime/compression.d.ts +21 -0
  82. package/dist/core/src/runtime/deep-equals.d.ts +56 -0
  83. package/dist/core/src/runtime/detection.d.ts +22 -0
  84. package/dist/core/src/runtime/escape.d.ts +34 -0
  85. package/dist/core/src/runtime/index.d.ts +44 -0
  86. package/dist/core/src/runtime/markdown.d.ts +44 -0
  87. package/dist/core/src/runtime/types.d.ts +436 -0
  88. package/dist/core/src/runtime-helpers.d.ts +67 -0
  89. package/dist/core/src/runtime.d.ts +10 -118
  90. package/dist/core/src/testing/HttpTester.d.ts +1 -0
  91. package/dist/core/src/transpiler-utils.d.ts +170 -0
  92. package/dist/{ripple/src/engines → engines}/BunEngine.d.ts +11 -0
  93. package/dist/engines/UWebSocketsEngine.d.ts +97 -0
  94. package/dist/engines/WsEngine.d.ts +69 -0
  95. package/dist/{ripple/src/engines → engines}/index.d.ts +4 -0
  96. package/dist/index.js +1 -7139
  97. package/dist/index.js.map +3 -69
  98. package/dist/{ripple/src/serializers → serializers}/ISerializer.d.ts +1 -1
  99. package/dist/{ripple/src/serializers → serializers}/JsonSerializer.d.ts +1 -1
  100. package/dist/{ripple/src/serializers → serializers}/ProtobufSerializer.d.ts +6 -3
  101. package/dist/{ripple/src/types.d.ts → types.d.ts} +11 -0
  102. package/package.json +7 -2
  103. package/dist/atlas/src/DB.d.ts +0 -301
  104. package/dist/atlas/src/OrbitAtlas.d.ts +0 -9
  105. package/dist/atlas/src/config/defineConfig.d.ts +0 -14
  106. package/dist/atlas/src/config/index.d.ts +0 -7
  107. package/dist/atlas/src/config/loadConfig.d.ts +0 -48
  108. package/dist/atlas/src/connection/Connection.d.ts +0 -108
  109. package/dist/atlas/src/connection/ConnectionManager.d.ts +0 -111
  110. package/dist/atlas/src/drivers/BunSQLDriver.d.ts +0 -32
  111. package/dist/atlas/src/drivers/BunSQLPreparedStatement.d.ts +0 -118
  112. package/dist/atlas/src/drivers/MongoDBDriver.d.ts +0 -36
  113. package/dist/atlas/src/drivers/MySQLDriver.d.ts +0 -66
  114. package/dist/atlas/src/drivers/PostgresDriver.d.ts +0 -83
  115. package/dist/atlas/src/drivers/RedisDriver.d.ts +0 -43
  116. package/dist/atlas/src/drivers/SQLiteDriver.d.ts +0 -45
  117. package/dist/atlas/src/drivers/types.d.ts +0 -260
  118. package/dist/atlas/src/errors/index.d.ts +0 -45
  119. package/dist/atlas/src/grammar/Grammar.d.ts +0 -342
  120. package/dist/atlas/src/grammar/MongoGrammar.d.ts +0 -47
  121. package/dist/atlas/src/grammar/MySQLGrammar.d.ts +0 -54
  122. package/dist/atlas/src/grammar/NullGrammar.d.ts +0 -35
  123. package/dist/atlas/src/grammar/PostgresGrammar.d.ts +0 -62
  124. package/dist/atlas/src/grammar/SQLiteGrammar.d.ts +0 -32
  125. package/dist/atlas/src/index.d.ts +0 -67
  126. package/dist/atlas/src/migration/Migration.d.ts +0 -64
  127. package/dist/atlas/src/migration/MigrationRepository.d.ts +0 -65
  128. package/dist/atlas/src/migration/Migrator.d.ts +0 -110
  129. package/dist/atlas/src/migration/index.d.ts +0 -6
  130. package/dist/atlas/src/observability/AtlasMetrics.d.ts +0 -11
  131. package/dist/atlas/src/observability/AtlasObservability.d.ts +0 -15
  132. package/dist/atlas/src/observability/AtlasTracer.d.ts +0 -12
  133. package/dist/atlas/src/observability/index.d.ts +0 -9
  134. package/dist/atlas/src/orm/index.d.ts +0 -5
  135. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +0 -121
  136. package/dist/atlas/src/orm/model/Model.d.ts +0 -449
  137. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +0 -20
  138. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +0 -136
  139. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +0 -36
  140. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +0 -87
  141. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +0 -117
  142. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +0 -64
  143. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +0 -15
  144. package/dist/atlas/src/orm/model/concerns/index.d.ts +0 -12
  145. package/dist/atlas/src/orm/model/decorators.d.ts +0 -109
  146. package/dist/atlas/src/orm/model/errors.d.ts +0 -52
  147. package/dist/atlas/src/orm/model/index.d.ts +0 -10
  148. package/dist/atlas/src/orm/model/relationships.d.ts +0 -207
  149. package/dist/atlas/src/orm/model/types.d.ts +0 -12
  150. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +0 -123
  151. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +0 -54
  152. package/dist/atlas/src/orm/schema/index.d.ts +0 -6
  153. package/dist/atlas/src/orm/schema/types.d.ts +0 -85
  154. package/dist/atlas/src/query/Expression.d.ts +0 -60
  155. package/dist/atlas/src/query/NPlusOneDetector.d.ts +0 -10
  156. package/dist/atlas/src/query/QueryBuilder.d.ts +0 -573
  157. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +0 -51
  158. package/dist/atlas/src/query/clauses/HavingClause.d.ts +0 -70
  159. package/dist/atlas/src/query/clauses/JoinClause.d.ts +0 -87
  160. package/dist/atlas/src/query/clauses/LimitClause.d.ts +0 -82
  161. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +0 -69
  162. package/dist/atlas/src/query/clauses/SelectClause.d.ts +0 -71
  163. package/dist/atlas/src/query/clauses/WhereClause.d.ts +0 -167
  164. package/dist/atlas/src/query/clauses/index.d.ts +0 -11
  165. package/dist/atlas/src/schema/Blueprint.d.ts +0 -276
  166. package/dist/atlas/src/schema/ColumnDefinition.d.ts +0 -154
  167. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +0 -37
  168. package/dist/atlas/src/schema/Schema.d.ts +0 -131
  169. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +0 -23
  170. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +0 -26
  171. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +0 -28
  172. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +0 -97
  173. package/dist/atlas/src/schema/grammars/index.d.ts +0 -7
  174. package/dist/atlas/src/schema/index.d.ts +0 -8
  175. package/dist/atlas/src/seed/Factory.d.ts +0 -90
  176. package/dist/atlas/src/seed/Seeder.d.ts +0 -28
  177. package/dist/atlas/src/seed/SeederRunner.d.ts +0 -74
  178. package/dist/atlas/src/seed/index.d.ts +0 -6
  179. package/dist/atlas/src/types/index.d.ts +0 -1100
  180. package/dist/atlas/src/utils/levenshtein.d.ts +0 -9
  181. package/dist/core/src/adapters/PhotonAdapter.d.ts +0 -171
  182. package/dist/core/src/adapters/photon-types.d.ts +0 -73
  183. package/dist/core/src/http/middleware/BodySizeLimit.d.ts +0 -16
  184. package/dist/core/src/http/middleware/Cors.d.ts +0 -24
  185. package/dist/core/src/http/middleware/Csrf.d.ts +0 -23
  186. package/dist/core/src/http/middleware/HeaderTokenGate.d.ts +0 -28
  187. package/dist/core/src/http/middleware/SecurityHeaders.d.ts +0 -29
  188. package/dist/core/src/http/middleware/ThrottleRequests.d.ts +0 -18
  189. package/dist/core/src/instrumentation/index.d.ts +0 -35
  190. package/dist/core/src/instrumentation/opentelemetry.d.ts +0 -178
  191. package/dist/core/src/instrumentation/types.d.ts +0 -182
  192. package/dist/photon/src/index.d.ts +0 -84
  193. package/dist/photon/src/middleware/binary.d.ts +0 -31
  194. package/dist/photon/src/middleware/htmx.d.ts +0 -39
  195. package/dist/photon/src/middleware/ratelimit.d.ts +0 -157
  196. package/dist/photon/src/openapi.d.ts +0 -19
  197. /package/dist/{ripple/src/channels → channels}/Channel.d.ts +0 -0
  198. /package/dist/{ripple/src/channels → channels}/ChannelManager.d.ts +0 -0
  199. /package/dist/{ripple/src/channels → channels}/index.d.ts +0 -0
  200. /package/dist/{ripple/src/drivers → drivers}/LocalDriver.d.ts +0 -0
  201. /package/dist/{ripple/src/drivers → drivers}/NATSDriver.d.ts +0 -0
  202. /package/dist/{ripple/src/drivers → drivers}/RedisDriver.d.ts +0 -0
  203. /package/dist/{ripple/src/drivers → drivers}/index.d.ts +0 -0
  204. /package/dist/{ripple/src/engines → engines}/IRippleEngine.d.ts +0 -0
  205. /package/dist/{ripple/src/errors → errors}/RippleError.d.ts +0 -0
  206. /package/dist/{ripple/src/errors → errors}/index.d.ts +0 -0
  207. /package/dist/{ripple/src/events → events}/BroadcastEvent.d.ts +0 -0
  208. /package/dist/{ripple/src/events → events}/BroadcastManager.d.ts +0 -0
  209. /package/dist/{ripple/src/events → events}/Broadcaster.d.ts +0 -0
  210. /package/dist/{ripple/src/events → events}/index.d.ts +0 -0
  211. /package/dist/{ripple/src/health → health}/HealthChecker.d.ts +0 -0
  212. /package/dist/{ripple/src/health → health}/index.d.ts +0 -0
  213. /package/dist/{ripple/src/index.d.ts → index.d.ts} +0 -0
  214. /package/dist/{ripple/src/logging → logging}/Logger.d.ts +0 -0
  215. /package/dist/{ripple/src/logging → logging}/index.d.ts +0 -0
  216. /package/dist/{ripple/src/middleware → middleware}/InterceptorManager.d.ts +0 -0
  217. /package/dist/{ripple/src/observability → observability}/RippleMetrics.d.ts +0 -0
  218. /package/dist/{ripple/src/reliability → reliability}/AckManager.d.ts +0 -0
  219. /package/dist/{ripple/src/serializers → serializers}/index.d.ts +0 -0
  220. /package/dist/{ripple/src/tracking → tracking}/ConnectionTracker.d.ts +0 -0
  221. /package/dist/{ripple/src/tracking → tracking}/SessionManager.d.ts +0 -0
  222. /package/dist/{ripple/src/tracking → tracking}/index.d.ts +0 -0
  223. /package/dist/{ripple/src/utils → utils}/MessageSerializer.d.ts +0 -0
  224. /package/dist/{ripple/src/utils → utils}/TokenBucket.d.ts +0 -0
  225. /package/dist/{ripple/src/utils → utils}/index.d.ts +0 -0
@@ -1,129 +1,32 @@
1
- import type { ConnectionContract } from '@gravito/atlas';
2
- import { type CircuitBreakerOptions } from './events/CircuitBreaker';
3
1
  import { DeadLetterQueue } from './events/DeadLetterQueue';
4
2
  import type { EventBackend } from './events/EventBackend';
5
3
  import type { EventOptions } from './events/EventOptions';
6
- import { EventPriorityQueue, type EventQueueConfig } from './events/EventPriorityQueue';
4
+ import { EventPriorityQueue } from './events/EventPriorityQueue';
7
5
  import { DeadLetterQueueManager } from './reliability/DeadLetterQueueManager';
6
+ export type { ActionCallback, FilterCallback, HookManagerConfig, ListenerInfo, ListenerOptions, } from './hooks/types';
7
+ import type { ActionCallback, FilterCallback, HookManagerConfig, ListenerInfo, ListenerOptions } from './hooks/types';
8
8
  /**
9
- * Callback function for filters (transforms values).
9
+ * Manager for WordPress-style hooks (actions and filters).
10
+ *
11
+ * 此為 facade 類別,將職責委派給專門的管理器:
12
+ * - FilterManager:處理 filter hook 的登記與執行
13
+ * - ActionManager:處理 action hook 的登記與執行
14
+ * - AsyncDetector:非同步偵測快取
15
+ * - MigrationWarner:遷移警告管理
16
+ *
10
17
  * @public
11
18
  */
12
- export type FilterCallback<T = unknown> = (value: T, ...args: unknown[]) => Promise<T> | T;
13
- /**
14
- * Callback function for actions (side effects).
15
- * @public
16
- */
17
- export type ActionCallback<TArgs = unknown> = (args: TArgs) => Promise<void> | void;
18
- /**
19
- * Options for listener registration.
20
- * @public
21
- */
22
- export interface ListenerOptions {
23
- /**
24
- * Explicitly specify the listener type.
25
- * - 'sync': Force synchronous dispatch for this listener
26
- * - 'async': Force asynchronous dispatch for this listener
27
- * - 'auto': Auto-detect based on function signature (default)
28
- * @default 'auto'
29
- */
30
- type?: 'sync' | 'async' | 'auto';
31
- /**
32
- * Circuit breaker configuration for this listener.
33
- */
34
- circuitBreaker?: CircuitBreakerOptions;
35
- }
36
- /**
37
- * Information about a registered listener.
38
- * @public
39
- */
40
- export interface ListenerInfo {
41
- /**
42
- * The callback function.
43
- */
44
- callback: ActionCallback;
45
- /**
46
- * Whether the listener is considered async.
47
- */
48
- isAsync: boolean;
49
- /**
50
- * The explicit type override, if any.
51
- */
52
- typeOverride?: 'sync' | 'async' | 'auto';
53
- }
54
- /**
55
- * Configuration for HookManager.
56
- * @public
57
- */
58
- export interface HookManagerConfig {
59
- /**
60
- * Enable async event dispatch by default.
61
- * When true, doAction() will automatically use async dispatch if any listener is async.
62
- * @default false
63
- */
64
- asyncByDefault?: boolean;
65
- /**
66
- * Migration mode for backward compatibility.
67
- * - 'sync': All events use synchronous dispatch (legacy mode)
68
- * - 'hybrid': Auto-detect and use async for async listeners (recommended)
69
- * - 'async': All events use async dispatch (future mode)
70
- * @default 'sync'
71
- */
72
- migrationMode?: 'sync' | 'hybrid' | 'async';
73
- /**
74
- * Enable deprecation warnings for synchronous event dispatch.
75
- * @default false
76
- */
77
- showDeprecationWarnings?: boolean;
78
- /**
79
- * Enable Dead Letter Queue for failed events.
80
- * @default true
81
- */
82
- enableDLQ?: boolean;
83
- /**
84
- * Configuration for the event priority queue (Backpressure).
85
- */
86
- queue?: EventQueueConfig;
87
- /**
88
- * Custom event backend for distributed processing.
89
- */
90
- backend?: EventBackend;
91
- /**
92
- * Database connection for persistent DLQ (optional).
93
- * If provided, failed events after max retries will be persisted to database.
94
- */
95
- db?: ConnectionContract;
96
- /**
97
- * Enable persistent DLQ for failed events (requires db).
98
- * @default false
99
- */
100
- enablePersistentDLQ?: boolean;
101
- }
102
19
  export declare class HookManager {
103
- private filters;
104
- private actions;
20
+ private filterManager;
21
+ private actionManager;
22
+ private asyncDetector;
23
+ private migrationWarner;
105
24
  private eventQueue;
106
25
  private backend;
107
26
  private dlq?;
108
27
  private persistentDlqManager?;
109
- private idempotencyCache;
28
+ private messageQueueBridge?;
110
29
  private config;
111
- private migrationWarner;
112
- /**
113
- * Cache for async detection results (WeakMap for automatic garbage collection).
114
- * @internal
115
- */
116
- private asyncDetectionCache;
117
- /**
118
- * Count of items in the async detection cache (for testing/debugging).
119
- * @internal
120
- */
121
- private asyncDetectionCacheCount;
122
- /**
123
- * Map of listener type overrides (callback -> type).
124
- * @internal
125
- */
126
- private listenerTypeOverrides;
127
30
  constructor(config?: HookManagerConfig);
128
31
  /**
129
32
  * Register a filter hook.
@@ -138,8 +41,8 @@ export declare class HookManager {
138
41
  * @example
139
42
  * ```typescript
140
43
  * core.hooks.addFilter('content', async (content: string) => {
141
- * return content.toUpperCase();
142
- * });
44
+ * return content.toUpperCase()
45
+ * })
143
46
  * ```
144
47
  */
145
48
  addFilter<T = unknown>(hook: string, callback: FilterCallback<T>): void;
@@ -156,7 +59,7 @@ export declare class HookManager {
156
59
  *
157
60
  * @example
158
61
  * ```typescript
159
- * const content = await core.hooks.applyFilters('content', 'hello world');
62
+ * const content = await core.hooks.applyFilters('content', 'hello world')
160
63
  * ```
161
64
  */
162
65
  applyFilters<T = unknown>(hook: string, initialValue: T, ...args: unknown[]): Promise<T>;
@@ -174,11 +77,8 @@ export declare class HookManager {
174
77
  * @example
175
78
  * ```typescript
176
79
  * core.hooks.addAction('user_registered', async (user: User) => {
177
- * await sendWelcomeEmail(user);
178
- * });
179
- *
180
- * // With explicit type override
181
- * core.hooks.addAction('sync_handler', handler, { type: 'async' });
80
+ * await sendWelcomeEmail(user)
81
+ * })
182
82
  * ```
183
83
  */
184
84
  addAction<TArgs = unknown>(hook: string, callback: ActionCallback<TArgs>, options?: ListenerOptions): void;
@@ -188,6 +88,9 @@ export declare class HookManager {
188
88
  * This method supports both synchronous and asynchronous dispatch based on configuration.
189
89
  * In hybrid mode, it auto-detects async listeners and uses async dispatch.
190
90
  *
91
+ * 注意:dispatch 模式決策在此層級完成,以確保子類別(如 ObservableHookManager)
92
+ * 可透過多型覆寫正確攔截 doActionSync / doActionAsync 的呼叫。
93
+ *
191
94
  * @template TArgs - The type of arguments passed to the action.
192
95
  * @param hook - The name of the hook.
193
96
  * @param args - The arguments to pass to the callbacks.
@@ -195,7 +98,7 @@ export declare class HookManager {
195
98
  *
196
99
  * @example
197
100
  * ```typescript
198
- * await core.hooks.doAction('user_registered', user);
101
+ * await core.hooks.doAction('user_registered', user)
199
102
  * ```
200
103
  */
201
104
  doAction<TArgs = unknown>(hook: string, args: TArgs, options?: EventOptions): Promise<void>;
@@ -205,18 +108,11 @@ export declare class HookManager {
205
108
  * @template TArgs - The type of arguments passed to the action.
206
109
  * @param hook - The name of the hook.
207
110
  * @param args - The arguments to pass to the callbacks.
208
- * @internal
209
111
  */
210
112
  doActionSync<TArgs = unknown>(hook: string, args: TArgs): Promise<void>;
211
113
  /**
212
114
  * Run all registered actions asynchronously via priority queue.
213
115
  *
214
- * This method uses EventPriorityQueue for async dispatch with support for:
215
- * - Priority-based processing (high > normal > low)
216
- * - Timeout handling
217
- * - Ordering guarantees (strict, partition, none)
218
- * - Idempotency
219
- *
220
116
  * @template TArgs - The type of arguments passed to the action.
221
117
  * @param hook - The name of the hook.
222
118
  * @param args - The arguments to pass to the callbacks.
@@ -229,18 +125,10 @@ export declare class HookManager {
229
125
  * ordering: 'partition',
230
126
  * partitionKey: order.id,
231
127
  * timeout: 5000,
232
- * });
128
+ * })
233
129
  * ```
234
130
  */
235
131
  doActionAsync<TArgs = unknown>(hook: string, args: TArgs, options?: EventOptions): Promise<void>;
236
- /**
237
- * Determine if async dispatch should be used.
238
- *
239
- * @param callbacks - Callbacks to check
240
- * @param options - Event options
241
- * @returns True if async dispatch should be used
242
- * @internal
243
- */
244
132
  /**
245
133
  * Determine the dispatch mode for an event.
246
134
  *
@@ -253,28 +141,14 @@ export declare class HookManager {
253
141
  /**
254
142
  * Check if a callback is an async function (with caching).
255
143
  *
256
- * Detection methods:
257
- * 1. Check cache first
258
- * 2. Check type override
259
- * 3. Check constructor.name === 'AsyncFunction'
260
- * 4. Fallback: Check function string representation
261
- *
262
144
  * @param callback - The callback to check
263
145
  * @returns True if the callback is async
264
146
  * @public
265
147
  */
266
148
  isAsyncListener(callback: ActionCallback): boolean;
267
- /**
268
- * Cache async detection result.
269
- * @internal
270
- */
271
- private cacheAsyncResult;
272
149
  /**
273
150
  * Runtime detection for functions that return Promises but aren't declared async.
274
151
  *
275
- * This method executes the callback with test args and checks if the result is a Promise.
276
- * Use with caution as it actually invokes the callback.
277
- *
278
152
  * @param callback - The callback to check
279
153
  * @param testArgs - Arguments to pass to the callback for testing
280
154
  * @returns True if the callback returns a Promise
@@ -302,14 +176,6 @@ export declare class HookManager {
302
176
  * @public
303
177
  */
304
178
  hasAsyncListeners(hook: string): boolean;
305
- /**
306
- * Check if a listener is effectively async (considering type override).
307
- *
308
- * @param callback - The callback to check
309
- * @returns True if the listener should be treated as async
310
- * @internal
311
- */
312
- private isListenerEffectivelyAsync;
313
179
  /**
314
180
  * Get detailed information about all listeners for a hook.
315
181
  *
@@ -318,7 +184,6 @@ export declare class HookManager {
318
184
  * @public
319
185
  */
320
186
  getListenerInfo(hook: string): ListenerInfo[];
321
- private shouldUseAsyncDispatch;
322
187
  /**
323
188
  * Get the current event queue depth.
324
189
  *
@@ -344,9 +209,14 @@ export declare class HookManager {
344
209
  *
345
210
  * @param hook - Hook name
346
211
  * @returns Array of callbacks
347
- * @internal
348
212
  */
349
213
  getListeners(hook: string): ActionCallback[];
214
+ /**
215
+ * Remove all listeners for a specific action hook.
216
+ *
217
+ * @param hook - Hook name
218
+ */
219
+ removeAction(hook: string): void;
350
220
  /**
351
221
  * Update HookManager configuration.
352
222
  *
@@ -443,11 +313,17 @@ export declare class HookManager {
443
313
  */
444
314
  resetCircuitBreaker(eventName: string): boolean;
445
315
  /**
446
- * Remove all listeners for a specific action hook.
316
+ * Get the current backpressure state.
447
317
  *
448
- * @param hook - Hook name
318
+ * @returns Backpressure state ('NORMAL', 'WARNING', 'CRITICAL', 'OVERFLOW') or undefined if not enabled
449
319
  */
450
- removeAction(hook: string): void;
320
+ getBackpressureState(): string | undefined;
321
+ /**
322
+ * Get backpressure metrics snapshot.
323
+ *
324
+ * @returns Backpressure metrics snapshot or undefined if not enabled
325
+ */
326
+ getBackpressureMetrics(): object | undefined;
451
327
  /**
452
328
  * Get the persistent DLQ manager instance.
453
329
  *
@@ -486,6 +362,69 @@ export declare class HookManager {
486
362
  succeeded: number;
487
363
  failed: number;
488
364
  }>;
365
+ /**
366
+ * Dispatch an event through Bull Queue(分佈式異步處理).
367
+ *
368
+ * 與 doActionAsync() 不同:
369
+ * - doActionAsync() 使用 EventPriorityQueue (Memory-based)
370
+ * - dispatchQueued() 使用 Bull Queue (Redis-backed, 分佈式)
371
+ *
372
+ * 適用於需要持久化和跨進程處理的事件。
373
+ *
374
+ * @template TArgs - 事件參數類型
375
+ * @param event - 事件名稱
376
+ * @param args - 事件參數
377
+ * @param options - 事件選項(可選)
378
+ * @returns Job ID
379
+ * @throws 如果未配置 MessageQueueBridge 或沒有 listeners
380
+ *
381
+ * @example
382
+ * ```typescript
383
+ * const jobId = await hookManager.dispatchQueued('order:created', {
384
+ * orderId: 'ORD-123',
385
+ * amount: 999.99
386
+ * })
387
+ * ```
388
+ *
389
+ * @public
390
+ */
391
+ dispatchQueued<TArgs = unknown>(event: string, args: TArgs, options?: any): Promise<string>;
392
+ /**
393
+ * Dispatch an event through Bull Queue with delay(延遲隊列分發).
394
+ *
395
+ * @template TArgs - 事件參數類型
396
+ * @param event - 事件名稱
397
+ * @param args - 事件參數
398
+ * @param delay - 延遲時間(毫秒)
399
+ * @param options - 事件選項(可選)
400
+ * @returns Job ID
401
+ * @throws 如果未配置 MessageQueueBridge
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * // 延遲 5 秒後處理
406
+ * const jobId = await hookManager.dispatchDeferredQueued(
407
+ * 'reminder:send',
408
+ * { userId: '123' },
409
+ * 5000
410
+ * )
411
+ * ```
412
+ *
413
+ * @public
414
+ */
415
+ dispatchDeferredQueued<TArgs = unknown>(event: string, args: TArgs, delay: number, options?: any): Promise<string>;
416
+ /**
417
+ * Get the execution status of an event.
418
+ *
419
+ * 查詢事件執行狀態,支持查詢 Bull Queue 和 DLQ 中的事件。
420
+ *
421
+ * @param eventId - 事件 ID (task.id 或 jobId)
422
+ * @returns 事件狀態信息
423
+ * @throws 如果未配置 MessageQueueBridge
424
+ *
425
+ * @public
426
+ */
427
+ getEventStatus(eventId: string): Promise<any>;
489
428
  /**
490
429
  * Get persistent DLQ statistics.
491
430
  *
@@ -16,6 +16,7 @@ import { HookManager } from './HookManager';
16
16
  import type { fail } from './helpers/response';
17
17
  import type { ContentfulStatusCode, GravitoContext } from './http/types';
18
18
  import { type Logger } from './Logger';
19
+ import { type ObservabilityProvider } from './observability/contracts';
19
20
  import type { ServiceProvider } from './ServiceProvider';
20
21
  /**
21
22
  * CacheService interface for orbit-injected cache
@@ -71,7 +72,14 @@ export type GravitoConfig = {
71
72
  config?: Record<string, unknown>;
72
73
  orbits?: (new () => GravitoOrbit)[] | GravitoOrbit[];
73
74
  /**
74
- * HTTP Adapter to use. Defaults to PhotonAdapter.
75
+ * HTTP Adapter to use. Defaults to BunNativeAdapter in Bun environments.
76
+ * In non-Bun environments, must be provided explicitly.
77
+ * @example
78
+ * ```typescript
79
+ * import { PhotonAdapter } from '@gravito/photon/adapter'
80
+ * new PlanetCore({ adapter: new PhotonAdapter() })
81
+ * ```
82
+ * See https://gravito.dev/guides/http-adapters for available adapters.
75
83
  * @since 2.0.0
76
84
  */
77
85
  adapter?: HttpAdapter;
@@ -82,6 +90,53 @@ export type GravitoConfig = {
82
90
  * @since 2.0.0
83
91
  */
84
92
  container?: Container;
93
+ /**
94
+ * Observability configuration for event system.
95
+ * @since 2.1.0
96
+ */
97
+ observability?: {
98
+ /**
99
+ * Enable event system observability (metrics, tracing).
100
+ * @default false
101
+ */
102
+ enabled?: boolean;
103
+ /**
104
+ * Enable OpenTelemetry distributed tracing.
105
+ * @default false
106
+ */
107
+ tracing?: boolean;
108
+ /**
109
+ * Prefix for metric names.
110
+ * @default 'gravito_event_'
111
+ */
112
+ metricsPrefix?: string;
113
+ /**
114
+ * Prometheus metrics configuration.
115
+ */
116
+ prometheus?: {
117
+ /**
118
+ * Enable Prometheus metrics endpoint.
119
+ * @default true
120
+ */
121
+ enabled?: boolean;
122
+ /**
123
+ * Port for Prometheus metrics endpoint.
124
+ * @default 9090
125
+ */
126
+ port?: number;
127
+ /**
128
+ * Endpoint path for metrics.
129
+ * @default '/metrics'
130
+ */
131
+ endpoint?: string;
132
+ };
133
+ };
134
+ /**
135
+ * Observability provider for distributed tracing and metrics.
136
+ * If provided, this will be used instead of the default OTel setup.
137
+ * @since 2.2.0
138
+ */
139
+ observabilityProvider?: ObservabilityProvider;
85
140
  };
86
141
  import { Router } from './Router';
87
142
  import { Encrypter } from './security/Encrypter';
@@ -119,9 +174,32 @@ export declare class PlanetCore {
119
174
  services: Map<string, unknown>;
120
175
  encrypter?: Encrypter;
121
176
  hasher: BunHasher;
177
+ /**
178
+ * Observability provider for distributed tracing and metrics.
179
+ * @since 2.2.0
180
+ */
181
+ observabilityProvider: ObservabilityProvider;
122
182
  private providers;
123
183
  private deferredProviders;
124
184
  private bootedProviders;
185
+ private isShuttingDown;
186
+ /**
187
+ * Initialize observability asynchronously (metrics, tracing, Prometheus).
188
+ * This is called from constructor but doesn't block initialization.
189
+ *
190
+ * Phase 2.2 Update: Now uses the observabilityProvider passed from @gravito/monitor
191
+ * or falls back to OTel implementation if available for backward compatibility.
192
+ *
193
+ * @internal
194
+ */
195
+ private initializeObservabilityAsync;
196
+ /**
197
+ * Initialize Prometheus metrics asynchronously.
198
+ *
199
+ * @internal
200
+ * @deprecated Prometheus setup has been moved to @gravito/monitor
201
+ */
202
+ private initializePrometheusAsync;
125
203
  /**
126
204
  * Register a service provider to the core.
127
205
  *
@@ -155,6 +233,34 @@ export declare class PlanetCore {
155
233
  * ```
156
234
  */
157
235
  bootstrap(): Promise<void>;
236
+ /**
237
+ * Called when the application is ready to accept requests.
238
+ *
239
+ * Invokes the `onReady()` lifecycle hook on all providers.
240
+ * Called automatically at the end of `bootstrap()`.
241
+ *
242
+ * @returns Promise that resolves when all providers are ready.
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * await core.ready();
247
+ * ```
248
+ */
249
+ ready(): Promise<void>;
250
+ /**
251
+ * Gracefully shutdown the application.
252
+ *
253
+ * Invokes the `onShutdown()` lifecycle hook on all providers in reverse order (LIFO).
254
+ * Should be called when the application receives a termination signal.
255
+ *
256
+ * @returns Promise that resolves when all providers have shut down.
257
+ *
258
+ * @example
259
+ * ```typescript
260
+ * process.on('SIGTERM', () => core.shutdown());
261
+ * ```
262
+ */
263
+ shutdown(): Promise<void>;
158
264
  /**
159
265
  * Setup deferred provider resolution.
160
266
  * Wraps container.make to auto-register deferred providers on first request.
@@ -179,7 +285,14 @@ export declare class PlanetCore {
179
285
  config?: Record<string, unknown>;
180
286
  adapter?: HttpAdapter;
181
287
  container?: Container;
288
+ observabilityProvider?: ObservabilityProvider;
182
289
  });
290
+ /**
291
+ * Setup process signal handlers for graceful shutdown
292
+ *
293
+ * @internal
294
+ */
295
+ private setupSignalHandlers;
183
296
  /**
184
297
  * Programmatically register an infrastructure module (Orbit).
185
298
  * @since 2.0.0
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @fileoverview RequestContext - AsyncLocalStorage-based request context management
3
+ *
4
+ * Allows deep service layers to access request-scoped data (requestId, userId, etc.)
5
+ * without passing parameters through the call stack.
6
+ *
7
+ * @module @gravito/core/RequestContext
8
+ * @since 2.2.0
9
+ */
10
+ /**
11
+ * 請求上下文資料介面
12
+ * 包含請求相關的唯一識別碼和上下文資訊
13
+ * @public
14
+ */
15
+ export interface RequestContextData {
16
+ /** 唯一的請求識別碼 */
17
+ requestId: string;
18
+ /** 使用者 ID(可選) */
19
+ userId?: string;
20
+ /** 租戶 ID(可選) */
21
+ tenantId?: string;
22
+ /** 追蹤 ID(可選) */
23
+ traceId?: string;
24
+ /** 自訂欄位 */
25
+ [key: string]: unknown;
26
+ }
27
+ /**
28
+ * RequestContext 物件 - 管理請求上下文的 API
29
+ *
30
+ * 提供在非同步鏈中存取和設定請求上下文的方法
31
+ * @public
32
+ */
33
+ export declare const RequestContext: {
34
+ /**
35
+ * 在給定的上下文中執行函式
36
+ *
37
+ * 確保函式及其所有非同步呼叫都在同一個上下文中執行
38
+ *
39
+ * @param data - 請求上下文資料
40
+ * @param fn - 要執行的函式(可以是非同步的或同步的)
41
+ * @returns 如果函式是非同步的,返回 Promise;如果是同步的,直接返回值
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * await RequestContext.run({ requestId: 'req-123' }, async () => {
46
+ * const userId = RequestContext.get()?.userId;
47
+ * });
48
+ *
49
+ * const result = RequestContext.run({ requestId: 'req-123' }, () => {
50
+ * return 'sync-result';
51
+ * });
52
+ * ```
53
+ */
54
+ run<T>(data: RequestContextData, fn: () => T | Promise<T>): T | Promise<T>;
55
+ /**
56
+ * 獲取當前請求的上下文資料
57
+ *
58
+ * @returns 請求上下文資料,如果不在請求上下文中則返回 undefined
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * const context = RequestContext.get();
63
+ * if (context) {
64
+ * console.log(context.requestId);
65
+ * }
66
+ * ```
67
+ */
68
+ get(): RequestContextData | undefined;
69
+ /**
70
+ * 獲取當前請求的上下文資料,如果不存在則拋出錯誤
71
+ *
72
+ * @returns 請求上下文資料
73
+ * @throws Error 如果不在請求上下文中
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const context = RequestContext.getOrThrow();
78
+ * console.log(context.requestId); // 保證不為 undefined
79
+ * ```
80
+ */
81
+ getOrThrow(): RequestContextData;
82
+ /**
83
+ * 在當前上下文中設定或修改值
84
+ *
85
+ * @param key - 要設定的欄位名稱
86
+ * @param value - 要設定的值
87
+ * @throws Error 如果不在請求上下文中
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * RequestContext.set('userId', 'user-456');
92
+ * const userId = RequestContext.get()?.userId; // 'user-456'
93
+ * ```
94
+ */
95
+ set(key: string, value: unknown): void;
96
+ };
97
+ export default RequestContext;