@gravito/core 1.6.0 → 1.6.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.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { G as GravitoVariables, H as HttpMethod, a as GravitoHandler, b as GravitoMiddleware, c as GravitoErrorHandler, d as GravitoNotFoundHandler, e as GravitoContext, C as ContentfulStatusCode, P as ProxyOptions, f as GravitoRequest, S as StatusCode } from './compat-C4Src6NN.js';
2
- export { g as GravitoNext, V as ValidationTarget } from './compat-C4Src6NN.js';
1
+ import { G as GravitoVariables, H as HttpMethod, a as GravitoHandler, b as GravitoMiddleware, c as GravitoErrorHandler, d as GravitoNotFoundHandler, e as GravitoContext, C as ContentfulStatusCode, P as ProxyOptions, f as GravitoRequest, S as StatusCode } from './compat-CI8hiulX.js';
2
+ export { g as GravitoNext, V as ValidationTarget } from './compat-CI8hiulX.js';
3
+ import { ZodSchema } from 'zod';
3
4
  import * as _opentelemetry_api from '@opentelemetry/api';
4
5
  import { Histogram, Counter, Span, Context, Meter } from '@opentelemetry/api';
5
6
  import { Photon, Context as Context$1 } from '@gravito/photon';
@@ -240,6 +241,12 @@ type AdapterFactory<V extends GravitoVariables = GravitoVariables> = (config?: A
240
241
  */
241
242
  declare function isHttpAdapter(value: unknown): value is HttpAdapter;
242
243
 
244
+ /**
245
+ * Configuration manager (ConfigManager)
246
+ *
247
+ * Unifies environment variables and application configuration access.
248
+ */
249
+
243
250
  /**
244
251
  * ConfigManager - Central configuration store.
245
252
  * Supports loading from environment variables and initial objects.
@@ -247,6 +254,7 @@ declare function isHttpAdapter(value: unknown): value is HttpAdapter;
247
254
  */
248
255
  declare class ConfigManager {
249
256
  private config;
257
+ private schema;
250
258
  constructor(initialConfig?: Record<string, unknown>);
251
259
  /**
252
260
  * Load all environment variables from the active runtime.
@@ -265,6 +273,244 @@ declare class ConfigManager {
265
273
  * Check whether a key exists.
266
274
  */
267
275
  has(key: string): boolean;
276
+ /**
277
+ * Define a Zod schema for configuration validation.
278
+ *
279
+ * @param schema - Zod schema for validation
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * config.defineSchema(z.object({
284
+ * DATABASE_URL: z.string().url(),
285
+ * PORT: z.number().default(3000),
286
+ * }))
287
+ * ```
288
+ */
289
+ defineSchema(schema: ZodSchema): void;
290
+ /**
291
+ * Validate configuration against the defined schema.
292
+ *
293
+ * Should be called during bootstrap to catch configuration errors early.
294
+ *
295
+ * @throws Error if validation fails with details about missing/invalid fields
296
+ *
297
+ * @example
298
+ * ```typescript
299
+ * try {
300
+ * config.validate()
301
+ * } catch (error) {
302
+ * console.error('Config validation failed:', error.message)
303
+ * process.exit(1)
304
+ * }
305
+ * ```
306
+ */
307
+ validate(): void;
308
+ }
309
+
310
+ /**
311
+ * RequestScopeMetrics - Observability for RequestScope lifecycle
312
+ *
313
+ * Tracks cleanup execution time, scope size, and service counts
314
+ * for performance monitoring and diagnostics.
315
+ *
316
+ * @example
317
+ * ```typescript
318
+ * const metrics = new RequestScopeMetrics()
319
+ * metrics.recordCleanupStart()
320
+ * await scope.cleanup()
321
+ * metrics.recordCleanupEnd()
322
+ *
323
+ * console.log(metrics.toJSON())
324
+ * // { cleanupDuration: 2.5, scopeSize: 3, servicesCleaned: 3 }
325
+ * ```
326
+ */
327
+ declare class RequestScopeMetrics {
328
+ private cleanupStartTime;
329
+ private cleanupDuration;
330
+ private scopeSize;
331
+ private servicesCleaned;
332
+ private errorsOccurred;
333
+ /**
334
+ * Record start of cleanup operation
335
+ */
336
+ recordCleanupStart(): void;
337
+ /**
338
+ * Record end of cleanup operation
339
+ *
340
+ * @param scopeSize - Number of services in the scope
341
+ * @param servicesCleaned - Number of services that had cleanup called
342
+ * @param errorsOccurred - Number of cleanup errors
343
+ */
344
+ recordCleanupEnd(scopeSize: number, servicesCleaned: number, errorsOccurred?: number): void;
345
+ /**
346
+ * Get cleanup duration in milliseconds
347
+ *
348
+ * @returns Duration in ms, or null if cleanup not completed
349
+ */
350
+ getCleanupDuration(): number | null;
351
+ /**
352
+ * Check if cleanup took longer than threshold (default 2ms)
353
+ * Useful for detecting slow cleanups
354
+ *
355
+ * @param thresholdMs - Threshold in milliseconds
356
+ * @returns True if cleanup exceeded threshold
357
+ */
358
+ isSlowCleanup(thresholdMs?: number): boolean;
359
+ /**
360
+ * Export metrics as JSON for logging/monitoring
361
+ */
362
+ toJSON(): {
363
+ cleanupDuration: number | null;
364
+ scopeSize: number;
365
+ servicesCleaned: number;
366
+ errorsOccurred: number;
367
+ hasErrors: boolean;
368
+ isSlowCleanup: boolean;
369
+ };
370
+ /**
371
+ * Export metrics as compact string for logging
372
+ */
373
+ toString(): string;
374
+ }
375
+ /**
376
+ * RequestScopeObserver - Hook for monitoring RequestScope lifecycle
377
+ *
378
+ * Implement this interface to receive callbacks during scope operations
379
+ */
380
+ interface RequestScopeObserver {
381
+ /**
382
+ * Called when a service is resolved in the scope
383
+ */
384
+ onServiceResolved?(key: string | symbol, isFromCache: boolean): void;
385
+ /**
386
+ * Called when cleanup starts
387
+ */
388
+ onCleanupStart?(): void;
389
+ /**
390
+ * Called when cleanup completes
391
+ */
392
+ onCleanupEnd?(metrics: RequestScopeMetrics): void;
393
+ /**
394
+ * Called when cleanup encounters an error
395
+ */
396
+ onCleanupError?(error: Error): void;
397
+ }
398
+ /**
399
+ * RequestScopeMetricsCollector - Aggregates metrics across multiple scopes
400
+ *
401
+ * Used for application-level monitoring and performance tracking
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * const collector = new RequestScopeMetricsCollector()
406
+ *
407
+ * // Record metrics from multiple requests
408
+ * collector.record(metrics1)
409
+ * collector.record(metrics2)
410
+ * collector.record(metrics3)
411
+ *
412
+ * // Get aggregated stats
413
+ * const stats = collector.getStats()
414
+ * console.log(stats.averageCleanupTime) // 3.5ms
415
+ * ```
416
+ */
417
+ declare class RequestScopeMetricsCollector {
418
+ private metrics;
419
+ /**
420
+ * Record metrics from a request scope
421
+ */
422
+ record(metrics: RequestScopeMetrics): void;
423
+ /**
424
+ * Get aggregated statistics
425
+ */
426
+ getStats(): {
427
+ count: number;
428
+ averageCleanupTime: number | null;
429
+ maxCleanupTime: number | null;
430
+ minCleanupTime: number | null;
431
+ totalErrorCount: number;
432
+ errorRate: number;
433
+ };
434
+ /**
435
+ * Clear collected metrics
436
+ */
437
+ clear(): void;
438
+ /**
439
+ * Get number of recorded metrics
440
+ */
441
+ size(): number;
442
+ /**
443
+ * Export metrics as JSON array
444
+ */
445
+ toJSON(): {
446
+ cleanupDuration: number | null;
447
+ scopeSize: number;
448
+ servicesCleaned: number;
449
+ errorsOccurred: number;
450
+ hasErrors: boolean;
451
+ isSlowCleanup: boolean;
452
+ }[];
453
+ }
454
+
455
+ /**
456
+ * Manages request-scoped service instances within a single HTTP request.
457
+ *
458
+ * Each request gets its own RequestScopeManager instance with isolated state.
459
+ * Services are cached within the request and automatically cleaned up when
460
+ * the request ends.
461
+ *
462
+ * @example
463
+ * ```typescript
464
+ * const scope = new RequestScopeManager()
465
+ * const cache = scope.resolve('productCache', () => new ProductCache())
466
+ * // ... use cache ...
467
+ * await scope.cleanup() // Called automatically by Gravito engine
468
+ * ```
469
+ */
470
+ declare class RequestScopeManager {
471
+ private scoped;
472
+ private metadata;
473
+ private metrics;
474
+ private observer;
475
+ constructor(observer?: RequestScopeObserver);
476
+ /**
477
+ * Set observer for monitoring scope lifecycle
478
+ */
479
+ setObserver(observer: RequestScopeObserver): void;
480
+ /**
481
+ * Get metrics for this scope
482
+ */
483
+ getMetrics(): RequestScopeMetrics;
484
+ /**
485
+ * Resolve or retrieve a request-scoped service instance.
486
+ *
487
+ * If the service already exists in this scope, returns the cached instance.
488
+ * Otherwise, calls the factory function to create a new instance and caches it.
489
+ *
490
+ * Automatically detects and records services with cleanup methods.
491
+ *
492
+ * @template T - The type of the service.
493
+ * @param key - The service key (for caching).
494
+ * @param factory - Factory function to create the instance if not cached.
495
+ * @returns The cached or newly created instance.
496
+ */
497
+ resolve<T>(key: ServiceKey, factory: () => T): T;
498
+ /**
499
+ * Clean up all request-scoped instances.
500
+ *
501
+ * Calls the cleanup() method on each service that has one.
502
+ * Silently ignores cleanup errors to prevent cascading failures.
503
+ * Called automatically by the Gravito engine in the request finally block.
504
+ *
505
+ * @returns Promise that resolves when all cleanup is complete.
506
+ */
507
+ cleanup(): Promise<void>;
508
+ /**
509
+ * Get the number of services in this scope (for monitoring).
510
+ *
511
+ * @returns The count of cached services.
512
+ */
513
+ size(): number;
268
514
  }
269
515
 
270
516
  /**
@@ -300,6 +546,27 @@ declare class Container {
300
546
  private bindings;
301
547
  private instances;
302
548
  private resolutionStack;
549
+ /**
550
+ * Run a function within a request scope context.
551
+ *
552
+ * All service resolutions within the function will use the provided scope,
553
+ * enabling request-scoped service instances to be properly isolated.
554
+ *
555
+ * @template T - The return type of the function.
556
+ * @param scope - The RequestScopeManager for this request.
557
+ * @param fn - The function to execute within the scope.
558
+ * @returns The result of the function.
559
+ *
560
+ * @example
561
+ * ```typescript
562
+ * const scope = new RequestScopeManager()
563
+ * const result = await Container.runWithScope(scope, async () => {
564
+ * const service = container.make('requestScoped')
565
+ * return service.doSomething()
566
+ * })
567
+ * ```
568
+ */
569
+ static runWithScope<T>(scope: RequestScopeManager, fn: () => T | Promise<T>): T | Promise<T>;
303
570
  /**
304
571
  * Bind a service to the container.
305
572
  *
@@ -332,6 +599,22 @@ declare class Container {
332
599
  * ```
333
600
  */
334
601
  singleton<T>(key: ServiceKey, factory: Factory$1<T>): void;
602
+ /**
603
+ * Bind a request-scoped service to the container.
604
+ *
605
+ * A new instance will be created for each request and cached within that request.
606
+ * The service is automatically cleaned up when the request ends.
607
+ *
608
+ * @template T - The type of the service being bound.
609
+ * @param key - The unique identifier for the service.
610
+ * @param factory - The factory function that creates the service instance.
611
+ *
612
+ * @example
613
+ * ```typescript
614
+ * container.scoped('requestCache', (c) => new RequestProductCache());
615
+ * ```
616
+ */
617
+ scoped<T>(key: ServiceKey, factory: Factory$1<T>): void;
335
618
  /**
336
619
  * Register an existing instance as a shared service.
337
620
  *
@@ -339,6 +622,13 @@ declare class Container {
339
622
  * @param instance - The instance to register.
340
623
  */
341
624
  instance<T>(key: ServiceKey, instance: T): void;
625
+ /**
626
+ * Check if a service is request-scoped.
627
+ *
628
+ * @param key - The service key to check.
629
+ * @returns True if the service is request-scoped.
630
+ */
631
+ isRequestScoped(key: ServiceKey): boolean;
342
632
  /**
343
633
  * Resolve a service instance from the container.
344
634
  *
@@ -977,6 +1267,11 @@ declare class HasPersistence {
977
1267
  * @returns True if the model has been persisted
978
1268
  */
979
1269
  get exists(): boolean;
1270
+ /**
1271
+ * Internal helper to retrieve the correct connection depending on sharding configuration
1272
+ * @internal
1273
+ */
1274
+ protected _getConnection(): ConnectionContract;
980
1275
  /**
981
1276
  * Save the model instance to the database (insert or update).
982
1277
  *
@@ -1580,11 +1875,19 @@ declare abstract class Model$1 {
1580
1875
  * @yields Chunks of model instances.
1581
1876
  */
1582
1877
  static cursor<T extends Model$1>(this: ModelConstructor$1<T> & typeof Model$1, chunkSize?: number): AsyncGenerator<T[], void, unknown>;
1878
+ /**
1879
+ * Initializes a fluent query builder for the model on a specific sharded connection.
1880
+ *
1881
+ * @param key - The shard distribution key
1882
+ * @returns A proxied query builder instance connected to the right shard.
1883
+ */
1884
+ static shard<T extends Model$1>(this: ModelConstructor$1<T> & typeof Model$1, key: string | number): QueryBuilderContract<T>;
1583
1885
  /**
1584
1886
  * Initializes a fluent query builder for the model.
1585
1887
  *
1586
1888
  * Automatically handles model hydration, soft delete filtering, and scope application.
1587
1889
  *
1890
+ * @param connectionContract - Optional specific database connection
1588
1891
  * @returns A proxied query builder instance.
1589
1892
  *
1590
1893
  * @example
@@ -1592,7 +1895,7 @@ declare abstract class Model$1 {
1592
1895
  * const users = await User.query().where('active', true).get();
1593
1896
  * ```
1594
1897
  */
1595
- static query<T extends Model$1>(this: ModelConstructor$1<T> & typeof Model$1): QueryBuilderContract<T>;
1898
+ static query<T extends Model$1>(this: ModelConstructor$1<T> & typeof Model$1, connectionContract?: ConnectionContract): QueryBuilderContract<T>;
1596
1899
  /**
1597
1900
  * Starts a query with a standard WHERE clause.
1598
1901
  *
@@ -1664,9 +1967,31 @@ interface AtlasMetricsConfig {
1664
1967
  declare class AtlasMetrics {
1665
1968
  private meter;
1666
1969
  private config;
1970
+ private poolCallbacks;
1667
1971
  readonly operationDuration?: Histogram;
1668
1972
  readonly operationErrors?: Counter;
1973
+ readonly poolSize?: any;
1974
+ readonly poolUtilization?: any;
1975
+ readonly poolWaitTime?: Histogram;
1976
+ readonly poolAcquisitionErrors?: Counter;
1669
1977
  constructor(config: AtlasMetricsConfig);
1978
+ /**
1979
+ * Register pool statistics callback for ObservableGauge
1980
+ */
1981
+ registerPoolStatsCallback(connectionName: string, getStats: () => {
1982
+ idle: number;
1983
+ active: number;
1984
+ pending: number;
1985
+ max: number;
1986
+ } | null): void;
1987
+ /**
1988
+ * Record connection wait time
1989
+ */
1990
+ recordConnectionWaitTime(connectionName: string, duration: number): void;
1991
+ /**
1992
+ * Record connection acquisition error
1993
+ */
1994
+ recordConnectionAcquisitionError(connectionName: string, error: string): void;
1670
1995
  }
1671
1996
 
1672
1997
  interface AtlasTracingConfig {
@@ -2156,6 +2481,27 @@ interface PoolStats {
2156
2481
  */
2157
2482
  max: number;
2158
2483
  }
2484
+ /**
2485
+ * Connection pool health status
2486
+ */
2487
+ interface PoolHealth {
2488
+ /**
2489
+ * Health status: 'healthy' | 'warning' | 'critical' | 'disconnected'
2490
+ */
2491
+ status: 'healthy' | 'warning' | 'critical' | 'disconnected';
2492
+ /**
2493
+ * Human-readable health message
2494
+ */
2495
+ message: string;
2496
+ /**
2497
+ * Pool statistics (when available)
2498
+ */
2499
+ stats?: PoolStats;
2500
+ /**
2501
+ * Last health check timestamp
2502
+ */
2503
+ lastCheck?: Date;
2504
+ }
2159
2505
  /**
2160
2506
  * Model base class (forward declaration)
2161
2507
  * Actual implementation in src/orm/model/Model.ts
@@ -2243,6 +2589,18 @@ interface DriverContract {
2243
2589
  * @returns Pool statistics or null if not supported
2244
2590
  */
2245
2591
  getPoolStats?(): PoolStats | null;
2592
+ /**
2593
+ * Get connection pool health status
2594
+ * @optional Only implemented by drivers that support connection pooling
2595
+ * @returns Pool health information
2596
+ */
2597
+ getPoolHealth?(): PoolHealth;
2598
+ /**
2599
+ * Adjust the connection pool size dynamically
2600
+ * @optional Only implemented by drivers that support pool resizing
2601
+ * @param targetSize - Target number of connections
2602
+ */
2603
+ adjustPoolSize?(targetSize: number): Promise<void>;
2246
2604
  }
2247
2605
  /**
2248
2606
  * Connection Contract
@@ -2771,12 +3129,50 @@ interface EventOptions {
2771
3129
  async?: boolean;
2772
3130
  /**
2773
3131
  * Priority level for event processing.
2774
- * - 'high': Critical events (e.g., order:created, payment:succeeded)
2775
- * - 'normal': Standard events (e.g., order:confirmed)
2776
- * - 'low': Non-critical events (e.g., analytics, logging)
3132
+ * - 'critical': Immediate processing, bypass queue (< 1ms)
3133
+ * - 'high': High priority events (< 50ms)
3134
+ * - 'normal': Standard events (< 200ms)
3135
+ * - 'low': Non-critical events (< 500ms)
2777
3136
  * @default 'normal'
2778
3137
  */
2779
- priority?: 'high' | 'normal' | 'low';
3138
+ priority?: 'critical' | 'high' | 'normal' | 'low';
3139
+ /**
3140
+ * Automatic priority escalation configuration.
3141
+ * Events can be automatically upgraded to higher priority based on wait time.
3142
+ */
3143
+ escalation?: {
3144
+ /**
3145
+ * Whether to enable automatic priority escalation.
3146
+ * @default true
3147
+ */
3148
+ enabled?: boolean;
3149
+ /**
3150
+ * Escalation thresholds in milliseconds.
3151
+ * Events exceeding these wait times are promoted.
3152
+ */
3153
+ thresholds?: {
3154
+ /**
3155
+ * Wait time before LOW events are promoted to NORMAL.
3156
+ * @default 200
3157
+ */
3158
+ lowToNormal?: number;
3159
+ /**
3160
+ * Wait time before NORMAL events are promoted to HIGH.
3161
+ * @default 100
3162
+ */
3163
+ normalToHigh?: number;
3164
+ /**
3165
+ * Wait time before HIGH events are promoted to CRITICAL.
3166
+ * @default 50
3167
+ */
3168
+ highToCritical?: number;
3169
+ };
3170
+ /**
3171
+ * Maximum wait time before forcing CRITICAL priority.
3172
+ * @default 500
3173
+ */
3174
+ maxWaitTimeMs?: number;
3175
+ };
2780
3176
  /**
2781
3177
  * Execution timeout in milliseconds.
2782
3178
  * If a listener exceeds this timeout, it will be terminated.
@@ -2862,6 +3258,63 @@ interface EventOptions {
2862
3258
  */
