@gravito/core 1.2.1 → 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/README.md CHANGED
@@ -12,15 +12,17 @@
12
12
  ## ✨ Features
13
13
 
14
14
  - 🪐 **PlanetCore** - A centralized Photon-based kernel to manage your application lifecycle.
15
+ - 🏢 **Application Container** - Enterprise-grade container with auto-discovery of providers and convention-over-configuration patterns.
15
16
  - 📦 **IoC Container** - A lightweight dependency injection container with binding and singleton support.
16
17
  - 🧩 **Service Providers** - Modular service registration and booting lifecycle.
17
18
  - 🪝 **Hook System** - WordPress-style async **Filters** and **Actions** for powerful extensibility.
19
+ - 📡 **Event System** - Centralized EventManager for cross-module communication and event-driven architecture.
18
20
  - 🛰️ **Orbit Mounting** - Easily mount external Photon applications (Orbits) to specific paths.
19
21
  - 📝 **Logger System** - PSR-3 style logger interface with default standard output implementation.
20
- - ⚙️ **Config Manager** - Unified configuration management supporting environment variables (`Bun.env`) and runtime injection.
22
+ - ⚙️ **Config Manager** - Unified configuration management supporting environment variables, runtime injection, and file-based config loading.
21
23
  - 🛡️ **Security Middleware** - Built-in protection including CSRF, CORS, HSTS, and request throttling.
22
24
  - 🔌 **Runtime Adapters** - Abstraction layer for underlying runtimes (Bun, Node.js) and HTTP engines.
23
- - 🛡️ **Error Handling** - Built-in standardized JSON error responses and 404 handling.
25
+ - 🛡️ **Error Handling** - Built-in standardized JSON error responses, 404 handling, and process-level error management.
24
26
  - 🚀 **Modern** - Built for **Bun** runtime with native TypeScript support.
25
27
  - 🪶 **Lightweight** - Zero external dependencies (except `@gravito/photon`).
26
28
 
@@ -32,12 +34,28 @@ bun add @gravito/core
32
34
 
33
35
  ## 🚀 Quick Start
34
36
 
35
- ### 1. Initialize the Core
37
+ ### 1. Initialize the Application
38
+
39
+ For enterprise applications, use the `Application` class which provides auto-discovery and conventions:
40
+
41
+ ```typescript
42
+ import { Application } from '@gravito/core';
43
+
44
+ const app = new Application({
45
+ basePath: import.meta.dir,
46
+ env: process.env.NODE_ENV as 'development' | 'production',
47
+ });
48
+
49
+ await app.boot();
50
+
51
+ export default app.core.liftoff();
52
+ ```
53
+
54
+ Or use the lightweight `PlanetCore` directly:
36
55
 
