@gravito/spectrum 3.0.0 → 3.0.2

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
@@ -1,20 +1,23 @@
1
- # @gravito/spectrum
1
+ # @gravito/spectrum 🔭
2
2
 
3
3
  > **Your telescope into the Gravito universe — real-time insights, zero configuration.**
4
4
 
5
- `@gravito/spectrum` is a powerful, zero-config debug dashboard designed specifically for the Gravito ecosystem. It acts as a telescope for your application, capturing HTTP requests, database queries, logs, and exceptions in real-time.
5
+ `@gravito/spectrum` is a powerful, zero-config observability and debug dashboard designed specifically for the Gravito ecosystem. It acts as a telescope for your application, capturing HTTP requests, database queries, and application logs in real-time.
6
6
 
7
7
  ![Spectrum Dashboard](https://via.placeholder.com/1200x600/0f172a/38bdf8?text=Gravito+Spectrum+UI)
8
8
 
9
- ## Features
9
+ ## 🌟 Features
10
10
 
11
- - **⚡️ Real-time Updates**: Powered by Server-Sent Events (SSE), observe requests as they happen without refreshing.
12
- - **🔍 Deep Inspection**: View detailed request/response headers, bodies, and execution time.
13
- - **🗄️ Database Profiling**: Automatically captures `@gravito/atlas` SQL queries with bindings and duration.
14
- - **↺ Request Replay**: One-click replay of any captured request to quickly reproduce bugs or test fixes.
15
- - **📊 Live Statistics**: Monitor error rates, average latency, and throughput in real-time.
16
- - **💾 Persistence**: Support for File-based storage to keep debug data across server restarts.
17
- - **🛡️ Security Gates**: Configurable authorization logic to secure the dashboard in sensitive environments.
11
+ - **⚡️ Real-time Updates**: Powered by **Server-Sent Events (SSE)**, observe requests and logs as they happen without refreshing the page.
12
+ - **🔍 Deep Inspection**: View detailed request/response headers, status codes, and precise execution timing.
13
+ - **🗄️ Database Profiling**: Automatically hooks into `@gravito/atlas` to capture SQL queries, bindings, and execution duration.
14
+ - **↺ Request Replay**: One-click replay of any captured request directly from the dashboard to quickly reproduce bugs or test fixes.
15
+ - **📊 Live Statistics**: Monitor total requests, average latency, and error rates via a real-time dashboard.
16
+ - **💾 Pluggable Storage**:
17
+ - **MemoryStorage**: Fast, zero-config storage for development (default).
18
+ - **FileStorage**: Persistent storage that survives server restarts.
19
+ - **🛡️ Security Gates**: Built-in authorization support to protect your debug data in sensitive environments.
20
+ - **🎨 Modern UI**: A clean, responsive dashboard built with Tailwind CSS and Vue.js.
18
21
 
19
22
  ## 📦 Installation
20
23
 
@@ -32,7 +35,7 @@ import { SpectrumOrbit } from '@gravito/spectrum'
32
35
 
33
36
  const core = new PlanetCore()
34
37
 
35
- // Initialize Spectrum (Development only recommended)
38
+ // Initialize Spectrum (Recommended for development only)
36
39
  if (process.env.NODE_ENV !== 'production') {
37
40
  await core.orbit(new SpectrumOrbit())
38
41
  }
@@ -40,72 +43,121 @@ if (process.env.NODE_ENV !== 'production') {
40
43
  await core.liftoff()
41
44
  ```
42
45
 
43
- Visit **http://localhost:3000/gravito/spectrum** to see your dashboard.
46
+ By default, visit **`http://localhost:3000/gravito/spectrum`** to access your dashboard.
44
47
 
45
48
  ## ⚙️ Configuration
46
49
 
47
- You can customize Spectrum by passing a configuration object.
50
+ You can customize Spectrum by passing a configuration object to the `SpectrumOrbit` constructor.
48
51
 
49
52
  ```typescript
53
+ import { SpectrumOrbit, FileStorage } from '@gravito/spectrum'
54
+
50
55
  await core.orbit(new SpectrumOrbit({
51
- // Change the dashboard path
56
+ // Custom dashboard path
52
57
  path: '/_debug',
53
58
 
54
- // Storage Strategy (Memory or File)
55
- storage: new MemoryStorage(),
59
+ // Storage Strategy (MemoryStorage or FileStorage)
60
+ storage: new FileStorage({ directory: './storage/spectrum' }),
56
61
 
62
+ // Maximum number of items to keep (per category)
63
+ maxItems: 500,
64
+
57
65
  // Sample Rate (0.0 to 1.0)
58
- // Useful for high-traffic environments to prevent flooding
66
+ // 1.0 captures everything, 0.1 captures only 10% of traffic
59
67
  sampleRate: 1.0,
60
68
 
61
69
  // Security Gate (Authorization)
62
70
  gate: async (c) => {
63
- // Return true to allow access
64
- return c.req.ip === '127.0.0.1'
71
+ // Return true to allow access, false to block
72
+ const user = c.get('auth')?.user;
73
+ return user?.isAdmin === true;
65
74
  }
66
75
  }))
67
76
  ```
68
77
 
69
78
  ## 🛡️ Production Safety
70
79
 
71
- Spectrum is designed primarily for **local development**. If you enable it in production, you **MUST** follow these rules:
72
-
73
- 1. **Configure a Gate**: Never leave the dashboard open to the public.
74
- 2. **Enable Persistence**: Use `FileStorage` so data isn't lost on restart, or stick to `MemoryStorage` to avoid filling up disk space.
75
- 3. **Set Sample Rate**: Set `sampleRate: 0.1` (10%) or lower to avoid performance impact on high-traffic sites.
80
+ Spectrum is optimized for local development. If you choose to enable it in production, please follow these security guidelines:
76
81
 
77
- ```typescript
78
- if (process.env.NODE_ENV === 'production') {
79
- await core.orbit(new SpectrumOrbit({
80
- storage: new FileStorage({ directory: './storage/spectrum' }),
81
- sampleRate: 0.05, // Capture only 5% of requests
82
- gate: async (c) => c.req.header('x-admin-token') === process.env.ADMIN_TOKEN
83
- }))
84
- }
85
- ```
82
+ 1. **Always Configure a Gate**: Never leave the dashboard publicly accessible. Use the `gate` option to implement authentication.
83
+ 2. **Enable Persistence with Caution**: Use `FileStorage` to keep data across restarts, but monitor disk usage.
84
+ 3. **Adjust Sample Rate**: For high-traffic applications, set a lower `sampleRate` (e.g., `0.01` or 1%) to minimize performance overhead.
86
85
 
87
86
  ## 🔌 Integrations
88
87
 
89
88
  ### Database (Atlas)
90
-
91
- If `@gravito/atlas` is installed and loaded in your application, Spectrum automatically detects it and begins capturing all database queries. No extra configuration is needed.
89
+ Spectrum automatically detects `@gravito/atlas` if it's part of your orbits. It will begin capturing all SQL queries, allowing you to see exactly what's happening at the database level for every request.
92
90
 
93
91
  ### Logs (Logger)
94
-
95
- Spectrum automatically wraps the core logger. Any call to `core.logger.info()`, `debug()`, `warn()`, or `error()` is captured and displayed in the dashboard alongside the request context.
92
+ Spectrum wraps the Gravito core logger. Any logs generated via `core.logger.info()`, `debug()`, `warn()`, or `error()` are captured and linked to the timeline of incoming requests.
96
93
 
97
94
  ## ❓ Spectrum vs Monitor
98
95
 
99
96
  | Feature | `@gravito/spectrum` | `@gravito/monitor` |
100
97
  |---------|---------------------|--------------------|
101
- | **Goal** | **Local Debugging** | **Cluster Observability** |
102
- | **Interface** | Built-in UI Dashboard | JSON / Prometheus / OTLP |
103
- | **Scope** | Single Node (Stateful) | Distributed (Stateless) |
104
- | **Data Retention** | Short-term (Recent 100) | Long-term (TSDB) |
105
- | **Best For** | Developers fixing bugs | DevOps monitoring uptime |
106
-
107
- If you are running in Kubernetes or Serverless and need aggregated logs from multiple instances, use **@gravito/monitor** with an external backend like Grafana or Datadog.
108
-
109
- ## License
110
-
111
- MIT
98
+ | **Primary Goal** | **Local Debugging & Profiling** | **Production Cluster Observability** |
99
+ | **Interface** | Built-in Web UI Dashboard | JSON / Prometheus / OpenTelemetry |
100
+ | **Data Scope** | Single Node (Stateful) | Distributed (Stateless) |
101
+ | **Retention** | Short-term (Recent items) | Long-term (TSDB Integration) |
102
+ | **Best For** | Developers fixing bugs locally | DevOps monitoring system health |
103
+
104
+ ## 🛠️ Roadmap & Future Improvements
105
+
106
+ ### Phase 1: Core Enhancement
107
+
108
+ | Feature | Description | Priority |
109
+ |---------|-------------|----------|
110
+ | **Request/Response Body Capture** | Capture and display request/response bodies with size limits and content-type filtering | High |
111
+ | **Advanced Filtering** | Add search, filter by method/status/duration in dashboard | High |
112
+ | **Export Functionality** | Export captured data as HAR, JSON, or CSV | Medium |
113
+ | **Request Diff View** | Compare two captured requests side-by-side | Medium |
114
+
115
+ ### Phase 2: Storage & Performance
116
+
117
+ | Feature | Description | Priority |
118
+ |---------|-------------|----------|
119
+ | **SQLite Storage** | Add SQLite backend for better query performance and data integrity | High |
120
+ | **Batch Write Optimization** | Buffer writes and flush periodically to reduce I/O | Medium |
121
+ | **Memory Limit Controls** | Configurable memory caps with automatic pruning | Medium |
122
+ | **Compression** | GZIP compression for FileStorage to reduce disk usage | Low |
123
+
124
+ ### Phase 3: Observability Integration
125
+
126
+ | Feature | Description | Priority |
127
+ |---------|-------------|----------|
128
+ | **OpenTelemetry Export** | Export traces to OTLP-compatible backends | High |
129
+ | **Trace Context Propagation** | Link requests to distributed traces | High |
130
+ | **Custom Span Annotations** | Allow manual span creation within request lifecycle | Medium |
131
+ | **Metrics Dashboard** | P50/P95/P99 latency charts, request rate graphs | Medium |
132
+
133
+ ### Phase 4: Developer Experience
134
+
135
+ | Feature | Description | Priority |
136
+ |---------|-------------|----------|
137
+ | **Dark/Light Theme Toggle** | User-selectable theme for dashboard | Low |
138
+ | **Keyboard Shortcuts** | Navigate and filter with keyboard | Low |
139
+ | **WebSocket Support** | Capture and display WebSocket frames | Medium |
140
+ | **Request Timeline View** | Visual timeline showing request waterfall | Medium |
141
+ | **Mobile-Responsive Dashboard** | Improved mobile layout for dashboard | Low |
142
+
143
+ ### Phase 5: Core Bug Fixes
144
+
145
+ | Issue | Description | Status | Priority |
146
+ |-------|-------------|--------|----------|
147
+ | **Request-Log-Query Correlation** | Link logs and queries to their originating request for better debugging | ✅ Fixed | High |
148
+ | **Config Consistency** | Ensure `SpectrumConfig.maxItems` is properly passed to Storage backends | ✅ Fixed | High |
149
+ | **FileStorage.prune()** | Currently only prunes requests, needs to handle logs and queries | ✅ Fixed | Medium |
150
+ | **SSE Connection Cleanup** | Improve handling of disconnected SSE clients to prevent memory leaks | ✅ Fixed | High |
151
+ | **Dashboard CSRF Protection** | Add CSRF protection for POST endpoints (`/clear`, `/replay`) | ✅ Fixed | High |
152
+ | **Large Payload Handling** | Implement streaming for large request/response bodies | ⏳ Planned | Medium |
153
+
154
+ ### Contributing
155
+
156
+ We welcome contributions! Priority areas:
157
+ - Storage backend implementations (Redis, PostgreSQL)
158
+ - Dashboard UI improvements
159
+ - Performance optimizations for high-traffic scenarios
160
+
161
+ ## 📄 License
162
+
163
+ MIT © Carl Lee
@@ -0,0 +1,163 @@
1
+ # @gravito/spectrum 🔭
2
+
3
+ > **您進入 Gravito 宇宙的望遠鏡 —— 即時分析,零配置。**
4
+
5
+ `@gravito/spectrum` 是專為 Gravito 生態系統設計的功能強大、零配置的可觀測性與除錯儀表板。它就像是您應用程式的望遠鏡,能即時捕捉 HTTP 請求、資料庫查詢以及應用程式日誌。
6
+
7
+ ![Spectrum 儀表板](https://via.placeholder.com/1200x600/0f172a/38bdf8?text=Gravito+Spectrum+UI)
8
+
9
+ ## 🌟 特性
10
+
11
+ - **⚡️ 即時更新**:基於 **Server-Sent Events (SSE)** 技術,無需重新整理頁面即可即時觀察請求與日誌。
12
+ - **🔍 深度檢查**:查看詳細的請求/回應標頭 (Headers)、狀態碼以及精確的執行時間。
13
+ - **🗄️ 資料庫分析**:自動整合 `@gravito/atlas`,捕捉所有 SQL 查詢、綁定參數以及執行耗時。
14
+ - **↺ 請求重放 (Replay)**:直接從儀表板一鍵重放任何已捕捉的請求,快速重現 Bug 或測試修復結果。
15
+ - **📊 即時統計**:透過即時儀表板監控總請求數、平均延遲以及錯誤率。
16
+ - **💾 可插拔儲存**:
17
+ - **MemoryStorage**:適用於開發環境的快速零配置儲存(預設)。
18
+ - **FileStorage**:持久化儲存,即使伺服器重啟資料也不會遺失。
19
+ - **🛡️ 安全閘門 (Security Gates)**:內建授權支援,在敏感環境中保護您的除錯數據。
20
+ - **🎨 現代化介面**:使用 Tailwind CSS 與 Vue.js 打造的簡潔、響應式儀表板。
21
+
22
+ ## 📦 安裝
23
+
24
+ ```bash
25
+ bun add @gravito/spectrum
26
+ ```
27
+
28
+ ## 🚀 快速上手
29
+
30
+ 只需在您的應用程式入口點註冊 `SpectrumOrbit`:
31
+
32
+ ```typescript
33
+ import { PlanetCore } from '@gravito/core'
34
+ import { SpectrumOrbit } from '@gravito/spectrum'
35
+
36
+ const core = new PlanetCore()
37
+
38
+ // 初始化 Spectrum (建議僅在開發環境中使用)
39
+ if (process.env.NODE_ENV !== 'production') {
40
+ await core.orbit(new SpectrumOrbit())
41
+ }
42
+
43
+ await core.liftoff()
44
+ ```
45
+
46
+ 預設情況下,訪問 **`http://localhost:3000/gravito/spectrum`** 即可進入儀表板。
47
+
48
+ ## ⚙️ 配置選項
49
+
50
+ 您可以透過向 `SpectrumOrbit` 建構函數傳遞配置物件來客製化 Spectrum。
51
+
52
+ ```typescript
53
+ import { SpectrumOrbit, FileStorage } from '@gravito/spectrum'
54
+
55
+ await core.orbit(new SpectrumOrbit({
56
+ // 客製化儀表板路徑
57
+ path: '/_debug',
58
+
59
+ // 儲存策略 (MemoryStorage 或 FileStorage)
60
+ storage: new FileStorage({ directory: './storage/spectrum' }),
61
+
62
+ // 每個類別保留的最大項目數
63
+ maxItems: 500,
64
+
65
+ // 採樣率 (0.0 到 1.0)
66
+ // 1.0 代表捕捉所有請求,0.1 代表僅捕捉 10% 的流量
67
+ sampleRate: 1.0,
68
+
69
+ // 安全閘門 (授權檢查)
70
+ gate: async (c) => {
71
+ // 回傳 true 允許訪問,false 則阻擋
72
+ const user = c.get('auth')?.user;
73
+ return user?.isAdmin === true;
74
+ }
75
+ }))
76
+ ```
77
+
78
+ ## 🛡️ 正式環境安全指南
79
+
80
+ Spectrum 主要針對本地開發進行優化。若您選擇在正式環境啟用,請遵循以下安全建議:
81
+
82
+ 1. **務必配置安全閘門**:絕不要讓儀表板處於公開可訪問狀態。請使用 `gate` 選項實作身份驗證。
83
+ 2. **謹慎啟用持久化**:使用 `FileStorage` 可保留重啟後的資料,但請監控磁碟空間使用量。
84
+ 3. **調整採樣率**:對於高流量應用,建議設定較低的 `sampleRate`(例如 `0.01` 或 1%),以將效能開銷降至最低。
85
+
86
+ ## 🔌 模組整合
87
+
88
+ ### 資料庫 (Atlas)
89
+ 若您的 Orbits 中包含 `@gravito/atlas`,Spectrum 會自動偵測並開始捕捉所有 SQL 查詢,讓您能精確掌握每個請求在資料庫層級的運作狀況。
90
+
91
+ ### 日誌 (Logger)
92
+ Spectrum 封裝了 Gravito 核心日誌系統。所有透過 `core.logger.info()`, `debug()`, `warn()`, 或 `error()` 產生的日誌都會被捕捉,並與當下的請求上下文關聯顯示。
93
+
94
+ ## ❓ Spectrum vs Monitor
95
+
96
+ | 特性 | `@gravito/spectrum` | `@gravito/monitor` |
97
+ |---------|---------------------|--------------------|
98
+ | **主要目標** | **本地除錯與效能分析** | **生產環境叢集觀測** |
99
+ | **界面** | 內建 Web UI 儀表板 | JSON / Prometheus / OpenTelemetry |
100
+ | **數據範圍** | 單節點 (具狀態) | 分散式 (無狀態) |
101
+ | **資料保留** | 短期 (近期項目) | 長期 (整合時序資料庫) |
102
+ | **適用對象** | 在本地修復 Bug 的開發者 | 監控系統健康狀況的 DevOps |
103
+
104
+ ## 🛠️ 發展藍圖與未來改進
105
+
106
+ ### 第一階段:核心功能強化
107
+
108
+ | 功能 | 描述 | 優先級 |
109
+ |------|------|--------|
110
+ | **請求/回應 Body 捕獲** | 捕獲並顯示請求/回應內容,支援大小限制和內容類型過濾 | 高 |
111
+ | **進階過濾功能** | 在儀表板中新增搜尋、依方法/狀態/耗時過濾 | 高 |
112
+ | **匯出功能** | 將捕獲的資料匯出為 HAR、JSON 或 CSV 格式 | 中 |
113
+ | **請求差異比較** | 並排比較兩個已捕獲的請求 | 中 |
114
+
115
+ ### 第二階段:儲存與效能優化
116
+
117
+ | 功能 | 描述 | 優先級 |
118
+ |------|------|--------|
119
+ | **SQLite 儲存** | 新增 SQLite 後端以提升查詢效能和資料完整性 | 高 |
120
+ | **批次寫入優化** | 緩衝寫入並定期刷新以減少 I/O 操作 | 中 |
121
+ | **記憶體限制控制** | 可配置的記憶體上限與自動修剪機制 | 中 |
122
+ | **壓縮功能** | FileStorage 支援 GZIP 壓縮以減少磁碟使用 | 低 |
123
+
124
+ ### 第三階段:可觀測性整合
125
+
126
+ | 功能 | 描述 | 優先級 |
127
+ |------|------|--------|
128
+ | **OpenTelemetry 匯出** | 將追蹤資料匯出至 OTLP 相容的後端 | 高 |
129
+ | **追蹤上下文傳播** | 將請求與分散式追蹤連結 | 高 |
130
+ | **自訂 Span 標註** | 允許在請求生命週期中手動建立 Span | 中 |
131
+ | **指標儀表板** | P50/P95/P99 延遲圖表、請求速率圖表 | 中 |
132
+
133
+ ### 第四階段:開發者體驗提升
134
+
135
+ | 功能 | 描述 | 優先級 |
136
+ |------|------|--------|
137
+ | **深色/淺色主題切換** | 使用者可選擇的儀表板主題 | 低 |
138
+ | **鍵盤快捷鍵** | 使用鍵盤導航和過濾 | 低 |
139
+ | **WebSocket 支援** | 捕獲並顯示 WebSocket 訊框 | 中 |
140
+ | **請求時間軸視圖** | 視覺化時間軸顯示請求瀑布流 | 中 |
141
+ | **行動裝置響應式儀表板** | 改善儀表板的行動裝置佈局 | 低 |
142
+
143
+ ### 第五階段:核心問題修復
144
+
145
+ | 問題 | 描述 | 優先級 |
146
+ |------|------|--------|
147
+ | **請求-日誌-查詢關聯** | 將日誌和查詢與其來源請求連結,以提升除錯效率 | 高 |
148
+ | **配置一致性** | 確保 `SpectrumConfig.maxItems` 正確傳遞給儲存後端 | 高 |
149
+ | **FileStorage.prune()** | 目前僅修剪 requests,需要處理 logs 和 queries | 中 |
150
+ | **SSE 連線清理** | 改善已斷開連線的 SSE 客戶端處理機制以防止記憶體洩漏 | 高 |
151
+ | **儀表板 CSRF 保護** | 為 POST 端點(`/clear`、`/replay`)新增 CSRF 保護 | 高 |
152
+ | **大型 Payload 處理** | 為大型請求/回應內容實作串流處理 | 中 |
153
+
154
+ ### 參與貢獻
155
+
156
+ 歡迎貢獻!優先領域:
157
+ - 儲存後端實作(Redis、PostgreSQL)
158
+ - 儀表板 UI 改進
159
+ - 高流量場景的效能優化
160
+
161
+ ## 📄 授權
162
+
163
+ MIT © Carl Lee