2863
3259
  halfOpenRequests?: number;
2864
3260
  };
3261
+ /**
3262
+ * Event aggregation configuration (FS-102).
3263
+ * Enables deduplication and micro-batching for improved throughput.
3264
+ * @default undefined (disabled)
3265
+ */
3266
+ aggregation?: {
3267
+ /**
3268
+ * Enable event aggregation.
3269
+ * @default false
3270
+ */
3271
+ enabled?: boolean;
3272
+ /**
3273
+ * Aggregation window size in milliseconds.
3274
+ * Backpressure-aware adjustment: 50-500ms
3275
+ * @default 200
3276
+ */
3277
+ windowMs?: number;
3278
+ /**
3279
+ * Batch size threshold for auto-flush.
3280
+ * @default 50
3281
+ */
3282
+ batchSize?: number;
3283
+ /**
3284
+ * Deduplication strategy.
3285
+ * @default 'pattern'
3286
+ */
3287
+ deduplication?: 'pattern' | 'idempotencyKey' | 'off';
3288
+ /**
3289
+ * Deduplication pattern (string or function).
3290
+ * String: hook-based pattern
3291
+ * Function: custom pattern from event args
3292
+ */
3293
+ pattern?: string | ((args: unknown) => string);
3294
+ /**
3295
+ * Priority merge strategy.
3296
+ * - 'highest': keep highest priority event
3297
+ * - 'earliest': keep earliest event
3298
+ * - 'latest': keep latest event
3299
+ * @default 'highest'
3300
+ */
3301
+ mergePriority?: 'highest' | 'earliest' | 'latest';
3302
+ /**
3303
+ * Enable automatic cleanup of expired entries.
3304
+ * @default true
3305
+ */
3306
+ enableCleanup?: boolean;
3307
+ /**
3308
+ * Cleanup interval in milliseconds.
3309
+ * @default 300000 (5 minutes)
3310
+ */
3311
+ cleanupIntervalMs?: number;
3312
+ /**
3313
+ * TTL for entries in milliseconds.
3314
+ * @default 600000 (10 minutes)
3315
+ */
3316
+ ttlMs?: number;
3317
+ };
2865
3318
  }
2866
3319
  /**
2867
3320
  * Default event options.
@@ -3400,54 +3853,421 @@ declare class DeadLetterQueueManager {
3400
3853
  * ```
3401
3854
  */
3402
3855
  clear(includeResolved?: boolean): Promise<number>;
3856
+ /**
3857
+ * 通過 Bull Job ID 查找 DLQ 記錄
3858
+ *
3859
+ * 用於 MessageQueueBridge 集成:當 Bull Queue job 失敗時,
3860
+ * 通過 Job ID 查找相應的 DLQ 記錄。
3861
+ *
3862
+ * @param bullJobId - Bull Queue Job ID
3863
+ * @returns DLQ 記錄或 undefined
3864
+ *
3865
+ * @example
3866
+ * ```typescript
3867
+ * const record = await dlqManager.findByBullJobId('job-abc123')
3868
+ * if (record) {
3869
+ * console.log(`Event ${record.event_name} is in DLQ`)
3870
+ * }
3871
+ * ```
3872
+ */
3873
+ findByBullJobId(bullJobId: string): Promise<DLQRecord | undefined>;
3874
+ /**
3875
+ * 調度延遲重試(整合 Bull Queue delayed jobs)
3876
+ *
3877
+ * 從 DLQ 中提取事件,通過 Bull Queue 的延遲 job 功能進行重試。
3878
+ *
3879
+ * @param dlqId - DLQ 記錄 ID
3880
+ * @param delayMs - 延遲時間(毫秒)
3881
+ * @throws 如果記錄不存在
3882
+ *
3883
+ * @example
3884
+ * ```typescript
3885
+ * // 延遲 1 小時後重試
3886
+ * await dlqManager.scheduleRetry('dlq-uuid-123', 3600000)
3887
+ * ```
3888
+ */
3889
+ scheduleRetry(dlqId: string, delayMs: number): Promise<void>;
3403
3890
  }
3404
3891
 
3405
3892
  /**
3406
- * Circuit Breaker state enum.
3407
- * @public
3408
- */
3409
- declare enum CircuitBreakerState {
3410
- CLOSED = "CLOSED",
3411
- OPEN = "OPEN",
3412
- HALF_OPEN = "HALF_OPEN"
3413
- }
3414
- /**
3415
- * Circuit Breaker metrics snapshot.
3416
- * @public
3893
+ * Event task for priority queue processing.
3894
+ * @internal
3417
3895
  */
3418
- interface CircuitBreakerMetrics {
3896
+ interface EventTask {
3419
3897
  /**
3420
- * Current state of the circuit breaker
3898
+ * Unique identifier for this event task.
3421
3899
  */
3422
- state: CircuitBreakerState;
3900
+ id: string;
3423
3901
  /**
3424
- * Number of failures in the current window
3902
+ * Event hook name.
3425
3903
  */
3426
- failures: number;
3904
+ hook: string;
3427
3905
  /**
3428
- * Number of successes in the current window
3906
+ * Event payload/arguments.
3429
3907
  */
3430
- successes: number;
3908
+ args: unknown;
3431
3909
  /**
3432
- * Timestamp of the last failure
3910
+ * Event options.
3433
3911
  */
3434
- lastFailureAt?: Date;
3912
+ options: EventOptions;
3435
3913
  /**
3436
- * Timestamp of the last success
3914
+ * Callbacks to execute for this event.
3437
3915
  */
3438
- lastSuccessAt?: Date;
3916
+ callbacks: ActionCallback[];
3439
3917
  /**
3440
- * Timestamp when the circuit was opened
3918
+ * Timestamp when the event was created.
3441
3919
  */
3442
- openedAt?: Date;
3920
+ createdAt: number;
3443
3921
  /**
3444
- * Total requests processed
3922
+ * Timestamp when the event was enqueued (added to the queue).
3923
+ * Used for priority escalation calculations.
3924
+ * @internal
3445
3925
  */
3446
- totalRequests: number;
3926
+ enqueuedAt: number;
3447
3927
  /**
3448
- * Total failures recorded
3928
+ * Partition key for ordering (if applicable).
3449
3929
  */
3450
- totalFailures: number;
3930
+ partitionKey?: string;
3931
+ /**
3932
+ * Number of retry attempts made.
3933
+ * @internal
3934
+ */
3935
+ retryCount?: number;
3936
+ /**
3937
+ * Timestamp when the event first failed.
3938
+ * @internal
3939
+ */
3940
+ firstFailedAt?: number;
3941
+ /**
3942
+ * Last error encountered.
3943
+ * @internal
3944
+ */
3945
+ lastError?: Error;
3946
+ }
3947
+ /**
3948
+ * Strategy for handling backpressure when the queue is full.
3949
+ */
3950
+ type BackpressureStrategy = 'reject' | 'drop-oldest' | 'drop-newest' | 'ignore';
3951
+ /**
3952
+ * Configuration for the event priority queue.
3953
+ */
3954
+ interface EventQueueConfig {
3955
+ /**
3956
+ * Maximum number of pending events in the queue.
3957
+ * If exceeded, the backpressure strategy is applied.
3958
+ * @default undefined (unbounded)
3959
+ */
3960
+ maxSize?: number;
3961
+ /**
3962
+ * Strategy to use when the queue is full.
3963
+ * - 'reject': Throw an error (default)
3964
+ * - 'drop-oldest': Drop the oldest lowest-priority event
3965
+ * - 'drop-newest': Drop the incoming event
3966
+ * - 'ignore': Silently drop the incoming event
3967
+ * @default 'reject'
3968
+ */
3969
+ strategy?: BackpressureStrategy;
3970
+ /**
3971
+ * Advanced backpressure management configuration.
3972
+ * When enabled, provides state-based flow control with multi-strategy support.
3973
+ * If not provided, falls back to simple strategy-based backpressure.
3974
+ * @default undefined (disabled, uses simple strategy)
3975
+ */
3976
+ backpressure?: BackpressureConfig;
3977
+ }
3978
+ /**
3979
+ * Multi-priority queue depth snapshot (FS-103)
3980
+ * Represents the current queue depth for each priority level.
3981
+ * @internal
3982
+ */
3983
+ interface MultiPriorityQueueDepth {
3984
+ /** Queue depth for CRITICAL priority events */
3985
+ critical: number;
3986
+ /** Queue depth for HIGH priority events */
3987
+ high: number;
3988
+ /** Queue depth for NORMAL priority events */
3989
+ normal: number;
3990
+ /** Queue depth for LOW priority events */
3991
+ low: number;
3992
+ /** Total queue depth across all priorities */
3993
+ total: number;
3994
+ }
3995
+ /**
3996
+ * Dead letter queue routing decision (FS-103)
3997
+ * Determines whether an event should be routed to the DLQ.
3998
+ * @internal
3999
+ */
4000
+ interface DeadLetterDecision {
4001
+ /** Whether the event should be routed to DLQ */
4002
+ shouldRoute: boolean;
4003
+ /** Reason for the decision (if applicable) */
4004
+ reason?: string;
4005
+ /** Suggested retry strategy */
4006
+ retryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
4007
+ }
4008
+
4009
+ /**
4010
+ * @gravito/core - Event System Backpressure Management
4011
+ *
4012
+ * Implements a backpressure management system to prevent high-priority events
4013
+ * from starving low-priority events when the queue is under resource constraints.
4014
+ *
4015
+ * 背壓管理器:在資源受限時進行智慧型流量控制,防止優先級飢餓。
4016
+ *
4017
+ * FS-103 增強:
4018
+ * - 多優先級隊列深度監控
4019
+ * - 背壓反饋迴路支持
4020
+ * - 智能 DLQ 路由決策
4021
+ */
4022
+
4023
+ /**
4024
+ * 背壓狀態枚舉。
4025
+ *
4026
+ * 狀態轉換:Normal → Warning → Critical → Overflow
4027
+ * 恢復方向:遲滯設計(需降至觸發閾值的 80%)
4028
+ *
4029
+ * @public
4030
+ */
4031
+ declare enum BackpressureState {
4032
+ /** 正常運作,無背壓 */
4033
+ NORMAL = "NORMAL",
4034
+ /** 警告狀態,開始限制低優先級事件 */
4035
+ WARNING = "WARNING",
4036
+ /** 危急狀態,僅允許高優先級事件 */
4037
+ CRITICAL = "CRITICAL",
4038
+ /** 溢位狀態,全部拒絕 */
4039
+ OVERFLOW = "OVERFLOW"
4040
+ }
4041
+ /**
4042
+ * 背壓配置選項。
4043
+ *
4044
+ * @public
4045
+ */
4046
+ interface BackpressureConfig {
4047
+ /** 是否啟用背壓管理器(預設 true) */
4048
+ enabled?: boolean;
4049
+ /** 總隊列深度限制(預設無限) */
4050
+ maxQueueSize?: number;
4051
+ /** 分優先級隊列深度限制 */
4052
+ maxSizeByPriority?: {
4053
+ critical?: number;
4054
+ high?: number;
4055
+ normal?: number;
4056
+ low?: number;
4057
+ };
4058
+ /** 每秒最大入隊速率(events/sec,預設無限) */
4059
+ maxEnqueueRate?: number;
4060
+ /** 速率限制滑動視窗大小(ms,預設 1000) */
4061
+ rateLimitWindowMs?: number;
4062
+ /** 背壓狀態閾值(佔 maxQueueSize 的百分比) */
4063
+ thresholds?: {
4064
+ /** WARNING 觸發百分比(預設 0.6 = 60%) */
4065
+ warning?: number;
4066
+ /** CRITICAL 觸發百分比(預設 0.85 = 85%) */
4067
+ critical?: number;
4068
+ /** OVERFLOW 觸發百分比(預設 1.0 = 100%) */
4069
+ overflow?: number;
4070
+ };
4071
+ /** 被拒絕事件的處理策略(預設 'drop-with-callback') */
4072
+ rejectionPolicy?: 'throw' | 'drop-silent' | 'drop-with-callback';
4073
+ /** 當 rejectionPolicy 為 'drop-with-callback' 時的回呼 */
4074
+ onRejected?: (eventName: string, priority: string, reason: string) => void;
4075
+ /** 背壓狀態變更回呼 */
4076
+ onStateChange?: (from: BackpressureState, to: BackpressureState) => void;
4077
+ /** 低優先級事件在 WARNING 狀態下的延遲入隊時間(ms,預設 100) */
4078
+ lowPriorityDelayMs?: number;
4079
+ /** 是否啟用優先級反轉防護(預設 true) */
4080
+ enableStarvationProtection?: boolean;
4081
+ /** 低優先級事件最大等待時間,超過則提升優先級(ms,預設 5000) */
4082
+ starvationTimeoutMs?: number;
4083
+ /** 當進入 OVERFLOW 狀態時,是否將被拒絕事件路由到 DLQ(預設 false) */
4084
+ dlqOnOverflow?: boolean;
4085
+ /** OVERFLOW 時的重試策略(預設 'dlq-only') */
4086
+ overflowRetryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
4087
+ /** OVERFLOW 延遲重試的基礎延遲時間(ms,預設 5000) */
4088
+ overflowRetryDelayMs?: number;
4089
+ }
4090
+ /**
4091
+ * 背壓決策結果。
4092
+ *
4093
+ * @public
4094
+ */
4095
+ interface BackpressureDecision {
4096
+ /** 是否允許入隊 */
4097
+ allowed: boolean;
4098
+ /** 拒絕原因(若不允許) */
4099
+ reason?: string;
4100
+ /** 是否需要延遲入隊 */
4101
+ delayed?: boolean;
4102
+ /** 延遲時間(ms) */
4103
+ delayMs?: number;
4104
+ /** 建議降級後的優先級(若降級) */
4105
+ degradedPriority?: 'high' | 'normal' | 'low';
4106
+ /** 是否是由於 OVERFLOW 狀態被拒絕 */
4107
+ isOverflow?: boolean;
4108
+ /** OVERFLOW 時的重試策略建議('immediate'、'delayed'、'dlq-only') */
4109
+ retryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
4110
+ }
4111
+ /**
4112
+ * 背壓指標快照。
4113
+ *
4114
+ * @public
4115
+ */
4116
+ interface BackpressureMetricsSnapshot {
4117
+ state: BackpressureState;
4118
+ totalDepth: number;
4119
+ depthByPriority: {
4120
+ critical: number;
4121
+ high: number;
4122
+ normal: number;
4123
+ low: number;
4124
+ };
4125
+ enqueueRate: number;
4126
+ rejectedCount: number;
4127
+ degradedCount: number;
4128
+ stateTransitions: number;
4129
+ dlqRouteCount?: number;
4130
+ windowAdjustmentCount?: number;
4131
+ }
4132
+ /**
4133
+ * 背壓管理器。
4134
+ *
4135
+ * 根據隊列深度、速率、優先級等因素,決定是否允許新事件入隊,
4136
+ * 以及是否需要降級優先級或延遲入隊。
4137
+ *
4138
+ * @public
4139
+ */
4140
+ declare class BackpressureManager {
4141
+ private enabled;
4142
+ private config;
4143
+ private onRejected?;
4144
+ private onStateChange?;
4145
+ private state;
4146
+ private rejectedCount;
4147
+ private degradedCount;
4148
+ private stateTransitions;
4149
+ private rateCounter;
4150
+ private depthByPriority;
4151
+ private windowAdjustmentHistory;
4152
+ private dlqRouteCount;
4153
+ constructor(config?: BackpressureConfig);
4154
+ /**
4155
+ * 評估是否允許新事件入隊。
4156
+ *
4157
+ * @param eventName 事件名稱
4158
+ * @param priority 事件優先級
4159
+ * @param queueDepth 當前隊列深度
4160
+ * @param depthByPriority 分優先級隊列深度
4161
+ * @returns 背壓決策結果
4162
+ */
4163
+ evaluate(eventName: string, priority: 'critical' | 'high' | 'normal' | 'low', queueDepth: number, depthByPriority: {
4164
+ critical: number;
4165
+ high: number;
4166
+ normal: number;
4167
+ low: number;
4168
+ }): BackpressureDecision;
4169
+ /**
4170
+ * 獲取當前背壓狀態。
4171
+ */
4172
+ getState(): BackpressureState;
4173
+ /**
4174
+ * 獲取背壓指標快照。
4175
+ */
4176
+ getMetrics(): BackpressureMetricsSnapshot;
4177
+ /**
4178
+ * 重置背壓管理器狀態。
4179
+ */
4180
+ reset(): void;
4181
+ /**
4182
+ * 同步隊列深度(由 EventPriorityQueue 調用)。
4183
+ * FS-103:多優先級隊列深度監控
4184
+ */
4185
+ updateQueueDepth(depths: MultiPriorityQueueDepth): void;
4186
+ /**
4187
+ * 獲取各優先級的隊列深度。
4188
+ * FS-103:提供實時隊列深度快照
4189
+ */
4190
+ getQueueDepthByPriority(): MultiPriorityQueueDepth;
4191
+ /**
4192
+ * 獲取總隊列深度。
4193
+ */
4194
+ getTotalQueueDepth(): number;
4195
+ /**
4196
+ * 接收來自 AggregationWindow 的窗口調整通知。
4197
+ * FS-103:背壓反饋迴路
4198
+ */
4199
+ notifyWindowAdjustment(oldWindowMs: number, newWindowMs: number): void;
4200
+ /**
4201
+ * 檢查是否可以從 CRITICAL 或更高級別降級。
4202
+ * FS-103:自動狀態恢復機制
4203
+ */
4204
+ private checkStateRecovery;
4205
+ /**
4206
+ * 決定是否應該將事件路由到死信隊列。
4207
+ * FS-103:智能 DLQ 路由決策
4208
+ */
4209
+ makeDeadLetterDecision(_eventName: string, priority: 'critical' | 'high' | 'normal' | 'low'): DeadLetterDecision;
4210
+ /**
4211
+ * 更新背壓狀態。
4212
+ * 使用遲滯設計(80% 回復比例)避免邊界震盪。
4213
+ */
4214
+ private updateState;
4215
+ /**
4216
+ * 執行狀態轉換。
4217
+ */
4218
+ private transitionTo;
4219
+ /**
4220
+ * 建立決策結果並記錄拒絕。
4221
+ */
4222
+ private createDecision;
4223
+ }
4224
+
4225
+ /**
4226
+ * Circuit Breaker state enum.
4227
+ * @public
4228
+ */
4229
+ declare enum CircuitBreakerState {
4230
+ CLOSED = "CLOSED",
4231
+ OPEN = "OPEN",
4232
+ HALF_OPEN = "HALF_OPEN"
4233
+ }
4234
+ /**
4235
+ * Circuit Breaker metrics snapshot.
4236
+ * @public
4237
+ */
4238
+ interface CircuitBreakerMetrics {
4239
+ /**
4240
+ * Current state of the circuit breaker
4241
+ */
4242
+ state: CircuitBreakerState;
4243
+ /**
4244
+ * Number of failures in the current window
4245
+ */
4246
+ failures: number;
4247
+ /**
4248
+ * Number of successes in the current window
4249
+ */
4250
+ successes: number;
4251
+ /**
4252
+ * Timestamp of the last failure
4253
+ */
4254
+ lastFailureAt?: Date;
4255
+ /**
4256
+ * Timestamp of the last success
4257
+ */
4258
+ lastSuccessAt?: Date;
4259
+ /**
4260
+ * Timestamp when the circuit was opened
4261
+ */
4262
+ openedAt?: Date;
4263
+ /**
4264
+ * Total requests processed
4265
+ */
4266
+ totalRequests: number;
4267
+ /**
4268
+ * Total failures recorded
4269
+ */
4270
+ totalFailures: number;
3451
4271
  /**
3452
4272
  * Total successes recorded
3453
4273
  */
@@ -3625,6 +4445,11 @@ declare class CircuitBreaker {
3625
4445
  private stateToNumber;
3626
4446
  }
3627
4447
 
4448
+ /**
4449
+ * Source of DLQ entry - reason why event entered the DLQ.
4450
+ * @public
4451
+ */
4452
+ type DLQEntrySource = 'retry_exhausted' | 'circuit_breaker' | 'backpressure_overflow' | 'manual';
3628
4453
  /**
3629
4454
  * Dead Letter Queue entry representing a failed event.
3630
4455
  * @public
@@ -3670,6 +4495,10 @@ interface DLQEntry {
3670
4495
  * Timestamp when the event was last retried (if any).
3671
4496
  */
3672
4497
  lastRetriedAt?: number;
4498
+ /**
4499
+ * Source of the DLQ entry - reason why event entered the DLQ.
4500
+ */
4501
+ source: DLQEntrySource;
3673
4502
  }
3674
4503
  /**
3675
4504
  * Filter options for querying DLQ entries.
@@ -3693,6 +4522,11 @@ interface DLQFilter {
3693
4522
  */
3694
4523
  limit?: number;
3695
4524
  }
