@gravito/core 1.6.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +100 -6
  2. package/README.zh-TW.md +101 -6
  3. package/dist/Application.d.ts +256 -0
  4. package/dist/CommandKernel.d.ts +33 -0
  5. package/dist/ConfigManager.d.ts +65 -0
  6. package/dist/Container/RequestScopeManager.d.ts +62 -0
  7. package/dist/Container/RequestScopeMetrics.d.ts +144 -0
  8. package/dist/Container.d.ts +153 -0
  9. package/dist/ErrorHandler.d.ts +66 -0
  10. package/dist/Event.d.ts +5 -0
  11. package/dist/EventManager.d.ts +123 -0
  12. package/dist/GlobalErrorHandlers.d.ts +47 -0
  13. package/dist/GravitoServer.d.ts +28 -0
  14. package/dist/HookManager.d.ts +435 -0
  15. package/dist/Listener.d.ts +4 -0
  16. package/dist/Logger.d.ts +20 -0
  17. package/dist/PlanetCore.d.ts +402 -0
  18. package/dist/RequestContext.d.ts +97 -0
  19. package/dist/Route.d.ts +36 -0
  20. package/dist/Router.d.ts +270 -0
  21. package/dist/ServiceProvider.d.ts +178 -0
  22. package/dist/adapters/GravitoEngineAdapter.d.ts +27 -0
  23. package/dist/adapters/bun/AdaptiveAdapter.d.ts +99 -0
  24. package/dist/adapters/bun/BunContext.d.ts +54 -0
  25. package/dist/adapters/bun/BunNativeAdapter.d.ts +66 -0
  26. package/dist/adapters/bun/BunRequest.d.ts +31 -0
  27. package/dist/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  28. package/dist/adapters/bun/RadixNode.d.ts +19 -0
  29. package/dist/adapters/bun/RadixRouter.d.ts +32 -0
  30. package/dist/adapters/bun/index.d.ts +7 -0
  31. package/dist/adapters/bun/types.d.ts +20 -0
  32. package/dist/adapters/index.d.ts +12 -0
  33. package/dist/adapters/types.d.ts +235 -0
  34. package/dist/binary/BinaryUtils.d.ts +105 -0
  35. package/dist/binary/index.d.ts +5 -0
  36. package/dist/cli/queue-commands.d.ts +6 -0
  37. package/dist/compat/async-local-storage.browser.d.ts +9 -0
  38. package/dist/compat/async-local-storage.d.ts +7 -0
  39. package/dist/compat/crypto.browser.d.ts +5 -0
  40. package/dist/compat/crypto.d.ts +6 -0
  41. package/dist/compat.d.ts +23 -1
  42. package/dist/compat.js +3 -0
  43. package/dist/compat.js.map +9 -0
  44. package/dist/engine/AOTRouter.d.ts +139 -0
  45. package/dist/engine/FastContext.d.ts +141 -0
  46. package/dist/engine/Gravito.d.ts +131 -0
  47. package/dist/engine/MinimalContext.d.ts +102 -0
  48. package/dist/engine/analyzer.d.ts +113 -0
  49. package/dist/engine/constants.d.ts +23 -0
  50. package/dist/engine/index.d.ts +14 -910
  51. package/dist/engine/index.js +623 -622
  52. package/dist/engine/index.js.map +23 -0
  53. package/dist/engine/path.d.ts +26 -0
  54. package/dist/engine/pool.d.ts +83 -0
  55. package/dist/engine/types.d.ts +149 -0
  56. package/dist/error-handling/RequestScopeErrorContext.d.ts +126 -0
  57. package/dist/events/BackpressureManager.d.ts +215 -0
  58. package/dist/events/CircuitBreaker.d.ts +229 -0
  59. package/dist/events/DeadLetterQueue.d.ts +219 -0
  60. package/dist/events/EventBackend.d.ts +12 -0
  61. package/dist/events/EventOptions.d.ts +204 -0
  62. package/dist/events/EventPriorityQueue.d.ts +63 -0
  63. package/dist/events/FlowControlStrategy.d.ts +109 -0
  64. package/dist/events/IdempotencyCache.d.ts +60 -0
  65. package/dist/events/MessageQueueBridge.d.ts +184 -0
  66. package/dist/events/PriorityEscalationManager.d.ts +82 -0
  67. package/dist/events/RetryScheduler.d.ts +104 -0
  68. package/dist/events/WorkerPool.d.ts +98 -0
  69. package/dist/events/WorkerPoolConfig.d.ts +153 -0
  70. package/dist/events/WorkerPoolMetrics.d.ts +65 -0
  71. package/dist/events/aggregation/AggregationWindow.d.ts +77 -0
  72. package/dist/events/aggregation/DeduplicationManager.d.ts +135 -0
  73. package/dist/events/aggregation/EventAggregationManager.d.ts +108 -0
  74. package/dist/events/aggregation/EventBatcher.d.ts +99 -0
  75. package/dist/events/aggregation/index.d.ts +10 -0
  76. package/dist/events/aggregation/types.d.ts +117 -0
  77. package/dist/events/index.d.ts +26 -0
  78. package/dist/events/observability/EventMetrics.d.ts +132 -0
  79. package/dist/events/observability/EventTracer.d.ts +68 -0
  80. package/dist/events/observability/EventTracing.d.ts +161 -0
  81. package/dist/events/observability/OTelEventMetrics.d.ts +332 -0
  82. package/dist/events/observability/ObservableHookManager.d.ts +108 -0
  83. package/dist/events/observability/StreamWorkerMetrics.d.ts +76 -0
  84. package/dist/events/observability/index.d.ts +24 -0
  85. package/dist/events/observability/metrics-types.d.ts +16 -0
  86. package/dist/events/queue-core.d.ts +77 -0
  87. package/dist/events/task-executor.d.ts +51 -0
  88. package/dist/events/types.d.ts +134 -0
  89. package/dist/exceptions/AuthenticationException.d.ts +8 -0
  90. package/dist/exceptions/AuthorizationException.d.ts +8 -0
  91. package/dist/exceptions/CircularDependencyException.d.ts +9 -0
  92. package/dist/exceptions/GravitoException.d.ts +23 -0
  93. package/dist/exceptions/HttpException.d.ts +9 -0
  94. package/dist/exceptions/ModelNotFoundException.d.ts +10 -0
  95. package/dist/exceptions/ValidationException.d.ts +22 -0
  96. package/dist/exceptions/index.d.ts +7 -0
  97. package/dist/ffi/NativeAccelerator.d.ts +69 -0
  98. package/dist/ffi/NativeHasher.d.ts +139 -0
  99. package/dist/ffi/cbor-fallback.d.ts +96 -0
  100. package/dist/ffi/hash-fallback.d.ts +33 -0
  101. package/dist/ffi/index.d.ts +10 -0
  102. package/dist/ffi/index.js +131 -0
  103. package/dist/ffi/index.js.map +11 -0
  104. package/dist/ffi/types.d.ts +135 -0
  105. package/dist/health/HealthProvider.d.ts +67 -0
  106. package/dist/helpers/Arr.d.ts +19 -0
  107. package/dist/helpers/Str.d.ts +38 -0
  108. package/dist/helpers/data.d.ts +25 -0
  109. package/dist/helpers/errors.d.ts +34 -0
  110. package/dist/helpers/response.d.ts +41 -0
  111. package/dist/helpers.d.ts +338 -0
  112. package/dist/hooks/ActionManager.d.ts +132 -0
  113. package/dist/hooks/AsyncDetector.d.ts +84 -0
  114. package/dist/hooks/FilterManager.d.ts +71 -0
  115. package/dist/hooks/MigrationWarner.d.ts +24 -0
  116. package/dist/hooks/dlq-operations.d.ts +60 -0
  117. package/dist/hooks/index.d.ts +11 -0
  118. package/dist/hooks/types.d.ts +107 -0
  119. package/dist/http/CookieJar.d.ts +51 -0
  120. package/dist/http/cookie.d.ts +29 -0
  121. package/dist/http/index.d.ts +12 -0
  122. package/dist/{compat-CI8hiulX.d.cts → http/types.d.ts} +35 -16
  123. package/dist/index.browser.d.ts +34 -0
  124. package/dist/index.d.ts +60 -10981
  125. package/dist/index.js +10808 -11273
  126. package/dist/index.js.map +166 -0
  127. package/dist/observability/QueueDashboard.d.ts +136 -0
  128. package/dist/observability/contracts.d.ts +137 -0
  129. package/dist/observability/index.d.ts +13 -0
  130. package/dist/reliability/DeadLetterQueueManager.d.ts +349 -0
  131. package/dist/reliability/RetryPolicy.d.ts +217 -0
  132. package/dist/reliability/index.d.ts +6 -0
  133. package/dist/router/ControllerDispatcher.d.ts +12 -0
  134. package/dist/router/RequestValidator.d.ts +20 -0
  135. package/dist/runtime/adapter-bun.d.ts +12 -0
  136. package/dist/runtime/adapter-deno.d.ts +12 -0
  137. package/dist/runtime/adapter-node.d.ts +12 -0
  138. package/dist/runtime/adapter-unknown.d.ts +13 -0
  139. package/dist/runtime/archive.d.ts +17 -0
  140. package/dist/runtime/compression.d.ts +21 -0
  141. package/dist/runtime/deep-equals.d.ts +56 -0
  142. package/dist/runtime/detection.d.ts +22 -0
  143. package/dist/runtime/escape.d.ts +34 -0
  144. package/dist/runtime/index.browser.d.ts +20 -0
  145. package/dist/runtime/index.d.ts +44 -0
  146. package/dist/runtime/markdown.d.ts +44 -0
  147. package/dist/runtime/types.d.ts +436 -0
  148. package/dist/runtime-helpers.d.ts +67 -0
  149. package/dist/runtime.d.ts +11 -0
  150. package/dist/security/Encrypter.d.ts +33 -0
  151. package/dist/security/Hasher.d.ts +29 -0
  152. package/dist/testing/HttpTester.d.ts +39 -0
  153. package/dist/testing/TestResponse.d.ts +78 -0
  154. package/dist/testing/index.d.ts +2 -0
  155. package/dist/transpiler-utils.d.ts +170 -0
  156. package/dist/types/events.d.ts +94 -0
  157. package/dist/types.d.ts +13 -0
  158. package/package.json +25 -56
  159. package/src/ffi/native/cbor.c +1148 -0
  160. package/dist/Metrics-VOWWRNNR.js +0 -219
  161. package/dist/chunk-R5U7XKVJ.js +0 -16
  162. package/dist/compat-CI8hiulX.d.ts +0 -376
  163. package/dist/compat.cjs +0 -18
  164. package/dist/compat.d.cts +0 -1
  165. package/dist/engine/index.cjs +0 -1764
  166. package/dist/engine/index.d.cts +0 -922
  167. package/dist/index.cjs +0 -14906
  168. package/dist/index.d.cts +0 -11008
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @fileoverview Gravito Core Engine Types
3
+ *
4
+ * Minimal, high-performance types for the standalone engine.
5
+ * These are intentionally simpler than the full framework types.
6
+ *
7
+ * @module @gravito/core/engine
8
+ */
9
+ import type { HttpMethod } from '../http/types';
10
+ /**
11
+ * FastContext - The pooled request context
12
+ */
13
+ export interface FastContext {
14
+ /** Request accessor */
15
+ readonly req: FastRequest;
16
+ /** Response helpers */
17
+ json<T>(data: T, status?: number): Response;
18
+ text(text: string, status?: number): Response;
19
+ html(html: string, status?: number): Response;
20
+ redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
21
+ body(data: BodyInit | null, status?: number): Response;
22
+ stream(stream: ReadableStream, status?: number): Response;
23
+ notFound(message?: string): Response;
24
+ forbidden(message?: string): Response;
25
+ unauthorized(message?: string): Response;
26
+ badRequest(message?: string): Response;
27
+ forward(target: string, options?: any): Promise<Response>;
28
+ escape(html: string): string;
29
+ /** Header management */
30
+ header(name: string): string | undefined;
31
+ header(name: string, value: string): void;
32
+ status(code: number): void;
33
+ /** Context Variables */
34
+ get<T>(key: string): T;
35
+ set(key: string, value: any): void;
36
+ /** Request Scope Management */
37
+ requestScope(): any;
38
+ scoped<T>(key: string | symbol, factory: () => T): T;
39
+ /** Lifecycle helpers */
40
+ route: (name: string, params?: any, query?: any) => string;
41
+ readonly native: any;
42
+ /** Internal initialization for pooling */
43
+ init(request: Request, params?: Record<string, string>, path?: string, routePattern?: string): this;
44
+ /** Internal cleanup for pooling */
45
+ reset(): void;
46
+ }
47
+ /**
48
+ * FastRequest - Minimal request interface
49
+ */
50
+ export interface FastRequest {
51
+ /** Full URL */
52
+ readonly url: string;
53
+ /** HTTP method */
54
+ readonly method: string;
55
+ /** Path without query */
56
+ readonly path: string;
57
+ /**
58
+ * Route pattern (e.g., /users/:id) for metrics labeling
59
+ * Prevents high cardinality issues in monitoring systems
60
+ */
61
+ readonly routePattern?: string;
62
+ /** Get route parameter */
63
+ param(name: string): string | undefined;
64
+ /** Get all route parameters */
65
+ params(): Record<string, string>;
66
+ /** Get query parameter */
67
+ query(name: string): string | undefined;
68
+ /** Get all query parameters */
69
+ queries(): Record<string, string | string[]>;
70
+ /** Get header */
71
+ header(name: string): string | undefined;
72
+ /** Get all headers */
73
+ headers(): Record<string, string>;
74
+ /** Get all cookies (Native Bun 1.39+ / Lazy Parsed) */
75
+ readonly cookies: Record<string, string>;
76
+ /** Parse JSON body */
77
+ json<T = unknown>(): Promise<T>;
78
+ /** Parse text body */
79
+ text(): Promise<string>;
80
+ /** Parse form data */
81
+ formData(): Promise<FormData>;
82
+ /** Raw Request object */
83
+ readonly raw: Request;
84
+ }
85
+ /**
86
+ * Route handler function
87
+ */
88
+ export type Handler = (ctx: FastContext) => Response | Promise<Response>;
89
+ /**
90
+ * Middleware function
91
+ */
92
+ export type Middleware = (ctx: FastContext, next: () => Promise<Response | undefined>) => Response | undefined | Promise<Response | undefined>;
93
+ /**
94
+ * Error handler function
95
+ */
96
+ export type ErrorHandler = (error: Error, ctx: FastContext) => Response | Promise<Response>;
97
+ /**
98
+ * Not found handler function
99
+ */
100
+ export type NotFoundHandler = (ctx: FastContext) => Response | Promise<Response>;
101
+ /**
102
+ * Route metadata for middleware management
103
+ */
104
+ export interface RouteMetadata {
105
+ handler: Handler;
106
+ middleware: Middleware[];
107
+ compiled?: CompiledHandler;
108
+ useMinimal?: boolean;
109
+ compiledVersion?: number;
110
+ }
111
+ /**
112
+ * Compiled handler function
113
+ */
114
+ export type CompiledHandler = (ctx: FastContext) => Promise<Response>;
115
+ /**
116
+ * Route match result from router
117
+ */
118
+ export interface RouteMatch {
119
+ /** Matched handler */
120
+ handler: Handler | null;
121
+ /** Extracted route parameters */
122
+ params: Record<string, string>;
123
+ /** Middleware to execute */
124
+ middleware: Middleware[];
125
+ /** Optional stable route pattern for caching */
126
+ routePattern?: string;
127
+ }
128
+ /**
129
+ * Internal route node
130
+ */
131
+ export interface RouteNode {
132
+ method: HttpMethod;
133
+ path: string;
134
+ handler: Handler;
135
+ middleware: Middleware[];
136
+ }
137
+ /**
138
+ * Engine configuration options
139
+ */
140
+ export interface EngineOptions {
141
+ /** Context pool size (default: 256) */
142
+ poolSize?: number;
143
+ /** Enable route compilation optimization (default: true) */
144
+ enableAOT?: boolean;
145
+ /** Custom error handler */
146
+ onError?: ErrorHandler;
147
+ /** Custom 404 handler */
148
+ onNotFound?: NotFoundHandler;
149
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * RequestScope-Aware Error Handling
3
+ *
4
+ * Integrates RequestScope lifecycle with error handling to provide:
5
+ * - Error context with request-scoped resources
6
+ * - Automatic cleanup of scoped services on error
7
+ * - Request tracing and diagnostics
8
+ * - Resource leak detection
9
+ */
10
+ import type { RequestScopeManager } from '../Container/RequestScopeManager';
11
+ import type { RequestScopeMetrics } from '../Container/RequestScopeMetrics';
12
+ import type { GravitoContext } from '../http/types';
13
+ /**
14
+ * Extended error context with RequestScope information
15
+ *
16
+ * Provides error handlers access to request-scoped resources
17
+ * for proper resource cleanup and error diagnostics.
18
+ */
19
+ export interface RequestScopeErrorContext {
20
+ /**
21
+ * The original error that was thrown
22
+ */
23
+ error: unknown;
24
+ /**
25
+ * HTTP context where error occurred
26
+ */
27
+ context: GravitoContext;
28
+ /**
29
+ * RequestScope manager for this request
30
+ * Allows error handlers to access or clean up scoped resources
31
+ */
32
+ scope?: RequestScopeManager;
33
+ /**
34
+ * Metrics about the request scope state
35
+ * Useful for diagnostics and understanding resource usage
36
+ */
37
+ scopeMetrics?: RequestScopeMetrics;
38
+ /**
39
+ * Number of scoped services at time of error
40
+ * High numbers might indicate resource leaks
41
+ */
42
+ scopeSize?: number;
43
+ /**
44
+ * Request processing time in milliseconds
45
+ * Useful for timeout errors
46
+ */
47
+ duration?: number;
48
+ /**
49
+ * Additional diagnostic information
50
+ */
51
+ diagnostics?: {
52
+ servicesCleanedUp?: string[];
53
+ cleanupErrors?: Array<{
54
+ service: string;
55
+ error: unknown;
56
+ }>;
57
+ peakMemoryMb?: number;
58
+ };
59
+ }
60
+ /**
61
+ * Error that occurred during RequestScope cleanup
62
+ *
63
+ * Wraps original error with cleanup context for proper error reporting
64
+ */
65
+ export declare class RequestScopeCleanupError extends Error {
66
+ originalError: unknown;
67
+ cleanupErrors: Array<{
68
+ service: string;
69
+ error: unknown;
70
+ }>;
71
+ constructor(message: string, originalError: unknown, cleanupErrors: Array<{
72
+ service: string;
73
+ error: unknown;
74
+ }>);
75
+ }
76
+ /**
77
+ * Helper to extract RequestScope context from GravitoContext
78
+ *
79
+ * @param ctx - Gravito context
80
+ * @returns RequestScope error context with available information
81
+ */
82
+ export declare function extractRequestScopeErrorContext(ctx: GravitoContext, error: unknown): RequestScopeErrorContext;
83
+ /**
84
+ * Cleanup scoped services safely during error handling
85
+ *
86
+ * Ensures all scoped services are cleaned up even if some fail,
87
+ * and collects cleanup errors for diagnostics.
88
+ *
89
+ * @param scope - RequestScope manager
90
+ * @returns Array of cleanup errors if any occurred
91
+ */
92
+ export declare function cleanupRequestScopeOnError(scope?: RequestScopeManager): Promise<Array<{
93
+ service: string;
94
+ error: unknown;
95
+ }>>;
96
+ /**
97
+ * Safe error handler wrapper that manages RequestScope cleanup
98
+ *
99
+ * Ensures scoped services are properly cleaned up before returning error response.
100
+ * Use this to wrap error handlers to make them RequestScope-aware.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * const errorHandler = withRequestScopeCleanup(async (ctx, error) => {
105
+ * // Handle error...
106
+ * return ctx.json({ error: error.message }, 500)
107
+ * })
108
+ *
109
+ * // In your app:
110
+ * try {
111
+ * // Handle request...
112
+ * } catch (error) {
113
+ * return errorHandler(ctx, error)
114
+ * }
115
+ * ```
116
+ */
117
+ export declare function withRequestScopeCleanup<T extends (ctx: GravitoContext, error: unknown) => Promise<Response>>(handler: T): T;
118
+ /**
119
+ * Detect potential resource leaks in RequestScope
120
+ *
121
+ * Returns diagnostic information about suspicious resource usage patterns
122
+ */
123
+ export declare function detectRequestScopeLeaks(context: RequestScopeErrorContext): {
124
+ potentialLeaks: boolean;
125
+ warnings: string[];
126
+ };
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @gravito/core - Event System Backpressure Management
3
+ *
4
+ * Implements a backpressure management system to prevent high-priority events
5
+ * from starving low-priority events when the queue is under resource constraints.
6
+ *
7
+ * 背壓管理器:在資源受限時進行智慧型流量控制,防止優先級飢餓。
8
+ *
9
+ * FS-103 增強:
10
+ * - 多優先級隊列深度監控
11
+ * - 背壓反饋迴路支持
12
+ * - 智能 DLQ 路由決策
13
+ */
14
+ import type { DeadLetterDecision, MultiPriorityQueueDepth } from './types';
15
+ /**
16
+ * 背壓狀態枚舉。
17
+ *
18
+ * 狀態轉換:Normal → Warning → Critical → Overflow
19
+ * 恢復方向:遲滯設計(需降至觸發閾值的 80%)
20
+ *
21
+ * @public
22
+ */
23
+ export declare enum BackpressureState {
24
+ /** 正常運作,無背壓 */
25
+ NORMAL = "NORMAL",
26
+ /** 警告狀態,開始限制低優先級事件 */
27
+ WARNING = "WARNING",
28
+ /** 危急狀態,僅允許高優先級事件 */
29
+ CRITICAL = "CRITICAL",
30
+ /** 溢位狀態,全部拒絕 */
31
+ OVERFLOW = "OVERFLOW"
32
+ }
33
+ /**
34
+ * 背壓配置選項。
35
+ *
36
+ * @public
37
+ */
38
+ export interface BackpressureConfig {
39
+ /** 是否啟用背壓管理器(預設 true) */
40
+ enabled?: boolean;
41
+ /** 總隊列深度限制(預設無限) */
42
+ maxQueueSize?: number;
43
+ /** 分優先級隊列深度限制 */
44
+ maxSizeByPriority?: {
45
+ critical?: number;
46
+ high?: number;
47
+ normal?: number;
48
+ low?: number;
49
+ };
50
+ /** 每秒最大入隊速率(events/sec,預設無限) */
51
+ maxEnqueueRate?: number;
52
+ /** 速率限制滑動視窗大小(ms,預設 1000) */
53
+ rateLimitWindowMs?: number;
54
+ /** 背壓狀態閾值(佔 maxQueueSize 的百分比) */
55
+ thresholds?: {
56
+ /** WARNING 觸發百分比(預設 0.6 = 60%) */
57
+ warning?: number;
58
+ /** CRITICAL 觸發百分比(預設 0.85 = 85%) */
59
+ critical?: number;
60
+ /** OVERFLOW 觸發百分比(預設 1.0 = 100%) */
61
+ overflow?: number;
62
+ };
63
+ /** 被拒絕事件的處理策略(預設 'drop-with-callback') */
64
+ rejectionPolicy?: 'throw' | 'drop-silent' | 'drop-with-callback';
65
+ /** 當 rejectionPolicy 為 'drop-with-callback' 時的回呼 */
66
+ onRejected?: (eventName: string, priority: string, reason: string) => void;
67
+ /** 背壓狀態變更回呼 */
68
+ onStateChange?: (from: BackpressureState, to: BackpressureState) => void;
69
+ /** 低優先級事件在 WARNING 狀態下的延遲入隊時間(ms,預設 100) */
70
+ lowPriorityDelayMs?: number;
71
+ /** 是否啟用優先級反轉防護(預設 true) */
72
+ enableStarvationProtection?: boolean;
73
+ /** 低優先級事件最大等待時間,超過則提升優先級(ms,預設 5000) */
74
+ starvationTimeoutMs?: number;
75
+ /** 當進入 OVERFLOW 狀態時,是否將被拒絕事件路由到 DLQ(預設 false) */
76
+ dlqOnOverflow?: boolean;
77
+ /** OVERFLOW 時的重試策略(預設 'dlq-only') */
78
+ overflowRetryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
79
+ /** OVERFLOW 延遲重試的基礎延遲時間(ms,預設 5000) */
80
+ overflowRetryDelayMs?: number;
81
+ }
82
+ /**
83
+ * 背壓決策結果。
84
+ *
85
+ * @public
86
+ */
87
+ export interface BackpressureDecision {
88
+ /** 是否允許入隊 */
89
+ allowed: boolean;
90
+ /** 拒絕原因(若不允許) */
91
+ reason?: string;
92
+ /** 是否需要延遲入隊 */
93
+ delayed?: boolean;
94
+ /** 延遲時間(ms) */
95
+ delayMs?: number;
96
+ /** 建議降級後的優先級(若降級) */
97
+ degradedPriority?: 'high' | 'normal' | 'low';
98
+ /** 是否是由於 OVERFLOW 狀態被拒絕 */
99
+ isOverflow?: boolean;
100
+ /** OVERFLOW 時的重試策略建議('immediate'、'delayed'、'dlq-only') */
101
+ retryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
102
+ }
103
+ /**
104
+ * 背壓指標快照。
105
+ *
106
+ * @public
107
+ */
108
+ export interface BackpressureMetricsSnapshot {
109
+ state: BackpressureState;
110
+ totalDepth: number;
111
+ depthByPriority: {
112
+ critical: number;
113
+ high: number;
114
+ normal: number;
115
+ low: number;
116
+ };
117
+ enqueueRate: number;
118
+ rejectedCount: number;
119
+ degradedCount: number;
120
+ stateTransitions: number;
121
+ dlqRouteCount?: number;
122
+ windowAdjustmentCount?: number;
123
+ }
124
+ /**
125
+ * 背壓管理器。
126
+ *
127
+ * 根據隊列深度、速率、優先級等因素,決定是否允許新事件入隊,
128
+ * 以及是否需要降級優先級或延遲入隊。
129
+ *
130
+ * @public
131
+ */
132
+ export declare class BackpressureManager {
133
+ private enabled;
134
+ private config;
135
+ private onRejected?;
136
+ private onStateChange?;
137
+ private state;
138
+ private rejectedCount;
139
+ private degradedCount;
140
+ private stateTransitions;
141
+ private rateCounter;
142
+ private depthByPriority;
143
+ private windowAdjustmentHistory;
144
+ private dlqRouteCount;
145
+ constructor(config?: BackpressureConfig);
146
+ /**
147
+ * 評估是否允許新事件入隊。
148
+ *
149
+ * @param eventName 事件名稱
150
+ * @param priority 事件優先級
151
+ * @param queueDepth 當前隊列深度
152
+ * @param depthByPriority 分優先級隊列深度
153
+ * @returns 背壓決策結果
154
+ */
155
+ evaluate(eventName: string, priority: 'critical' | 'high' | 'normal' | 'low', queueDepth: number, depthByPriority: {
156
+ critical: number;
157
+ high: number;
158
+ normal: number;
159
+ low: number;
160
+ }): BackpressureDecision;
161
+ /**
162
+ * 獲取當前背壓狀態。
163
+ */
164
+ getState(): BackpressureState;
165
+ /**
166
+ * 獲取背壓指標快照。
167
+ */
168
+ getMetrics(): BackpressureMetricsSnapshot;
169
+ /**
170
+ * 重置背壓管理器狀態。
171
+ */
172
+ reset(): void;
173
+ /**
174
+ * 同步隊列深度(由 EventPriorityQueue 調用)。
175
+ * FS-103:多優先級隊列深度監控
176
+ */
177
+ updateQueueDepth(depths: MultiPriorityQueueDepth): void;
178
+ /**
179
+ * 獲取各優先級的隊列深度。
180
+ * FS-103:提供實時隊列深度快照
181
+ */
182
+ getQueueDepthByPriority(): MultiPriorityQueueDepth;
183
+ /**
184
+ * 獲取總隊列深度。
185
+ */
186
+ getTotalQueueDepth(): number;
187
+ /**
188
+ * 接收來自 AggregationWindow 的窗口調整通知。
189
+ * FS-103:背壓反饋迴路
190
+ */
191
+ notifyWindowAdjustment(oldWindowMs: number, newWindowMs: number): void;
192
+ /**
193
+ * 檢查是否可以從 CRITICAL 或更高級別降級。
194
+ * FS-103:自動狀態恢復機制
195
+ */
196
+ private checkStateRecovery;
197
+ /**
198
+ * 決定是否應該將事件路由到死信隊列。
199
+ * FS-103:智能 DLQ 路由決策
200
+ */
201
+ makeDeadLetterDecision(_eventName: string, priority: 'critical' | 'high' | 'normal' | 'low'): DeadLetterDecision;
202
+ /**
203
+ * 更新背壓狀態。
204
+ * 使用遲滯設計(80% 回復比例)避免邊界震盪。
205
+ */
206
+ private updateState;
207
+ /**
208
+ * 執行狀態轉換。
209
+ */
210
+ private transitionTo;
211
+ /**
212
+ * 建立決策結果並記錄拒絕。
213
+ */
214
+ private createDecision;
215
+ }