37
56
  ```typescript
38
57
  import { PlanetCore } from '@gravito/core';
39
58
 
40
- // Initialize with options (v0.2.0+)
41
59
  const core = new PlanetCore({
42
60
  config: {
43
61
  PORT: 4000,
@@ -138,7 +156,15 @@ core.hooks.addAction('processError:report', async (ctx) => {
138
156
 
139
157
  ## 📖 API Reference
140
158
 
141
- ### `PlanetCore`
159
+ ### `Application` (Enterprise Container)
160
+
161
+ - **`constructor(options: ApplicationConfig)`**: Create an application instance.
162
+ - **`boot()`**: Orchestrate the boot sequence (config loading, provider discovery).
163
+ - **`make<T>(key)`**: Resolve a service from the shared container.
164
+ - **`getConfig(key, default?)`**: Retrieve configuration.
165
+ - **`path(...segments)`**: Path helper relative to base path.
166
+
167
+ ### `PlanetCore` (Micro-kernel)
142
168
 
143
169
  - **`constructor(options?)`**: Initialize the core with optional Logger and Config.
144
170
  - **`register(provider: ServiceProvider)`**: Register a service provider.
@@ -148,6 +174,7 @@ core.hooks.addAction('processError:report', async (ctx) => {
148
174
  - **`container`**: Access the IoC Container.
149
175
  - **`app`**: Access the internal Photon instance.
150
176
  - **`hooks`**: Access the HookManager.
177
+ - **`events`**: Access the EventManager.
151
178
  - **`logger`**: Access the Logger instance.
152
179
  - **`config`**: Access the ConfigManager.
153
180
 
@@ -155,10 +182,28 @@ core.hooks.addAction('processError:report', async (ctx) => {
155
182
 
156
183
  - **`bind(key, factory)`**: Register a transient binding.
157
184
  - **`singleton(key, factory)`**: Register a shared binding.
158
- - **`make<T>(key)`**: Resolve a service instance.
185
+ - **`make(key)`**: Resolve a service instance. Supports automatic type inference via `ServiceMap` augmentation.
159
186
  - **`instance(key, instance)`**: Register an existing object instance.
160
187
  - **`has(key)`**: Check if a service is bound.
161
188
 
189
+ #### Type Safety (ServiceMap)
190
+
191
+ You can extend the `ServiceMap` interface to get automatic type inference for `container.make()`:
192
+
193
+ ```typescript
194
+ // types.d.ts
195
+ import { Logger } from './Logger';
196
+
197
+ declare module '@gravito/core' {
198
+ interface ServiceMap {
199
+ logger: Logger;
200
+ }
201
+ }
202
+
203
+ // usage.ts
204
+ const logger = container.make('logger'); // inferred as Logger
205
+ ```
206
+
162
207
  ### `HookManager`
163
208
 
164
209
  - **`addFilter(hook, callback)`**: Register a filter.
@@ -166,6 +211,12 @@ core.hooks.addAction('processError:report', async (ctx) => {
166
211
  - **`addAction(hook, callback)`**: Register an action.
167
212
  - **`doAction(hook, ...args)`**: Execute actions.
168
213
 
214
+ ### `EventManager`
215
+
216
+ - **`emit(event, ...args)`**: Dispatch an event.
217
+ - **`on(event, callback)`**: Listen to an event.
218
+ - **`off(event, callback)`**: Remove a listener.
219
+
169
220
  ### `ConfigManager`
170
221
 
171
222
  - **`get(key, default?)`**: Retrieve a config value.
package/README.zh-TW.md CHANGED
@@ -1,24 +1,215 @@
1
1
  # @gravito/core
2
2
 
3
- > Galaxy 架構的微核心,基於 Photon 與 Bun 的輕量可擴充框架核心。
3
+ > Galaxy 架構的微核心。輕量、可擴展,基於 Photon 與 Bun 構建。
4
4
 
5
- ## 安裝
5
+ [![npm version](https://img.shields.io/npm/v/@gravito/core.svg)](https://www.npmjs.com/package/@gravito/core)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
8
+ [![Bun](https://img.shields.io/badge/Bun-1.0+-black.svg)](https://bun.sh/)
9
+
10
+ **@gravito/core** 是使用 **Galaxy 架構** 構建模組化後端應用的基礎。它提供了一個強大的 Hook 系統(Filters 與 Actions)和 Orbit 掛載機制,讓您能夠構建低耦合、高擴展性的系統。
11
+
12
+ ## ✨ 特性
13
+
14
+ - 🪐 **PlanetCore** - 基於 Photon 的中央核心,管理應用程式生命週期。
15
+ - 🏢 **Application Container** - 企業級容器,支援 Provider 自動發現與慣例優於配置(Convention-over-Configuration)模式。
16
+ - 📦 **IoC Container** - 輕量級依賴注入容器,支援綁定(Binding)與單例(Singleton)。
17
+ - 🧩 **Service Providers** - 模組化的服務註冊與啟動生命週期。
18
+ - 🪝 **Hook System** - WordPress 風格的異步 **Filters** 與 **Actions**,提供強大的擴展能力。
19
+ - 📡 **Event System** - 中央 EventManager,支援跨模組通訊與事件驅動架構。
20
+ - 🛰️ **Orbit Mounting** - 輕鬆將外部 Photon 應用程式(Orbits)掛載到特定路徑。
21
+ - 📝 **Logger System** - PSR-3 風格的日誌介面,內建標準輸出實作。
22
+ - ⚙️ **Config Manager** - 統一的配置管理,支援環境變數、運行時注入與基於檔案的配置載入。
23
+ - 🛡️ **Security Middleware** - 內建保護功能,包括 CSRF、CORS、HSTS 與請求限流(Throttling)。
24
+ - 🔌 **Runtime Adapters** - 底層運行時(Bun, Node.js)與 HTTP 引擎的抽象層。
25
+ - 🛡️ **Error Handling** - 內建標準化 JSON 錯誤回應、404 處理與進程級別錯誤管理。
26
+ - 🚀 **Modern** - 專為 **Bun** 運行時設計,原生支援 TypeScript。
27
+ - 🪶 **Lightweight** - 除了 `@gravito/photon` 外零外部依賴。
28
+
29
+ ## 📦 安裝
6
30
 
7
31
  ```bash