4525
+ /**
4526
+ * Callback type for DLQ entry events.
4527
+ * @public
4528
+ */
4529
+ type DLQEntryCallback = (entry: DLQEntry) => void;
3696
4530
  /**
3697
4531
  * Dead Letter Queue Manager for handling failed events.
3698
4532
  *
@@ -3704,6 +4538,15 @@ interface DLQFilter {
3704
4538
  declare class DeadLetterQueue {
3705
4539
  private entries;
3706
4540
  private entryIdCounter;
4541
+ private maxEntries?;
4542
+ private onEntryAdded?;
4543
+ private onEntryRemoved?;
4544
+ /**
4545
+ * Create a new DeadLetterQueue instance.
4546
+ *
4547
+ * @param maxEntries - Maximum number of entries to keep (optional, no limit if not set)
4548
+ */
4549
+ constructor(maxEntries?: number);
3707
4550
  /**
3708
4551
  * Add a failed event to the Dead Letter Queue.
3709
4552
  *
@@ -3713,9 +4556,10 @@ declare class DeadLetterQueue {
3713
4556
  * @param error - Error that caused the failure
3714
4557
  * @param retryCount - Number of retry attempts made
3715
4558
  * @param firstFailedAt - Timestamp of first failure
4559
+ * @param source - Source of the DLQ entry (default: 'retry_exhausted')
3716
4560
  * @returns DLQ entry ID
3717
4561
  */
3718
- add(eventName: string, payload: unknown, options: EventOptions, error: Error, retryCount: number, firstFailedAt: number): string;
4562
+ add(eventName: string, payload: unknown, options: EventOptions, error: Error, retryCount: number, firstFailedAt: number, source?: DLQEntrySource): string;
3719
4563
  /**
3720
4564
  * Get a specific DLQ entry by ID.
3721
4565
  *
@@ -3768,80 +4612,56 @@ declare class DeadLetterQueue {
3768
4612
  * @internal
3769
4613
  */
3770
4614
  updateLastRetried(entryId: string): void;
3771
- }
3772
-
3773
- /**
3774
- * Event task for priority queue processing.
3775
- * @internal
3776
- */
3777
- interface EventTask {
3778
- /**
3779
- * Unique identifier for this event task.
3780
- */
3781
- id: string;
3782
- /**
3783
- * Event hook name.
3784
- */
3785
- hook: string;
3786
- /**
3787
- * Event payload/arguments.
3788
- */
3789
- args: unknown;
3790
- /**
3791
- * Event options.
3792
- */
3793
- options: EventOptions;
3794
4615
  /**
3795
- * Callbacks to execute for this event.
4616
+ * Evict the oldest entry from the DLQ.
4617
+ * Used when capacity limit is reached.
4618
+ *
4619
+ * @private
3796
4620
  */
3797
- callbacks: ActionCallback[];
4621
+ private evictOldest;
3798
4622
  /**
3799
- * Timestamp when the event was created.
4623
+ * Get the oldest entry in the DLQ.
4624
+ *
4625
+ * @returns Oldest DLQ entry or undefined if empty
3800
4626
  */
3801
- createdAt: number;
4627
+ getOldestEntry(): DLQEntry | undefined;
3802
4628
  /**
3803
- * Partition key for ordering (if applicable).
4629
+ * Get the newest entry in the DLQ.
4630
+ *
4631
+ * @returns Newest DLQ entry or undefined if empty
3804
4632
  */
3805
- partitionKey?: string;
4633
+ getNewestEntry(): DLQEntry | undefined;
3806
4634
  /**
3807
- * Number of retry attempts made.
3808
- * @internal
4635
+ * Get all entries grouped by source.
4636
+ *
4637
+ * @param source - Source to filter by
4638
+ * @returns Array of entries matching the source
3809
4639
  */
3810
- retryCount?: number;
4640
+ getEntriesBySource(source: DLQEntrySource): DLQEntry[];
3811
4641
  /**
3812
- * Timestamp when the event first failed.
3813
- * @internal
4642
+ * Set callback for when an entry is added to the DLQ.
4643
+ *
4644
+ * @param callback - Callback function or undefined to clear
3814
4645
  */
3815
- firstFailedAt?: number;
4646
+ setOnEntryAdded(callback?: DLQEntryCallback): void;
3816
4647
  /**
3817
- * Last error encountered.
3818
- * @internal
4648
+ * Set callback for when an entry is removed from the DLQ.
4649
+ *
4650
+ * @param callback - Callback function or undefined to clear
3819
4651
  */
3820
- lastError?: Error;
3821
- }
3822
- /**
3823
- * Strategy for handling backpressure when the queue is full.
3824
- */
3825
- type BackpressureStrategy = 'reject' | 'drop-oldest' | 'drop-newest' | 'ignore';
3826
- /**
3827
- * Configuration for the event priority queue.
3828
- */
3829
- interface EventQueueConfig {
4652
+ setOnEntryRemoved(callback?: DLQEntryCallback): void;
3830
4653
  /**
3831
- * Maximum number of pending events in the queue.
3832
- * If exceeded, the backpressure strategy is applied.
3833
- * @default undefined (unbounded)
4654
+ * Get the maximum number of entries allowed in the DLQ.
4655
+ *
4656
+ * @returns Max entries limit or undefined if no limit
3834
4657
  */
3835
- maxSize?: number;
4658
+ getMaxEntries(): number | undefined;
3836
4659
  /**
3837
- * Strategy to use when the queue is full.
3838
- * - 'reject': Throw an error (default)
3839
- * - 'drop-oldest': Drop the oldest lowest-priority event
3840
- * - 'drop-newest': Drop the incoming event
3841
- * - 'ignore': Silently drop the incoming event
3842
- * @default 'reject'
4660
+ * Set the maximum number of entries allowed in the DLQ.
4661
+ *
4662
+ * @param maxEntries - Maximum entries or undefined to remove limit
3843
4663
  */
3844
- strategy?: BackpressureStrategy;
4664
+ setMaxEntries(maxEntries?: number): void;
3845
4665
  }
3846
4666
 
3847
4667
  /**
@@ -3851,8 +4671,9 @@ interface EventBackend {
3851
4671
  /**
3852
4672
  * Enqueue an event for processing.
3853
4673
  * @param task - The event task to process
4674
+ * @returns Task ID or 'dropped' if event was rejected (can be async for some backends)
3854
4675
  */
3855
- enqueue(task: EventTask): Promise<void> | void;
4676
+ enqueue(task: EventTask): string | Promise<void>;
3856
4677
  }
3857
4678
 
