@gravito/ripple 4.0.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/atlas/src/DB.d.ts +51 -4
  2. package/dist/atlas/src/config/index.d.ts +1 -1
  3. package/dist/atlas/src/config/loadConfig.d.ts +0 -7
  4. package/dist/atlas/src/connection/Connection.d.ts +4 -0
  5. package/dist/atlas/src/connection/ConnectionManager.d.ts +75 -6
  6. package/dist/atlas/src/connection/ReplicaConnectionPool.d.ts +54 -0
  7. package/dist/atlas/src/drivers/MySQLDriver.d.ts +16 -3
  8. package/dist/atlas/src/drivers/PostgresDriver.d.ts +15 -2
  9. package/dist/atlas/src/index.d.ts +15 -3
  10. package/dist/atlas/src/observability/AtlasMetrics.d.ts +22 -0
  11. package/dist/atlas/src/orm/Repository.d.ts +247 -0
  12. package/dist/atlas/src/orm/index.d.ts +1 -0
  13. package/dist/atlas/src/orm/model/Model.d.ts +11 -2
  14. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +14 -0
  15. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +5 -0
  16. package/dist/atlas/src/orm/model/decorators.d.ts +29 -0
  17. package/dist/atlas/src/orm/model/index.d.ts +1 -1
  18. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +1 -0
  19. package/dist/atlas/src/pool/AdaptivePoolManager.d.ts +98 -0
  20. package/dist/atlas/src/pool/PoolHealthChecker.d.ts +91 -0
  21. package/dist/atlas/src/pool/PoolStrategy.d.ts +129 -0
  22. package/dist/atlas/src/pool/PoolWarmer.d.ts +92 -0
  23. package/dist/atlas/src/query/QueryBuilder.d.ts +71 -1
  24. package/dist/atlas/src/query/RelationshipResolver.d.ts +23 -0
  25. package/dist/atlas/src/schema/MigrationGenerator.d.ts +45 -0
  26. package/dist/atlas/src/schema/SchemaDiff.d.ts +73 -0
  27. package/dist/atlas/src/schema/TypeGenerator.d.ts +57 -0
  28. package/dist/atlas/src/schema/TypeWriter.d.ts +42 -0
  29. package/dist/atlas/src/sharding/ShardingManager.d.ts +59 -0
  30. package/dist/atlas/src/types/index.d.ts +83 -1
  31. package/dist/atlas/src/utils/CursorEncoding.d.ts +63 -0
  32. package/dist/core/src/ConfigManager.d.ts +39 -0
  33. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  34. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  35. package/dist/core/src/Container.d.ts +45 -0
  36. package/dist/core/src/ErrorHandler.d.ts +3 -0
  37. package/dist/core/src/HookManager.d.ts +95 -0
  38. package/dist/core/src/PlanetCore.d.ts +89 -0
  39. package/dist/core/src/RequestContext.d.ts +97 -0
  40. package/dist/core/src/ServiceProvider.d.ts +22 -0
  41. package/dist/core/src/adapters/PhotonAdapter.d.ts +4 -0
  42. package/dist/core/src/adapters/bun/BunContext.d.ts +4 -0
  43. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  44. package/dist/core/src/engine/AOTRouter.d.ts +6 -1
  45. package/dist/core/src/engine/FastContext.d.ts +23 -0
  46. package/dist/core/src/engine/Gravito.d.ts +0 -1
  47. package/dist/core/src/engine/MinimalContext.d.ts +21 -0
  48. package/dist/core/src/engine/types.d.ts +3 -0
  49. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  50. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  51. package/dist/core/src/events/DeadLetterQueue.d.ts +75 -1
  52. package/dist/core/src/events/EventBackend.d.ts +2 -1
  53. package/dist/core/src/events/EventOptions.d.ts +99 -4
  54. package/dist/core/src/events/EventPriorityQueue.d.ts +105 -6
  55. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  56. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  57. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  58. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  59. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  60. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  61. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  62. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  63. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  64. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  65. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  66. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  67. package/dist/core/src/events/index.d.ts +11 -0
  68. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +92 -0
  69. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  70. package/dist/core/src/events/observability/index.d.ts +4 -0
  71. package/dist/core/src/events/types.d.ts +59 -0
  72. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  73. package/dist/core/src/http/types.d.ts +19 -0
  74. package/dist/core/src/index.d.ts +13 -1
  75. package/dist/core/src/observability/Metrics.d.ts +244 -0
  76. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  77. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +34 -0
  78. package/dist/index.js +403 -40
  79. package/dist/index.js.map +11 -9
  80. package/dist/photon/src/index.d.ts +5 -0
  81. package/dist/photon/src/middleware/ratelimit-redis.d.ts +50 -0
  82. package/dist/photon/src/middleware/ratelimit.d.ts +4 -0
  83. package/dist/ripple/src/RippleServer.d.ts +0 -1
  84. package/dist/ripple/src/engines/UWebSocketsEngine.d.ts +97 -0
  85. package/dist/ripple/src/engines/WsEngine.d.ts +69 -0
  86. package/dist/ripple/src/engines/index.d.ts +4 -0
  87. package/dist/ripple/src/serializers/ISerializer.d.ts +1 -1
  88. package/dist/ripple/src/serializers/JsonSerializer.d.ts +1 -1
  89. package/dist/ripple/src/serializers/ProtobufSerializer.d.ts +6 -3
  90. package/dist/ripple/src/types.d.ts +11 -0
  91. package/package.json +3 -2
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Configuration manager (ConfigManager)
3
+ *
4
+ * Unifies environment variables and application configuration access.
5
+ */
6
+ import type { ZodSchema } from 'zod';
1
7
  /**
2
8
  * ConfigManager - Central configuration store.
3
9
  * Supports loading from environment variables and initial objects.
@@ -5,6 +11,7 @@
5
11
  */