8
32
  bun add @gravito/core
9
33
  ```
10
34
 
11
- ## 快速開始
35
+ ## 🚀 快速上手
36
+
37
+ ### 1. 初始化應用程式
38
+
39
+ 對於企業級應用,使用 `Application` 類別,它提供自動發現與開發慣例:
40
+
41
+ ```typescript
42
+ import { Application } from '@gravito/core';
43
+
44
+ const app = new Application({
45
+ basePath: import.meta.dir,
46
+ env: process.env.NODE_ENV as 'development' | 'production',
47
+ });
48
+
49
+ await app.boot();
50
+
51
+ export default app.core.liftoff();
52
+ ```
53
+
54
+ 或者直接使用輕量級的 `PlanetCore`:
12
55
 
13
56
  ```typescript
14
- import { PlanetCore } from '@gravito/core'
57
+ import { PlanetCore } from '@gravito/core';
15
58
 
16
59
  const core = new PlanetCore({
17
60
  config: {
18
61
  PORT: 4000,
19
62
  DEBUG: true
20
63
  }
21
- })
64
+ });
65
+ ```
66
+
67
+ ### 2. 依賴注入
68
+
69
+ 使用 IoC 容器管理應用程式服務:
70
+
71
+ ```typescript
72
+ import { ServiceProvider, Container } from '@gravito/core';
73
+
74
+ class CacheServiceProvider extends ServiceProvider {
75
+ register(container: Container) {
76
+ // 綁定單例服務
77
+ container.singleton('cache', (c) => {
78
+ return new RedisCache(process.env.REDIS_URL);
79
+ });
80
+ }
81
+
82
+ async boot(core: PlanetCore) {
83
+ // 執行啟動邏輯
84
+ core.logger.info('Cache provider booted');
85
+ }
86
+ }
87
+
88
+ // 註冊 Provider
89
+ core.register(new CacheServiceProvider());
90
+
91
+ // 啟動應用程式(執行 register() 與 boot())
92
+ await core.bootstrap();
93
+
94
+ // 解析服務
95
+ const cache = core.container.make('cache');
96
+ ```
97
+
98
+ ### 3. 註冊 Hooks
99
+
100
+ 使用 **Filters** 修改資料:
101
+
102
+ ```typescript
103
+ core.hooks.addFilter('modify_content', async (content: string) => {
104
+ return content.toUpperCase();
105
+ });
106
+
107
+ const result = await core.hooks.applyFilters('modify_content', 'hello galaxy');
108
+ // 回傳: "HELLO GALAXY"
109
+ ```
110
+
111
+ 使用 **Actions** 觸發副作用:
112
+
113
+ ```typescript
114
+ core.hooks.addAction('user_registered', async (userId: string) => {
115
+ core.logger.info(`Sending welcome email to ${userId}`);
116
+ });
117
+
118
+ await core.hooks.doAction('user_registered', 'user_123');
119
+ ```
120
+
121
+ ### 4. 掛載 Orbit
122
+
123
+ Orbits 是標準的 Photon 應用程式,可以插入核心中。
124
+
125
+ ```typescript
126
+ import { Photon } from '@gravito/photon';
127
+
128
+ const blogOrbit = new Photon();
129
+ blogOrbit.get('/posts', (c) => c.json({ posts: [] }));
130
+
131
+ // 將 orbit 掛載到 /api/blog
132
+ core.mountOrbit('/api/blog', blogOrbit);
133
+ ```
134
+
135
+ ### 5. Liftoff! 🚀
136
+
137
+ ```typescript
138
+ // 為 Bun.serve 導出
139
+ export default core.liftoff(); // 自動使用來自配置或環境變數的 PORT
140
+ ```
22
141
 
23
- export default core.liftoff()
142
+ ### 6. 進程級別錯誤處理(推薦)
143
+
144
+ 請求級別的錯誤由 `PlanetCore` 自動處理,但背景工作與啟動代碼仍可能在請求生命週期外失敗。
145
+
146
+ ```ts
147
+ // 註冊 `unhandledRejection` / `uncaughtException`
148
+ const unregister = core.registerGlobalErrorHandlers()
149
+
150
+ // 選配:回報至 Sentry / 自定義回報器
151
+ core.hooks.addAction('processError:report', async (ctx) => {
152
+ // ctx.kind: 'unhandledRejection' | 'uncaughtException'
153
+ // ctx.error: unknown
154
+ })
24
155
  ```
156
+
157
+ ## 📖 API 參考
158
+
159
+ ### `Application` (企業級容器)
160
+
161
+ - **`constructor(options: ApplicationConfig)`**: 建立應用程式實例。
162
+ - **`boot()`**: 統籌啟動順序(配置載入、Provider 發現)。
163
+ - **`make<T>(key)`**: 從共享容器中解析服務。
164
+ - **`getConfig(key, default?)`**: 取得配置資訊。
165
+ - **`path(...segments)`**: 相對於基礎路徑的路徑輔助函數。
166
+
167
+ ### `PlanetCore` (微核心)
168
+
169
+ - **`constructor(options?)`**: 初始化核心,可選配 Logger 與 Config。
170
+ - **`register(provider: ServiceProvider)`**: 註冊服務提供者。
171
+ - **`bootstrap()`**: 啟動所有已註冊的提供者。
172
+ - **`mountOrbit(path: string, app: Photon)`**: 將 Photon 應用掛載到子路徑。
173
+ - **`liftoff(port?: number)`**: 回傳用於 `Bun.serve` 的配置物件。
174
+ - **`container`**: 存取 IoC 容器。
175
+ - **`app`**: 存取內部 Photon 實例。
176
+ - **`hooks`**: 存取 HookManager。
177
+ - **`events`**: 存取 EventManager。
178
+ - **`logger`**: 存取 Logger 實例。
179
+ - **`config`**: 存取 ConfigManager。
180
+
181
+ ### `Container`
182
+
183
+ - **`bind(key, factory)`**: 註冊瞬時綁定(每次解析皆建立新實例)。
184
+ - **`singleton(key, factory)`**: 註冊共享綁定(單例)。
185
+ - **`make<T>(key)`**: 解析服務實例。
186
+ - **`instance(key, instance)`**: 註冊現有的物件實例。
187
+ - **`has(key)`**: 檢查服務是否已綁定。
188
+
189
+ ### `HookManager`
190
+
191
+ - **`addFilter(hook, callback)`**: 註冊過濾器。
192
+ - **`applyFilters(hook, initialValue, ...args)`**: 依序執行過濾器。
193
+ - **`addAction(hook, callback)`**: 註冊動作。
194
+ - **`doAction(hook, ...args)`**: 執行動作。
195
+
196
+ ### `EventManager`
197
+
198
+ - **`emit(event, ...args)`**: 觸發事件。
199
+ - **`on(event, callback)`**: 監聽事件。
200
+ - **`off(event, callback)`**: 移除監聽器。
201
+
202
+ ### `ConfigManager`
203
+
204
+ - **`get(key, default?)`**: 取得配置值。
205
+ - **`set(key, value)`**: 設定配置值。
206
+ - **`has(key)`**: 檢查配置鍵是否存在。
207
+
208
+ ## 🤝 貢獻
209
+
210
+ 歡迎提交貢獻、問題與功能請求!
211
+ 請隨時查看 [Issues 頁面](https://github.com/gravito-framework/gravito/issues)。
212
+
213
+ ## 📝 授權
214
+
215
+ MIT © [Carl Lee](https://github.com/gravito-framework/gravito)
@@ -0,0 +1,219 @@
1
+ import "./chunk-R5U7XKVJ.js";
2
+
3
+ // src/observability/Metrics.ts
4
+ var DEFAULTS = {
5
+ port: 9090,
6
+ prefix: "gravito_event_",
7
+ interval: 6e4,
8
+ // 60 秒
9
+ defaultMetrics: true
10
+ };
11
+ async function setupPrometheusMetrics(config = {}) {
12
+ const finalConfig = {
13
+ port: config.port ?? parseInt(process.env.PROMETHEUS_PORT || String(DEFAULTS.port), 10),
14
+ prefix: config.prefix ?? process.env.PROMETHEUS_PREFIX ?? DEFAULTS.prefix,
15
+ interval: config.interval ?? parseInt(process.env.PROMETHEUS_INTERVAL || String(DEFAULTS.interval), 10),
16
+ defaultMetrics: config.defaultMetrics ?? process.env.PROMETHEUS_DEFAULT_METRICS !== "false"
17
+ };
18
+ try {
19
+ const { metrics } = await import("@opentelemetry/api");
20
+ const { MeterProvider } = await import("@opentelemetry/sdk-metrics");
21
+ const { PrometheusExporter } = await import("@opentelemetry/exporter-prometheus");
22
+ const exporter = new PrometheusExporter(
23
+ {
24
+ port: finalConfig.port,
25
+ endpoint: "/metrics"
26
+ },
27
+ () => {
28
+ console.log(
29
+ `[Metrics] Prometheus metrics available at http://localhost:${finalConfig.port}/metrics`
30
+ );
31
+ }
32
+ );
33
+ const meterProvider = new MeterProvider({
34
+ exporter,
35
+ interval: finalConfig.interval
36
+ });
37
+ metrics.setGlobalMeterProvider(meterProvider);
38
+ if (finalConfig.defaultMetrics) {
39
+ try {
40
+ const { collectDefaultMetrics } = await import("@opentelemetry/auto-instrumentations-node");
41
+ collectDefaultMetrics({ meterProvider, prefix: finalConfig.prefix });
42
+ } catch (error) {
43
+ console.warn("[Metrics] Failed to setup default metrics:", error);
44
+ }
45
+ }
46
+ return {
47
+ port: finalConfig.port,
48
+ endpoint: `/metrics`
49
+ };
50
+ } catch (error) {
51
+ console.warn("[Metrics] Failed to setup Prometheus exporter:", error);
52
+ console.log("[Metrics] Metrics will not be exported to Prometheus");
53
+ return null;
54
+ }
55
+ }
56
+ function getEventMetricsDefinition(prefix = DEFAULTS.prefix) {
57
+ return {
58
+ dispatchLatency: {
59
+ name: `${prefix}dispatch_latency_seconds`,
60
+ help: "Event dispatch latency distribution",
61
+ labels: ["event_name", "priority"],
62
+ buckets: [1e-3, 5e-3, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
63
+ },
64
+ listenerExecutionTime: {
65
+ name: `${prefix}listener_execution_seconds`,
66
+ help: "Individual listener execution time",
67
+ labels: ["event_name", "listener_name"],
68
+ buckets: [1e-3, 5e-3, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
69
+ },
70
+ queueDepth: {
71
+ name: `${prefix}queue_depth`,
72
+ help: "Current queue depth by priority",
73
+ labels: ["priority"]
74
+ },
75
+ failureRate: {
76
+ name: `${prefix}failures_total`,
77
+ help: "Total event processing failures",
78
+ labels: ["event_name", "error_type"]
79
+ },
80
+ timeoutCount: {
81
+ name: `${prefix}timeouts_total`,
82
+ help: "Total event timeouts",
83
+ labels: ["event_name"]
84
+ },
85
+ throughput: {
86
+ name: `${prefix}throughput_total`,
87
+ help: "Total events processed",
88
+ labels: ["event_name", "status"]
89
+ },
90
+ circuitBreakerState: {
91
+ name: `${prefix}circuit_breaker_state`,
92
+ help: "Current circuit breaker state (0=CLOSED, 1=HALF_OPEN, 2=OPEN)",
93
+ labels: ["event_name"]
94
+ },
95
+ circuitBreakerTransitions: {
96
+ name: `${prefix}circuit_breaker_transitions_total`,
97
+ help: "Total number of circuit breaker state transitions",
98
+ labels: ["event_name", "from_state", "to_state"]
99
+ },
100
+ circuitBreakerFailures: {
101
+ name: `${prefix}circuit_breaker_failures_total`,
102
+ help: "Total number of failures tracked by circuit breaker",
103
+ labels: ["event_name"]
104
+ },
105
+ circuitBreakerSuccesses: {
106
+ name: `${prefix}circuit_breaker_successes_total`,
107
+ help: "Total number of successes tracked by circuit breaker",
108
+ labels: ["event_name"]
109
+ },
110
+ circuitBreakerOpenDuration: {
111
+ name: `${prefix}circuit_breaker_open_duration_seconds`,
112
+ help: "Duration of circuit breaker OPEN state in seconds",
113
+ labels: ["event_name"],
114
+ buckets: [1, 5, 10, 30, 60, 120, 300]
115
+ }
116
+ };
117
+ }
118
+ var PROMETHEUS_QUERIES = {
119
+ /** 事件派發延遲 P95 */
120
+ dispatchLatencyP95: "histogram_quantile(0.95, rate(gravito_event_dispatch_latency_seconds_bucket[5m]))",
121
+ /** 事件派發延遲 P99 */
122
+ dispatchLatencyP99: "histogram_quantile(0.99, rate(gravito_event_dispatch_latency_seconds_bucket[5m]))",
123
+ /** 隊列深度(按優先級) */
124
+ queueDepthByPriority: "gravito_event_queue_depth",
125
+ /** 吞吐量(事件/秒) */
126
+ throughput: "rate(gravito_event_throughput_total[1m])",
127
+ /** 失敗率 */
128
+ failureRate: "rate(gravito_event_failures_total[5m]) / rate(gravito_event_throughput_total[5m])",
129
+ /** 監聽器執行時間 P99 */
130
+ listenerLatencyP99: "histogram_quantile(0.99, rate(gravito_event_listener_execution_seconds_bucket[5m]))",
131
+ /** 超時次數 */
132
+ timeoutCount: "rate(gravito_event_timeouts_total[5m])",
133
+ /** 吞吐量異常檢測 */
134
+ throughputAnomaly: "rate(gravito_event_throughput_total[5m]) < 100",
135
+ /** 熔斷器狀態(0=CLOSED, 1=HALF_OPEN, 2=OPEN) */
136
+ circuitBreakerState: "gravito_event_circuit_breaker_state",
137
+ /** 熔斷器開啟率 */
138
+ circuitBreakerOpenRate: 'rate(gravito_event_circuit_breaker_transitions_total{to_state="OPEN"}[5m])',
139
+ /** 熔斷器恢復率 */
140
+ circuitBreakerRecoveryRate: 'rate(gravito_event_circuit_breaker_transitions_total{to_state="CLOSED"}[5m])',
141
+ /** 熔斷器失敗率 */
142
+ circuitBreakerFailureRate: "rate(gravito_event_circuit_breaker_failures_total[5m])",
143
+ /** 熔斷器 OPEN 持續時間 P95 */
144
+ circuitBreakerOpenDurationP95: "histogram_quantile(0.95, rate(gravito_event_circuit_breaker_open_duration_seconds_bucket[5m]))",
145
+ /** 熔斷器 OPEN 持續時間 P99 */
146
+ circuitBreakerOpenDurationP99: "histogram_quantile(0.99, rate(gravito_event_circuit_breaker_open_duration_seconds_bucket[5m]))"
147
+ };
148
+ var PROMETHEUS_ALERT_RULES = {
149
+ /** P99 延遲過高 */
150
+ HighDispatchLatency: {
151
+ expr: "histogram_quantile(0.99, gravito_event_dispatch_latency_seconds) > 0.8",
152
+ for: "5m",
153
+ severity: "critical",
154
+ summary: "\u4E8B\u4EF6\u6D3E\u767C P99 \u5EF6\u9072\u904E\u9AD8",
155
+ description: "P99 \u5EF6\u9072: {{ $value }}s\uFF0C\u5DF2\u8D85\u904E 800ms"
156
+ },
157
+ /** 隊列深度過高 */
158
+ HighQueueDepth: {
159
+ expr: 'gravito_event_queue_depth{priority="high"} > 1000',
160
+ for: "2m",
161
+ severity: "warning",
162
+ summary: "\u9AD8\u512A\u5148\u7D1A\u4E8B\u4EF6\u968A\u5217\u5806\u7A4D",
163
+ description: "\u968A\u5217\u6DF1\u5EA6: {{ $value }}\uFF0C\u61C9\u8ABF\u67E5\u539F\u56E0"
164
+ },
165
+ /** 失敗率過高 */
166
+ HighFailureRate: {
167
+ expr: "(rate(gravito_event_failures_total[5m]) / rate(gravito_event_throughput_total[5m])) > 0.05",
168
+ for: "3m",
169
+ severity: "critical",
170
+ summary: "\u4E8B\u4EF6\u8655\u7406\u5931\u6557\u7387\u904E\u9AD8",
171
+ description: "\u5931\u6557\u7387: {{ $value | humanizePercentage }}\uFF0C\u8D85\u904E 5%"
172
+ },
173
+ /** 監聽器執行時間過長 */
174
+ SlowListener: {
175
+ expr: "histogram_quantile(0.99, gravito_event_listener_execution_seconds) > 1.0",
176
+ for: "5m",
177
+ severity: "warning",
178
+ summary: "\u76E3\u807D\u5668\u57F7\u884C\u6642\u9593\u904E\u9577",
179
+ description: "P99 \u8017\u6642: {{ $value }}s\uFF0C\u76E3\u807D\u5668: {{ $labels.listener_name }}"
180
+ },
181
+ /** 吞吐量異常下降 */
182
+ ThroughputDrop: {
183
+ expr: "rate(gravito_event_throughput_total[5m]) < 100 and increase(gravito_event_throughput_total[1h]) > 0",
184
+ for: "2m",
185
+ severity: "critical",
186
+ summary: "\u4E8B\u4EF6\u541E\u5410\u91CF\u7570\u5E38\u4E0B\u964D",
187
+ description: "\u7576\u524D\u541E\u5410: {{ $value | humanize }} events/sec"
188
+ },
189
+ /** 熔斷器持續開啟 */
190
+ CircuitBreakerOpen: {
191
+ expr: 'gravito_event_circuit_breaker_state{event_name=~".+"} == 2',
192
+ for: "5m",
193
+ severity: "warning",
194
+ summary: "\u7194\u65B7\u5668\u6301\u7E8C\u958B\u555F",
195
+ description: "\u4E8B\u4EF6 {{ $labels.event_name }} \u7194\u65B7\u5668\u5DF2\u958B\u555F\u8D85\u904E 5 \u5206\u9418"
196
+ },
197
+ /** 熔斷器頻繁切換 */
198
+ CircuitBreakerFlapping: {
199
+ expr: "rate(gravito_event_circuit_breaker_transitions_total[5m]) > 10",
200
+ for: "2m",
201
+ severity: "critical",
202
+ summary: "\u7194\u65B7\u5668\u983B\u7E41\u5207\u63DB",
203
+ description: "\u4E8B\u4EF6 {{ $labels.event_name }} \u7194\u65B7\u5668\u72C0\u614B\u5207\u63DB\u904E\u65BC\u983B\u7E41\uFF0C\u5207\u63DB\u901F\u7387: {{ $value }}/sec"
204
+ },
205
+ /** 熔斷器故障率過高 */
206
+ CircuitBreakerHighFailureRate: {
207
+ expr: "rate(gravito_event_circuit_breaker_failures_total[5m]) > rate(gravito_event_circuit_breaker_successes_total[5m])",
208
+ for: "3m",
209
+ severity: "critical",
210
+ summary: "\u7194\u65B7\u5668\u6545\u969C\u7387\u8D85\u904E\u6210\u529F\u7387",
211
+ description: "\u4E8B\u4EF6 {{ $labels.event_name }} \u7684\u5931\u6557\u7387\u5DF2\u8D85\u904E\u6210\u529F\u7387"
212
+ }
213
+ };
214
+ export {
215
+ PROMETHEUS_ALERT_RULES,
216
+ PROMETHEUS_QUERIES,
217
+ getEventMetricsDefinition,
218
+ setupPrometheusMetrics
219
+ };
@@ -0,0 +1,16 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ export {
14
+ __require,
15
+ __export
16
+ };