3858
4679
  interface EventMetricGauge {
@@ -4151,28 +4972,770 @@ declare class EventTracing {
4151
4972
  declare function getEventTracing(config?: EventTracingConfig): EventTracing;
4152
4973
 
4153
4974
  /**
4154
- * Priority queue for event processing.
4155
- * Events are processed based on their priority level:
4156
- * - High priority events are processed first
4157
- * - Normal priority events are processed second
4158
- * - Low priority events are processed last
4975
+ * @gravito/core - OpenTelemetry Event Metrics
4159
4976
  *
4160
- * @internal
4977
+ * Provides event system metrics using OpenTelemetry API directly.
4978
+ * This enables Prometheus export without requiring @gravito/monitor dependency.
4979
+ *
4980
+ * Metrics:
4981
+ * - gravito_event_dispatch_duration_seconds (Histogram)
4982
+ * - gravito_event_listener_duration_seconds (Histogram)
4983
+ * - gravito_event_queue_depth (Observable Gauge)
4984
+ *
4985
+ * @packageDocumentation
4161
4986
  */
4162
- declare class EventPriorityQueue implements EventBackend {
4163
- private highPriority;
4164
- private normalPriority;
4165
- private lowPriority;
4166
- private processing;
4167
- private taskIdCounter;
4987
+
4988
+ /**
4989
+ * Queue depth callback type.
4990
+ * Returns the current queue depths for each priority level.
4991
+ */
4992
+ type QueueDepthCallback = () => {
4993
+ critical: number;
4994
+ high: number;
4995
+ normal: number;
4996
+ low: number;
4997
+ };
4998
+ /**
4999
+ * Circuit breaker state callback type.
5000
+ * Returns the current state of a circuit breaker.
5001
+ */
5002
+ type CircuitBreakerStateCallback = () => {
5003
+ eventName: string;
5004
+ listenerIndex: number;
5005
+ state: 0 | 1 | 2;
5006
+ };
5007
+ /**
5008
+ * OpenTelemetry-based Event Metrics collector.
5009
+ *
5010
+ * Uses OpenTelemetry API directly for metrics collection, enabling
5011
+ * Prometheus export through the OpenTelemetry SDK.
5012
+ *
5013
+ * @example
5014
+ * ```typescript
5015
+ * import { metrics } from '@opentelemetry/api'
5016
+ * import { OTelEventMetrics } from '@gravito/core'
5017
+ *
5018
+ * const meter = metrics.getMeter('@gravito/core', '1.0.0')
5019
+ * const eventMetrics = new OTelEventMetrics(meter)
5020
+ *
5021
+ * // Record dispatch duration
5022
+ * eventMetrics.recordDispatchDuration('order:created', 'high', 0.123)
5023
+ *
5024
+ * // Record listener duration
5025
+ * eventMetrics.recordListenerDuration('order:created', 0, 0.456)
5026
+ *
5027
+ * // Set queue depth callback
5028
+ * eventMetrics.setQueueDepthCallback(() => ({
5029
+ * high: 10,
5030
+ * normal: 50,
5031
+ * low: 100
5032
+ * }))
5033
+ * ```
5034
+ *
5035
+ * @public
5036
+ */
5037
+ declare class OTelEventMetrics implements CircuitBreakerMetricsRecorder {
5038
+ private readonly meter;
5039
+ private readonly prefix;
5040
+ private readonly dispatchDurationHistogram;
5041
+ private readonly listenerDurationHistogram;
5042
+ private readonly queueDepthGauge;
5043
+ private readonly cbStateGauge;
5044
+ private readonly cbFailuresCounter;
5045
+ private readonly cbSuccessesCounter;
5046
+ private readonly cbTransitionsCounter;
5047
+ private readonly cbOpenDurationHistogram;
5048
+ private readonly backpressureRejectionsCounter;
5049
+ private readonly backpressureStateGauge;
5050
+ private readonly backpressureDegradationsCounter;
5051
+ private backpressureStateValue;
5052
+ private readonly dlqEntriesCounter;
5053
+ private readonly dlqDepthGauge;
5054
+ private readonly dlqRequeueCounter;
5055
+ private readonly retryAttemptsCounter;
5056
+ private dlqDepthCallback?;
5057
+ private readonly priorityEscalationCounter;
5058
+ private queueDepthCallback?;
5059
+ private circuitBreakerStateCallbacks;
5060
+ private recordedCircuitBreakerStates;
5061
+ /**
5062
+ * Bucket boundaries for dispatch duration histogram.
5063
+ */
5064
+ private readonly dispatchDurationBuckets;
5065
+ /**
5066
+ * Bucket boundaries for listener duration histogram.
5067
+ */
5068
+ private readonly listenerDurationBuckets;
5069
+ /**
5070
+ * Bucket boundaries for circuit breaker open duration histogram.
5071
+ */
5072
+ private readonly cbOpenDurationBuckets;
5073
+ /**
5074
+ * Create a new OTelEventMetrics instance.
5075
+ *
5076
+ * @param meter - OpenTelemetry Meter instance
5077
+ * @param prefix - Metric name prefix (default: 'gravito_event_')
5078
+ */
5079
+ constructor(meter: Meter, prefix?: string);
5080
+ /**
5081
+ * Record event dispatch duration.
5082
+ *
5083
+ * @param eventName - Name of the event
5084
+ * @param priority - Priority level (high, normal, low)
5085
+ * @param durationSeconds - Duration in seconds
5086
+ */
5087
+ recordDispatchDuration(eventName: string, priority: string, durationSeconds: number): void;
5088
+ /**
5089
+ * Record listener execution duration.
5090
+ *
5091
+ * @param eventName - Name of the event
5092
+ * @param listenerIndex - Index of the listener in the callback list
5093
+ * @param durationSeconds - Duration in seconds
5094
+ */
5095
+ recordListenerDuration(eventName: string, listenerIndex: number, durationSeconds: number): void;
5096
+ /**
5097
+ * Set the callback for queue depth observable gauge.
5098
+ *
5099
+ * The callback will be invoked when metrics are collected,
5100
+ * allowing real-time reporting of queue depths.
5101
+ *
5102
+ * @param callback - Function returning current queue depths
5103
+ */
5104
+ setQueueDepthCallback(callback: QueueDepthCallback): void;
5105
+ /**
5106
+ * Register a circuit breaker state callback for monitoring.
5107
+ *
5108
+ * @param key - Unique identifier for the circuit breaker (e.g., "order:created-0")
5109
+ * @param callback - Function returning current circuit breaker state
5110
+ */
5111
+ registerCircuitBreakerStateCallback(key: string, callback: CircuitBreakerStateCallback): void;
5112
+ /**
5113
+ * Unregister a circuit breaker state callback.
5114
+ *
5115
+ * @param key - Unique identifier for the circuit breaker
5116
+ */
5117
+ unregisterCircuitBreakerStateCallback(key: string): void;
5118
+ /**
5119
+ * Record circuit breaker state change.
5120
+ *
5121
+ * @param name - Name of the circuit breaker (usually event name)
5122
+ * @param state - State as number (0=CLOSED, 1=HALF_OPEN, 2=OPEN)
5123
+ */
5124
+ recordState(name: string, state: number): void;
5125
+ /**
5126
+ * Record circuit breaker state transition.
5127
+ *
5128
+ * @param name - Name of the circuit breaker
5129
+ * @param fromState - Previous state
5130
+ * @param toState - New state
5131
+ */
5132
+ recordTransition(name: string, fromState: string, toState: string): void;
5133
+ /**
5134
+ * Record circuit breaker failure.
5135
+ *
5136
+ * @param name - Name of the circuit breaker
5137
+ */
5138
+ recordFailure(name: string): void;
5139
+ /**
5140
+ * Record circuit breaker success.
5141
+ *
5142
+ * @param name - Name of the circuit breaker
5143
+ */
5144
+ recordSuccess(name: string): void;
5145
+ /**
5146
+ * Record circuit breaker open duration.
5147
+ *
5148
+ * @param name - Name of the circuit breaker
5149
+ * @param seconds - Duration in seconds
5150
+ */
5151
+ recordOpenDuration(name: string, seconds: number): void;
5152
+ /**
5153
+ * Record circuit breaker failure.
5154
+ *
5155
+ * @param eventName - Name of the event
5156
+ * @param listenerIndex - Index of the listener
5157
+ */
5158
+ recordCircuitBreakerFailure(eventName: string, listenerIndex: number): void;
5159
+ /**
5160
+ * Record circuit breaker success.
5161
+ *
5162
+ * @param eventName - Name of the event
5163
+ * @param listenerIndex - Index of the listener
5164
+ */
5165
+ recordCircuitBreakerSuccess(eventName: string, listenerIndex: number): void;
5166
+ /**
5167
+ * Record circuit breaker state transition.
5168
+ *
5169
+ * @param eventName - Name of the event
5170
+ * @param listenerIndex - Index of the listener
5171
+ * @param fromState - Previous state (CLOSED, HALF_OPEN, OPEN)
5172
+ * @param toState - New state (CLOSED, HALF_OPEN, OPEN)
5173
+ */
5174
+ recordCircuitBreakerTransition(eventName: string, listenerIndex: number, fromState: string, toState: string): void;
5175
+ /**
5176
+ * Record circuit breaker open duration.
5177
+ *
5178
+ * @param eventName - Name of the event
5179
+ * @param listenerIndex - Index of the listener
5180
+ * @param durationSeconds - Duration in seconds
5181
+ */
5182
+ recordCircuitBreakerOpenDuration(eventName: string, listenerIndex: number, durationSeconds: number): void;
5183
+ /**
5184
+ * Get the bucket boundaries for dispatch duration histogram.
5185
+ *
5186
+ * @returns Array of bucket boundaries in seconds
5187
+ */
5188
+ getDispatchDurationBuckets(): number[];
5189
+ /**
5190
+ * Get the bucket boundaries for listener duration histogram.
5191
+ *
5192
+ * @returns Array of bucket boundaries in seconds
5193
+ */
5194
+ getListenerDurationBuckets(): number[];
5195
+ /**
5196
+ * Get the OpenTelemetry Meter instance.
5197
+ *
5198
+ * @returns Meter instance
5199
+ */
5200
+ getMeter(): Meter;
5201
+ /**
5202
+ * Get the metric name prefix.
5203
+ *
5204
+ * @returns Metric name prefix
5205
+ */
5206
+ getPrefix(): string;
5207
+ /**
5208
+ * Get the bucket boundaries for circuit breaker open duration histogram.
5209
+ *
5210
+ * @returns Array of bucket boundaries in seconds
5211
+ */
5212
+ getCircuitBreakerOpenDurationBuckets(): number[];
5213
+ /**
5214
+ * Get all registered circuit breaker state callback keys.
5215
+ *
5216
+ * @returns Array of registered keys
5217
+ */
5218
+ getRegisteredCircuitBreakers(): string[];
5219
+ /**
5220
+ * Clear all circuit breaker state callbacks.
5221
+ */
5222
+ clearCircuitBreakerCallbacks(): void;
5223
+ /**
5224
+ * Record a backpressure rejection event.
5225
+ *
5226
+ * @param eventName - Event name
5227
+ * @param priority - Event priority
5228
+ * @param reason - Rejection reason
5229
+ */
5230
+ recordBackpressureRejection(eventName: string, priority: string, reason: string): void;
5231
+ /**
5232
+ * Record a backpressure state change event.
5233
+ *
5234
+ * @param state - New backpressure state (NORMAL, WARNING, CRITICAL, OVERFLOW)
5235
+ */
5236
+ recordBackpressureState(state: string): void;
5237
+ /**
5238
+ * Record a backpressure degradation event.
5239
+ *
5240
+ * @param eventName - Event name
5241
+ * @param fromPriority - Original priority
5242
+ * @param toPriority - Degraded priority
5243
+ */
5244
+ recordBackpressureDegradation(eventName: string, fromPriority: string, toPriority: string): void;
5245
+ /**
5246
+ * Record an event added to Dead Letter Queue.
5247
+ *
5248
+ * @param eventName - Event name
5249
+ * @param source - Source of DLQ entry (retry_exhausted, circuit_breaker, backpressure_overflow)
5250
+ */
5251
+ recordDLQEntry(eventName: string, source: string): void;
5252
+ /**
5253
+ * Set the callback for DLQ depth observable gauge.
5254
+ *
5255
+ * @param callback - Function returning current DLQ depth
5256
+ */
5257
+ setDLQDepthCallback(callback: () => number): void;
5258
+ /**
5259
+ * Record a DLQ requeue attempt.
5260
+ *
5261
+ * @param eventName - Event name
5262
+ * @param result - Result of requeue (success or failure)
5263
+ */
5264
+ recordDLQRequeue(eventName: string, result: 'success' | 'failure'): void;
5265
+ /**
5266
+ * Record an event retry attempt.
5267
+ *
5268
+ * @param eventName - Event name
5269
+ * @param attemptNumber - Attempt number
5270
+ */
5271
+ recordRetryAttempt(eventName: string, attemptNumber: number): void;
5272
+ /**
5273
+ * Record a priority escalation event.
5274
+ *
5275
+ * @param eventName - Event name
5276
+ * @param fromPriority - Original priority
5277
+ * @param toPriority - Escalated priority
5278
+ */
5279
+ recordPriorityEscalation(eventName: string, fromPriority: string, toPriority: string): void;
5280
+ /**
5281
+ * Record event deduplication (FS-102).
5282
+ *
5283
+ * @param eventName - Event name
5284
+ * @param deduplicatedCount - Number of events after deduplication
5285
+ * @param totalCount - Total number of events before deduplication
5286
+ */
5287
+ recordDeduplication(eventName: string, deduplicatedCount: number, totalCount: number): void;
5288
+ /**
5289
+ * Record batch submission (FS-102).
5290
+ *
5291
+ * @param eventName - Event name
5292
+ * @param batchSize - Size of submitted batch
5293
+ * @param windowMs - Aggregation window size
5294
+ */
5295
+ recordBatch(eventName: string, batchSize: number, windowMs: number): void;
5296
+ /**
5297
+ * Record window adjustment (FS-102).
5298
+ *
5299
+ * @param oldWindowMs - Previous window size
5300
+ * @param newWindowMs - New window size
5301
+ * @param reason - Adjustment reason
5302
+ */
5303
+ recordWindowAdjustment(oldWindowMs: number, newWindowMs: number, reason: string): void;
5304
+ }
5305
+
5306
+ /**
5307
+ * 優先級統計器
5308
+ * 追蹤優先級分布和升級事件
5309
+ *
5310
+ * @internal
5311
+ */
5312
+ declare class PriorityStatistics {
5313
+ private eventCounts;
5314
+ private escalationCounts;
5315
+ private totalEscalations;
5316
+ /**
5317
+ * 記錄一個優先級的事件
5318
+ */
5319
+ recordEvent(priority: 'critical' | 'high' | 'normal' | 'low'): void;
5320
+ /**
5321
+ * 記錄優先級升級
5322
+ */
5323
+ recordEscalation(fromPriority: 'critical' | 'high' | 'normal' | 'low', toPriority: 'critical' | 'high' | 'normal' | 'low'): void;
5324
+ /**
5325
+ * 獲取優先級分布
5326
+ */
5327
+ getDistribution(): Record<'critical' | 'high' | 'normal' | 'low', string>;
5328
+ /**
5329
+ * 獲取升級統計
5330
+ */
5331
+ getEscalationStats(): {
5332
+ total: number;
5333
+ byTransition: Record<string, number>;
5334
+ };
5335
+ /**
5336
+ * 重置統計信息
5337
+ */
5338
+ reset(): void;
5339
+ /**
5340
+ * 獲取所有統計信息
5341
+ */
5342
+ getStats(): {
5343
+ eventCounts: Record<'critical' | 'high' | 'normal' | 'low', number>;
5344
+ escalationStats: {
5345
+ total: number;
5346
+ byTransition: Record<string, number>;
5347
+ };
5348
+ distribution: Record<'critical' | 'high' | 'normal' | 'low', string>;
5349
+ };
5350
+ }
5351
+
5352
+ /**
5353
+ * @gravito/core - Retry Scheduler
5354
+ *
5355
+ * 分佈式重試排程器,使用 Bull Queue 進行異步延遲重試。
5356
+ * 支援指數回退、Redis 持久化、重試失敗回呼。
5357
+ *
5358
+ * Distributed retry scheduler using Bull Queue for async delayed retries.
5359
+ * Supports exponential backoff, Redis persistence, and failure callbacks.
5360
+ */
5361
+
5362
+ /**
5363
+ * 重試排程器配置介面
5364
+ */
5365
+ interface RetrySchedulerConfig {
5366
+ /** 是否啟用 Bull Queue 重試(預設 true) */
5367
+ enabled?: boolean;
5368
+ /** Redis 連接配置(可選,使用全域 Redis) */
5369
+ redisUrl?: string;
5370
+ /** 預設最大重試次數(預設 5) */
5371
+ maxRetries?: number;
5372
+ /** 初始延遲時間(ms,預設 1000) */
5373
+ initialDelayMs?: number;
5374
+ /** 指數回退倍數(預設 2.0) */
5375
+ backoffMultiplier?: number;
5376
+ /** 最大延遲時間(ms,預設 1h) */
5377
+ maxDelayMs?: number;
5378
+ /** 重試失敗回呼 */
5379
+ onRetryFailed?: (eventName: string, error: Error, retryCount: number) => void;
5380
+ }
5381
+ /**
5382
+ * 隊列統計資訊
5383
+ */
5384
+ interface QueueStats {
5385
+ name: string;
5386
+ jobCounts: {
5387
+ waiting: number;
5388
+ active: number;
5389
+ delayed: number;
5390
+ failed: number;
5391
+ };
5392
+ completedCount: number;
5393
+ failedCount: number;
5394
+ }
5395
+ /**
5396
+ * 重試排程器
5397
+ *
5398
+ * 提供異步分佈式重試機制,利用 Bull Queue 進行延遲重試。
5399
+ * 支援指數回退、Redis 持久化、隊列統計。
5400
+ */
5401
+ declare class RetryScheduler {
5402
+ private enabled;
5403
+ private config;
5404
+ private queues;
5405
+ private bullmqModule;
5406
+ private bullmqLoadError;
5407
+ constructor(config?: RetrySchedulerConfig);
5408
+ /**
5409
+ * 動態加載 bullmq 模組
5410
+ */
5411
+ private loadBullmq;
5412
+ /**
5413
+ * 檢查排程器是否啟用
5414
+ */
5415
+ isEnabled(): boolean;
5416
+ /**
5417
+ * 計算指數回退延遲時間
5418
+ *
5419
+ * @param retryCount 當前重試次數(從 0 開始)
5420
+ * @returns 延遲時間(毫秒)
5421
+ */
5422
+ private calculateDelay;
5423
+ /**
5424
+ * 獲取或創建隊列
5425
+ *
5426
+ * @param eventName 事件名稱
5427
+ * @returns Queue 實例
5428
+ */
5429
+ private getOrCreateQueue;
5430
+ /**
5431
+ * 排程重試任務
5432
+ *
5433
+ * @param eventName 事件名稱
5434
+ * @param payload 事件負載
5435
+ * @param options 事件選項
5436
+ * @param error 原始錯誤
5437
+ * @param retryCount 當前重試次數
5438
+ */
5439
+ scheduleRetry(eventName: string, payload: unknown, _options: EventOptions, error: Error, retryCount: number): Promise<void>;
5440
+ /**
5441
+ * 獲取特定事件的隊列
5442
+ *
5443
+ * @param eventName 事件名稱
5444
+ * @returns Queue 實例或 undefined
5445
+ */
5446
+ getQueue(eventName: string): unknown;
5447
+ /**
5448
+ * 取得所有隊列統計
5449
+ */
5450
+ getStats(): Map<string, QueueStats>;
5451
+ /**
5452
+ * 關閉所有隊列並清理資源
5453
+ */
5454
+ shutdown(): Promise<void>;
5455
+ }
5456
+
5457
+ /**
5458
+ * Worker Pool Configuration and Types
5459
+ *
5460
+ * Defines configuration interfaces and data types for worker pool management.
5461
+ *
5462
+ * @internal
5463
+ */
5464
+
5465
+ /**
5466
+ * Task source interface for fetching and acknowledging tasks.
5467
+ * Supports integration with external task systems like Bull Queue.
5468
+ */
5469
+ interface TaskSource {
5470
+ /**
5471
+ * Fetch the next task from the source.
5472
+ * Returns null if no tasks available.
5473
+ */
5474
+ fetchTask(): Promise<EventTask | null>;
5475
+ /**
5476
+ * Acknowledge successful task completion.
5477
+ */
5478
+ acknowledgeCompletion(taskId: string): Promise<void>;
5479
+ /**
5480
+ * Acknowledge task failure.
5481
+ */
5482
+ acknowledgeFailure(taskId: string, error: Error): Promise<void>;
5483
+ }
5484
+ /**
5485
+ * Worker Pool Configuration
5486
+ */
5487
+ interface WorkerPoolConfig {
5488
+ /**
5489
+ * Maximum number of concurrent tasks being processed.
5490
+ * @default 4
5491
+ */
5492
+ concurrency?: number;
5493
+ /**
5494
+ * Number of worker threads to maintain.
5495
+ * @default Number of CPU cores
5496
+ */
5497
+ workerThreads?: number;
5498
+ /**
5499
+ * Task execution timeout in milliseconds.
5500
+ * @default 30000
5501
+ */
5502
+ taskTimeout?: number;
5503
+ /**
5504
+ * Maximum number of retries for failed tasks.
5505
+ * @default 3
5506
+ */
5507
+ maxRetries?: number;
5508
+ /**
5509
+ * Enable automatic scaling based on load.
5510
+ * @default true
5511
+ */
5512
+ enableAutoScaling?: boolean;
5513
+ /**
5514
+ * Minimum number of workers for auto-scaling.
5515
+ * @default 1
5516
+ */
5517
+ minWorkers?: number;
5518
+ /**
5519
+ * Maximum number of workers for auto-scaling.
5520
+ * @default 2 * CPU cores
5521
+ */
5522
+ maxWorkers?: number;
5523
+ /**
5524
+ * Worker utilization threshold for scaling up (0-1).
5525
+ * @default 0.8
5526
+ */
5527
+ scaleUpThreshold?: number;
5528
+ /**
5529
+ * Worker utilization threshold for scaling down (0-1).
5530
+ * @default 0.2
5531
+ */
5532
+ scaleDownThreshold?: number;
5533
+ /**
5534
+ * Interval for collecting metrics in milliseconds.
5535
+ * @default 5000
5536
+ */
5537
+ metricsInterval?: number;
5538
+ /**
5539
+ * External task source (e.g., Bull Queue).
5540
+ * When provided, workers fetch tasks from this source.
5541
+ */
5542
+ taskSource?: TaskSource;
5543
+ }
5544
+ /**
5545
+ * Worker State
5546
+ */
5547
+ type WorkerState = 'idle' | 'busy' | 'terminated';
5548
+ /**
5549
+ * Worker Statistics
5550
+ */
5551
+ interface WorkerStats {
5552
+ /**
5553
+ * Unique worker identifier.
5554
+ */
5555
+ id: string;
5556
+ /**
5557
+ * Current worker state.
5558
+ */
5559
+ state: WorkerState;
5560
+ /**
5561
+ * Total tasks processed by this worker.
5562
+ */
5563
+ tasksProcessed: number;
5564
+ /**
5565
+ * Total successful tasks.
5566
+ */
5567
+ tasksSuccess: number;
5568
+ /**
5569
+ * Total failed tasks.
5570
+ */
5571
+ tasksFailed: number;
5572
+ /**
5573
+ * Average task execution duration in milliseconds.
5574
+ */
5575
+ avgDurationMs: number;
5576
+ /**
5577
+ * Worker uptime in milliseconds.
5578
+ */
5579
+ uptime: number;
5580
+ }
5581
+ /**
5582
+ * Worker Pool Statistics
5583
+ */
5584
+ interface WorkerPoolStats {
5585
+ /**
5586
+ * Total tasks in queue.
5587
+ */
5588
+ queueDepth: number;
5589
+ /**
5590
+ * Worker utilization (0-1).
5591
+ */
5592
+ utilization: number;
5593
+ /**
5594
+ * Current number of active workers.
5595
+ */
5596
+ activeWorkers: number;
5597
+ /**
5598
+ * Total tasks processed.
5599
+ */
5600
+ totalTasksProcessed: number;
5601
+ /**
5602
+ * Total successful tasks.
5603
+ */
5604
+ totalSuccess: number;
5605
+ /**
5606
+ * Total failed tasks.
5607
+ */
5608
+ totalFailures: number;
5609
+ }
5610
+
5611
+ /**
5612
+ * Worker Pool for concurrent event task processing.
5613
+ *
5614
+ * Manages a pool of workers for executing event tasks concurrently.
5615
+ * Supports auto-scaling, health checks, and OpenTelemetry metrics integration.
5616
+ *
5617
+ * @internal
5618
+ */
5619
+
5620
+ /**
5621
+ * Worker Pool for managing concurrent task execution
5622
+ */
5623
+ declare class WorkerPool {
5624
+ private workers;
5625
+ private taskQueue;
5626
+ private config;
5627
+ private metrics?;
5628
+ private healthCheckTimer?;
5629
+ private metricsTimer?;
5630
+ private isRunning;
5631
+ private scaleDownCounter;
5632
+ constructor(config?: WorkerPoolConfig, meter?: Meter);
5633
+ /**
5634
+ * Start the worker pool
5635
+ */
5636
+ start(): Promise<void>;
5637
+ /**
5638
+ * Stop the worker pool
5639
+ */
5640
+ stop(): Promise<void>;
5641
+ /**
5642
+ * Submit a task to the worker pool
5643
+ */
5644
+ submitTask(task: EventTask): Promise<void>;
5645
+ /**
5646
+ * Process next task in queue
5647
+ */
5648
+ private processQueue;
5649
+ /**
5650
+ * Execute task on a worker
5651
+ */
5652
+ private executeTask;
5653
+ /**
5654
+ * Execute task callbacks
5655
+ */
5656
+ private executeTaskCallbacks;
5657
+ /**
5658
+ * Create a timeout promise
5659
+ */
5660
+ private createTimeout;
5661
+ /**
5662
+ * Create a new worker
5663
+ */
5664
+ private createWorker;
5665
+ /**
5666
+ * Remove a worker
5667
+ */
5668
+ private removeWorker;
5669
+ /**
5670
+ * Perform health check and cleanup
5671
+ */
5672
+ private performHealthCheck;
5673
+ /**
5674
+ * Perform auto-scaling based on load
5675
+ */
5676
+ private performAutoScaling;
5677
+ /**
5678
+ * Collect metrics
5679
+ */
5680
+ private collectMetrics;
5681
+ /**
5682
+ * Get number of active workers (not terminated)
5683
+ */
5684
+ private getActiveWorkerCount;
5685
+ /**
5686
+ * Get worker utilization (0-1)
5687
+ */
5688
+ private getUtilization;
5689
+ /**
5690
+ * Get queue depth
5691
+ */
5692
+ getQueueDepth(): number;
5693
+ /**
5694
+ * Get worker utilization
5695
+ */
5696
+ getWorkerUtilization(): number;
5697
+ /**
5698
+ * Get worker statistics
5699
+ */
5700
+ getWorkerStats(): WorkerStats[];
5701
+ /**
5702
+ * Get pool statistics
5703
+ */
5704
+ getPoolStats(): WorkerPoolStats;
5705
+ }
5706
+
5707
+ /**
5708
+ * Priority queue for event processing.
5709
+ * Events are processed based on their priority level:
5710
+ * - Critical priority events are processed first (< 1ms)
5711
+ * - High priority events are processed second (< 50ms)
5712
+ * - Normal priority events are processed third (< 200ms)
5713
+ * - Low priority events are processed last (< 500ms)
5714
+ *
5715
+ * Supports automatic priority escalation based on wait time.
5716
+ *
5717
+ * @internal
5718
+ */
5719
+ declare class EventPriorityQueue implements EventBackend {
5720
+ private criticalPriority;
5721
+ private highPriority;
5722
+ private normalPriority;
5723
+ private lowPriority;
5724
+ private processing;
5725
+ private taskIdCounter;
4168
5726
  private dlq?;
4169
5727
  private persistentDLQHandler?;
4170
5728
  private config;
4171
5729
  private processingPartitions;
4172
5730
  private eventCircuitBreakers;
4173
5731
  private eventMetrics?;
5732
+ private otelEventMetrics?;
4174
5733
  private eventTracing?;
4175
5734
  private currentDispatchSpan?;
5735
+ private backpressureManager?;
5736
+ private workerPool?;
5737
+ private retryScheduler?;
5738
+ private priorityStats?;
4176
5739
  constructor(config?: EventQueueConfig);
4177
5740
  /**
4178
5741
  * Set the Dead Letter Queue for failed events.
@@ -4193,6 +5756,27 @@ declare class EventPriorityQueue implements EventBackend {
4193
5756
  * @internal
4194
5757
  */
4195
5758
  setEventMetrics(metrics: EventMetrics): void;
5759
+ /**
5760
+ * Set the OTelEventMetrics instance for recording DLQ and backpressure metrics.
5761
+ *
5762
+ * @param metrics - OTelEventMetrics instance
5763
+ * @internal
5764
+ */
5765
+ setOTelEventMetrics(metrics: OTelEventMetrics): void;
5766
+ /**
5767
+ * Set the PriorityStatistics instance for tracking priority distribution.
5768
+ *
5769
+ * @param stats - PriorityStatistics instance
5770
+ * @internal
5771
+ */
5772
+ setPriorityStatistics(stats: PriorityStatistics): void;
5773
+ /**
5774
+ * Get the PriorityStatistics instance.
5775
+ *
5776
+ * @returns PriorityStatistics instance or undefined
5777
+ * @internal
5778
+ */
5779
+ getPriorityStatistics(): PriorityStatistics | undefined;
4196
5780
  /**
4197
5781
  * Set the EventTracing instance for distributed tracing.
4198
5782
  *
@@ -4214,6 +5798,20 @@ declare class EventPriorityQueue implements EventBackend {
4214
5798
  * @internal
4215
5799
  */
4216
5800
  getCurrentDispatchSpan(): Span | undefined;
5801
+ /**
5802
+ * Set the RetryScheduler for async distributed retries.
5803
+ *
5804
+ * @param scheduler - RetryScheduler instance
5805
+ * @internal
5806
+ */
5807
+ setRetryScheduler(scheduler: RetryScheduler): void;
5808
+ /**
5809
+ * Get the RetryScheduler instance.
5810
+ *
5811
+ * @returns RetryScheduler instance or undefined
5812
+ * @internal
5813
+ */
5814
+ getRetryScheduler(): RetryScheduler | undefined;
4217
5815
  /**
4218
5816
  * Get or create a circuit breaker for an event hook.
4219
5817
  *
@@ -4232,7 +5830,7 @@ declare class EventPriorityQueue implements EventBackend {
4232
5830
  * @param options - Event options
4233
5831
  * @returns Task ID
4234
5832
  */
4235
- enqueue(task: EventTask): void;
5833
+ enqueue(task: EventTask): string;
4236
5834
  enqueue(hook: string, args: unknown, callbacks: ActionCallback[], options: EventOptions): string;
4237
5835
  /**
4238
5836
  * Handle backpressure when queue is full.
@@ -4241,17 +5839,20 @@ declare class EventPriorityQueue implements EventBackend {
4241
5839
  private handleBackpressure;
4242
5840
  /**
4243
5841
  * Drop the oldest event from the queue, prioritizing low priority events.
5842
+ * Drops in order: LOW → NORMAL → HIGH → CRITICAL
4244
5843
  */
4245
5844
  private dropOldest;
4246
5845
  /**
4247
5846
  * Process the next task in the queue.
4248
5847
  * Tasks are processed in priority order: high > normal > low
5848
+ * If WorkerPool is configured, tasks are submitted to the pool for concurrent execution.
4249
5849
  *
4250
5850
  * @internal
4251
5851
  */
4252
5852
  private processNext;
4253
5853
  /**
4254
5854
  * Dequeue the next task based on priority and partition ordering.
5855
+ * Priority order: CRITICAL > HIGH > NORMAL > LOW
4255
5856
  *
4256
5857
  * @returns Next task to process, or undefined if queue is empty
4257
5858
  * @internal
@@ -4302,18 +5903,39 @@ declare class EventPriorityQueue implements EventBackend {
4302
5903
  */
4303
5904
  private executeWithTimeout;
4304
5905
  /**
4305
- * Get the current depth of the queue.
5906
+ * Get the current depth of the queue.
5907
+ *
5908
+ * @returns Total number of tasks in the queue
5909
+ */
5910
+ getDepth(): number;
5911
+ /**
5912
+ * Get the depth of a specific priority queue.
5913
+ *
5914
+ * @param priority - Priority level
5915
+ * @returns Number of tasks in the specified priority queue
5916
+ */
5917
+ getDepthByPriority(priority: 'critical' | 'high' | 'normal' | 'low'): number;
5918
+ /**
5919
+ * Get the BackpressureManager instance if enabled.
5920
+ *
5921
+ * @returns BackpressureManager instance or undefined if not enabled
5922
+ * @internal
5923
+ */
5924
+ getBackpressureManager(): BackpressureManager | undefined;
5925
+ /**
5926
+ * Set the WorkerPool for concurrent task execution.
4306
5927
  *
4307
- * @returns Total number of tasks in the queue
5928
+ * @param pool - WorkerPool instance
5929
+ * @internal
4308
5930
  */
4309
- getDepth(): number;
5931
+ setWorkerPool(pool: WorkerPool): void;
4310
5932
  /**
4311
- * Get the depth of a specific priority queue.
5933
+ * Get the WorkerPool instance if set.
4312
5934
  *
4313
- * @param priority - Priority level
4314
- * @returns Number of tasks in the specified priority queue
5935
+ * @returns WorkerPool instance or undefined if not set
5936
+ * @internal
4315
5937
  */
4316
- getDepthByPriority(priority: 'high' | 'normal' | 'low'): number;
5938
+ getWorkerPool(): WorkerPool | undefined;
4317
5939
  /**
4318
5940
  * Clear all tasks from the queue.
4319
5941
  */
@@ -4341,420 +5963,387 @@ declare class EventPriorityQueue implements EventBackend {
4341
5963
  * @internal
4342
5964
  */
4343
5965
  resetCircuitBreaker(hook: string): boolean;
4344
- }
4345
-
4346
- /**
4347
- * @gravito/core - Event System Tracer
4348
- *
4349
- * Manages OpenTelemetry distributed tracing for event dispatch.
4350
- */
4351
-
4352
- /**
4353
- * Event tracer for distributed tracing support.
4354
- *
4355
- * Integrates with OpenTelemetry to provide:
4356
- * - Event dispatch tracing
4357
- * - Listener execution tracing
4358
- * - Error recording
4359
- * - Span hierarchy
4360
- *
4361
- * @public
4362
- */
4363
- declare class EventTracer {
4364
- private tracer;
4365
- /**
4366
- * Create a new EventTracer instance.
4367
- *
4368
- * @param tracerName - Name of the tracer (default: '@gravito/core')
4369
- */
4370
- constructor(tracerName?: string);
4371
- /**
4372
- * Start a span for event dispatch.
4373
- *
4374
- * @param eventName - Name of the event
4375
- * @param callbackCount - Number of callbacks registered for this event
4376
- * @param priority - Priority level (high, normal, low)
4377
- * @returns Span for the event dispatch
4378
- */
4379
- startDispatchSpan(eventName: string, callbackCount: number, priority: string): Span;
4380
- /**
4381
- * Start a span for listener execution.
4382
- *
4383
- * @param _parentSpan - Parent span for this listener
4384
- * @param eventName - Name of the event
4385
- * @param listenerIndex - Index of the listener in the callback list
4386
- * @returns Child span for the listener execution
4387
- */
4388
- startListenerSpan(_parentSpan: Span, eventName: string, listenerIndex: number): Span;
4389
5966
  /**
4390
- * Record an error in the span.
5967
+ * Batch enqueue multiple tasks (FS-102).
5968
+ * Supports aggregation layer batch submission.
4391
5969
  *
4392
- * @param span - Span to record error in
4393
- * @param error - Error that occurred
5970
+ * @param tasks - Array of tasks to enqueue
5971
+ * @returns Array of task IDs
5972
+ * @internal
4394
5973
  */
4395
- recordError(span: Span, error: Error): void;
5974
+ enqueueBatch(tasks: EventTask[]): string[];
4396
5975
  /**
4397
- * End a span with a specific status.
5976
+ * Get queue depth for each priority level (FS-103).
5977
+ * Used by BackpressureManager for multi-priority depth monitoring.
4398
5978
  *
4399
- * @param span - Span to end
4400
- * @param status - Status ('ok' or 'error')
5979
+ * @returns Queue depth snapshot with depths for each priority
5980
+ * @internal
4401
5981
  */
4402
- endSpan(span: Span, status?: 'ok' | 'error'): void;
5982
+ getQueueDepthByPriority(): MultiPriorityQueueDepth;
4403
5983
  /**
4404
- * Create a timer span for measuring duration.
5984
+ * Sync queue depth to BackpressureManager (FS-103).
5985
+ * Called whenever queue depth changes to keep BackpressureManager
5986
+ * synchronized with real-time queue state.
4405
5987
  *
4406
- * @param eventName - Name of the event
4407
- * @returns Object with span and duration recording function
5988
+ * @private
5989
+ * @internal
4408
5990
  */
4409
- startTimer(eventName: string): {
4410
- span: Span;
4411
- endTimer: (status?: 'ok' | 'error') => void;
4412
- };
5991
+ private syncBackpressure;
4413
5992
  }
4414
5993
 
4415
5994
  /**
4416
- * @gravito/core - Observable Hook Manager
5995
+ * @gravito/core - Message Queue Bridge
4417
5996
  *
4418
- * Wraps HookManager with observability support (metrics and tracing).
5997
+ * 橋接層,連接 HookManager Bull Queue (via StreamEventBackend)
5998
+ * 支持分佈式事件流:HookManager → Bull Queue → Worker → 完成/DLQ
4419
5999
  */
4420
6000
 
4421
6001
  /**
4422
- * Configuration for observability features.
4423
- * @public
6002
+ * 事件執行狀態
4424
6003
  */
4425
- interface ObservabilityConfig {
6004
+ interface EventStatus {
6005
+ eventId: string;
6006
+ status: 'pending' | 'processing' | 'completed' | 'failed' | 'in_dlq';
6007
+ attempts: number;
6008
+ lastError?: string;
6009
+ createdAt: number;
6010
+ processedAt?: number;
6011
+ }
6012
+ /**
6013
+ * MessageQueueBridge 配置
6014
+ */
6015
+ interface MessageQueueBridgeConfig {
4426
6016
  /**
4427
- * Enable observability features.
4428
- * @default false
6017
+ * HookManager 實例
4429
6018
  */
4430
- enabled?: boolean;
6019
+ hookManager: HookManager;
4431
6020
  /**
4432
- * MetricsRegistry instance from @gravito/monitor.
4433
- * Required if metrics collection is enabled.
6021
+ * Worker 線程池(可選)
4434
6022
  */
4435
- metrics?: any;
6023
+ workerPool?: WorkerPool;
4436
6024
  /**
4437
- * Enable OpenTelemetry distributed tracing.
4438
- * @default false
6025
+ * 分佈式事件後端(Bull Queue)
4439
6026
  */
4440
- tracing?: boolean;
6027
+ eventBackend: EventBackend;
4441
6028
  /**
4442
- * Prefix for metric names.
4443
- * @default 'gravito_event_'
6029
+ * Dead Letter Queue 管理器
4444
6030
  */
4445
- metricsPrefix?: string;
6031
+ dlqManager: DeadLetterQueueManager;
6032
+ /**
6033
+ * 是否啟用 CircuitBreaker 檢查
6034
+ * @default false
6035
+ */
6036
+ enableCircuitBreaker?: boolean;
4446
6037
  }
4447
6038
  /**
4448
- * Observable Hook Manager - extends HookManager with observability.
6039
+ * MessageQueueBridge - 連接 HookManager Bull Queue 的橋接層
4449
6040
  *
4450
- * Provides metrics and distributed tracing for event dispatch and listener execution.
4451
- * Maintains 100% backward compatibility with HookManager.
6041
+ * 功能:
6042
+ * 1. 通過 Bull Queue 分發事件(dispatchWithQueue)
6043
+ * 2. Worker 中處理隊列事件(processQueuedEvent)
6044
+ * 3. 失敗任務轉移至 DLQ(handleJobFailure)
6045
+ * 4. 查詢事件執行狀態(getEventStatus)
4452
6046
  *
4453
- * @public
6047
+ * @example
6048
+ * ```typescript
6049
+ * const bridge = new MessageQueueBridge({
6050
+ * hookManager,
6051
+ * eventBackend: streamEventBackend,
6052
+ * dlqManager,
6053
+ * enableCircuitBreaker: true
6054
+ * })
6055
+ *
6056
+ * // 分發事件至 Bull Queue
6057
+ * const jobId = await bridge.dispatchWithQueue('order:created', { orderId: 123 })
6058
+ *
6059
+ * // Worker 處理事件
6060
+ * await bridge.processQueuedEvent(jobId, task)
6061
+ * ```
4454
6062
  */
4455
- declare class ObservableHookManager extends HookManager {
4456
- private eventMetrics?;
4457
- private eventTracer?;
4458
- private eventTracing?;
4459
- private obsConfig;
6063
+ declare class MessageQueueBridge {
6064
+ private config;
6065
+ constructor(config: MessageQueueBridgeConfig);
4460
6066
  /**
4461
- * Create a new ObservableHookManager instance.
6067
+ * 通過 Bull Queue 分發事件(分佈式異步處理)
4462
6068
  *
4463
- * @param config - HookManager configuration
4464
- * @param obsConfig - Observability configuration
4465
- */
4466
- constructor(config?: HookManagerConfig, obsConfig?: ObservabilityConfig);
4467
- /**
4468
- * Run all registered actions asynchronously via priority queue with observability.
6069
+ * 流程:
6070
+ * 1. 驗證事件 listeners 存在
6071
+ * 2. 檢查 CircuitBreaker 狀態(如果啟用)
6072
+ * 3. 構建 EventTask
6073
+ * 4. 入隊到 eventBackend (Bull Queue)
4469
6074
  *
4470
- * This override adds metrics and tracing to the base implementation.
6075
+ * @param eventName - 事件名稱
6076
+ * @param args - 事件參數
6077
+ * @param options - 事件選項(可選)
6078
+ * @returns Job ID
6079
+ * @throws 如果沒有 listeners 或 CircuitBreaker 打開
4471
6080
  *
4472
- * @template TArgs - The type of arguments passed to the action.
4473
- * @param hook - The name of the hook.
4474
- * @param args - The arguments to pass to the callbacks.
4475
- * @param options - Event options for async dispatch.
6081
+ * @example
6082
+ * ```typescript
6083
+ * const jobId = await bridge.dispatchWithQueue('order:created', {
6084
+ * orderId: 'ORD-123',
6085
+ * amount: 999.99
6086
+ * })
6087
+ * ```
4476
6088
  */
4477
- doActionAsync<TArgs = unknown>(hook: string, args: TArgs, options?: EventOptions): Promise<void>;
6089
+ dispatchWithQueue<TArgs = unknown>(eventName: string, args: TArgs, options?: any): Promise<string>;
4478
6090
  /**
4479
- * Run all registered actions synchronously with observability.
6091
+ * 處理隊列事件(由 Bull Queue Worker 調用)
4480
6092
  *
4481
- * This override adds metrics and tracing to the base implementation.
6093
+ * 重要:使用 doActionSync() 避免遞迴
6094
+ * - 不能使用 doActionAsync()(會導致事件再次入隊)
6095
+ * - Worker 中直接同步執行 callbacks
4482
6096
  *
4483
- * @template TArgs - The type of arguments passed to the action.
4484
- * @param hook - The name of the hook.
4485
- * @param args - The arguments to pass to the callbacks.
6097
+ * 流程:
6098
+ * 1. 直接執行 callbacks(不使用 doActionSync,避免吞掉錯誤)
6099
+ * 2. 記錄成功或失敗
6100
+ * 3. 拋出錯誤讓 Bull Queue 處理重試
6101
+ *
6102
+ * @param jobId - Bull Queue Job ID
6103
+ * @param task - 事件任務
6104
+ * @throws 如果 callback 執行失敗,讓 Bull Queue 處理重試
6105
+ *
6106
+ * @example
6107
+ * ```typescript
6108
+ * // 在 Bull Queue Worker 中:
6109
+ * await bridge.processQueuedEvent(jobId, task)
6110
+ * ```
4486
6111
  */
4487
- doActionSync<TArgs = unknown>(hook: string, args: TArgs): Promise<void>;
6112
+ processQueuedEvent(jobId: string, task: EventTask): Promise<void>;
4488
6113
  /**
4489
- * Get the EventMetrics instance.
6114
+ * 處理 Bull Queue 任務失敗(由 onFailed callback 調用)
4490
6115
  *
4491
- * @returns EventMetrics instance if observability is enabled, undefined otherwise
6116
+ * 流程:
6117
+ * 1. 記錄警告日誌
6118
+ * 2. 移至 persistent DLQ(DeadLetterQueueManager)
6119
+ * 3. 持久化到 event_dlq 表,支持延遲重試
6120
+ *
6121
+ * @param jobId - Bull Queue Job ID
6122
+ * @param task - 事件任務
6123
+ * @param error - 導致失敗的錯誤
6124
+ * @param retryCount - 已重試次數(可選)
6125
+ *
6126
+ * @example
6127
+ * ```typescript
6128
+ * // 在 Bull Queue onFailed callback 中:
6129
+ * await bridge.handleJobFailure(jobId, task, error, 3)
6130
+ * ```
4492
6131
  */
4493
- getMetrics(): EventMetrics | undefined;
6132
+ handleJobFailure(jobId: string, task: EventTask, error: Error, retryCount?: number): Promise<void>;
4494
6133
  /**
4495
- * Get the EventTracer instance.
6134
+ * 查詢事件執行狀態
4496
6135
  *
4497
- * @returns EventTracer instance if tracing is enabled, undefined otherwise
6136
+ * 支持查詢:
6137
+ * 1. 待處理事件
6138
+ * 2. 正在處理的事件
6139
+ * 3. 已完成事件
6140
+ * 4. 失敗事件(在 DLQ 中)
6141
+ *
6142
+ * @param eventId - 事件 ID(task.id 或 jobId)
6143
+ * @returns 事件狀態
6144
+ *
6145
+ * @example
6146
+ * ```typescript
6147
+ * const status = await bridge.getEventStatus('queue-1707000000000-abc123')
6148
+ * console.log(status) // { eventId, status, attempts, ... }
6149
+ * ```
4498
6150
  */
4499
- getTracer(): EventTracer | undefined;
6151
+ getEventStatus(eventId: string): Promise<EventStatus>;
4500
6152
  /**
4501
- * Update observability configuration at runtime.
6153
+ * 獲取 EventBackend 實例(用於高級操作)
4502
6154
  *
4503
- * @param config - New observability configuration
6155
+ * @returns EventBackend 實例
6156
+ * @internal
4504
6157
  */
4505
- setObservabilityConfig(config: Partial<ObservabilityConfig>): void;
6158
+ getEventBackend(): EventBackend;
4506
6159
  /**
4507
- * Get the EventTracing instance.
6160
+ * 獲取 DLQ 管理器實例(用於高級操作)
4508
6161
  *
4509
- * @returns EventTracing instance if tracing is enabled, undefined otherwise
6162
+ * @returns DeadLetterQueueManager 實例
6163
+ * @internal
4510
6164
  */
4511
- getEventTracing(): EventTracing | undefined;
6165
+ getDLQManager(): DeadLetterQueueManager;
4512
6166
  /**
4513
- * Get current observability configuration.
6167
+ * 獲取 HookManager 實例(用於高級操作)
4514
6168
  *
4515
- * @returns Current observability configuration
6169
+ * @returns HookManager 實例
6170
+ * @internal
4516
6171
  */
4517
- getObservabilityConfig(): ObservabilityConfig;
6172
+ getHookManager(): HookManager;
4518
6173
  }
4519
6174
 
4520
6175
  /**
4521
- * @gravito/core - OpenTelemetry Event Metrics
4522
- *
4523
- * Provides event system metrics using OpenTelemetry API directly.
4524
- * This enables Prometheus export without requiring @gravito/monitor dependency.
4525
- *
4526
- * Metrics:
4527
- * - gravito_event_dispatch_duration_seconds (Histogram)
4528
- * - gravito_event_listener_duration_seconds (Histogram)
4529
- * - gravito_event_queue_depth (Observable Gauge)
6176
+ * @gravito/core - Event System Tracer
4530
6177
  *
4531
- * @packageDocumentation
6178
+ * Manages OpenTelemetry distributed tracing for event dispatch.
4532
6179
  */
4533
6180
 
4534
6181
  /**
4535
- * Queue depth callback type.
4536
- * Returns the current queue depths for each priority level.
4537
- */
4538
- type QueueDepthCallback = () => {
4539
- high: number;
4540
- normal: number;
4541
- low: number;
4542
- };
4543
- /**
4544
- * Circuit breaker state callback type.
4545
- * Returns the current state of a circuit breaker.
4546
- */
4547
- type CircuitBreakerStateCallback = () => {
4548
- eventName: string;
4549
- listenerIndex: number;
4550
- state: 0 | 1 | 2;
4551
- };
4552
- /**
4553
- * OpenTelemetry-based Event Metrics collector.
4554
- *
4555
- * Uses OpenTelemetry API directly for metrics collection, enabling
4556
- * Prometheus export through the OpenTelemetry SDK.
4557
- *
4558
- * @example
4559
- * ```typescript
4560
- * import { metrics } from '@opentelemetry/api'
4561
- * import { OTelEventMetrics } from '@gravito/core'
4562
- *
4563
- * const meter = metrics.getMeter('@gravito/core', '1.0.0')
4564
- * const eventMetrics = new OTelEventMetrics(meter)
4565
- *
4566
- * // Record dispatch duration
4567
- * eventMetrics.recordDispatchDuration('order:created', 'high', 0.123)
4568
- *
4569
- * // Record listener duration
4570
- * eventMetrics.recordListenerDuration('order:created', 0, 0.456)
4571
- *
4572
- * // Set queue depth callback
4573
- * eventMetrics.setQueueDepthCallback(() => ({
4574
- * high: 10,
4575
- * normal: 50,
4576
- * low: 100
4577
- * }))
4578
- * ```
6182
+ * Event tracer for distributed tracing support.
4579
6183
  *
4580
- * @public
4581
- */
4582
- declare class OTelEventMetrics implements CircuitBreakerMetricsRecorder {
4583
- private readonly meter;
4584
- private readonly prefix;
4585
- private readonly dispatchDurationHistogram;
4586
- private readonly listenerDurationHistogram;
4587
- private readonly queueDepthGauge;
4588
- private readonly cbStateGauge;
4589
- private readonly cbFailuresCounter;
4590
- private readonly cbSuccessesCounter;
4591
- private readonly cbTransitionsCounter;
4592
- private readonly cbOpenDurationHistogram;
4593
- private queueDepthCallback?;
4594
- private circuitBreakerStateCallbacks;
4595
- private recordedCircuitBreakerStates;
4596
- /**
4597
- * Bucket boundaries for dispatch duration histogram.
4598
- */
4599
- private readonly dispatchDurationBuckets;
4600
- /**
4601
- * Bucket boundaries for listener duration histogram.
4602
- */
4603
- private readonly listenerDurationBuckets;
4604
- /**
4605
- * Bucket boundaries for circuit breaker open duration histogram.
4606
- */
4607
- private readonly cbOpenDurationBuckets;
6184
+ * Integrates with OpenTelemetry to provide:
6185
+ * - Event dispatch tracing
6186
+ * - Listener execution tracing
6187
+ * - Error recording
6188
+ * - Span hierarchy
6189
+ *
6190
+ * @public
6191
+ */
6192
+ declare class EventTracer {
6193
+ private tracer;
4608
6194
  /**
4609
- * Create a new OTelEventMetrics instance.
6195
+ * Create a new EventTracer instance.
4610
6196
  *
4611
- * @param meter - OpenTelemetry Meter instance
4612
- * @param prefix - Metric name prefix (default: 'gravito_event_')
6197
+ * @param tracerName - Name of the tracer (default: '@gravito/core')
4613
6198
  */
4614
- constructor(meter: Meter, prefix?: string);
6199
+ constructor(tracerName?: string);
4615
6200
  /**
4616
- * Record event dispatch duration.
6201
+ * Start a span for event dispatch.
4617
6202
  *
4618
6203
  * @param eventName - Name of the event
6204
+ * @param callbackCount - Number of callbacks registered for this event
4619
6205
  * @param priority - Priority level (high, normal, low)
4620
- * @param durationSeconds - Duration in seconds
6206
+ * @returns Span for the event dispatch
4621
6207
  */
4622
- recordDispatchDuration(eventName: string, priority: string, durationSeconds: number): void;
6208
+ startDispatchSpan(eventName: string, callbackCount: number, priority: string): Span;
4623
6209
  /**
4624
- * Record listener execution duration.
6210
+ * Start a span for listener execution.
4625
6211
  *
6212
+ * @param _parentSpan - Parent span for this listener
4626
6213
  * @param eventName - Name of the event
4627
6214
  * @param listenerIndex - Index of the listener in the callback list
4628
- * @param durationSeconds - Duration in seconds
4629
- */
4630
- recordListenerDuration(eventName: string, listenerIndex: number, durationSeconds: number): void;
4631
- /**
4632
- * Set the callback for queue depth observable gauge.
4633
- *
4634
- * The callback will be invoked when metrics are collected,
4635
- * allowing real-time reporting of queue depths.
4636
- *
4637
- * @param callback - Function returning current queue depths
6215
+ * @returns Child span for the listener execution
4638
6216
  */
4639
- setQueueDepthCallback(callback: QueueDepthCallback): void;
6217
+ startListenerSpan(_parentSpan: Span, eventName: string, listenerIndex: number): Span;
4640
6218
  /**
4641
- * Register a circuit breaker state callback for monitoring.
6219
+ * Record an error in the span.
4642
6220
  *
4643
- * @param key - Unique identifier for the circuit breaker (e.g., "order:created-0")
4644
- * @param callback - Function returning current circuit breaker state
6221
+ * @param span - Span to record error in
6222
+ * @param error - Error that occurred
4645
6223
  */
4646
- registerCircuitBreakerStateCallback(key: string, callback: CircuitBreakerStateCallback): void;
6224
+ recordError(span: Span, error: Error): void;
4647
6225
  /**
4648
- * Unregister a circuit breaker state callback.
6226
+ * End a span with a specific status.
4649
6227
  *
4650
- * @param key - Unique identifier for the circuit breaker
6228
+ * @param span - Span to end
6229
+ * @param status - Status ('ok' or 'error')
4651
6230
  */
4652
- unregisterCircuitBreakerStateCallback(key: string): void;
6231
+ endSpan(span: Span, status?: 'ok' | 'error'): void;
4653
6232
  /**
4654
- * Record circuit breaker state change.
6233
+ * Create a timer span for measuring duration.
4655
6234
  *
4656
- * @param name - Name of the circuit breaker (usually event name)
4657
- * @param state - State as number (0=CLOSED, 1=HALF_OPEN, 2=OPEN)
6235
+ * @param eventName - Name of the event
6236
+ * @returns Object with span and duration recording function
4658
6237
  */
4659
- recordState(name: string, state: number): void;
6238
+ startTimer(eventName: string): {
6239
+ span: Span;
6240
+ endTimer: (status?: 'ok' | 'error') => void;
6241
+ };
6242
+ }
6243
+
6244
+ /**
6245
+ * @gravito/core - Observable Hook Manager
6246
+ *
6247
+ * Wraps HookManager with observability support (metrics and tracing).
6248
+ */
6249
+
6250
+ /**
6251
+ * Configuration for observability features.
6252
+ * @public
6253
+ */
6254
+ interface ObservabilityConfig {
4660
6255
  /**
4661
- * Record circuit breaker state transition.
4662
- *
4663
- * @param name - Name of the circuit breaker
4664
- * @param fromState - Previous state
4665
- * @param toState - New state
6256
+ * Enable observability features.
6257
+ * @default false
4666
6258
  */
4667
- recordTransition(name: string, fromState: string, toState: string): void;
6259
+ enabled?: boolean;
4668
6260
  /**
4669
- * Record circuit breaker failure.
4670
- *
4671
- * @param name - Name of the circuit breaker
6261
+ * MetricsRegistry instance from @gravito/monitor.
6262
+ * Required if metrics collection is enabled.
4672
6263
  */
4673
- recordFailure(name: string): void;
6264
+ metrics?: any;
4674
6265
  /**
4675
- * Record circuit breaker success.
4676
- *
4677
- * @param name - Name of the circuit breaker
6266
+ * Enable OpenTelemetry distributed tracing.
6267
+ * @default false
4678
6268
  */
4679
- recordSuccess(name: string): void;
6269
+ tracing?: boolean;
4680
6270
  /**
4681
- * Record circuit breaker open duration.
4682
- *
4683
- * @param name - Name of the circuit breaker
4684
- * @param seconds - Duration in seconds
6271
+ * Prefix for metric names.
6272
+ * @default 'gravito_event_'
4685
6273
  */
4686
- recordOpenDuration(name: string, seconds: number): void;
6274
+ metricsPrefix?: string;
6275
+ }
6276
+ /**
6277
+ * Observable Hook Manager - extends HookManager with observability.
6278
+ *
6279
+ * Provides metrics and distributed tracing for event dispatch and listener execution.
6280
+ * Maintains 100% backward compatibility with HookManager.
6281
+ *
6282
+ * @public
6283
+ */
6284
+ declare class ObservableHookManager extends HookManager {
6285
+ private eventMetrics?;
6286
+ private eventTracer?;
6287
+ private eventTracing?;
6288
+ private obsConfig;
4687
6289
  /**
4688
- * Record circuit breaker failure.
6290
+ * Create a new ObservableHookManager instance.
4689
6291
  *
4690
- * @param eventName - Name of the event
4691
- * @param listenerIndex - Index of the listener
6292
+ * @param config - HookManager configuration
6293
+ * @param obsConfig - Observability configuration
4692
6294
  */
4693
- recordCircuitBreakerFailure(eventName: string, listenerIndex: number): void;
6295
+ constructor(config?: HookManagerConfig, obsConfig?: ObservabilityConfig);
4694
6296
  /**
4695
- * Record circuit breaker success.
6297
+ * Run all registered actions asynchronously via priority queue with observability.
4696
6298
  *
4697
- * @param eventName - Name of the event
4698
- * @param listenerIndex - Index of the listener
4699
- */
4700
- recordCircuitBreakerSuccess(eventName: string, listenerIndex: number): void;
4701
- /**
4702
- * Record circuit breaker state transition.
6299
+ * This override adds metrics and tracing to the base implementation.
4703
6300
  *
4704
- * @param eventName - Name of the event
4705
- * @param listenerIndex - Index of the listener
4706
- * @param fromState - Previous state (CLOSED, HALF_OPEN, OPEN)
4707
- * @param toState - New state (CLOSED, HALF_OPEN, OPEN)
6301
+ * @template TArgs - The type of arguments passed to the action.
6302
+ * @param hook - The name of the hook.
6303
+ * @param args - The arguments to pass to the callbacks.
6304
+ * @param options - Event options for async dispatch.
4708
6305
  */
4709
- recordCircuitBreakerTransition(eventName: string, listenerIndex: number, fromState: string, toState: string): void;
6306
+ doActionAsync<TArgs = unknown>(hook: string, args: TArgs, options?: EventOptions): Promise<void>;
4710
6307
  /**
4711
- * Record circuit breaker open duration.
6308
+ * Run all registered actions synchronously with observability.
4712
6309
  *
4713
- * @param eventName - Name of the event
4714
- * @param listenerIndex - Index of the listener
4715
- * @param durationSeconds - Duration in seconds
4716
- */
4717
- recordCircuitBreakerOpenDuration(eventName: string, listenerIndex: number, durationSeconds: number): void;
4718
- /**
4719
- * Get the bucket boundaries for dispatch duration histogram.
6310
+ * This override adds metrics and tracing to the base implementation.
4720
6311
  *
4721
- * @returns Array of bucket boundaries in seconds
6312
+ * @template TArgs - The type of arguments passed to the action.
6313
+ * @param hook - The name of the hook.
6314
+ * @param args - The arguments to pass to the callbacks.
4722
6315
  */
4723
- getDispatchDurationBuckets(): number[];
6316
+ doActionSync<TArgs = unknown>(hook: string, args: TArgs): Promise<void>;
4724
6317
  /**
4725
- * Get the bucket boundaries for listener duration histogram.
6318
+ * Get the EventMetrics instance.
4726
6319
  *
4727
- * @returns Array of bucket boundaries in seconds
6320
+ * @returns EventMetrics instance if observability is enabled, undefined otherwise
4728
6321
  */
4729
- getListenerDurationBuckets(): number[];
6322
+ getMetrics(): EventMetrics | undefined;
4730
6323
  /**
4731
- * Get the OpenTelemetry Meter instance.
6324
+ * Get the EventTracer instance.
4732
6325
  *
4733
- * @returns Meter instance
6326
+ * @returns EventTracer instance if tracing is enabled, undefined otherwise
4734
6327
  */
4735
- getMeter(): Meter;
6328
+ getTracer(): EventTracer | undefined;
4736
6329
  /**
4737
- * Get the metric name prefix.
6330
+ * Update observability configuration at runtime.
4738
6331
  *
4739
- * @returns Metric name prefix
6332
+ * @param config - New observability configuration
4740
6333
  */
4741
- getPrefix(): string;
6334
+ setObservabilityConfig(config: Partial<ObservabilityConfig>): void;
4742
6335
  /**
4743
- * Get the bucket boundaries for circuit breaker open duration histogram.
6336
+ * Get the EventTracing instance.
4744
6337
  *
4745
- * @returns Array of bucket boundaries in seconds
6338
+ * @returns EventTracing instance if tracing is enabled, undefined otherwise
4746
6339
  */
4747
- getCircuitBreakerOpenDurationBuckets(): number[];
6340
+ getEventTracing(): EventTracing | undefined;
4748
6341
  /**
4749
- * Get all registered circuit breaker state callback keys.
6342
+ * Get current observability configuration.
4750
6343
  *
4751
- * @returns Array of registered keys
4752
- */
4753
- getRegisteredCircuitBreakers(): string[];
4754
- /**
4755
- * Clear all circuit breaker state callbacks.
6344
+ * @returns Current observability configuration
4756
6345
  */
4757
- clearCircuitBreakerCallbacks(): void;
6346
+ getObservabilityConfig(): ObservabilityConfig;
4758
6347
  }
4759
6348
 
4760
6349
  /**
@@ -4850,6 +6439,16 @@ interface HookManagerConfig {
4850
6439
  * @default false
4851
6440
  */
4852
6441
  enablePersistentDLQ?: boolean;
6442
+ /**
6443
+ * Message Queue Bridge for distributed event processing via Bull Queue.
6444
+ * When provided, enables dispatchQueued() method for routing events to Redis-backed queue.
6445
+ */
6446
+ messageQueueBridge?: any;
6447
+ /**
6448
+ * Event aggregation configuration (FS-102).
6449
+ * Enables deduplication and micro-batching for improved throughput.
6450
+ */
6451
+ aggregation?: any;
4853
6452
  }
4854
6453
  declare class HookManager {
4855
6454
  private filters;
@@ -4858,9 +6457,11 @@ declare class HookManager {
4858
6457
  private backend;
4859
6458
  private dlq?;
4860
6459
  private persistentDlqManager?;
6460
+ private messageQueueBridge?;
4861
6461
  private idempotencyCache;
4862
6462
  private config;
4863
6463
  private migrationWarner;
6464
+ private aggregationManager?;
4864
6465
  /**
4865
6466
  * Cache for async detection results (WeakMap for automatic garbage collection).
4866
6467
  * @internal
@@ -5194,6 +6795,18 @@ declare class HookManager {
5194
6795
  * @returns True if reset, false if circuit breaker not found
5195
6796
  */
5196
6797
  resetCircuitBreaker(eventName: string): boolean;
6798
+ /**
6799
+ * Get the current backpressure state.
6800
+ *
6801
+ * @returns Backpressure state ('NORMAL', 'WARNING', 'CRITICAL', 'OVERFLOW') or undefined if not enabled
6802
+ */
6803
+ getBackpressureState(): string | undefined;
6804
+ /**
6805
+ * Get backpressure metrics snapshot.
6806
+ *
6807
+ * @returns Backpressure metrics snapshot or undefined if not enabled
6808
+ */
6809
+ getBackpressureMetrics(): object | undefined;
5197
6810
  /**
5198
6811
  * Remove all listeners for a specific action hook.
5199
6812
  *
@@ -5238,6 +6851,77 @@ declare class HookManager {
5238
6851
  succeeded: number;
5239
6852
  failed: number;
5240
6853
  }>;
6854
+ /**
6855
+ * Dispatch an event through Bull Queue (分佈式異步處理).
6856
+ *
6857
+ * 與 doActionAsync() 不同:
6858
+ * - doActionAsync() 使用 EventPriorityQueue (Memory-based)
6859
+ * - dispatchQueued() 使用 Bull Queue (Redis-backed, 分佈式)
6860
+ *
6861
+ * 適用於需要持久化和跨進程處理的事件。
6862
+ *
6863
+ * @template TArgs - 事件參數類型
6864
+ * @param event - 事件名稱
6865
+ * @param args - 事件參數
6866
+ * @param options - 事件選項(可選)
6867
+ * @returns Job ID
6868
+ * @throws 如果未配置 MessageQueueBridge 或沒有 listeners
6869
+ *
6870
+ * @example
6871
+ * ```typescript
6872
+ * const jobId = await hookManager.dispatchQueued('order:created', {
6873
+ * orderId: 'ORD-123',
6874
+ * amount: 999.99
6875
+ * })
6876
+ * ```
6877
+ *
6878
+ * @public
6879
+ */
6880
+ dispatchQueued<TArgs = unknown>(event: string, args: TArgs, options?: any): Promise<string>;
6881
+ /**
6882
+ * Dispatch an event through Bull Queue with delay (延遲隊列分發).
6883
+ *
6884
+ * 通過 Bull Queue 的 delayed jobs 功能實現延遲處理。
6885
+ *
6886
+ * @template TArgs - 事件參數類型
6887
+ * @param event - 事件名稱
6888
+ * @param args - 事件參數
6889
+ * @param delay - 延遲時間(毫秒)
6890
+ * @param options - 事件選項(可選)
6891
+ * @returns Job ID
6892
+ * @throws 如果未配置 MessageQueueBridge
6893
+ *
6894
+ * @example
6895
+ * ```typescript
6896
+ * // 延遲 5 秒後處理
6897
+ * const jobId = await hookManager.dispatchDeferredQueued(
6898
+ * 'reminder:send',
6899
+ * { userId: '123' },
6900
+ * 5000
6901
+ * )
6902
+ * ```
6903
+ *
6904
+ * @public
6905
+ */
6906
+ dispatchDeferredQueued<TArgs = unknown>(event: string, args: TArgs, delay: number, options?: any): Promise<string>;
6907
+ /**
6908
+ * Get the execution status of an event.
6909
+ *
6910
+ * 查詢事件執行狀態,支持查詢 Bull Queue 和 DLQ 中的事件。
6911
+ *
6912
+ * @param eventId - 事件 ID (task.id 或 jobId)
6913
+ * @returns 事件狀態信息
6914
+ * @throws 如果未配置 MessageQueueBridge
6915
+ *
6916
+ * @example
6917
+ * ```typescript
6918
+ * const status = await hookManager.getEventStatus('queue-1707000000000-abc123')
6919
+ * console.log(status) // { eventId, status, attempts, createdAt, ... }
6920
+ * ```
6921
+ *
6922
+ * @public
6923
+ */
6924
+ getEventStatus(eventId: string): Promise<any>;
5241
6925
  /**
5242
6926
  * Get persistent DLQ statistics.
5243
6927
  *
@@ -5351,16 +7035,38 @@ declare abstract class ServiceProvider {
5351
7035
  *
5352
7036
  * @param container - The IoC container instance
5353
7037
  */
5354
- abstract register(container: Container): void | Promise<void>;
7038
+ abstract register(container: Container): void | Promise<void>;
7039
+ /**
7040
+ * Bootstrap any application services.
7041
+ *
7042
+ * This method is called after ALL providers have registered.
7043
+ * You can safely resolve services from the container here.
7044
+ *
7045
+ * @param core - The PlanetCore application instance
7046
+ */
7047
+ boot?(core: PlanetCore): void | Promise<void>;
7048
+ /**
7049
+ * Called when the application is ready to accept requests.
7050
+ *
7051
+ * This method is called after ALL providers have booted.
7052
+ * Use this for final initialization before the server starts accepting traffic.
7053
+ *
7054
+ * @param core - The PlanetCore application instance
7055
+ * @since 2.2.0
7056
+ */
7057
+ onReady?(core: PlanetCore): void | Promise<void>;
5355
7058
  /**
5356
- * Bootstrap any application services.
7059
+ * Called when the application is shutting down.
5357
7060
  *
5358
- * This method is called after ALL providers have registered.
5359
- * You can safely resolve services from the container here.
7061
+ * This method is called during graceful shutdown.
7062
+ * Use this to clean up resources, close connections, etc.
7063
+ *
7064
+ * Providers are called in reverse order (LIFO).
5360
7065
  *
5361
7066
  * @param core - The PlanetCore application instance
7067
+ * @since 2.2.0
5362
7068
  */
5363
- boot?(core: PlanetCore): void | Promise<void>;
7069
+ onShutdown?(core: PlanetCore): void | Promise<void>;
5364
7070
  /**
5365
7071
  * Set the core instance reference.
5366
7072
  * Called internally by the application during registration.
@@ -5898,6 +7604,47 @@ type GravitoConfig = {
5898
7604
  * @since 2.0.0
5899
7605
  */
5900
7606
  container?: Container;
7607
+ /**
7608
+ * Observability configuration for event system.
7609
+ * @since 2.1.0
7610
+ */
7611
+ observability?: {
7612
+ /**
7613
+ * Enable event system observability (metrics, tracing).
7614
+ * @default false
7615
+ */
7616
+ enabled?: boolean;
7617
+ /**
7618
+ * Enable OpenTelemetry distributed tracing.
7619
+ * @default false
7620
+ */
7621
+ tracing?: boolean;
7622
+ /**
7623
+ * Prefix for metric names.
7624
+ * @default 'gravito_event_'
7625
+ */
7626
+ metricsPrefix?: string;
7627
+ /**
7628
+ * Prometheus metrics configuration.
7629
+ */
7630
+ prometheus?: {
7631
+ /**
7632
+ * Enable Prometheus metrics endpoint.
7633
+ * @default true
7634
+ */
7635
+ enabled?: boolean;
7636
+ /**
7637
+ * Port for Prometheus metrics endpoint.
7638
+ * @default 9090
7639
+ */
7640
+ port?: number;
7641
+ /**
7642
+ * Endpoint path for metrics.
7643
+ * @default '/metrics'
7644
+ */
7645
+ endpoint?: string;
7646
+ };
7647
+ };
5901
7648
  };
5902
7649
 
5903
7650
  /**
@@ -5936,6 +7683,20 @@ declare class PlanetCore {
5936
7683
  private providers;
5937
7684
  private deferredProviders;
5938
7685
  private bootedProviders;
7686
+ private isShuttingDown;
7687
+ /**
7688
+ * Initialize observability asynchronously (metrics, tracing, Prometheus).
7689
+ * This is called from constructor but doesn't block initialization.
7690
+ *
7691
+ * @internal
7692
+ */
7693
+ private initializeObservabilityAsync;
7694
+ /**
7695
+ * Initialize Prometheus metrics asynchronously.
7696
+ *
7697
+ * @internal
7698
+ */
7699
+ private initializePrometheusAsync;
5939
7700
  /**
5940
7701
  * Register a service provider to the core.
5941
7702
  *
@@ -5969,6 +7730,34 @@ declare class PlanetCore {
5969
7730
  * ```
5970
7731
  */
5971
7732
  bootstrap(): Promise<void>;
7733
+ /**
7734
+ * Called when the application is ready to accept requests.
7735
+ *
7736
+ * Invokes the `onReady()` lifecycle hook on all providers.
7737
+ * Called automatically at the end of `bootstrap()`.
7738
+ *
7739
+ * @returns Promise that resolves when all providers are ready.
7740
+ *
7741
+ * @example
7742
+ * ```typescript
7743
+ * await core.ready();
7744
+ * ```
7745
+ */
7746
+ ready(): Promise<void>;
7747
+ /**
7748
+ * Gracefully shutdown the application.
7749
+ *
7750
+ * Invokes the `onShutdown()` lifecycle hook on all providers in reverse order (LIFO).
7751
+ * Should be called when the application receives a termination signal.
7752
+ *
7753
+ * @returns Promise that resolves when all providers have shut down.
7754
+ *
7755
+ * @example
7756
+ * ```typescript
7757
+ * process.on('SIGTERM', () => core.shutdown());
7758
+ * ```
7759
+ */
7760
+ shutdown(): Promise<void>;
5972
7761
  /**
5973
7762
  * Setup deferred provider resolution.
5974
7763
  * Wraps container.make to auto-register deferred providers on first request.
@@ -5994,6 +7783,12 @@ declare class PlanetCore {
5994
7783
  adapter?: HttpAdapter;
5995
7784
  container?: Container;
5996
7785
  });
7786
+ /**
7787
+ * Setup process signal handlers for graceful shutdown
7788
+ *
7789
+ * @internal
7790
+ */
7791
+ private setupSignalHandlers;
5997
7792
  /**
5998
7793
  * Programmatically register an infrastructure module (Orbit).
5999
7794
  * @since 2.0.0
@@ -6136,6 +7931,9 @@ interface FastContext$1 {
6136
7931
  /** Context Variables */
6137
7932
  get<T>(key: string): T;
6138
7933
  set(key: string, value: any): void;
7934
+ /** Request Scope Management */
7935
+ requestScope(): any;
7936
+ scoped<T>(key: string | symbol, factory: () => T): T;
6139
7937
  /** Lifecycle helpers */
6140
7938
  route: (name: string, params?: any, query?: any) => string;
6141
7939
  readonly native: any;
@@ -6264,7 +8062,6 @@ declare class Gravito {
6264
8062
  staticRoutes: Map<string, RouteMetadata>;
6265
8063
  private isPureStaticApp;
6266
8064
  private compiledDynamicRoutes;
6267
- private middlewareVersion;
6268
8065
  /**
6269
8066
  * Create a new Gravito instance
6270
8067
  *
@@ -6450,6 +8247,7 @@ declare class PhotonRequestWrapper implements GravitoRequest {
6450
8247
  declare class PhotonContextWrapper<V extends GravitoVariables = GravitoVariables> implements GravitoContext<V> {
6451
8248
  private _req;
6452
8249
  private photonCtx;
8250
+ private _requestScope;
6453
8251
  route: (name: string, params?: Record<string, any>, query?: Record<string, any>) => string;
6454
8252
  /**
6455
8253
  * Reset the wrapper for pooling
@@ -6490,6 +8288,8 @@ declare class PhotonContextWrapper<V extends GravitoVariables = GravitoVariables
6490
8288
  get env(): Record<string, unknown> | undefined;
6491
8289
  get native(): Context$1;
6492
8290
  forward(target: string, options?: ProxyOptions): Promise<Response>;
8291
+ requestScope(): RequestScopeManager;
8292
+ scoped<T>(key: string | symbol, factory: () => T): T;
6493
8293
  }
6494
8294
  /**
6495
8295
  * Default HTTP adapter using the optimized Gravito Core Engine.
@@ -6806,6 +8606,143 @@ declare class CommandKernel {
6806
8606
  handle(argv: string[]): Promise<void>;
6807
8607
  }
6808
8608
 
8609
+ /**
8610
+ * Configuration for QueueDashboard
8611
+ * All subsystem references are optional to support progressive integration
8612
+ */
8613
+ interface QueueDashboardConfig {
8614
+ eventQueue?: EventPriorityQueue;
8615
+ workerPool?: WorkerPool;
8616
+ hookManager?: HookManager;
8617
+ dlq?: DeadLetterQueue;
8618
+ messageQueueBridge?: MessageQueueBridge;
8619
+ }
8620
+ /**
8621
+ * Queue depth and backpressure metrics
8622
+ */
8623
+ interface QueueMetrics {
8624
+ depth: {
8625
+ total: number;
8626
+ high: number;
8627
+ normal: number;
8628
+ low: number;
8629
+ };
8630
+ backpressure: {
8631
+ state: string;
8632
+ rejectedCount: number;
8633
+ degradedCount: number;
8634
+ enqueueRate: number;
8635
+ };
8636
+ processing: boolean;
8637
+ }
8638
+ /**
8639
+ * Worker pool and thread statistics
8640
+ */
8641
+ interface WorkerMetrics {
8642
+ poolSize: number;
8643
+ activeWorkers: number;
8644
+ utilization: number;
8645
+ queueDepth: number;
8646
+ totalProcessed: number;
8647
+ totalSuccess: number;
8648
+ totalFailures: number;
8649
+ successRate: number;
8650
+ workers: Array<{
8651
+ id: string;
8652
+ state: string;
8653
+ tasksProcessed: number;
8654
+ tasksSucceeded: number;
8655
+ tasksFailed: number;
8656
+ avgDurationMs: number;
8657
+ currentLoad: number;
8658
+ }>;
8659
+ }
8660
+ /**
8661
+ * Timeline event for job processing history
8662
+ */
8663
+ interface JobEvent {
8664
+ id: string;
8665
+ hook: string;
8666
+ status: 'pending' | 'processing' | 'completed' | 'failed' | 'in_dlq';
8667
+ priority: string;
8668
+ createdAt: number;
8669
+ error?: string;
8670
+ retryCount: number;
8671
+ }
8672
+ /**
8673
+ * Error statistics and circuit breaker status
8674
+ */
8675
+ interface ErrorStats {
8676
+ totalErrors: number;
8677
+ byEvent: Record<string, number>;
8678
+ circuitBreakers: Array<{
8679
+ eventName: string;
8680
+ state: string;
8681
+ failures: number;
8682
+ successes: number;
8683
+ }>;
8684
+ dlqCount: number;
8685
+ }
8686
+ /**
8687
+ * Complete dashboard snapshot at a point in time
8688
+ */
8689
+ interface DashboardSnapshot {
8690
+ timestamp: number;
8691
+ queue: QueueMetrics;
8692
+ workers: WorkerMetrics;
8693
+ timeline: JobEvent[];
8694
+ errors: ErrorStats;
8695
+ }
8696
+ /**
8697
+ * QueueDashboard aggregates metrics from all event processing subsystems
8698
+ * Uses Facade pattern to read-only aggregate data without modifying subsystems
8699
+ */
8700
+ declare class QueueDashboard {
8701
+ private readonly config;
8702
+ constructor(config: QueueDashboardConfig);
8703
+ /**
8704
+ * Get current queue metrics (depth, backpressure state, enqueue rate)
8705
+ */
8706
+ getQueueMetrics(): QueueMetrics;
8707
+ /**
8708
+ * Get current worker pool metrics (size, utilization, success rate)
8709
+ */
8710
+ getWorkerMetrics(): WorkerMetrics;
8711
+ /**
8712
+ * Get job event timeline from DLQ entries (recent failures)
8713
+ * @param limit Maximum number of entries to return (default: 50)
8714
+ */
8715
+ getJobTimeline(limit?: number): JobEvent[];
8716
+ /**
8717
+ * Get error statistics including circuit breaker status and DLQ counts
8718
+ */
8719
+ getErrorBreakdown(): ErrorStats;
8720
+ /**
8721
+ * Export metrics in JSON or Prometheus format
8722
+ * @param format Export format: 'json' or 'prometheus'
8723
+ */
8724
+ exportMetrics(format: 'json' | 'prometheus'): string;
8725
+ /**
8726
+ * Get complete snapshot of all metrics at a point in time
8727
+ */
8728
+ getSnapshot(options?: {
8729
+ timelineLimit?: number;
8730
+ }): DashboardSnapshot;
8731
+ /**
8732
+ * Format metrics in Prometheus/OpenMetrics text format
8733
+ */
8734
+ private formatPrometheus;
8735
+ /**
8736
+ * Escape special characters in Prometheus labels
8737
+ */
8738
+ private escapePrometheusLabel;
8739
+ }
8740
+
8741
+ /**
8742
+ * Register queue management commands with CommandKernel
8743
+ */
8744
+ declare function registerQueueCommands(kernel: CommandKernel, dashboard: QueueDashboard): void;
8745
+
6809
8746
  /**
6810
8747
  * @fileoverview ErrorHandler - Centralized Error Handling for Gravito Framework
6811
8748
  *
@@ -6848,6 +8785,9 @@ declare class ErrorHandler {
6848
8785
  constructor(deps: ErrorHandlerDeps);
6849
8786
  /**
6850
8787
  * Handle application errors
8788
+ *
8789
+ * Integrates RequestScope cleanup to ensure proper resource management
8790
+ * even when errors occur during request processing.
6851
8791
  */
6852
8792
  handleError(err: unknown, c: GravitoContext): Promise<Response>;
6853
8793
  /**
@@ -6868,6 +8808,131 @@ declare class ErrorHandler {
6868
8808
  private renderErrorResponse;
6869
8809
  }
6870
8810
 
8811
+ /**
8812
+ * RequestScope-Aware Error Handling
8813
+ *
8814
+ * Integrates RequestScope lifecycle with error handling to provide:
8815
+ * - Error context with request-scoped resources
8816
+ * - Automatic cleanup of scoped services on error
8817
+ * - Request tracing and diagnostics
8818
+ * - Resource leak detection
8819
+ */
8820
+
8821
+ /**
8822
+ * Extended error context with RequestScope information
8823
+ *
8824
+ * Provides error handlers access to request-scoped resources
8825
+ * for proper resource cleanup and error diagnostics.
8826
+ */
8827
+ interface RequestScopeErrorContext {
8828
+ /**
8829
+ * The original error that was thrown
8830
+ */
8831
+ error: unknown;
8832
+ /**
8833
+ * HTTP context where error occurred
8834
+ */
8835
+ context: GravitoContext;
8836
+ /**
8837
+ * RequestScope manager for this request
8838
+ * Allows error handlers to access or clean up scoped resources
8839
+ */
8840
+ scope?: RequestScopeManager;
8841
+ /**
8842
+ * Metrics about the request scope state
8843
+ * Useful for diagnostics and understanding resource usage
8844
+ */
8845
+ scopeMetrics?: RequestScopeMetrics;
8846
+ /**
8847
+ * Number of scoped services at time of error
8848
+ * High numbers might indicate resource leaks
8849
+ */
8850
+ scopeSize?: number;
8851
+ /**
8852
+ * Request processing time in milliseconds
8853
+ * Useful for timeout errors
8854
+ */
8855
+ duration?: number;
8856
+ /**
8857
+ * Additional diagnostic information
8858
+ */
8859
+ diagnostics?: {
8860
+ servicesCleanedUp?: string[];
8861
+ cleanupErrors?: Array<{
8862
+ service: string;
8863
+ error: unknown;
8864
+ }>;
8865
+ peakMemoryMb?: number;
8866
+ };
8867
+ }
8868
+ /**
8869
+ * Error that occurred during RequestScope cleanup
8870
+ *
8871
+ * Wraps original error with cleanup context for proper error reporting
8872
+ */
8873
+ declare class RequestScopeCleanupError extends Error {
8874
+ originalError: unknown;
8875
+ cleanupErrors: Array<{
8876
+ service: string;
8877
+ error: unknown;
8878
+ }>;
8879
+ constructor(message: string, originalError: unknown, cleanupErrors: Array<{
8880
+ service: string;
8881
+ error: unknown;
8882
+ }>);
8883
+ }
8884
+ /**
8885
+ * Helper to extract RequestScope context from GravitoContext
8886
+ *
8887
+ * @param ctx - Gravito context
8888
+ * @returns RequestScope error context with available information
8889
+ */
8890
+ declare function extractRequestScopeErrorContext(ctx: GravitoContext, error: unknown): RequestScopeErrorContext;
8891
+ /**
8892
+ * Cleanup scoped services safely during error handling
8893
+ *
8894
+ * Ensures all scoped services are cleaned up even if some fail,
8895
+ * and collects cleanup errors for diagnostics.
8896
+ *
8897
+ * @param scope - RequestScope manager
8898
+ * @returns Array of cleanup errors if any occurred
8899
+ */
8900
+ declare function cleanupRequestScopeOnError(scope?: RequestScopeManager): Promise<Array<{
8901
+ service: string;
8902
+ error: unknown;
8903
+ }>>;
8904
+ /**
8905
+ * Safe error handler wrapper that manages RequestScope cleanup
8906
+ *
8907
+ * Ensures scoped services are properly cleaned up before returning error response.
8908
+ * Use this to wrap error handlers to make them RequestScope-aware.
8909
+ *
8910
+ * @example
8911
+ * ```typescript
8912
+ * const errorHandler = withRequestScopeCleanup(async (ctx, error) => {
8913
+ * // Handle error...
8914
+ * return ctx.json({ error: error.message }, 500)
8915
+ * })
8916
+ *
8917
+ * // In your app:
8918
+ * try {
8919
+ * // Handle request...
8920
+ * } catch (error) {
8921
+ * return errorHandler(ctx, error)
8922
+ * }
8923
+ * ```
8924
+ */
8925
+ declare function withRequestScopeCleanup<T extends (ctx: GravitoContext, error: unknown) => Promise<Response>>(handler: T): T;
8926
+ /**
8927
+ * Detect potential resource leaks in RequestScope
8928
+ *
8929
+ * Returns diagnostic information about suspicious resource usage patterns
8930
+ */
8931
+ declare function detectRequestScopeLeaks(context: RequestScopeErrorContext): {
8932
+ potentialLeaks: boolean;
8933
+ warnings: string[];
8934
+ };
8935
+
6871
8936
  /**
6872
8937
  * Options for creating a GravitoException
6873
8938
  * @public
@@ -6984,6 +9049,71 @@ declare class GravitoServer {
6984
9049
  static create(manifest: GravitoManifest, resolvers: Record<string, ModuleResolver>, baseOrbits?: any[]): Promise<PlanetCore>;
6985
9050
  }
6986
9051
 
9052
+ /**
9053
+ * @fileoverview HealthProvider - Cloud-native health checks
9054
+ *
9055
+ * Provides liveness and readiness probes for Kubernetes and cloud deployments
9056
+ *
9057
+ * @module @gravito/core/health
9058
+ * @since 2.2.0
9059
+ */
9060
+
9061
+ /**
9062
+ * Health check result
9063
+ * @public
9064
+ */
9065
+ interface HealthCheckResult {
9066
+ /** Health status */
9067
+ status: 'healthy' | 'unhealthy';
9068
+ /** Optional message */
9069
+ message?: string;
9070
+ }
9071
+ /**
9072
+ * Health check function interface
9073
+ * @public
9074
+ */
9075
+ interface HealthCheck {
9076
+ /** Unique name for this check */
9077
+ name: string;
9078
+ /** Check function that returns health status */
9079
+ check(): Promise<HealthCheckResult>;
9080
+ }
9081
+ /**
9082
+ * HealthProvider - Provides /health/liveness and /health/readiness endpoints
9083
+ *
9084
+ * - Liveness: Always returns 200 OK (just checks if server is running)
9085
+ * - Readiness: Returns 200 if all checks are healthy, 503 otherwise
9086
+ *
9087
+ * @public
9088
+ */
9089
+ declare class HealthProvider extends ServiceProvider {
9090
+ private checks;
9091
+ register(container: Container): void;
9092
+ /**
9093
+ * Register a health check
9094
+ *
9095
+ * @param check - The health check to register
9096
+ *
9097
+ * @example
9098
+ * ```typescript
9099
+ * const health = core.container.make<HealthProvider>('health')
9100
+ * health.registerCheck({
9101
+ * name: 'database',
9102
+ * check: async () => {
9103
+ * try {
9104
+ * await db.ping()
9105
+ * return { status: 'healthy' }
9106
+ * } catch {
9107
+ * return { status: 'unhealthy', message: 'DB unreachable' }
9108
+ * }
9109
+ * }
9110
+ * })
9111
+ * ```
9112
+ */
9113
+ registerCheck(check: HealthCheck): void;
9114
+ boot(core: PlanetCore): void;
9115
+ }
9116
+
6987
9117
  /**
6988
9118
  * Path segment (key) in a data structure.
6989
9119
  * @public
@@ -8015,6 +10145,103 @@ declare namespace index$1 {
8015
10145
  export { index$1_DEFAULT_CONFIG as DEFAULT_CONFIG, type index$1_MetricsConfig as MetricsConfig, type index$1_MetricsExporter as MetricsExporter, index$1_OTEL_ENV_VARS as OTEL_ENV_VARS, type index$1_OpenTelemetryConfig as OpenTelemetryConfig, type index$1_OpenTelemetrySDK as OpenTelemetrySDK, type index$1_TracingConfig as TracingConfig, type index$1_TracingExporter as TracingExporter, index$1_getMeter as getMeter, index$1_getOpenTelemetrySDK as getOpenTelemetrySDK, index$1_getTracer as getTracer, index$1_isOpenTelemetryInitialized as isOpenTelemetryInitialized, index$1_resetOpenTelemetry as resetOpenTelemetry, index$1_setupOpenTelemetry as setupOpenTelemetry, index$1_shutdownOpenTelemetry as shutdownOpenTelemetry };
8016
10146
  }
8017
10147
 
10148
+ /**
10149
+ * @fileoverview RequestContext - AsyncLocalStorage-based request context management
10150
+ *
10151
+ * Allows deep service layers to access request-scoped data (requestId, userId, etc.)
10152
+ * without passing parameters through the call stack.
10153
+ *
10154
+ * @module @gravito/core/RequestContext
10155
+ * @since 2.2.0
10156
+ */
10157
+ /**
10158
+ * 請求上下文資料介面
10159
+ * 包含請求相關的唯一識別碼和上下文資訊
10160
+ * @public
10161
+ */
10162
+ interface RequestContextData {
10163
+ /** 唯一的請求識別碼 */
10164
+ requestId: string;
10165
+ /** 使用者 ID(可選) */
10166
+ userId?: string;
10167
+ /** 租戶 ID(可選) */
10168
+ tenantId?: string;
10169
+ /** 追蹤 ID(可選) */
10170
+ traceId?: string;
10171
+ /** 自訂欄位 */
10172
+ [key: string]: unknown;
10173
+ }
10174
+ /**
10175
+ * RequestContext 物件 - 管理請求上下文的 API
10176
+ *
10177
+ * 提供在非同步鏈中存取和設定請求上下文的方法
10178
+ * @public
10179
+ */
10180
+ declare const RequestContext: {
10181
+ /**
10182
+ * 在給定的上下文中執行函式
10183
+ *
10184
+ * 確保函式及其所有非同步呼叫都在同一個上下文中執行
10185
+ *
10186
+ * @param data - 請求上下文資料
10187
+ * @param fn - 要執行的函式(可以是非同步的或同步的)
10188
+ * @returns 如果函式是非同步的,返回 Promise;如果是同步的,直接返回值
10189
+ *
10190
+ * @example
10191
+ * ```typescript
10192
+ * await RequestContext.run({ requestId: 'req-123' }, async () => {
10193
+ * const userId = RequestContext.get()?.userId;
10194
+ * });
10195
+ *
10196
+ * const result = RequestContext.run({ requestId: 'req-123' }, () => {
10197
+ * return 'sync-result';
10198
+ * });
10199
+ * ```
10200
+ */
10201
+ run<T>(data: RequestContextData, fn: () => T | Promise<T>): T | Promise<T>;
10202
+ /**
10203
+ * 獲取當前請求的上下文資料
10204
+ *
10205
+ * @returns 請求上下文資料,如果不在請求上下文中則返回 undefined
10206
+ *
10207
+ * @example
10208
+ * ```typescript
10209
+ * const context = RequestContext.get();
10210
+ * if (context) {
10211
+ * console.log(context.requestId);
10212
+ * }
10213
+ * ```
10214
+ */
10215
+ get(): RequestContextData | undefined;
10216
+ /**
10217
+ * 獲取當前請求的上下文資料,如果不存在則拋出錯誤
10218
+ *
10219
+ * @returns 請求上下文資料
10220
+ * @throws Error 如果不在請求上下文中
10221
+ *
10222
+ * @example
10223
+ * ```typescript
10224
+ * const context = RequestContext.getOrThrow();
10225
+ * console.log(context.requestId); // 保證不為 undefined
10226
+ * ```
10227
+ */
10228
+ getOrThrow(): RequestContextData;
10229
+ /**
10230
+ * 在當前上下文中設定或修改值
10231
+ *
10232
+ * @param key - 要設定的欄位名稱
10233
+ * @param value - 要設定的值
10234
+ * @throws Error 如果不在請求上下文中
10235
+ *
10236
+ * @example
10237
+ * ```typescript
10238
+ * RequestContext.set('userId', 'user-456');
10239
+ * const userId = RequestContext.get()?.userId; // 'user-456'
10240
+ * ```
10241
+ */
10242
+ set(key: string, value: unknown): void;
10243
+ };
10244
+
8018
10245
  /**
8019
10246
  * TestResponse wraps a standard Fetch Response and provides fluent assertion methods
8020
10247
  * inspired by Laravel's TestResponse.
@@ -8290,7 +10517,12 @@ declare class AOTRouter {
8290
10517
  private dynamicRoutePatterns;
8291
10518
  private middlewareCache;
8292
10519
  private cacheMaxSize;
8293
- private version;
10520
+ private _version;
10521
+ /**
10522
+ * Get the current version for cache invalidation
10523
+ * Incremented whenever middleware or routes are modified
10524
+ */
10525
+ get version(): number;
8294
10526
  /**
8295
10527
  * Register a route
8296
10528
  *
@@ -8400,6 +10632,11 @@ declare class FastRequestImpl implements FastRequest {
8400
10632
  private _headers;
8401
10633
  private _cachedJson;
8402
10634
  private _jsonParsed;
10635
+ private _cachedText;
10636
+ private _textParsed;
10637
+ private _cachedFormData;
10638
+ private _formDataParsed;
10639
+ private _cachedQueries;
8403
10640
  private _ctx;
8404
10641
  constructor(ctx: FastContext);
8405
10642
  /**
@@ -8437,6 +10674,7 @@ declare class FastContext implements FastContext$1 {
8437
10674
  readonly req: FastRequestImpl;
8438
10675
  private _headers;
8439
10676
  _isReleased: boolean;
10677
+ private _requestScope;
8440
10678
  /**
8441
10679
  * Initialize context for a new request
8442
10680
  *
@@ -8471,6 +10709,22 @@ declare class FastContext implements FastContext$1 {
8471
10709
  private _store;
8472
10710
  get<T>(key: string): T;
8473
10711
  set(key: string, value: any): void;
10712
+ /**
10713
+ * Get the request-scoped service manager for this request.
10714
+ *
10715
+ * @returns The RequestScopeManager for this request.
10716
+ * @throws Error if called before init() or after reset().
10717
+ */
10718
+ requestScope(): RequestScopeManager;
10719
+ /**
10720
+ * Resolve a request-scoped service (convenience method).
10721
+ *
10722
+ * @template T - The service type.
10723
+ * @param key - The service key for caching.
10724
+ * @param factory - Factory function to create the service.
10725
+ * @returns The cached or newly created service instance.
10726
+ */
10727
+ scoped<T>(key: string | symbol, factory: () => T): T;
8474
10728
  route: (name: string, params?: any, query?: any) => string;
8475
10729
  get native(): this;
8476
10730
  }
@@ -8498,6 +10752,10 @@ declare class MinimalRequest implements FastRequest {
8498
10752
  private readonly _path;
8499
10753
  private readonly _routePattern?;
8500
10754
  private _searchParams;
10755
+ private _cachedQueries;
10756
+ private _cachedJsonPromise;
10757
+ private _cachedTextPromise;
10758
+ private _cachedFormDataPromise;
8501
10759
  constructor(_request: Request, _params: Record<string, string>, _path: string, _routePattern?: string | undefined);
8502
10760
  get url(): string;
8503
10761
  get method(): string;
@@ -8530,6 +10788,7 @@ declare class MinimalRequest implements FastRequest {
8530
10788
  declare class MinimalContext implements FastContext$1 {
8531
10789
  readonly req: MinimalRequest;
8532
10790
  private _resHeaders;
10791
+ private _requestScope;
8533
10792
  constructor(request: Request, params: Record<string, string>, path: string, routePattern?: string);
8534
10793
  private getHeaders;
8535
10794
  json<T>(data: T, status?: number): Response;
@@ -8548,6 +10807,21 @@ declare class MinimalContext implements FastContext$1 {
8548
10807
  forward(target: string, _options?: any): Promise<Response>;
8549
10808
  get<T>(_key: string): T;
8550
10809
  set(_key: string, _value: any): void;
10810
+ /**
10811
+ * Get the request-scoped service manager for this request.
10812
+ *
10813
+ * @returns The RequestScopeManager for this request.
10814
+ */
10815
+ requestScope(): RequestScopeManager;
10816
+ /**
10817
+ * Resolve a request-scoped service (convenience method).
10818
+ *
10819
+ * @template T - The service type.
10820
+ * @param key - The service key for caching.
10821
+ * @param factory - Factory function to create the service.
10822
+ * @returns The cached or newly created service instance.
10823
+ */
10824
+ scoped<T>(key: string | symbol, factory: () => T): T;
8551
10825
  route: (name: string, params?: any, query?: any) => string;
8552
10826
  get native(): this;
8553
10827
  init(_request: Request, _params?: Record<string, string>, _path?: string): this;
@@ -8731,4 +11005,4 @@ declare const VERSION: string;
8731
11005
  */
8732
11006
  declare function defineConfig(config: GravitoConfig): GravitoConfig;
8733
11007
 
8734
- export { type ActionCallback, type AdapterConfig, type AdapterFactory, type ApiFailure, type ApiSuccess, Application, type ApplicationConfig, Arr, AuthenticationException, AuthorizationException, type BodySizeLimitOptions, type CacheService, type Channel, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerState, CircularDependencyException, type CommandHandler, CommandKernel, ConfigManager, ConsoleLogger, Container, ContentfulStatusCode, type ControllerClass, CookieJar, type CookieOptions, type CorsOptions, type CorsOrigin, type CsrfOptions, DEFAULT_EVENT_OPTIONS, type DLQEntry, type DLQFilter, type DLQManagerFilter, type DLQRecord, type DLQStats, type DataPath, DeadLetterQueue, DeadLetterQueueManager, DumpDieError, type DumpOptions, Encrypter, type EncrypterOptions, type ErrorBag, ErrorHandler, type ErrorHandlerContext, type ErrorHandlerDeps, Event, type EventBackend, EventManager, EventMetrics, type EventOptions, EventPriorityQueue, type EventTask, EventTracer, EventTracing, type EventTracingConfig, type ExceptionOptions, FORM_REQUEST_SYMBOL, type Factory$1 as Factory, type FilterCallback, type FormRequestClass, type FormRequestLike, type GlobalErrorHandlersMode, type GlobalProcessErrorHandlerContext, type GlobalProcessErrorKind, GravitoAdapter, type GravitoConfig, GravitoContext, GravitoEngineAdapter, GravitoErrorHandler, GravitoException, GravitoHandler, type GravitoManifest, GravitoMiddleware, GravitoNotFoundHandler, type GravitoOrbit, GravitoRequest, GravitoServer, GravitoVariables, type HeaderTokenGateOptions, HookManager, type HookManagerConfig, type HstsOptions, type HttpAdapter, HttpException, HttpMethod, HttpTester, type Listener, type ListenerInfo, type ListenerOptions, type Logger, type MetricsExporter, ModelNotFoundException, DEFAULT_CONFIG as OTEL_DEFAULT_CONFIG, OTEL_ENV_VARS, OTelEventMetrics, type ObservabilityConfig, ObservableHookManager, type OpenTelemetryConfig, type OpenTelemetrySDK, type MetricsConfig as OtelMetricsConfig, type TracingConfig as OtelTracingConfig, type PathSegment, PhotonAdapter, PhotonContextWrapper, PhotonRequestWrapper, PlanetCore, type QueueDepthCallback, type RegisterGlobalErrorHandlersOptions, type RequireHeaderTokenOptions, RetryEngine, type RetryPolicy, Route, type RouteDefinition$1 as RouteDefinition, RouteGroup, type RouteHandler, type RouteOptions, Router, type RuntimeAdapter, type RuntimeFileStat, type RuntimeKind, type RuntimePasswordAdapter, type RuntimeProcess, type RuntimeServeConfig, type RuntimeServer, type RuntimeSpawnOptions, type RuntimeSqliteDatabase, type RuntimeSqliteStatement, type SecurityHeadersOptions, type ServiceKey, type ServiceMap, ServiceProvider, type ShouldBroadcast, type ShouldQueue, StatusCode, Str, TestResponse, ThrottleRequests, type TracingExporter, VERSION, type ValidationError, ValidationException, type ViewService, abort, abortIf, abortUnless, app, blank, bodySizeLimit, codeFromStatus, config, cors, createErrorBag, createGravitoAdapter, createHeaderGate, createHttpTester, createPhotonAdapter, createSqliteDatabase, csrfProtection, dataGet, dataHas, dataSet, dd, defineConfig, deleteCookie, dump, index as engine, env, errors, fail, filled, getCookie, getCsrfToken, getDefaultRetryPolicy, getEventTracing, getMeter, getOpenTelemetrySDK, getTracer as getOtelTracer, getPasswordAdapter, getPresetRetryPolicy, getRuntimeAdapter, getRuntimeEnv, hasApp, index$1 as instrumentation, isHttpAdapter, isOpenTelemetryInitialized, jsonFail, jsonSuccess, logger, messageFromStatus, ok, old, registerGlobalErrorHandlers, requireHeaderToken, resetOpenTelemetry, router, securityHeaders, setApp, setCookie, setupOpenTelemetry, shutdownOpenTelemetry, tap, throwIf, throwUnless, value };
11008
+ export { type ActionCallback, type AdapterConfig, type AdapterFactory, type ApiFailure, type ApiSuccess, Application, type ApplicationConfig, Arr, AuthenticationException, AuthorizationException, type BodySizeLimitOptions, type CacheService, type Channel, CircuitBreaker, type CircuitBreakerOptions, CircuitBreakerState, CircularDependencyException, type CommandHandler, CommandKernel, ConfigManager, ConsoleLogger, Container, ContentfulStatusCode, type ControllerClass, CookieJar, type CookieOptions, type CorsOptions, type CorsOrigin, type CsrfOptions, DEFAULT_EVENT_OPTIONS, type DLQEntry, type DLQFilter, type DLQManagerFilter, type DLQRecord, type DLQStats, type DashboardSnapshot, type DataPath, DeadLetterQueue, DeadLetterQueueManager, DumpDieError, type DumpOptions, Encrypter, type EncrypterOptions, type ErrorBag, ErrorHandler, type ErrorHandlerContext, type ErrorHandlerDeps, type ErrorStats, Event, type EventBackend, EventManager, EventMetrics, type EventOptions, EventPriorityQueue, type EventTask, EventTracer, EventTracing, type EventTracingConfig, type ExceptionOptions, FORM_REQUEST_SYMBOL, type Factory$1 as Factory, type FilterCallback, type FormRequestClass, type FormRequestLike, type GlobalErrorHandlersMode, type GlobalProcessErrorHandlerContext, type GlobalProcessErrorKind, GravitoAdapter, type GravitoConfig, GravitoContext, GravitoEngineAdapter, GravitoErrorHandler, GravitoException, GravitoHandler, type GravitoManifest, GravitoMiddleware, GravitoNotFoundHandler, type GravitoOrbit, GravitoRequest, GravitoServer, GravitoVariables, type HeaderTokenGateOptions, type HealthCheck, type HealthCheckResult, HealthProvider, HookManager, type HookManagerConfig, type HstsOptions, type HttpAdapter, HttpException, HttpMethod, HttpTester, type JobEvent, type Listener, type ListenerInfo, type ListenerOptions, type Logger, type MetricsExporter, ModelNotFoundException, DEFAULT_CONFIG as OTEL_DEFAULT_CONFIG, OTEL_ENV_VARS, OTelEventMetrics, type ObservabilityConfig, ObservableHookManager, type OpenTelemetryConfig, type OpenTelemetrySDK, type MetricsConfig as OtelMetricsConfig, type TracingConfig as OtelTracingConfig, type PathSegment, PhotonAdapter, PhotonContextWrapper, PhotonRequestWrapper, PlanetCore, QueueDashboard, type QueueDashboardConfig, type QueueDepthCallback, type QueueMetrics, type WorkerMetrics as QueueWorkerMetrics, type RegisterGlobalErrorHandlersOptions, RequestContext, type RequestContextData, RequestScopeCleanupError, type RequestScopeErrorContext, RequestScopeManager, RequestScopeMetrics, RequestScopeMetricsCollector, type RequestScopeObserver, type RequireHeaderTokenOptions, RetryEngine, type RetryPolicy, Route, type RouteDefinition$1 as RouteDefinition, RouteGroup, type RouteHandler, type RouteOptions, Router, type RuntimeAdapter, type RuntimeFileStat, type RuntimeKind, type RuntimePasswordAdapter, type RuntimeProcess, type RuntimeServeConfig, type RuntimeServer, type RuntimeSpawnOptions, type RuntimeSqliteDatabase, type RuntimeSqliteStatement, type SecurityHeadersOptions, type ServiceKey, type ServiceMap, ServiceProvider, type ShouldBroadcast, type ShouldQueue, StatusCode, Str, TestResponse, ThrottleRequests, type TracingExporter, VERSION, type ValidationError, ValidationException, type ViewService, abort, abortIf, abortUnless, app, blank, bodySizeLimit, cleanupRequestScopeOnError, codeFromStatus, config, cors, createErrorBag, createGravitoAdapter, createHeaderGate, createHttpTester, createPhotonAdapter, createSqliteDatabase, csrfProtection, dataGet, dataHas, dataSet, dd, defineConfig, deleteCookie, detectRequestScopeLeaks, dump, index as engine, env, errors, extractRequestScopeErrorContext, fail, filled, getCookie, getCsrfToken, getDefaultRetryPolicy, getEventTracing, getMeter, getOpenTelemetrySDK, getTracer as getOtelTracer, getPasswordAdapter, getPresetRetryPolicy, getRuntimeAdapter, getRuntimeEnv, hasApp, index$1 as instrumentation, isHttpAdapter, isOpenTelemetryInitialized, jsonFail, jsonSuccess, logger, messageFromStatus, ok, old, registerGlobalErrorHandlers, registerQueueCommands, requireHeaderToken, resetOpenTelemetry, router, securityHeaders, setApp, setCookie, setupOpenTelemetry, shutdownOpenTelemetry, tap, throwIf, throwUnless, value, withRequestScopeCleanup };