6
12
  export declare class ConfigManager {
7
13
  private config;
14
+ private schema;
8
15
  constructor(initialConfig?: Record<string, unknown>);
9
16
  /**
10
17
  * Load all environment variables from the active runtime.
@@ -23,4 +30,36 @@ export declare class ConfigManager {
23
30
  * Check whether a key exists.
24
31
  */
25
32
  has(key: string): boolean;
33
+ /**
34
+ * Define a Zod schema for configuration validation.
35
+ *
36
+ * @param schema - Zod schema for validation
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * config.defineSchema(z.object({
41
+ * DATABASE_URL: z.string().url(),
42
+ * PORT: z.number().default(3000),
43
+ * }))
44
+ * ```
45
+ */
46
+ defineSchema(schema: ZodSchema): void;
47
+ /**
48
+ * Validate configuration against the defined schema.
49
+ *
50
+ * Should be called during bootstrap to catch configuration errors early.
51
+ *
52
+ * @throws Error if validation fails with details about missing/invalid fields
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * try {
57
+ * config.validate()
58
+ * } catch (error) {
59
+ * console.error('Config validation failed:', error.message)
60
+ * process.exit(1)
61
+ * }
62
+ * ```
63
+ */
64
+ validate(): void;
26
65
  }
@@ -0,0 +1,62 @@
1
+ import type { ServiceKey } from '../Container';
2
+ import { RequestScopeMetrics, type RequestScopeObserver } from './RequestScopeMetrics';
3
+ /**
4
+ * Manages request-scoped service instances within a single HTTP request.
5
+ *
6
+ * Each request gets its own RequestScopeManager instance with isolated state.
7
+ * Services are cached within the request and automatically cleaned up when
8
+ * the request ends.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const scope = new RequestScopeManager()
13
+ * const cache = scope.resolve('productCache', () => new ProductCache())
14
+ * // ... use cache ...
15
+ * await scope.cleanup() // Called automatically by Gravito engine
16
+ * ```
17
+ */
18
+ export declare class RequestScopeManager {
19
+ private scoped;
20
+ private metadata;
21
+ private metrics;
22
+ private observer;
23
+ constructor(observer?: RequestScopeObserver);
24
+ /**
25
+ * Set observer for monitoring scope lifecycle
26
+ */
27
+ setObserver(observer: RequestScopeObserver): void;
28
+ /**
29
+ * Get metrics for this scope
30
+ */
31
+ getMetrics(): RequestScopeMetrics;
32
+ /**
33
+ * Resolve or retrieve a request-scoped service instance.
34
+ *
35
+ * If the service already exists in this scope, returns the cached instance.
36
+ * Otherwise, calls the factory function to create a new instance and caches it.
37
+ *
38
+ * Automatically detects and records services with cleanup methods.
39
+ *
40
+ * @template T - The type of the service.
41
+ * @param key - The service key (for caching).
42
+ * @param factory - Factory function to create the instance if not cached.
43
+ * @returns The cached or newly created instance.
44
+ */
45
+ resolve<T>(key: ServiceKey, factory: () => T): T;
46
+ /**
47
+ * Clean up all request-scoped instances.
48
+ *
49
+ * Calls the cleanup() method on each service that has one.
50
+ * Silently ignores cleanup errors to prevent cascading failures.
51
+ * Called automatically by the Gravito engine in the request finally block.
52
+ *
53
+ * @returns Promise that resolves when all cleanup is complete.
54
+ */
55
+ cleanup(): Promise<void>;
56
+ /**
57
+ * Get the number of services in this scope (for monitoring).
58
+ *
59
+ * @returns The count of cached services.
60
+ */
61
+ size(): number;
62
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * RequestScopeMetrics - Observability for RequestScope lifecycle
3
+ *
4
+ * Tracks cleanup execution time, scope size, and service counts
5
+ * for performance monitoring and diagnostics.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const metrics = new RequestScopeMetrics()
10
+ * metrics.recordCleanupStart()
11
+ * await scope.cleanup()
12
+ * metrics.recordCleanupEnd()
13
+ *
14
+ * console.log(metrics.toJSON())
15
+ * // { cleanupDuration: 2.5, scopeSize: 3, servicesCleaned: 3 }
16
+ * ```
17
+ */
18
+ export declare class RequestScopeMetrics {
19
+ private cleanupStartTime;
20
+ private cleanupDuration;
21
+ private scopeSize;
22
+ private servicesCleaned;
23
+ private errorsOccurred;
24
+ /**
25
+ * Record start of cleanup operation
26
+ */
27
+ recordCleanupStart(): void;
28
+ /**
29
+ * Record end of cleanup operation
30
+ *
31
+ * @param scopeSize - Number of services in the scope
32
+ * @param servicesCleaned - Number of services that had cleanup called
33
+ * @param errorsOccurred - Number of cleanup errors
34
+ */
35
+ recordCleanupEnd(scopeSize: number, servicesCleaned: number, errorsOccurred?: number): void;
36
+ /**
37
+ * Get cleanup duration in milliseconds
38
+ *
39
+ * @returns Duration in ms, or null if cleanup not completed
40
+ */
41
+ getCleanupDuration(): number | null;
42
+ /**
43
+ * Check if cleanup took longer than threshold (default 2ms)
44
+ * Useful for detecting slow cleanups
45
+ *
46
+ * @param thresholdMs - Threshold in milliseconds
47
+ * @returns True if cleanup exceeded threshold
48
+ */
49
+ isSlowCleanup(thresholdMs?: number): boolean;
50
+ /**
51
+ * Export metrics as JSON for logging/monitoring
52
+ */
53
+ toJSON(): {
54
+ cleanupDuration: number | null;
55
+ scopeSize: number;
56
+ servicesCleaned: number;
57
+ errorsOccurred: number;
58
+ hasErrors: boolean;
59
+ isSlowCleanup: boolean;
60
+ };
61
+ /**
62
+ * Export metrics as compact string for logging
63
+ */
64
+ toString(): string;
65
+ }
66
+ /**
67
+ * RequestScopeObserver - Hook for monitoring RequestScope lifecycle
68
+ *
69
+ * Implement this interface to receive callbacks during scope operations
70
+ */
71
+ export interface RequestScopeObserver {
72
+ /**
73
+ * Called when a service is resolved in the scope
74
+ */
75
+ onServiceResolved?(key: string | symbol, isFromCache: boolean): void;
76
+ /**
77
+ * Called when cleanup starts
78
+ */
79
+ onCleanupStart?(): void;
80
+ /**
81
+ * Called when cleanup completes
82
+ */
83
+ onCleanupEnd?(metrics: RequestScopeMetrics): void;
84
+ /**
85
+ * Called when cleanup encounters an error
86
+ */
87
+ onCleanupError?(error: Error): void;
88
+ }
89
+ /**
90
+ * RequestScopeMetricsCollector - Aggregates metrics across multiple scopes
91
+ *
92
+ * Used for application-level monitoring and performance tracking
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const collector = new RequestScopeMetricsCollector()
97
+ *
98
+ * // Record metrics from multiple requests
99
+ * collector.record(metrics1)
100
+ * collector.record(metrics2)
101
+ * collector.record(metrics3)
102
+ *
103
+ * // Get aggregated stats
104
+ * const stats = collector.getStats()
105
+ * console.log(stats.averageCleanupTime) // 3.5ms
106
+ * ```
107
+ */
108
+ export declare class RequestScopeMetricsCollector {
109
+ private metrics;
110
+ /**
111
+ * Record metrics from a request scope
112
+ */
113
+ record(metrics: RequestScopeMetrics): void;
114
+ /**
115
+ * Get aggregated statistics
116
+ */
117
+ getStats(): {
118
+ count: number;
119
+ averageCleanupTime: number | null;
120
+ maxCleanupTime: number | null;
121
+ minCleanupTime: number | null;
122
+ totalErrorCount: number;
123
+ errorRate: number;
124
+ };
125
+ /**
126
+ * Clear collected metrics
127
+ */
128
+ clear(): void;
129
+ /**
130
+ * Get number of recorded metrics
131
+ */
132
+ size(): number;
133
+ /**
134
+ * Export metrics as JSON array
135
+ */
136
+ toJSON(): {
137
+ cleanupDuration: number | null;
138
+ scopeSize: number;
139
+ servicesCleaned: number;
140
+ errorsOccurred: number;
141
+ hasErrors: boolean;
142
+ isSlowCleanup: boolean;
143
+ }[];
144
+ }
@@ -1,3 +1,4 @@
1
+ import type { RequestScopeManager } from './Container/RequestScopeManager';
1
2
  /**
2
3
  * Factory type for creating service instances
3
4
  */
@@ -31,6 +32,27 @@ export declare class Container {
31
32
  private bindings;
32
33
  private instances;
33
34
  private resolutionStack;
35
+ /**
36
+ * Run a function within a request scope context.
37
+ *
38
+ * All service resolutions within the function will use the provided scope,
39
+ * enabling request-scoped service instances to be properly isolated.
40
+ *
41
+ * @template T - The return type of the function.
42
+ * @param scope - The RequestScopeManager for this request.
43
+ * @param fn - The function to execute within the scope.
44
+ * @returns The result of the function.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * const scope = new RequestScopeManager()
49
+ * const result = await Container.runWithScope(scope, async () => {
50
+ * const service = container.make('requestScoped')
51
+ * return service.doSomething()
52
+ * })
53
+ * ```
54
+ */
55
+ static runWithScope<T>(scope: RequestScopeManager, fn: () => T | Promise<T>): T | Promise<T>;
34
56
  /**
35
57
  * Bind a service to the container.
36
58
  *
@@ -63,6 +85,22 @@ export declare class Container {
63
85
  * ```
64
86
  */
65
87
  singleton<T>(key: ServiceKey, factory: Factory<T>): void;
88
+ /**
89
+ * Bind a request-scoped service to the container.
90
+ *
91
+ * A new instance will be created for each request and cached within that request.
92
+ * The service is automatically cleaned up when the request ends.
93
+ *
94
+ * @template T - The type of the service being bound.
95
+ * @param key - The unique identifier for the service.
96
+ * @param factory - The factory function that creates the service instance.
97
+ *
98
+ * @example
99
+ * ```typescript
100
+ * container.scoped('requestCache', (c) => new RequestProductCache());
101
+ * ```
102
+ */
103
+ scoped<T>(key: ServiceKey, factory: Factory<T>): void;
66
104
  /**
67
105
  * Register an existing instance as a shared service.
68
106
  *
@@ -70,6 +108,13 @@ export declare class Container {
70
108
  * @param instance - The instance to register.
71
109
  */
72
110
  instance<T>(key: ServiceKey, instance: T): void;
111
+ /**
112
+ * Check if a service is request-scoped.
113
+ *
114
+ * @param key - The service key to check.
115
+ * @returns True if the service is request-scoped.
116
+ */
117
+ isRequestScoped(key: ServiceKey): boolean;
73
118
  /**
74
119
  * Resolve a service instance from the container.
75
120
  *
@@ -42,6 +42,9 @@ export declare class ErrorHandler {
42
42
  constructor(deps: ErrorHandlerDeps);
43
43
  /**
44
44
  * Handle application errors
45
+ *
46
+ * Integrates RequestScope cleanup to ensure proper resource management
47
+ * even when errors occur during request processing.
45
48
  */
46
49
  handleError(err: unknown, c: GravitoContext): Promise<Response>;
47
50
  /**
@@ -98,6 +98,16 @@ export interface HookManagerConfig {
98
98
  * @default false
99
99
  */
100
100
  enablePersistentDLQ?: boolean;
101
+ /**
102
+ * Message Queue Bridge for distributed event processing via Bull Queue.
103
+ * When provided, enables dispatchQueued() method for routing events to Redis-backed queue.
104
+ */
105
+ messageQueueBridge?: any;
106
+ /**
107
+ * Event aggregation configuration (FS-102).
108
+ * Enables deduplication and micro-batching for improved throughput.
109
+ */
110
+ aggregation?: any;
101
111
  }
102
112
  export declare class HookManager {
103
113
  private filters;
@@ -106,9 +116,11 @@ export declare class HookManager {
106
116
  private backend;
107
117
  private dlq?;
108
118
  private persistentDlqManager?;
119
+ private messageQueueBridge?;
109
120
  private idempotencyCache;
110
121
  private config;
111
122
  private migrationWarner;
123
+ private aggregationManager?;
112
124
  /**
113
125
  * Cache for async detection results (WeakMap for automatic garbage collection).
114
126
  * @internal
@@ -442,6 +454,18 @@ export declare class HookManager {
442
454
  * @returns True if reset, false if circuit breaker not found
443
455
  */
444
456
  resetCircuitBreaker(eventName: string): boolean;
457
+ /**
458
+ * Get the current backpressure state.
459
+ *
460
+ * @returns Backpressure state ('NORMAL', 'WARNING', 'CRITICAL', 'OVERFLOW') or undefined if not enabled
461
+ */
462
+ getBackpressureState(): string | undefined;
463
+ /**
464
+ * Get backpressure metrics snapshot.
465
+ *
466
+ * @returns Backpressure metrics snapshot or undefined if not enabled
467
+ */
468
+ getBackpressureMetrics(): object | undefined;
445
469
  /**
446
470
  * Remove all listeners for a specific action hook.
447
471
  *
@@ -486,6 +510,77 @@ export declare class HookManager {
486
510
  succeeded: number;
487
511
  failed: number;
488
512
  }>;
513
+ /**
514
+ * Dispatch an event through Bull Queue (分佈式異步處理).
515
+ *
516
+ * 與 doActionAsync() 不同:
517
+ * - doActionAsync() 使用 EventPriorityQueue (Memory-based)
518
+ * - dispatchQueued() 使用 Bull Queue (Redis-backed, 分佈式)
519
+ *
520
+ * 適用於需要持久化和跨進程處理的事件。
521
+ *
522
+ * @template TArgs - 事件參數類型
523
+ * @param event - 事件名稱
524
+ * @param args - 事件參數
525
+ * @param options - 事件選項(可選)
526
+ * @returns Job ID
527
+ * @throws 如果未配置 MessageQueueBridge 或沒有 listeners
528
+ *
529
+ * @example
530
+ * ```typescript
531
+ * const jobId = await hookManager.dispatchQueued('order:created', {
532
+ * orderId: 'ORD-123',
533
+ * amount: 999.99
534
+ * })
535
+ * ```
536
+ *
537
+ * @public
538
+ */
539
+ dispatchQueued<TArgs = unknown>(event: string, args: TArgs, options?: any): Promise<string>;
540
+ /**
541
+ * Dispatch an event through Bull Queue with delay (延遲隊列分發).
542
+ *
543
+ * 通過 Bull Queue 的 delayed jobs 功能實現延遲處理。
544
+ *
545
+ * @template TArgs - 事件參數類型
546
+ * @param event - 事件名稱
547
+ * @param args - 事件參數
548
+ * @param delay - 延遲時間(毫秒)
549
+ * @param options - 事件選項(可選)
550
+ * @returns Job ID
551
+ * @throws 如果未配置 MessageQueueBridge
552
+ *
553
+ * @example
554
+ * ```typescript
555
+ * // 延遲 5 秒後處理
556
+ * const jobId = await hookManager.dispatchDeferredQueued(
557
+ * 'reminder:send',
558
+ * { userId: '123' },
559
+ * 5000
560
+ * )
561
+ * ```
562
+ *
563
+ * @public
564
+ */
565
+ dispatchDeferredQueued<TArgs = unknown>(event: string, args: TArgs, delay: number, options?: any): Promise<string>;
566
+ /**
567
+ * Get the execution status of an event.
568
+ *
569
+ * 查詢事件執行狀態,支持查詢 Bull Queue 和 DLQ 中的事件。
570
+ *
571
+ * @param eventId - 事件 ID (task.id 或 jobId)
572
+ * @returns 事件狀態信息
573
+ * @throws 如果未配置 MessageQueueBridge
574
+ *
575
+ * @example
576
+ * ```typescript
577
+ * const status = await hookManager.getEventStatus('queue-1707000000000-abc123')
578
+ * console.log(status) // { eventId, status, attempts, createdAt, ... }
579
+ * ```
580
+ *
581
+ * @public
582
+ */
583
+ getEventStatus(eventId: string): Promise<any>;
489
584
  /**
490
585
  * Get persistent DLQ statistics.
491
586
  *
@@ -82,6 +82,47 @@ export type GravitoConfig = {
82
82
  * @since 2.0.0
83
83
  */
84
84
  container?: Container;
85
+ /**
86
+ * Observability configuration for event system.
87
+ * @since 2.1.0
88
+ */
89
+ observability?: {
90
+ /**
91
+ * Enable event system observability (metrics, tracing).
92
+ * @default false
93
+ */
94
+ enabled?: boolean;
95
+ /**
96
+ * Enable OpenTelemetry distributed tracing.
97
+ * @default false
98
+ */
99
+ tracing?: boolean;
100
+ /**
101
+ * Prefix for metric names.
102
+ * @default 'gravito_event_'
103
+ */
104
+ metricsPrefix?: string;
105
+ /**
106
+ * Prometheus metrics configuration.
107
+ */
108
+ prometheus?: {
109
+ /**
110
+ * Enable Prometheus metrics endpoint.
111
+ * @default true
112
+ */
113
+ enabled?: boolean;
114
+ /**
115
+ * Port for Prometheus metrics endpoint.
116
+ * @default 9090
117
+ */
118
+ port?: number;
119
+ /**
120
+ * Endpoint path for metrics.
121
+ * @default '/metrics'
122
+ */
123
+ endpoint?: string;
124
+ };
125
+ };
85
126
  };
86
127
  import { Router } from './Router';
87
128
  import { Encrypter } from './security/Encrypter';
@@ -122,6 +163,20 @@ export declare class PlanetCore {
122
163
  private providers;
123
164
  private deferredProviders;
124
165
  private bootedProviders;
166
+ private isShuttingDown;
167
+ /**
168
+ * Initialize observability asynchronously (metrics, tracing, Prometheus).
169
+ * This is called from constructor but doesn't block initialization.
170
+ *
171
+ * @internal
172
+ */
173
+ private initializeObservabilityAsync;
174
+ /**
175
+ * Initialize Prometheus metrics asynchronously.
176
+ *
177
+ * @internal
178
+ */
179
+ private initializePrometheusAsync;
125
180
  /**
126
181
  * Register a service provider to the core.
127
182
  *
@@ -155,6 +210,34 @@ export declare class PlanetCore {
155
210
  * ```
156
211
  */
157
212
  bootstrap(): Promise<void>;
213
+ /**
214
+ * Called when the application is ready to accept requests.
215
+ *
216
+ * Invokes the `onReady()` lifecycle hook on all providers.
217
+ * Called automatically at the end of `bootstrap()`.
218
+ *
219
+ * @returns Promise that resolves when all providers are ready.
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * await core.ready();
224
+ * ```
225
+ */
226
+ ready(): Promise<void>;
227
+ /**
228
+ * Gracefully shutdown the application.
229
+ *
230
+ * Invokes the `onShutdown()` lifecycle hook on all providers in reverse order (LIFO).
231
+ * Should be called when the application receives a termination signal.
232
+ *
233
+ * @returns Promise that resolves when all providers have shut down.
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * process.on('SIGTERM', () => core.shutdown());
238
+ * ```
239
+ */
240
+ shutdown(): Promise<void>;
158
241
  /**
159
242
  * Setup deferred provider resolution.
160
243
  * Wraps container.make to auto-register deferred providers on first request.
@@ -180,6 +263,12 @@ export declare class PlanetCore {
180
263
  adapter?: HttpAdapter;
181
264
  container?: Container;
182
265
  });
266
+ /**
267
+ * Setup process signal handlers for graceful shutdown
268
+ *
269
+ * @internal
270
+ */
271
+ private setupSignalHandlers;
183
272
  /**
184
273
  * Programmatically register an infrastructure module (Orbit).
185
274
  * @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;
@@ -74,6 +74,28 @@ export declare abstract class ServiceProvider {
74
74
  * @param core - The PlanetCore application instance
75
75
  */
76
76
  boot?(core: PlanetCore): void | Promise<void>;
77
+ /**
78
+ * Called when the application is ready to accept requests.
79
+ *
80
+ * This method is called after ALL providers have booted.
81
+ * Use this for final initialization before the server starts accepting traffic.
82
+ *
83
+ * @param core - The PlanetCore application instance
84
+ * @since 2.2.0
85
+ */
86
+ onReady?(core: PlanetCore): void | Promise<void>;
87
+ /**
88
+ * Called when the application is shutting down.
89
+ *
90
+ * This method is called during graceful shutdown.
91
+ * Use this to clean up resources, close connections, etc.
92
+ *
93
+ * Providers are called in reverse order (LIFO).
94
+ *
95
+ * @param core - The PlanetCore application instance
96
+ * @since 2.2.0
97
+ */
98
+ onShutdown?(core: PlanetCore): void | Promise<void>;
77
99
  /**
78
100
  * Set the core instance reference.
79
101
  * Called internally by the application during registration.