mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-28 13:46:38 +08:00
Compare commits
127 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 24862dcbed | |||
| 920a530aa7 | |||
| bfd9de69af | |||
| 204f6d9a8b | |||
| 04f029c705 | |||
| 7401f5d0b4 | |||
| 0bb6830047 | |||
| 6f221b042e | |||
| fb5a4e5b59 | |||
| ee9d651c8a | |||
| 9aec984bee | |||
| bf71bc540b | |||
| e49078ac3b | |||
| 177578ef4e | |||
| 4c0c389122 | |||
| a0ccafc6ee | |||
| 26057514a1 | |||
| 55f8c9a527 | |||
| 802d516f5b | |||
| 71ce028f91 | |||
| f0e234df1f | |||
| 9a0974cce8 | |||
| 3b9f4daa4e | |||
| 285f127d48 | |||
| 79820b33eb | |||
| ce736e2de4 | |||
| a0fcf9f627 | |||
| 368df3f76b | |||
| 15e614b304 | |||
| 46941f65d5 | |||
| 0c2961ae6d | |||
| a61d55bb1b | |||
| 6b6c786cfe | |||
| 26be762c3a | |||
| 0548a8a5d4 | |||
| 60bc03f519 | |||
| 9dc3983e0f | |||
| 1eff7878a1 | |||
| 08e8eea932 | |||
| 85d5c8568c | |||
| 74ddf97b36 | |||
| a1a997bcda | |||
| d36409fbf9 | |||
| 4000366856 | |||
| af20e2e838 | |||
| 2fff30e188 | |||
| 74c2f57453 | |||
| 30e09f5985 | |||
| 43e293e062 | |||
| 439ac41da8 | |||
| d97581fb1e | |||
| 83f126795d | |||
| 69467914fc | |||
| c624512da6 | |||
| 50717d1baf | |||
| fc569d1758 | |||
| ec4f1d4d23 | |||
| 9268acb84c | |||
| 41cd23a64d | |||
| f02fc9676a | |||
| 31b4886a14 | |||
| efcf61e32d | |||
| d615d85a26 | |||
| 8afd103751 | |||
| 7ef84cce52 | |||
| 96b8ddc077 | |||
| 03b81e5f74 | |||
| 5b52acdd6c | |||
| fb3dd5afe6 | |||
| 1160d5846a | |||
| 350b433cc1 | |||
| d4d9bad74d | |||
| d0536fcdd5 | |||
| e51f1e583d | |||
| b835144cd0 | |||
| 53c868e99b | |||
| 50678756d4 | |||
| 3eb670c674 | |||
| d10132fb02 | |||
| 61cf581621 | |||
| e2ac531abb | |||
| c8b1289043 | |||
| 13c5073bf8 | |||
| da1dd92404 | |||
| 4b11279662 | |||
| bbadcca294 | |||
| 44ce6497a1 | |||
| 4b83f91b31 | |||
| 9d2fac5d4c | |||
| b4b93ff4ed | |||
| 160e63558f | |||
| 9b3555c569 | |||
| b928928958 | |||
| b312460ddf | |||
| 50f7257d93 | |||
| 336185f01c | |||
| 44bba0f19a | |||
| f0eca028f9 | |||
| 58624db397 | |||
| 38946d1af5 | |||
| caf2ffcff4 | |||
| 0e86fe3547 | |||
| 6525bef15d | |||
| 3e910f1961 | |||
| 28c14eb054 | |||
| ae618905a3 | |||
| 5ad151469c | |||
| 6467b32d8e | |||
| cf72420815 | |||
| 34225cb88a | |||
| 389f02b6b0 | |||
| 2fcbb945fb | |||
| 23501259b2 | |||
| c561e65cd3 | |||
| 97095e8f12 | |||
| 23be2f9296 | |||
| 113ea25aa4 | |||
| c230d5a744 | |||
| c02b649b46 | |||
| fb54d6da61 | |||
| 9c7896df50 | |||
| 01ebec6dfb | |||
| 2816152536 | |||
| b029714c7a | |||
| e0f452eaae | |||
| d721a8fd74 | |||
| 1e349e5cde |
@@ -7,7 +7,18 @@ description: "Wavelet 项目专用:根据自上一个正式版本 Tag 以来
|
||||
|
||||
## 目标
|
||||
|
||||
当用户准备发布 Wavelet 新版本时,本 Skill 只负责生成用于版本提交的 Commit Message。
|
||||
当用户准备发布 Wavelet 新版本时,本 Skill 负责:
|
||||
|
||||
1. 根据上一正式版本 Tag 以来的提交,整理面向用户的发版说明;
|
||||
2. 新建 **独立的** `chore(release): vX.Y.Z` 提交(可附带将 `docs/changelog` 从 `[unreleased]` 落版)。
|
||||
|
||||
## 硬性约束(禁止改写历史)
|
||||
|
||||
- **禁止** `git commit --amend` 修改任何**已经 push 到远端**的提交。
|
||||
- **禁止** 为了发版去改写已有功能/修复提交的 message 或内容。
|
||||
- **禁止** 发版流程中的 force-push(除非用户明确要求且知晓后果)。
|
||||
- 发版提交必须是 **新增 commit**:在当前 `HEAD` 之上 `git commit` 一次。
|
||||
- 默认 **不要 push、不要打 tag**;生成并完成本地 release commit 后,把后续 `push` / `git tag` 命令交给用户确认执行。
|
||||
|
||||
## 生成提交信息
|
||||
|
||||
@@ -26,7 +37,11 @@ description: "Wavelet 项目专用:根据自上一个正式版本 Tag 以来
|
||||
|
||||
固定使用以下分类:
|
||||
|
||||
text ### 🛠 修复 ### ⚡️ 优化与改进 ### 💄 其他/体验
|
||||
```text
|
||||
### 🛠 修复
|
||||
### ⚡️ 优化与改进
|
||||
### 💄 其他/体验
|
||||
```
|
||||
|
||||
分类规则:
|
||||
|
||||
@@ -37,6 +52,8 @@ text ### 🛠 修复 ### ⚡️ 优化与改进 ### 💄 其他/体验
|
||||
示例:
|
||||
|
||||
```
|
||||
chore(release): v3.3.0
|
||||
|
||||
### 🛠 修复
|
||||
- 修复了通过 MCP 接口操作时笔记库范围限制未正确生效的问题。
|
||||
- 修复了 MCP 接口返回数据格式不一致的问题。
|
||||
@@ -49,6 +66,39 @@ text ### 🛠 修复 ### ⚡️ 优化与改进 ### 💄 其他/体验
|
||||
- 优化了 WebSocket 错误日志,增加请求路径信息,方便问题排查。
|
||||
```
|
||||
|
||||
## 提交
|
||||
## 提交步骤
|
||||
|
||||
生成完 Commit Message 后调用命令工具修改最后一次提交信息, 不要提交, 不要推送, 你的任务到此结束。
|
||||
1. 确认工作区干净,且 `HEAD` 与将要发布的代码一致(通常已与 `origin/main` 对齐或仅含未 push 的合法新提交)。
|
||||
2. 将 `docs/changelog/index.md` 中 `[unreleased]` 落版为 `[vX.Y.Z] - YYYY-MM-DD`(按需整理条目)。
|
||||
3. **新建** release 提交(不要 amend):
|
||||
|
||||
```bash
|
||||
git add docs/changelog/index.md # 及其他发版所需文件
|
||||
git commit -m "$(cat <<'EOF'
|
||||
chore(release): vX.Y.Z
|
||||
|
||||
### 🛠 修复
|
||||
- ...
|
||||
|
||||
### ⚡️ 优化与改进
|
||||
- ...
|
||||
|
||||
### 💄 其他/体验
|
||||
- ...
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
4. 向用户展示完整 commit message,并说明后续可由用户执行:
|
||||
|
||||
```bash
|
||||
git push origin main
|
||||
git tag vX.Y.Z
|
||||
git push origin vX.Y.Z
|
||||
```
|
||||
|
||||
(打 tag 后由 CI 创建双语 Release。)
|
||||
|
||||
## 任务结束条件
|
||||
|
||||
本地已存在 **新的** `chore(release): vX.Y.Z` 提交,且**未**改写任何已 push 提交、**未**擅自 push/tag。
|
||||
|
||||
+23
-7
@@ -1,7 +1,8 @@
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# openflare — 环境变量配置模板
|
||||
# 复制此文件为 .env 并填入实际值: cp .env.example .env
|
||||
# 环境变量优先级高于 config.yaml / config.docker.yaml
|
||||
# 环境变量优先级高于 config.yaml
|
||||
# docker compose 会读取本文件(env_file: .env)并替换 compose 中的 ${VAR}
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# ─── 时区 ─────────────────────────────────────────────────────────────────────
|
||||
@@ -22,15 +23,16 @@ APP_SESSION_HTTP_ONLY=true
|
||||
# HTTPS 部署时设为 true,HTTP 环境必须为 false
|
||||
APP_SESSION_SECURE=true
|
||||
|
||||
# ─── 数据库 ────────────────────────────────────────────────────────────────────
|
||||
# ─── 数据库(PostgreSQL)──────────────────────────────────────────────────────
|
||||
# 设置 DB_HOST 后自动启用 PostgreSQL,也可通过 DB_ENABLED 显式控制
|
||||
# DB_ENABLED=false 时使用 SQLite 作为后备数据库
|
||||
DB_ENABLED=true
|
||||
# SQLITE_PATH=./data/openflare.db
|
||||
# compose 内应用连服务名;本机直连 Docker 映射端口时用 127.0.0.1
|
||||
DB_HOST=postgres
|
||||
DB_PORT=5432
|
||||
DB_USERNAME=postgres
|
||||
DB_PASSWORD=postgres
|
||||
DB_USERNAME=openflare
|
||||
DB_PASSWORD=replace-with-strong-password
|
||||
DB_NAME=openflare
|
||||
DB_SSL_MODE=disable
|
||||
DB_TIMEZONE=Asia/Shanghai
|
||||
@@ -38,7 +40,7 @@ DB_TIMEZONE=Asia/Shanghai
|
||||
# DB_MAX_IDLE_CONN=16
|
||||
# DB_MAX_OPEN_CONN=128
|
||||
|
||||
# ─── Redis ─────────────────────────────────────────────────────────────────────
|
||||
# ─── Redis / Valkey ────────────────────────────────────────────────────────────
|
||||
# 设置 REDIS_ADDR 后自动启用,也可通过 REDIS_ENABLED 显式控制
|
||||
REDIS_ENABLED=true
|
||||
REDIS_ADDR=redis:6379
|
||||
@@ -47,13 +49,22 @@ REDIS_ADDR=redis:6379
|
||||
# REDIS_DB=0
|
||||
REDIS_KEY_PREFIX=openflare:
|
||||
# REDIS_POOL_SIZE=100
|
||||
# 启动时开关;修改后需重启服务
|
||||
REDIS_MAINT_NOTIFICATIONS=false
|
||||
# compose 宿主机映射端口(仅 docker-compose 使用)
|
||||
# REDIS_PORT=6379
|
||||
|
||||
# ─── ClickHouse(必需)────────────────────────────────────────────────────
|
||||
# ─── ClickHouse(必需)────────────────────────────────────────────────────────
|
||||
# CLICKHOUSE_HOST 设置后会自动启用;测试环境可显式 CLICKHOUSE_ENABLED=true 做 live 联调
|
||||
CLICKHOUSE_ENABLED=true
|
||||
# compose 内:clickhouse:9000;本机连映射端口:127.0.0.1:9000
|
||||
CLICKHOUSE_HOST=clickhouse:9000
|
||||
CLICKHOUSE_USERNAME=default
|
||||
CLICKHOUSE_PASSWORD=123456
|
||||
# 须与 compose clickhouse 服务密码一致(首次初始化后改密码需清 data/clickhouse_data)
|
||||
CLICKHOUSE_PASSWORD=replace-with-clickhouse-password
|
||||
CLICKHOUSE_NAME=openflare
|
||||
|
||||
|
||||
# ─── 日志 ──────────────────────────────────────────────────────────────────────
|
||||
LOG_LEVEL=info
|
||||
LOG_FORMAT=console
|
||||
@@ -67,6 +78,11 @@ OTEL_EXPORTER_OTLP_INSECURE=true
|
||||
OTEL_SAMPLING_RATE=0.0
|
||||
# 全局 Tracer 命名空间,默认为 github.com/Rain-kl/OpenFlare
|
||||
# OTEL_TRACER_NAME=github.com/Rain-kl/OpenFlare
|
||||
# compose 可选端口覆盖
|
||||
# JAEGER_VERSION=2.19.0
|
||||
# JAEGER_UI_PORT=16686
|
||||
# JAEGER_OTLP_GRPC_PORT=4317
|
||||
# JAEGER_OTLP_HTTP_PORT=4318
|
||||
|
||||
# ─── Worker ────────────────────────────────────────────────────────────────────
|
||||
# WORKER_CONCURRENCY=20
|
||||
|
||||
+5
-1
@@ -77,4 +77,8 @@ profile.cov
|
||||
.grok
|
||||
/.gomodcache/
|
||||
*.mmdb
|
||||
!internal/apps/agent/geoipdata/GeoLite2-Country.mmdb
|
||||
!internal/apps/agent/geoipdata/GeoLite2-Country.mmdb
|
||||
!internal/apps/agent/geoipdata/GeoLite2-City.mmdb
|
||||
|
||||
/.superpowers/
|
||||
/.worktrees/
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
- 所有 HTTP 路由仅在 `internal/router/router.go` 中注册。
|
||||
- 当 API Handler 发生变化时,更新 Swagger 文档(运行 `make swagger`)。
|
||||
- 在完成代码开发后必须运行 `make code-check`, 并修复报错。
|
||||
- 在完成代码开发后或者 git 提交前必须运行 `make prettier` 格式化代码。
|
||||
- 需要缓存或文件管理能力时,必须复用现有平台实现,禁止在业务包中自行创建缓存目录、直接管理缓存文件或重复封装存储后端。
|
||||
- 文件摄取必须通过 `upload.Ingest`(`upload.PolicyCreate` / `PolicyDedupNewRecord` / `PolicyResolveExisting`);删除必须通过 `upload.Remove` 或 `upload.RemoveOwned`。禁止业务模块直接调用 `repository.CreateUpload` / `repository.SoftDeleteUpload`,禁止 `db.Create(&model.Upload{})` 旁路写 `w_uploads`。
|
||||
- 禁止在 `init()` 中注册跨模块集成(任务 Handler、推送内置事件、域事件监听器、任务完成钩子)。统一通过 `internal/bootstrap` 在 `internal/cmd` 入口显式装配。
|
||||
@@ -70,9 +71,16 @@
|
||||
3. **开发计划与交接**:
|
||||
* 正在进行的开发计划或 AI 接手交接发生变化时,在 `docs/plan/` 下更新对应的开发计划或接手文档,并使用相应模板初始化。
|
||||
4. **文档与变更日志**:
|
||||
* 当相关内容发生变化时,同步更新对应的**中文文档**(不要同步英文文档)。
|
||||
* 代码或配置变更完成后,必须在 [`docs/changelog/index.md`](./docs/changelog/index.md) 的 `[Unreleased]` 区块补充对应变更条目。
|
||||
* **纯文档变更(如 `docs/` 下的 Markdown 文档、README 等)不需要写入 changelog。**
|
||||
* 当相关内容发生变化时,同步更新对应的**中文文档**(不要同步英文文档)。
|
||||
* 代码或配置变更完成后,必须在 [`docs/changelog/index.md`](./docs/changelog/index.md) 的 `[Unreleased]` 区块补充对应变更条目。
|
||||
* **纯文档变更(如 `docs/` 下的 Markdown 文档、README 等)不需要写入 changelog。**
|
||||
* 更新 changelog 时遵循以下书写规则:
|
||||
1. 合并重复或相近的变更,不按提交逐条罗列。
|
||||
2. 不记录格式化、临时调试、无关重构等对用户无意义的变更。
|
||||
3. 使用用户可理解的表述,不描述内部实现细节。
|
||||
4. 每条均使用完整中文句子,并尽量说明修复或优化的内容及其带来的效果。
|
||||
5. 仅基于实际变更撰写,不编造提交或代码中不存在的信息。
|
||||
6. 不记录 Token、密钥、私有地址等敏感信息;没有内容的分类可以省略。
|
||||
|
||||
## 项目介绍
|
||||
|
||||
@@ -352,5 +360,5 @@ frontend/lib/services/<service-name>/
|
||||
```
|
||||
|
||||
- 服务类继承 `BaseService`,定义 `basePath`,并暴露有类型的静态方法。
|
||||
- **防止回调 `this` 上下文丢失(核心规范)**:在传递服务类的静态方法作为组件事件回调(如 `onClick`)或 React Query 的 `mutationFn`/`queryFn` 时,**禁止直接传递静态方法引用**(如 `mutationFn: DnsAccountService.create`),必须使用箭头函数包裹以防止 `this` 上下文丢失导致运行时崩溃(如 `mutationFn: (payload) => DnsAccountService.create(payload)`)。
|
||||
- 在 `frontend/lib/services/index.ts` 中注册新服务。
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.PHONY: swagger license license-check build-embedded build-test cross-build code-check build-backend build-frontend build-agent build-relay build-flared build-all
|
||||
.PHONY: swagger license license-check prettier build-embedded build-test cross-build code-check build-backend build-frontend build-agent build-relay build-flared build-all
|
||||
|
||||
VERSION ?= dev
|
||||
BUILD_DATE ?= $(shell date -u +'%Y-%m-%dT%H:%M:%SZ')
|
||||
@@ -13,6 +13,12 @@ license:
|
||||
license-check:
|
||||
scripts/update_go_license.sh --check
|
||||
|
||||
prettier:
|
||||
@echo "==> Formatting backend Go source..."
|
||||
gofmt -w $$(find . -type f -name '*.go' -not -path './.git/*' -not -path './frontend/*')
|
||||
@echo "==> Formatting frontend source..."
|
||||
cd frontend && pnpm format
|
||||
|
||||
build-embedded:
|
||||
@echo "==> Building embedded frontend version=$(VERSION) build_date=$(BUILD_DATE)..."
|
||||
cd frontend && \
|
||||
|
||||
+19
-35
@@ -56,7 +56,7 @@ Quick links:
|
||||
```yaml
|
||||
services:
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare-server:latest
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
environment:
|
||||
@@ -64,7 +64,7 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- openflare_uploads:/app/uploads
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -77,13 +77,13 @@ services:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
POSTGRES_DB: ${DB_NAME:-openflare}
|
||||
POSTGRES_USER: ${DB_USERNAME:-openflare}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-replace-with-strong-password}
|
||||
volumes:
|
||||
- ./data/postgres_data:/var/lib/postgresql/data
|
||||
- openflare_postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-openflare} -d ${DB_NAME:-openflare}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -93,7 +93,7 @@ services:
|
||||
restart: unless-stopped
|
||||
command: ["valkey-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- ./data/valkey:/data
|
||||
- openflare_redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "valkey-cli", "ping"]
|
||||
interval: 10s
|
||||
@@ -105,19 +105,25 @@ services:
|
||||
image: clickhouse/clickhouse-server:25.3-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CLICKHOUSE_DB: openflare
|
||||
CLICKHOUSE_USER: default
|
||||
CLICKHOUSE_PASSWORD: 123456
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_NAME:-openflare}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USERNAME:-default}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- openflare_clickhouse_data:/var/lib/clickhouse
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "${CLICKHOUSE_USERNAME:-default}", "--password", "${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
volumes:
|
||||
openflare_uploads:
|
||||
openflare_postgres_data:
|
||||
openflare_redis_data:
|
||||
openflare_clickhouse_data:
|
||||
```
|
||||
|
||||
```bash
|
||||
@@ -204,28 +210,6 @@ The version number format is fixed as `YYYYMMDD-NNN`. Historical versions are im
|
||||
|
||||

|
||||
|
||||
## Management Panel & API
|
||||
|
||||
The management panel includes:
|
||||
|
||||
* Reverse Proxy Rules
|
||||
* Configuration Versions
|
||||
* Node Management
|
||||
* Application Records
|
||||
* TLS Certificates
|
||||
* Domain Management
|
||||
* Pages Static Hosting
|
||||
* WAF Rule Groups
|
||||
* Intranet Tunnels
|
||||
* Uptime Kuma Monitoring Sync
|
||||
* SSO Login Configuration
|
||||
* User Management
|
||||
* Settings
|
||||
* Version Updates
|
||||
* PoW Rules
|
||||
|
||||
After logging in to the dashboard, access Swagger UI at: `/swagger/index.html`
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under [Apache License 2.0](./LICENSE).
|
||||
|
||||
@@ -21,7 +21,7 @@ OpenFlare 是开源 CDN 编排与边缘安全平台。它支持反向代理、
|
||||
</p>
|
||||
|
||||
> [!WARNING]
|
||||
> 使用 `root` 用户初次登录系统后,务必修改默认密码 `123456`。
|
||||
> 使用 `admin` 用户初次登录系统后,务必修改默认密码 `12345678`。
|
||||
>
|
||||
> BETA 版本为开发测试阶段的临时产物,可能存在未知问题,请勿在生产环境使用。
|
||||
|
||||
@@ -48,16 +48,41 @@ OpenFlare 是开源 CDN 编排与边缘安全平台。它支持反向代理、
|
||||
* **SSO 单点登录**:支持 GitHub OAuth 与标准 OIDC 协议,无缝接入企业身份提供商实现统一登录。
|
||||
* **统一观测**:聚合节点请求指标、实时访问日志明细、宿主机与 Nginx 资源快照、健康事件以及网络波动补传缓冲。
|
||||
|
||||
## 界面预览
|
||||
|
||||
### 仪表盘总览
|
||||
|
||||

|
||||
|
||||
### 节点详情
|
||||
|
||||

|
||||
|
||||
### 配置新增
|
||||
|
||||

|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 启动 Server
|
||||
|
||||
使用 docker-compose
|
||||
|
||||
```bash
|
||||
# 下载环境变量模板并创建 .env 文件
|
||||
curl -o .env.example https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/.env.example
|
||||
cp .env.example .env
|
||||
|
||||
# ClickHouse 服务端:curl performance.xml 到 ./config/clickhouse,并以单文件方式挂载到 config.d
|
||||
mkdir -p ./config/clickhouse
|
||||
curl -fsSL -o ./config/clickhouse/performance.xml \
|
||||
https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/config/clickhouse/performance.xml
|
||||
```
|
||||
|
||||
```yaml
|
||||
services:
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare-server:latest
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
environment:
|
||||
@@ -65,7 +90,7 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- openflare_uploads:/app/uploads
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -78,13 +103,13 @@ services:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
POSTGRES_DB: ${DB_NAME:-openflare}
|
||||
POSTGRES_USER: ${DB_USERNAME:-openflare}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-replace-with-strong-password}
|
||||
volumes:
|
||||
- ./data/postgres_data:/var/lib/postgresql/data
|
||||
- openflare_postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-openflare} -d ${DB_NAME:-openflare}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -94,7 +119,7 @@ services:
|
||||
restart: unless-stopped
|
||||
command: ["valkey-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- ./data/valkey:/data
|
||||
- openflare_redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "valkey-cli", "ping"]
|
||||
interval: 10s
|
||||
@@ -106,19 +131,30 @@ services:
|
||||
image: clickhouse/clickhouse-server:25.3-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CLICKHOUSE_DB: openflare
|
||||
CLICKHOUSE_USER: default
|
||||
CLICKHOUSE_PASSWORD: 123456
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_NAME:-openflare}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USERNAME:-default}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 262144
|
||||
hard: 262144
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- openflare_clickhouse_data:/var/lib/clickhouse
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "${CLICKHOUSE_USERNAME:-default}", "--password", "${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
volumes:
|
||||
openflare_uploads:
|
||||
openflare_postgres_data:
|
||||
openflare_redis_data:
|
||||
openflare_clickhouse_data:
|
||||
```
|
||||
|
||||
详细部署说明见 [部署文档](https://open-flare.pages.dev/deployment/deployment)。
|
||||
@@ -127,8 +163,8 @@ services:
|
||||
|
||||
默认账号:
|
||||
|
||||
* 用户名:`root`
|
||||
* 密码:`123456`
|
||||
* 用户名:`admin`
|
||||
* 密码:`12345678`
|
||||
|
||||
### 2. 安装 Agent
|
||||
|
||||
@@ -150,42 +186,6 @@ docker run -d --name openflare-agent --restart unless-stopped \
|
||||
ghcr.io/rain-kl/openflare-agent:latest
|
||||
```
|
||||
|
||||
## 界面预览
|
||||
|
||||
### 仪表盘总览
|
||||
|
||||

|
||||
|
||||
### 节点详情
|
||||
|
||||

|
||||
|
||||
### 配置新增
|
||||
|
||||

|
||||
|
||||
## 管理端与接口
|
||||
|
||||
管理端当前覆盖:
|
||||
|
||||
* 反代规则
|
||||
* 配置版本
|
||||
* 节点管理
|
||||
* 应用记录
|
||||
* TLS 证书
|
||||
* 域名管理
|
||||
* Pages 静态托管
|
||||
* WAF 规则组
|
||||
* 内网穿透(Tunnels)
|
||||
* Uptime Kuma 监控同步
|
||||
* SSO 登录配置
|
||||
* 用户管理
|
||||
* 设置
|
||||
* 版本更新
|
||||
* PoW 规则
|
||||
|
||||
登录管理端后,可访问 Swagger UI:`/swagger/index.html`
|
||||
|
||||
## 开源协议
|
||||
|
||||
本项目采用 [Apache License 2.0](./LICENSE) 开源。
|
||||
|
||||
+16
-4
@@ -66,6 +66,7 @@ func main() {
|
||||
"lua_dir", cfg.LuaDir,
|
||||
"runtime_config_dir", cfg.RuntimeConfigDir,
|
||||
"mmdb_path", cfg.MMDBPath,
|
||||
"city_mmdb_path", cfg.CityMMDBPath,
|
||||
)
|
||||
|
||||
client := httpclient.New(cfg.ServerURL, cfg.InitialAuthToken(), cfg.RequestTimeout.Duration())
|
||||
@@ -81,6 +82,8 @@ func main() {
|
||||
LuaDir: cfg.LuaDir,
|
||||
NginxLuaDir: cfg.OpenrestyLuaDir,
|
||||
RuntimeConfigDir: cfg.RuntimeConfigDir,
|
||||
MMDBPath: cfg.MMDBPath,
|
||||
CityMMDBPath: cfg.CityMMDBPath,
|
||||
PagesDir: cfg.PagesDir,
|
||||
OpenrestyObservabilityListen: nginx.ObservabilityListenAddress(cfg.OpenrestyObservabilityPort),
|
||||
OpenrestyObservabilityPort: cfg.OpenrestyObservabilityPort,
|
||||
@@ -122,10 +125,9 @@ func main() {
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
geoIPUpdater := &geoipupdate.Updater{
|
||||
MMDBPath: cfg.MMDBPath,
|
||||
DownloadURL: cfg.MMDBDownloadURL,
|
||||
UpdateInterval: cfg.MMDBUpdateInterval.Duration(),
|
||||
geoIPUpdater := newGeoIPUpdater(cfg)
|
||||
if err = geoIPUpdater.EnsureInitialDatabases(ctx); err != nil {
|
||||
slog.Warn("failed to prepare GeoIP databases before agent startup", "error", err)
|
||||
}
|
||||
go geoIPUpdater.Run(ctx)
|
||||
slog.Info("agent process started")
|
||||
@@ -138,3 +140,13 @@ func main() {
|
||||
stop()
|
||||
slog.Info("agent process stopped")
|
||||
}
|
||||
|
||||
func newGeoIPUpdater(cfg *config.Config) *geoipupdate.Updater {
|
||||
return &geoipupdate.Updater{
|
||||
MMDBPath: cfg.MMDBPath,
|
||||
DownloadURL: cfg.MMDBDownloadURL,
|
||||
CityMMDBPath: cfg.CityMMDBPath,
|
||||
CityDownloadURL: cfg.CityMMDBDownloadURL,
|
||||
UpdateInterval: cfg.MMDBUpdateInterval.Duration(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Rain-kl/Wavelet/internal/apps/agent/config"
|
||||
)
|
||||
|
||||
func TestNewGeoIPUpdaterWiresCountryAndCity(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
MMDBPath: "/data/GeoLite2-Country.mmdb",
|
||||
MMDBDownloadURL: "https://geo.example/GeoLite2-Country.mmdb",
|
||||
CityMMDBPath: "/data/GeoLite2-City.mmdb",
|
||||
CityMMDBDownloadURL: "https://geo.example/GeoLite2-City.mmdb",
|
||||
MMDBUpdateInterval: config.MillisecondDuration(time.Hour),
|
||||
}
|
||||
updater := newGeoIPUpdater(cfg)
|
||||
if updater.MMDBPath != cfg.MMDBPath || updater.DownloadURL != cfg.MMDBDownloadURL ||
|
||||
updater.CityMMDBPath != cfg.CityMMDBPath || updater.CityDownloadURL != cfg.CityMMDBDownloadURL ||
|
||||
updater.UpdateInterval != time.Hour {
|
||||
t.Fatalf("GeoIP updater wiring incomplete: %#v", updater)
|
||||
}
|
||||
}
|
||||
+10
-6
@@ -31,7 +31,7 @@ database:
|
||||
max_open_conn: 128
|
||||
conn_max_lifetime: 1800
|
||||
conn_max_idle_time: 600
|
||||
log_level: "info" # error | warn | info | debug | silent
|
||||
log_level: "info" # error | warn | info | debug | silent;SQL 语句仅在 log.level=debug 时输出
|
||||
ssl_mode: "disable"
|
||||
time_zone: "UTC"
|
||||
application_name: "openflare-server"
|
||||
@@ -67,6 +67,7 @@ redis:
|
||||
max_retries: 3
|
||||
pool_timeout: 4
|
||||
conn_max_idle_time: 300
|
||||
maint_notifications: false # 启动时开关;启用 Redis maintenance notifications 自动协商,修改后需重启
|
||||
|
||||
# ─── Logging ────────────────────────────────────────────────────────────────────
|
||||
log:
|
||||
@@ -99,15 +100,18 @@ otel:
|
||||
|
||||
|
||||
# ─── ClickHouse (required) ──────────────────────────────────────────────────────
|
||||
# Analytics / observability OLAP store. Telemetry writes are best-effort (async batch).
|
||||
clickhouse:
|
||||
enabled: true
|
||||
hosts:
|
||||
- "127.0.0.1:9000"
|
||||
- "127.0.0.1:9000" # compose 内应用可用 clickhouse:9000(经 CLICKHOUSE_HOST)
|
||||
username: "default"
|
||||
password: "123456"
|
||||
password: "replace-with-clickhouse-password" # 与 .env / compose CLICKHOUSE_PASSWORD 一致
|
||||
database: "openflare"
|
||||
max_idle_conn: 10
|
||||
max_open_conn: 100
|
||||
max_idle_conn: 8 # keep warm sockets low to save client + server RAM
|
||||
max_open_conn: 16 # cap concurrent native sessions on modest CH boxes
|
||||
conn_max_lifetime: 3600
|
||||
dial_timeout: 5
|
||||
block_buffer_size: 10
|
||||
block_buffer_size: 32 # rows buffered per block; 32 is enough for our batch sizes
|
||||
# Runtime client also enables async_insert (wait_for_async_insert=1, busy_timeout≈2s)
|
||||
# in internal/db/clickhouse.go — not configured via YAML.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0"?>
|
||||
<!--
|
||||
Tuned for small control-plane hosts (e.g. 3c6g).
|
||||
|
||||
background_pool_size * background_merges_mutations_concurrency_ratio must stay
|
||||
greater than merge_tree number_of_free_entries_in_pool_to_execute_mutation
|
||||
(ClickHouse 25.x refuses to start otherwise). Keep the merge free-entry
|
||||
thresholds low so a small pool remains valid.
|
||||
-->
|
||||
<clickhouse>
|
||||
<max_concurrent_queries>20</max_concurrent_queries>
|
||||
<background_pool_size>4</background_pool_size>
|
||||
<background_merges_mutations_concurrency_ratio>2</background_merges_mutations_concurrency_ratio>
|
||||
<background_schedule_pool_size>4</background_schedule_pool_size>
|
||||
<background_common_pool_size>2</background_common_pool_size>
|
||||
<background_fetches_pool_size>2</background_fetches_pool_size>
|
||||
<background_move_pool_size>1</background_move_pool_size>
|
||||
<mark_cache_size>268435456</mark_cache_size>
|
||||
<uncompressed_cache_size>0</uncompressed_cache_size>
|
||||
<merge_tree>
|
||||
<number_of_free_entries_in_pool_to_execute_mutation>2</number_of_free_entries_in_pool_to_execute_mutation>
|
||||
<number_of_free_entries_in_pool_to_lower_max_size_of_merge>2</number_of_free_entries_in_pool_to_lower_max_size_of_merge>
|
||||
<number_of_free_entries_in_pool_to_execute_optimize_entire_partition>2</number_of_free_entries_in_pool_to_execute_optimize_entire_partition>
|
||||
</merge_tree>
|
||||
</clickhouse>
|
||||
+17
-12
@@ -5,7 +5,7 @@ services:
|
||||
dockerfile: docker/Dockerfile
|
||||
args:
|
||||
VERSION: v0.9.9
|
||||
# image: ghcr.io/rain-kl/openflare-server:latest
|
||||
# image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
environment:
|
||||
@@ -34,13 +34,13 @@ services:
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
POSTGRES_DB: ${DB_NAME:-openflare}
|
||||
POSTGRES_USER: ${DB_USERNAME:-openflare}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-replace-with-strong-password}
|
||||
volumes:
|
||||
- ./data/postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-openflare} -d ${DB_NAME:-openflare}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -74,18 +74,23 @@ services:
|
||||
image: clickhouse/clickhouse-server:25.3-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CLICKHOUSE_DB: openflare
|
||||
CLICKHOUSE_USER: default
|
||||
CLICKHOUSE_PASSWORD: 123456
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_NAME:-openflare}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USERNAME:-default}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 262144
|
||||
hard: 262144
|
||||
ports:
|
||||
- "${CLICKHOUSE_HTTP_PORT:-8123}:8123"
|
||||
- "${CLICKHOUSE_NATIVE_PORT:-9000}:9000"
|
||||
- "8123:8123"
|
||||
- "9000:9000"
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "${CLICKHOUSE_USERNAME:-default}", "--password", "${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -105,7 +110,7 @@ services:
|
||||
- ./data/agent/:/data
|
||||
environment:
|
||||
OPENFLARE_SERVER_URL: "http://host.docker.internal:3000"
|
||||
OPENFLARE_AGENT_TOKEN: "3f7b66c9329a0cf253e71a86681223aa"
|
||||
OPENFLARE_AGENT_TOKEN: "af2fb112f36a0055ec25dd164c908fea"
|
||||
LOG_LEVEL: "debug"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 350 KiB After Width: | Height: | Size: 141 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 272 KiB After Width: | Height: | Size: 131 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 64 KiB |
+135
-4
@@ -11,6 +11,9 @@ sidebar: false
|
||||
## 重大变更
|
||||
|
||||
> [!IMPORTANT]
|
||||
>
|
||||
> 3.1.2 版本更新了 CLickHouse 部署配置。
|
||||
>
|
||||
> 3.0.0 版本为 Wavelet 平台迁移与架构重构版本,涉及数据库表结构、环境变量以及前后端底层架构的重大变更。请务必在升级前备份数据库,并且更新到 V2.3.4。
|
||||
> 目前已知的兼容性问题:
|
||||
> - Pages 无法迁移, 升级前请先手动下载并备份 Pages 静态站点的 ZIP 包,升级后重新创建。
|
||||
@@ -18,6 +21,133 @@ sidebar: false
|
||||
|
||||
## [unreleased]
|
||||
|
||||
## [v3.4.0] - 2026-07-19
|
||||
|
||||
### 新增
|
||||
|
||||
- 访问日志重构为「概览」「IP 明细」与「日志明细」:概览含请求量/访问量/带宽趋势与 Top 排行;IP 明细可按时间窗查看请求数、2xx 比例、入出站流量并支持详情分析;日志明细展示完整请求字段。
|
||||
- 边缘访问日志支持 User-Agent 与 `cache_status`(命中/回源/未缓存);概览新增设备类型、浏览器、操作系统与状态码分布。
|
||||
- 访问日志概览支持按 Zone/域名多选筛选;明细列表在 IP 旁展示地区信息。
|
||||
- 新建站点开启缓存时推荐「标准静态资源」(不含 HTML);原按 URL/空策略存量行为保留为「所有可缓存 GET」。
|
||||
- Pages 现支持上传 zip、tar.gz、tar.xz、tar.bz2、tar、7z 等常用压缩格式的部署包。
|
||||
- 管理员可在运维设置中配置 Pages 部署包大小上限与每个项目的历史部署保留数量。
|
||||
- Pages 支持从 URL 导入部署包:填写下载链接后由控制面代为拉取并创建部署。
|
||||
- 观测存储新增 `of_node_edge_health` 与 `of_access_log_hourly`,业务趋势优先读访问日志小时汇总。
|
||||
- 访问日志增加 `request_length` / `request_time_ms`,用于接收数据与耗时统计。
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复访问日志概览按域名筛选无效的问题,现已兼容 `hosts` / `hosts[]` 参数。
|
||||
- 修复 Agent 观测缓冲合并访问日志时忽略 `cache_status` 导致缓存状态被去重丢弃的问题。
|
||||
- 修复访问日志概览在 ClickHouse 查询失败时静默吞错的问题,现会输出错误日志。
|
||||
- 修复数据看板业务流量趋势与已提供数据口径不一致的问题:业务量统一由访问日志聚合。
|
||||
- 修复节点地图在缺少精确经纬度时,把香港/新加坡/台湾等地区错误标到占位坐标的问题。
|
||||
|
||||
### 变更
|
||||
|
||||
- 边缘观测改为「访问日志为业务唯一真相」:Agent 仅上报明细、主机指标与 OpenResty 健康/连接;协议去掉旧兼容字段,**升级需重建或替换 Agent**。
|
||||
- Agent 默认心跳改为 3 秒、离线判定 60 秒,离线补传窗口默认 60 分钟。
|
||||
- 看板 UV 使用窗口内真正去重;Zone 曲线标明分桶 UV;磁盘读写改为按小时速率(B/s)展示。
|
||||
- 不再采集或展示宿主机网卡入/出站;网络趋势仅保留访问日志已提供/接收数据。
|
||||
- Pages 包大小与历史保留可配置,边缘按项目只保留最新激活部署;创建规则表单与详情一致支持直连/隧道/Pages 源站类型。
|
||||
- 优化 Pages 部署包校验性能:不再为包内每个文件计算哈希,整包校验和保障完整性。
|
||||
- 优化访问日志排行榜与饼图布局;页签状态支持 URL 参数记忆。
|
||||
- 启用 `cache_status` 与边缘缓存策略变更需执行相关迁移并重新发布节点配置。
|
||||
|
||||
### 移除
|
||||
|
||||
- 移除请求预聚合表与 OpenResty 吞吐观测相关路径;管理端不再返回 `traffic_reports` 与 `openresty_rx|tx`。
|
||||
- 访问日志已移除时间折叠视图;IP 情报从日志明细详情迁出至 IP 明细。
|
||||
|
||||
## [v3.3.0] - 2026-07-14
|
||||
|
||||
### 新增
|
||||
|
||||
- WAF 规则现支持可视化编排、版本冲突保护和按顺序绑定路由,便于创建和维护复杂的防护策略。
|
||||
- WAF IP 组现支持按城市匹配来源地址,帮助更精细地控制访问范围。
|
||||
|
||||
### 变更
|
||||
|
||||
- 优化了 WAF 规则编辑器的初始视图和操作方式,编辑规则时可看到更多上下文并可直接管理节点、连线和启用状态。
|
||||
- WAF 地域匹配编辑器改用完整国家与一级行政区数据,国家选项同时显示中文名称和 ISO 代码,行政区支持按名称或代码搜索。
|
||||
- Agent 现内置国家和城市地址库,首次启动无需下载即可使用地区匹配功能,并会在后续自动更新数据。
|
||||
- 默认关闭 Redis maintenance notifications 自动协商,减少不支持该功能的 Redis 服务产生兼容性警告。
|
||||
|
||||
### 移除
|
||||
|
||||
- 移除了 WAF 旧版固定名单与人机验证配置;升级后请在发布前使用新的可视化规则重新编排防护策略。
|
||||
|
||||
|
||||
## [v3.2.0] - 2026-07-12
|
||||
|
||||
### 新增
|
||||
|
||||
- 新增网站和域名管理能力,并提供 24 小时、7 天和 30 天的流量概览,便于集中查看访问趋势和已提供的数据量。
|
||||
|
||||
### 变更
|
||||
|
||||
- 网站管理入口调整为网站详情中的概览、域名、路由、证书和设置页面,域名与证书的关联方式更加统一。
|
||||
- 配置发布、边缘代理和监控现统一从网站域名读取域名与证书,减少配置不一致导致的运行问题。
|
||||
- 自动清理说明明确了分析数据的最短保留期限,便于管理员预期数据保存时间。
|
||||
|
||||
### 移除
|
||||
|
||||
- 移除了旧版托管域名管理入口,请改用网站及网站域名管理功能。
|
||||
- 移除了网站、域名、路由和 WAF 相关对象的备注字段;证书和源站备注仍可继续使用。
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复了网站概览中已提供的数据量无法统计的问题,使流量数据更加准确。
|
||||
- 修复了嵌入式前端打开网站详情时可能错误跳回首页的问题。
|
||||
- 修复了 Docker 部署中 ClickHouse 可能无法从宿主机访问的问题。
|
||||
|
||||
## [v3.1.2] - 2026-07-10
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复了节点和仪表盘在 24 小时范围内容量、网络与磁盘趋势数据不完整的问题。
|
||||
- 优化了 ClickHouse 的写入、查询和后台处理方式,降低节点空闲时的资源占用并提升高负载下的稳定性。
|
||||
- 修复了数据保留清理和写入失败重试的统计问题,使清理结果和运行状态更可信。
|
||||
- 改进了小规格环境下的 ClickHouse 部署配置,减少启动和连接争用问题。
|
||||
|
||||
## [v3.1.1] - 2026-07-06
|
||||
|
||||
### 修改
|
||||
|
||||
- 默认关闭登录页面的人机验证,减少普通登录流程的额外操作;管理员仍可按需启用。
|
||||
|
||||
## [v3.1.0] - 2026-07-04
|
||||
|
||||
### 变更
|
||||
|
||||
- 优化了分析数据的写入、查询、缓存和自动过期策略,降低高频心跳和访问日志对系统资源的影响。
|
||||
- 调整了 ClickHouse 的连接、批处理和 Docker 部署配置,提升小规格环境下的运行稳定性。
|
||||
- 收紧了审计访问日志的请求头记录范围并进行脱敏,减少敏感数据暴露风险。
|
||||
- 更新了管理后台的文档入口和全局搜索范围,使常用功能更容易查找。
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复了数据库迁移、系统自更新和设置页跳转可能失败的问题。
|
||||
|
||||
## [v3.0.2] - 2026-06-30
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复了历史数据迁移后 PostgreSQL 自增编号可能与现有数据冲突的问题,避免后续创建记录失败。
|
||||
|
||||
## [v3.0.1] - 2026-06-30
|
||||
|
||||
### 新增
|
||||
|
||||
- 新增用户资料编辑、密码重置和按邮箱搜索功能,便于管理员维护用户账号。
|
||||
- 新增命令行密码重置工具,方便无法登录管理后台时恢复账号访问。
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复了创建 DNS 账号可能失败的问题。
|
||||
- 修复了主题切换后侧边栏和危险操作按钮颜色异常的问题,提升界面可读性。
|
||||
- 修复了部分服务运行模式无法正确启动的问题。
|
||||
|
||||
## [v3.0.0] - 2026-06-27
|
||||
|
||||
### 升级与迁移注意事项
|
||||
@@ -28,10 +158,11 @@ sidebar: false
|
||||
|
||||
### 重大重构说明
|
||||
|
||||
本项目近期完成了**前后端底层架构的重大迁移与重构**,将原有的独立控制端重构为基于 **Wavelet 统一开发框架** 的全新架构:
|
||||
- **后端重构**:全面接入 Wavelet 服务平台,收敛并复用了标准的用户管理、安全验证(PoW/邮件验证)、RAM L1 缓存以及 Redis 订阅发布同步机制。配置体系从原 `of_options` 物理表完全迁移合并至标准系统配置框架 `w_system_configs`(类型归为 `business` 业务级配置),废弃原进程级 `OptionMap` 热重载。
|
||||
- **前端重构**:管理后台前端使用 Next.js App Router、TypeScript 与 Tailwind CSS(基于 shadcn/ui 组件库与 Wavelet 设计风格)进行了完全重写,提供了更具呼吸感和一致性的用户界面,优化了配置版本预览与发布体验。
|
||||
- **架构解耦**:将原有“站点 (Site)”配置体系拆分为 **「网站管理 -> 域名列表」**(处理域名与证书绑定)与 **「规则管理」**(处理反向代理、静态托管、WAF 和缓存等路由匹配规则)两个维度,极大地提升了复杂拓扑配置的灵活性。内网穿透隧道也统一作为 `tunnel_client` 类型节点整合进了 **「节点管理」** 中。
|
||||
本版本完成了控制面的重大升级:
|
||||
|
||||
- 管理后台重构为统一的用户、登录验证和系统设置体验,配置管理更加集中。
|
||||
- 网站管理拆分为域名、路由、静态托管、WAF 和缓存等独立能力,更适合维护复杂站点配置。
|
||||
- Tunnel 节点统一纳入节点管理,配置发布和运行状态查看更加一致。
|
||||
|
||||
|
||||
## [v2.3.4] - 2026-06-17
|
||||
|
||||
+7
-1
@@ -73,6 +73,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
|
||||
{ text: '概览', link: '' },
|
||||
{ text: '快速开始', link: 'quick-start' },
|
||||
{ text: 'TLS 证书与自动续期', link: 'certificates' },
|
||||
{ text: 'Zone 域名迁移', link: 'zone-domain-migration' },
|
||||
{ text: '新建反代配置', link: 'proxy-config' },
|
||||
{ text: 'Pages 静态托管使用', link: 'pages-usage' },
|
||||
{ text: '内网穿透与隧道使用', link: 'tunnel-usage' },
|
||||
@@ -125,14 +126,19 @@ function sidebarDesign(): DefaultTheme.SidebarItem[] {
|
||||
items: [
|
||||
{ text: '产品边界', link: '' },
|
||||
{ text: '系统架构', link: 'architecture' },
|
||||
{ text: 'Zone 与域名资源设计', link: 'zone-design' },
|
||||
{ text: 'Agent 与发布模型', link: 'agent-design' },
|
||||
{ text: '内网穿透隧道设计', link: 'tunnel-design' },
|
||||
{ text: 'WAF 设计', link: 'waf-design' },
|
||||
{ text: 'WAF 可编排规则设计', link: 'waf-orchestration-design' },
|
||||
{ text: 'Pages 静态托管设计', link: 'pages-design' },
|
||||
{ text: '边缘缓存策略设计', link: 'edge-cache-design' },
|
||||
{ text: '边缘可观测与业务流量统计', link: 'observability-design' },
|
||||
{ text: '观测数据传输模型', link: 'observability-transport-model' },
|
||||
{ text: '观测上报协议与表结构', link: 'observability-data-model' },
|
||||
{ text: 'Uptime Kuma 监控同步设计', link: 'kuma-design' },
|
||||
{ text: '登录验证码设计', link: 'login-captcha' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -90,8 +90,8 @@ curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/inst
|
||||
"data_dir": "./data",
|
||||
"openresty_path": "openresty",
|
||||
"openresty_observability_port": 18081,
|
||||
"observability_replay_minutes": 15,
|
||||
"heartbeat_interval": 10000,
|
||||
"observability_replay_minutes": 60,
|
||||
"heartbeat_interval": 3000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
@@ -110,7 +110,7 @@ curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/inst
|
||||
"cert_dir": "/var/lib/openflare-agent/etc/nginx/certs",
|
||||
"lua_dir": "/var/lib/openflare-agent/etc/nginx/lua",
|
||||
"runtime_config_dir": "/var/lib/openflare-agent/etc/openflare",
|
||||
"heartbeat_interval": 10000,
|
||||
"heartbeat_interval": 3000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
|
||||
@@ -81,6 +81,7 @@ Agent:
|
||||
仓库根目录已提供完整 `docker-compose.yaml`(含 PostgreSQL、Redis、ClickHouse、Jaeger)。
|
||||
|
||||
```bash
|
||||
curl -o .env.example https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/.env.example
|
||||
cp .env.example .env
|
||||
# 编辑 .env,至少修改 APP_SESSION_SECRET 与数据库密码
|
||||
docker compose up -d
|
||||
@@ -88,7 +89,7 @@ docker compose ps
|
||||
docker compose logs -f openflare
|
||||
```
|
||||
|
||||
首次访问 `http://localhost:3000`,默认账号为 `root` / `123456`。登录后请立即修改默认密码。
|
||||
首次访问 `http://localhost:3000`,默认账号为 `admin` / `12345678`。登录后请立即修改默认密码。
|
||||
|
||||
## 源码启动 Server
|
||||
|
||||
@@ -117,22 +118,6 @@ go run main.go all
|
||||
|
||||
Docker 部署是 Agent 推荐的部署方式。Docker 部署时直接运行 Agent 镜像,该镜像基于 OpenResty 镜像制作,内置 Agent 控制器与 OpenResty 二进制。未显式配置 `node_ip` 时,Agent 会优先通过第三方 API 获取真实出口 IP,避免把 Docker 网桥地址登记为节点 IP。
|
||||
|
||||
> [!NOTE]
|
||||
> Agent 镜像已完成非 Root 安全加固,统一以普通用户 `openflare` 权限运行,通过内核 capabilities 授权(`cap_net_bind_service`)监听 80/443 特权端口,并自动重定向临时文件和 PID 路径至容器内 `/data` 目录以防止写入冲突。
|
||||
|
||||
挂载配置文件:
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/rain-kl/openflare-agent:latest
|
||||
docker rm -f openflare-agent 2>/dev/null || true
|
||||
docker run -d --name openflare-agent --restart unless-stopped \
|
||||
-p 80:80 -p 443:443/tcp -p 443:443/udp \
|
||||
-v ./agent.json:/etc/openflare/agent.json:ro \
|
||||
ghcr.io/rain-kl/openflare-agent:latest
|
||||
```
|
||||
|
||||
使用环境变量:
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/rain-kl/openflare-agent:latest
|
||||
docker rm -f openflare-agent 2>/dev/null || true
|
||||
@@ -209,7 +194,7 @@ export LOG_LEVEL='info'
|
||||
"agent_token": "replace-with-node-auth-token",
|
||||
"data_dir": "./data",
|
||||
"openresty_path": "openresty",
|
||||
"heartbeat_interval": 10000,
|
||||
"heartbeat_interval": 3000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
@@ -219,26 +204,3 @@ export LOG_LEVEL='info'
|
||||
默认情况下,Agent 在 HTTP 心跳成功后会尝试升级为 WebSocket。升级成功时,Server 发布或激活配置会立即通知 Agent;如果 WebSocket 无法建立或意外断开,Agent 会自动退回 HTTP 心跳同步。
|
||||
|
||||
WAF 地域规则依赖 Agent 本地 `GeoLite2-Country.mmdb`。Agent 启动时会在 `data_dir/etc/openflare/GeoLite2-Country.mmdb` 初始化内置数据库,并按配置周期尝试更新;更新失败只记录警告,不影响配置同步与 OpenResty reload。
|
||||
|
||||
## 升级与卸载
|
||||
|
||||
Server:
|
||||
|
||||
* Root 用户可在管理端顶栏检查并升级正式版。
|
||||
* 如需尝试 preview 版本,可手动检查对应发布。
|
||||
* 也可通过上传 Server 二进制的方式执行确认升级。
|
||||
|
||||
Agent:
|
||||
|
||||
* Agent 默认只跟随正式版自动更新。
|
||||
* Agent 自更新从 GitHub Release 拉取目标二进制,优先使用 Release API 的 `digest` 字段做 SHA-256 校验;仅当 digest 为空(历史 Release)时才回退读取同名 `.sha256` 侧车文件,校验通过后才替换本地可执行文件。
|
||||
* 安装脚本可重复执行,用于重装或升级 Agent。
|
||||
* preview 升级需要手动触发。
|
||||
|
||||
卸载 Agent:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/uninstall-agent.sh | bash
|
||||
```
|
||||
|
||||
卸载脚本会停止 Agent、删除 systemd 服务和安装目录,不会删除本机 OpenResty。
|
||||
|
||||
+91
-30
@@ -8,6 +8,29 @@ OpenFlare Server 是 Gin + GORM 单体控制面,负责管理端 UI、管理 AP
|
||||
> **关于外部依赖**:
|
||||
> OpenFlare 系统内建了对后台异步任务(Asynq 框架)及海量节点日志分析与度量指标(观测面板)的支持。因此,**无论采用何种部署模式,系统都必须依赖 Redis(或 Valkey)与 ClickHouse 的运行**。各个部署方案的主要差异在于主关系型数据库的选择(SQLite vs PostgreSQL)以及是否启用链路追踪服务(Jaeger)。
|
||||
|
||||
> [!TIP]
|
||||
> **ClickHouse 服务端性能配置(推荐挂载)**
|
||||
> 控制面常见为小规格主机(如 3c6g)。仓库提供的 `performance.xml` 会收紧后台 merge/mutation 线程池,避免默认配置在小机器上静置 CPU 偏高或 ClickHouse 25.x 启动校验失败。
|
||||
> 将本地 `./config/clickhouse/performance.xml` 以单文件方式挂载到容器 `/etc/clickhouse-server/config.d/performance.xml`,以保留官方镜像内置的 Docker 网络监听配置。
|
||||
|
||||
部署前将配置拉到本地:
|
||||
|
||||
```bash
|
||||
mkdir -p ./config/clickhouse
|
||||
curl -fsSL -o ./config/clickhouse/performance.xml \
|
||||
https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/config/clickhouse/performance.xml
|
||||
```
|
||||
|
||||
在 ClickHouse 服务的 `volumes` 中增加(与数据卷并列):
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse # 或 named volume
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
```
|
||||
|
||||
修改 `performance.xml` 后需 `docker compose restart clickhouse` 才生效。
|
||||
|
||||
---
|
||||
|
||||
## 方式一:Docker 部署 (推荐)
|
||||
@@ -27,7 +50,7 @@ version: '3.8'
|
||||
|
||||
services:
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare-server:latest
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
container_name: openflare-server
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
@@ -71,10 +94,15 @@ services:
|
||||
CLICKHOUSE_PASSWORD: 123456
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: Asia/Shanghai
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 262144
|
||||
hard: 262144
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "default", "--password", "123456", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -84,6 +112,9 @@ services:
|
||||
运行启动命令:
|
||||
|
||||
```bash
|
||||
mkdir -p ./config/clickhouse
|
||||
curl -fsSL -o ./config/clickhouse/performance.xml \
|
||||
https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/config/clickhouse/performance.xml
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
@@ -100,7 +131,7 @@ docker compose up -d
|
||||
```yaml
|
||||
services:
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare-server:latest
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
environment:
|
||||
@@ -108,7 +139,7 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- openflare_uploads:/app/uploads
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -121,13 +152,13 @@ services:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
POSTGRES_DB: ${DB_NAME:-openflare}
|
||||
POSTGRES_USER: ${DB_USERNAME:-openflare}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-replace-with-strong-password}
|
||||
volumes:
|
||||
- ./data/postgres_data:/var/lib/postgresql/data
|
||||
- openflare_postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-openflare} -d ${DB_NAME:-openflare}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -137,7 +168,7 @@ services:
|
||||
restart: unless-stopped
|
||||
command: ["valkey-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- ./data/valkey:/data
|
||||
- openflare_redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "valkey-cli", "ping"]
|
||||
interval: 10s
|
||||
@@ -149,24 +180,39 @@ services:
|
||||
image: clickhouse/clickhouse-server:25.3-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CLICKHOUSE_DB: openflare
|
||||
CLICKHOUSE_USER: default
|
||||
CLICKHOUSE_PASSWORD: replace-with-clickhouse-password
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_NAME:-openflare}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USERNAME:-default}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 262144
|
||||
hard: 262144
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- openflare_clickhouse_data:/var/lib/clickhouse
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "${CLICKHOUSE_USERNAME:-default}", "--password", "${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
volumes:
|
||||
openflare_uploads:
|
||||
openflare_postgres_data:
|
||||
openflare_redis_data:
|
||||
openflare_clickhouse_data:
|
||||
```
|
||||
|
||||
创建对应的 `.env` 文件来配置系统环境变量(可复制并修改根目录下的 `.env.example`):
|
||||
|
||||
```bash
|
||||
mkdir -p ./config/clickhouse
|
||||
curl -fsSL -o ./config/clickhouse/performance.xml \
|
||||
https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/config/clickhouse/performance.xml
|
||||
curl -o .env.example https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/.env.example
|
||||
cp .env.example .env
|
||||
# 编辑 .env 文件,填入对应的数据库、Redis、ClickHouse 连接地址、密码与 APP_SESSION_SECRET
|
||||
|
||||
@@ -188,7 +234,7 @@ version: '3.8'
|
||||
|
||||
services:
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare-server:latest
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
restart: unless-stopped
|
||||
env_file: .env
|
||||
environment:
|
||||
@@ -199,7 +245,7 @@ services:
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- openflare_uploads:/app/uploads
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -214,13 +260,13 @@ services:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
POSTGRES_DB: ${DB_NAME:-openflare}
|
||||
POSTGRES_USER: ${DB_USERNAME:-openflare}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-replace-with-strong-password}
|
||||
volumes:
|
||||
- ./data/postgres_data:/var/lib/postgresql/data
|
||||
- openflare_postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-openflare} -d ${DB_NAME:-openflare}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -230,7 +276,7 @@ services:
|
||||
restart: unless-stopped
|
||||
command: ["valkey-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- ./data/valkey:/data
|
||||
- openflare_redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "valkey-cli", "ping"]
|
||||
interval: 10s
|
||||
@@ -252,24 +298,39 @@ services:
|
||||
image: clickhouse/clickhouse-server:25.3-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CLICKHOUSE_DB: openflare
|
||||
CLICKHOUSE_USER: default
|
||||
CLICKHOUSE_PASSWORD: replace-with-clickhouse-password
|
||||
CLICKHOUSE_DB: ${CLICKHOUSE_NAME:-openflare}
|
||||
CLICKHOUSE_USER: ${CLICKHOUSE_USERNAME:-default}
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 262144
|
||||
hard: 262144
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- openflare_clickhouse_data:/var/lib/clickhouse
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "${CLICKHOUSE_USERNAME:-default}", "--password", "${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
volumes:
|
||||
openflare_uploads:
|
||||
openflare_postgres_data:
|
||||
openflare_redis_data:
|
||||
openflare_clickhouse_data:
|
||||
```
|
||||
|
||||
启动并验证:
|
||||
|
||||
```bash
|
||||
mkdir -p ./config/clickhouse
|
||||
curl -fsSL -o ./config/clickhouse/performance.xml \
|
||||
https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/config/clickhouse/performance.xml
|
||||
curl -o .env.example https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/.env.example
|
||||
cp .env.example .env
|
||||
# 编辑 .env 文件并确保设置好 APP_SESSION_SECRET 密码
|
||||
|
||||
@@ -290,7 +351,7 @@ docker compose up -d
|
||||
| Go | `1.25+` |
|
||||
| Node.js | `18+` |
|
||||
| pnpm | 推荐通过 `corepack enable` 使用项目声明的 pnpm |
|
||||
| 外部服务 | 必须在本地或远端运行 Redis (Valkey) 和 ClickHouse 实例 |
|
||||
| 外部服务 | 必须在本地或远端运行 Redis (Valkey) 和 ClickHouse 实例;ClickHouse 建议挂载仓库提供的 `performance.xml`(见上文「ClickHouse 服务端性能配置」) |
|
||||
|
||||
### 1. 构建管理端前端
|
||||
|
||||
@@ -345,7 +406,7 @@ Server 默认监听 `3000` 端口,启动成功后可以使用浏览器访问
|
||||
|
||||
| 用户名 | 密码 |
|
||||
| --- | --- |
|
||||
| `root` | `123456` |
|
||||
| `admin` | `12345678` |
|
||||
|
||||
> [!WARNING]
|
||||
> 为了你的系统安全,首次登录后请立即前往个人设置页面修改默认密码。
|
||||
|
||||
@@ -27,7 +27,7 @@ Agent 主要由以下核心子模块组成,共同配合完成其完整的生
|
||||
| **OpenResty 管控** | `nginx/` | 执行 Nginx 配置校验 (`openresty -t`)、重写、平滑重载 (`reload`) 及进程自启动。 |
|
||||
| **本地状态库** | `state/` | 持久化记录本地应用版本、错误日志及未成功上报的可观测性指标缓冲。 |
|
||||
| **自更新服务** | `updater/` | 监听 Server 自更新指令,安全拉取新版本二进制并完成原地热升级。 |
|
||||
| **可观测性** | `observability/` | 采集系统宿主机 CPU/内存/磁盘及 Nginx 性能指标,处理访问日志并上报。 |
|
||||
| **可观测性** | `observability/` | 采集宿主机资源读数、OpenResty 健康/连接,并 tail 访问日志明细上报;**不做** UV/TopN/吞吐等业务预聚合。详见 [边缘可观测与业务流量统计](./observability-design.md)。 |
|
||||
| **GeoIP 维护** | `geoipdata/` `geoipupdate/` | 维护并定期更新本地 GeoIP 数据库,为 WAF 地域过滤提供支撑。 |
|
||||
|
||||
---
|
||||
@@ -98,7 +98,7 @@ Agent 对数据面 OpenResty 的管控实现了端到端的闭环,包含配置
|
||||
* `certs/`:证书存放目录(文件命名为 `{cert_id}.crt` 和 `{cert_id}.key`)。
|
||||
* `waf/` 与 `pow/`:WAF 及防 CC 挑战所需的专用 Lua 运行时脚本。
|
||||
* `waf_config.json` 与 `waf_ip_groups.json`:WAF 过滤引擎所需的结构化规则配置文件。
|
||||
* `pages_dir`:Pages 静态站点部署目录,默认位于 `data_dir/var/lib/openflare/pages`。当激活配置引用 Pages 部署时,Agent 会下载部署 zip、校验 checksum、解压到部署 release 目录,并切换 `deployments/{deployment_id}/current` 供 OpenResty `root`/`try_files` 读取。
|
||||
* `pages_dir`:Pages 静态站点部署目录,默认位于 `data_dir/var/lib/openflare/pages`。当激活配置引用 Pages **项目**时,Agent 按 `project_id` 请求控制面「最新激活包」(hash + package,下载后再校验 hash 防竞态),解压到 `projects/{project_id}/releases/{hash}`,切换 `current` 后**立即删除同项目其它历史 release**(仅保留最新)。项目内切换激活无需重发主配置;多项目对账时单项目失败不阻塞其它项目。
|
||||
|
||||
### 2. 精细化的重载动作
|
||||
1. **备份当前配置**:在写入新文件之前,Agent 会将现有的配置文件复制到 `.backup` 临时目录下,保留完整的现场快照。
|
||||
@@ -173,3 +173,4 @@ graph TD
|
||||
1. **零特权指令通道**:Server 绝对禁止向 Agent 传递任何任意 shell 命令或远程执行脚本(如 exec/eval 等)。所有系统控制原语(如启动、停止、重载、更新)必须硬编码在 Agent 二进制内部。
|
||||
2. **严格的 Token 过滤与前缀验证**:Agent 侧向 Server 请求资源时,接口端点固定以 `/api/v1/agent/` 为前缀,并强制携带 `X-Agent-Token` 进行签名或令牌核验。
|
||||
3. **节点自治原则**:Agent 须具备完备的离线工作能力。在与 Server 失去连接期间,本地 OpenResty 必须依靠本地已落地的配置保持反向代理服务的绝对正常运行。
|
||||
4. **观测只上报事实**:访问日志以明细形式上送;主机指标上报计数器/瞬时读数。禁止在 Agent 内计算业务 UV、Top 域名、24h 已提供数据等结论性指标(由 Server 聚合)。详见 [边缘可观测与业务流量统计](./observability-design.md)。
|
||||
|
||||
+34
-10
@@ -65,8 +65,8 @@ OpenResty (Agent, TLS/WAF)
|
||||
|
||||
| 组件 | 职责 | 详细设计参考 |
|
||||
| --------------- | ---------------------------------------------------------------------- | ------------ |
|
||||
| **Server** | 管理端 UI/API、控制面状态持久化、配置编译渲染、发布版本控制、Pages 部署包存储、Uptime Kuma 监控同步与登录验证码防护 | [Agent 与发布模型](./agent-design.md) / [Uptime Kuma 监控同步设计](./kuma-design.md) / [登录验证码设计](./login-captcha.md) |
|
||||
| **Agent** | 周期心跳与 WS 同步、静态资源包拉取与解压、OpenResty 配置写入/校验/重载与自愈 | [Agent 与发布模型](./agent-design.md) |
|
||||
| **Server** | 管理端 UI/API、控制面状态持久化、配置编译渲染、发布版本控制、Pages 部署包存储、访问日志入库与业务流量聚合、Uptime Kuma 监控同步与登录验证码防护 | [Agent 与发布模型](./agent-design.md) / [边缘可观测与业务流量统计](./observability-design.md) / [Uptime Kuma 监控同步设计](./kuma-design.md) / [登录验证码设计](./login-captcha.md) |
|
||||
| **Agent** | 周期心跳与 WS 同步、静态资源包拉取与解压、OpenResty 配置写入/校验/重载与自愈;观测仅上报访问明细与主机/健康读数,不做业务预聚合 | [Agent 与发布模型](./agent-design.md) / [边缘可观测与业务流量统计](./observability-design.md) |
|
||||
| **OpenResty** | 接收真实流量,执行 WAF 过滤、PoW 防护、Basic Auth 认证与静态/反代服务 | [WAF 设计](./waf-design.md) / [Pages 设计](./pages-design.md) |
|
||||
| **Relay** | 部署于边缘节点,管理 `frps` 守护进程生命周期,接受心跳派发的穿透中继配置 | [内网穿透设计](./tunnel-design.md) |
|
||||
| **OpenFlared** | 部署于内网,管理 `frpc` 进程组,向多个 Relay 建立反向隧道,上报连接状态 | [内网穿透设计](./tunnel-design.md) |
|
||||
@@ -95,7 +95,7 @@ OpenResty (Agent, TLS/WAF)
|
||||
### 3. OpenResty (数据面)
|
||||
接收访客流量并执行最终的业务落地:
|
||||
* 流量入口,支持 HTTP/2、HTTP/3(QUIC)和 TLS 证书动态绑定。
|
||||
* 嵌入 Lua 逻辑,在 `access_by_lua` 阶段高效过滤 WAF 规则、验证工作量证明 (PoW) 挑战,并在此之后执行连接数/速率限制及基础缓存。
|
||||
* 嵌入 Lua 逻辑,在 `access_by_lua` 阶段高效过滤 WAF 规则、验证工作量证明 (PoW) 挑战,并在此之后执行连接数/速率限制及基础缓存(策略见 [边缘缓存策略设计](./edge-cache-design.md))。
|
||||
* *详细设计请参阅:[WAF 设计文档](./waf-design.md) 与 [Pages 静态托管设计文档](./pages-design.md)*
|
||||
|
||||
### 4. Relay 与 OpenFlared (穿透组件)
|
||||
@@ -124,14 +124,34 @@ OpenResty (Agent, TLS/WAF)
|
||||
* *同步与自愈的精细时序及回滚模型详见:[Agent 与发布模型设计](./agent-design.md)*
|
||||
|
||||
### 2. 静态托管与 API 代理流
|
||||
* 静态资源解压落地于 Agent 节点的 `deployments/{id}/current` 下,OpenResty 通过 `root`/`index`/`try_files` 指令在边缘直接向访客提供极低延迟的静态资源服务。
|
||||
* 静态资源解压落地于 Agent 节点的 `projects/{project_id}/current` 下(按项目 latest 拉取,仅保留最新包),OpenResty 通过 `root`/`index`/`try_files` 在边缘直接提供静态资源服务。
|
||||
* 当启用 API 代理时,OpenResty 自动根据站点配置的 `api_proxy_path`(如 `/api`)将 API 请求重写并转发(`proxy_pass`)给后端动态接口。
|
||||
* *部署包校验、解压逃逸防御及 Nginx 规则渲染详见:[Pages 静态托管设计文档](./pages-design.md)*
|
||||
|
||||
### 3. WAF 安全过滤流
|
||||
* WAF 引擎嵌入在 OpenResty 请求生命周期中。
|
||||
* 过滤规则直接从 Agent 落地在节点本地的 `waf_config.json` 及 `waf_ip_groups.json` 读取,判决逻辑白名单优先、黑名单层层过滤,完全在本地内存中完成,不产生数据库或网络 I/O 损耗。
|
||||
* *IP组增量同步、自动 IP 组计算与拦截响应机制详见:[WAF 设计文档](./waf-design.md)*
|
||||
* WAF 规则由控制面以可视化 DAG 编排,发布时编译为运行态图;OpenResty reload 后由每个 Worker 加载一次,后续请求只遍历内存对象。
|
||||
* 全局规则固定前置,路由绑定规则按显式顺序执行;当前规则抵达“通过”后继续下一条,抵达“阻止”则立即返回该节点配置的拦截响应。
|
||||
* IP 组成员独立热更新:协调 Worker 每 5 秒检查一次 checksum,仅在变化时加载完整快照,各 Worker 的请求路径始终读取本地内存对象。
|
||||
* *IP 组来源与同步机制详见:[WAF 设计文档](./waf-design.md);图模型、执行语义与发布约束详见:[WAF 可编排规则设计](./waf-orchestration-design.md)。*
|
||||
|
||||
### 4. 边缘可观测与业务流量统计流
|
||||
```text
|
||||
OpenResty access.log(业务事实)
|
||||
|
|
||||
| Agent tail 增量明细(不 sum/count/uniq)
|
||||
v
|
||||
Server 入库 ClickHouse
|
||||
|
|
||||
+---> 全局聚合 --> 看板「已提供数据 / 请求 / UV」
|
||||
+---> host∈Zone --> Zone「已提供数据」等(同一套语义)
|
||||
+---> node_id 过滤 --> 节点业务量
|
||||
|
||||
主机 /proc 网卡与 CPU 等 --> Agent 读数快照 --> 宿主机资源趋势(与业务交付分开展示)
|
||||
OpenResty 健康与连接数 --> 边缘健康(瞬时,不作 24h 业务总量)
|
||||
```
|
||||
* **原则**:Agent 只上报事实,Server 解释事实;业务流量唯一真相为访问日志。`openresty_tx` 与「已提供数据」不得双轨并存。
|
||||
* *传输模型、示例与采集频率详见:[观测数据传输模型](./observability-transport-model.md);字段收敛与迁移详见:[边缘可观测与业务流量统计](./observability-design.md)*
|
||||
|
||||
---
|
||||
|
||||
@@ -139,7 +159,7 @@ OpenResty (Agent, TLS/WAF)
|
||||
|
||||
当前系统核心实体包括:
|
||||
|
||||
* **反代与配置**:`proxy_routes` (网站配置), `origins` (源站), `config_versions` (配置版本), `tls_certificates` (证书), `managed_domains` (托管域名).
|
||||
* **反代与配置**:`zones` (根域管理边界), `zone_domains` (明确域名与证书/路由关联), `proxy_routes` (路由策略), `origins` (源站), `config_versions` (配置版本), `tls_certificates` (证书). 详见 [Zone 与域名资源设计](./zone-design.md)。
|
||||
* **Pages 静态托管**:`pages_projects` (Pages项目), `pages_deployments` (不可变部署), `pages_deployment_files` (部署文件清单).
|
||||
* **节点与穿透**:`nodes` (节点), `tunnels` (隧道客户端), `node_system_profiles` (系统概况), `apply_logs` (应用日志).
|
||||
* **WAF 与安全**:`waf_rule_groups` (WAF规则组), `waf_ip_groups` (WAF IP组), `waf_rule_group_bindings` (网站WAF绑定).
|
||||
@@ -154,9 +174,11 @@ OpenResty (Agent, TLS/WAF)
|
||||
| 完整配置版本,而不是在线 patch | 让预览、激活、历史和回滚有稳定边界,保证节点状态一致 |
|
||||
| Agent 主动拉取 | Server 不需要 SSH 权限,降低安全风险;支持 HTTP 与 WebSocket 双协议灵活切换 |
|
||||
| 全局单激活版本 | 降低控制面复杂度,保证所有节点默认一致;提供一键秒级回滚的稳定机制 |
|
||||
| 网站配置聚合多域名 | 支持单个业务站点共享站点级策略,同时支持按域名灵活绑定不同的 TLS 证书 |
|
||||
| Zone 域名与路由策略分离 | Zone 提供根域入口与域名边界;路由仍可复用同一套站点级策略并按域名绑定证书 |
|
||||
| 内网穿透基于 frp 整合 | 复用成熟隧道协议,避免自研隧道引起稳定性风险;其 Vhost 机制天然适配反代路由 |
|
||||
| 运行时配置与控制库解耦 | 如 WAF 运行时只读取本地 JSON 规则包,配置变更通过差分广播或快速重载热生效 |
|
||||
| 运行时配置与控制库解耦 | WAF 规则发布时编译并随 OpenResty reload 加载;动态 IP 组通过 checksum 驱动的内存快照独立刷新 |
|
||||
| 业务流量以访问日志为唯一真相 | Agent 禁止业务预聚合;看板与 Zone 共用 Server 侧聚合,避免 openresty_tx 与 bytes_sent 双轨 |
|
||||
| 业务交付 / 边缘健康 / 主机资源分层 | 已提供数据≠宿主机网卡出站≠OpenResty 连接数,UI 与 API 分名分区 |
|
||||
|
||||
---
|
||||
|
||||
@@ -167,8 +189,10 @@ OpenResty (Agent, TLS/WAF)
|
||||
1. **[产品边界](./index.md)**:了解 OpenFlare 核心定位与不允许逾越的设计边界。
|
||||
3. **[Agent 与发布模型](./agent-design.md)**:理解版本快照同步及失败回滚的安全兜底逻辑。
|
||||
4. **细分领域设计**:
|
||||
* Zone 与域名相关开发:阅读 [Zone 与域名资源设计](./zone-design.md)。
|
||||
* 穿透相关开发:阅读 [内网穿透隧道设计](./tunnel-design.md)。
|
||||
* WAF 相关开发:阅读 [WAF 设计](./waf-design.md)。
|
||||
* WAF 相关开发:阅读 [WAF 设计](./waf-design.md) 与 [WAF 可编排规则设计](./waf-orchestration-design.md)。
|
||||
* Pages 托管开发:阅读 [Pages 静态托管设计](./pages-design.md)。
|
||||
* 监控同步开发:阅读 [Uptime Kuma 监控同步设计](./kuma-design.md)。
|
||||
* 看板/访问日志/节点指标开发:阅读 [观测数据传输模型](./observability-transport-model.md) 与 [边缘可观测与业务流量统计](./observability-design.md)。
|
||||
5. **[仓库结构](./index.md#仓库结构)**:明确各个物理目录分层职责,避免堆砌和重复开发。
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
# 边缘缓存策略设计(对标 Cloudflare 默认可缓存范围)
|
||||
|
||||
你会学到:OpenFlare 边缘 `proxy_cache` 的产品边界、默认可缓存范围如何对齐 Cloudflare「静态资源默认可缓存」、策略枚举与渲染规则、兼容迁移,以及本阶段明确不做的能力。
|
||||
|
||||
本设计是 [系统架构](./architecture.md) 中「基础缓存」的产品化专章;访问日志中的缓存结果见 [观测数据模型 §3.5.1](./observability-data-model.md)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与非目标
|
||||
|
||||
### 1.1 目标(第一期)
|
||||
|
||||
* **开箱接近 CF 默认**:路由开启缓存后,**默认只缓存静态扩展名**,不默认缓存 HTML/无扩展名动态路径。
|
||||
* **行为可解释**:与现有安全旁路(非 GET、Authorization、会话 Cookie、请求 `Cache-Control`)叠加,不削弱安全。
|
||||
* **可观测一致**:继续依赖 `$upstream_cache_status` → `cache_status` 明细三态。
|
||||
* **兼容存量**:旧路由 `cache_policy=url`(近似「过旁路即可缓存」)迁移为显式策略 `all`,行为不变。
|
||||
|
||||
### 1.2 非目标(后续迭代)
|
||||
|
||||
* Cache Rules 表达式引擎
|
||||
* Edge TTL / `proxy_cache_valid` / 忽略源站 `Cache-Control`
|
||||
* 可配置 Cookie 旁路列表、Query 忽略列表
|
||||
* Purge(按 URL/前缀/全站)
|
||||
* 浏览器 TTL 改写、客户端 `CF-Cache-Status` 响应头
|
||||
* 命中率看板
|
||||
|
||||
---
|
||||
|
||||
## 2. 现状摘要
|
||||
|
||||
| 层 | 现状 |
|
||||
| --- | --- |
|
||||
| 全局 | `proxy_cache_path` / key / lock / stale(Performance 部分字段) |
|
||||
| 路由 | `cache_enabled` + `cache_policy`:`url` \| `suffix` \| `path_prefix` \| `path_exact` |
|
||||
| 旁路 | 渲染器硬编码:非 GET、Authorization、会话 Cookie、请求 Cache-Control |
|
||||
| TTL | **无** `proxy_cache_valid`;存多久主要看源站头 + `inactive` |
|
||||
| 观测 | 已上报 `cache_status`,UI 三态:命中 / 回源 / 未缓存 |
|
||||
|
||||
问题:默认策略 `url` 对「过旁路的 GET」范围过宽,与 CF「默认主要缓存静态扩展名、默认不缓存 HTML」不一致。
|
||||
|
||||
---
|
||||
|
||||
## 3. 产品语义
|
||||
|
||||
### 3.1 双层开关(不变)
|
||||
|
||||
* **全局** `openresty_cache_enabled`:生成 `proxy_cache_path` 等;关闭则路由级缓存指令不生效。
|
||||
* **路由** `cache_enabled`:是否在该站点 `location` 启用 `proxy_cache`。
|
||||
|
||||
两者均开启时才进入缓存逻辑。
|
||||
|
||||
### 3.2 策略枚举(第一期)
|
||||
|
||||
| `cache_policy` | 含义 | 新建默认 | 旧值兼容 |
|
||||
| --- | --- | --- | --- |
|
||||
| **`static`** | 仅 URI 匹配**标准静态扩展名**(内置表)才允许缓存 | **是** | — |
|
||||
| **`all`** | 过安全旁路后,不限制路径/扩展名(等同今日 `url`) | 否 | 存量 `url` → `all` |
|
||||
| **`suffix`** | 自定义扩展名列表(`cache_rules`) | 否 | 保持 |
|
||||
| **`path_prefix`** | 自定义路径前缀 | 否 | 保持 |
|
||||
| **`path_exact`** | 自定义精确路径 | 否 | 保持 |
|
||||
|
||||
> 渲染层:读到历史值 `url` 时按 `all` 处理,避免未迁移数据行为突变;API 校验与 UI 只暴露上表枚举(写入时可将 `url` 规范为 `all`)。
|
||||
|
||||
### 3.3 标准静态扩展名(内置,V1 硬编码)
|
||||
|
||||
对齐 Cloudflare 常见「默认可缓存静态」集合,**默认不包含** `html` / `htm`:
|
||||
|
||||
```text
|
||||
css js mjs map json
|
||||
ico cur gif jpg jpeg png webp avif svg svgz
|
||||
ttf otf woff woff2 eot
|
||||
mp3 mp4 webm ogg flac
|
||||
wasm pdf
|
||||
zip 7z gz tar
|
||||
```
|
||||
|
||||
* 匹配对象:`$uri` 的扩展名(大小写不敏感),实现上与现有 `suffix` 策略相同:
|
||||
`if ($uri !~* \.(?:css|js|…)$) { set $openflare_skip_cache 1; }`
|
||||
* **V1.1(可选)**:全局配置项覆盖该列表;第一期不强制。
|
||||
|
||||
### 3.4 安全旁路(保持硬编码)
|
||||
|
||||
在策略匹配之前/之外,仍设置 `$openflare_skip_cache=1`:
|
||||
|
||||
1. `$request_method != GET`(含 HEAD,与现网一致)
|
||||
2. `$http_authorization != ""`
|
||||
3. 会话类 Cookie 正则(现网列表)
|
||||
4. 请求 `$http_cache_control` 匹配 `no-cache|no-store|private`
|
||||
|
||||
`proxy_cache_bypass` / `proxy_no_cache` 均绑定 `$openflare_skip_cache`。
|
||||
|
||||
### 3.5 与源站头的关系(本阶段不改)
|
||||
|
||||
* 仍不输出 `proxy_cache_valid`。
|
||||
* 对象**是否进入缓存流程**由策略 + 旁路决定;**存多久**继续依赖源站 `Cache-Control` / `Expires` 等及全局 `inactive`。
|
||||
* Edge TTL / 强制忽略源站头 → 后续专项。
|
||||
|
||||
---
|
||||
|
||||
## 4. 渲染与数据流
|
||||
|
||||
```text
|
||||
全局 cache_enabled?
|
||||
│ no → 不生成 proxy_cache_*
|
||||
▼ yes
|
||||
路由 cache_enabled?
|
||||
│ no → location 无 proxy_cache
|
||||
▼ yes
|
||||
set $openflare_skip_cache 0
|
||||
→ 安全旁路 if → 置 1
|
||||
→ 策略 if(static/all/suffix/…)→ 可置 1
|
||||
proxy_cache openflare_cache
|
||||
proxy_cache_methods GET
|
||||
proxy_cache_bypass / proxy_no_cache $openflare_skip_cache
|
||||
→
|
||||
access.log cache_status=$upstream_cache_status
|
||||
```
|
||||
|
||||
### 4.1 策略 → Nginx 条件
|
||||
|
||||
| 策略 | 额外条件 |
|
||||
| --- | --- |
|
||||
| `static` | `$uri` 不匹配内置扩展名表 → skip |
|
||||
| `all` | 无额外路径条件 |
|
||||
| `suffix` | 不匹配 `cache_rules` 扩展名 → skip |
|
||||
| `path_prefix` / `path_exact` | 同现实现 |
|
||||
|
||||
### 4.2 涉及代码面(实现时)
|
||||
|
||||
| 区域 | 路径 |
|
||||
| --- | --- |
|
||||
| 渲染 | `pkg/render/openresty/render.go`(策略分支 + 内置扩展名常量) |
|
||||
| 校验 | `internal/apps/openflare/proxy_route/helpers.go` |
|
||||
| 模型/默认 | 创建路由默认 `cache_policy=static`;读写时 `url`→`all` |
|
||||
| 快照 | `config_version/snapshot.go` |
|
||||
| UI | `proxy-routes/detail/components/cache-section.tsx` |
|
||||
| 测试 | `pkg/render/openresty/render_test.go`、proxy_route helpers 测试 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 兼容与迁移
|
||||
|
||||
| 数据 | 处理 |
|
||||
| --- | --- |
|
||||
| DB 中 `cache_policy=''` 或 `url`(且已启用缓存) | 读取 / 快照 / 渲染均规范为 **`all`**,保证存量「宽缓存」不变 |
|
||||
| API 写入时 `enabled` 且 policy 为空 | 规范为 **`all`**(兼容旧客户端);UI 新建开启时**显式提交** `static` |
|
||||
| 新建路由 | 默认 `cache_enabled=false`;表单开启缓存时默认策略 **`static`** |
|
||||
| 已开启且 `url` 的站点 | 显示与发布为 `all`,**缓存范围不变** |
|
||||
| 期望「只缓存静态」的旧站点 | 用户在 UI 改为 `static` 或自定义 `suffix` |
|
||||
|
||||
**发布说明建议:** 说明默认策略变更仅影响**新配置**;存量 `url` 视为 `all`。
|
||||
|
||||
---
|
||||
|
||||
## 6. UI 文案要点(缓存 Tab)
|
||||
|
||||
* 开启缓存后默认:**标准静态资源**(列出扩展名摘要,并写明不含 HTML)。
|
||||
* 选项:**标准静态资源** / **所有可缓存 GET(高级)** / 自定义后缀 / 路径前缀 / 精确路径。
|
||||
* 固定说明:非 GET、带 Authorization、常见登录 Cookie、请求禁止缓存头时跳过缓存。
|
||||
* 提示:全局 Performance 中缓存总开关须开启,否则站点开关无效。
|
||||
|
||||
---
|
||||
|
||||
## 7. 验证要点
|
||||
|
||||
* 渲染:`static` 生成扩展名 `if`;`all`/`url` 无路径限制;旁路四条仍在。
|
||||
* 单测:内置表含 `css`/`js`/`woff2`,不含 `html`。
|
||||
* 手动:开启 `static` 后请求 `/a.css` 可出现 HIT/MISS;`/index.html` 或 `/api` 多为未缓存/BYPASS。
|
||||
* 观测:access log `cache_status` 与列表三态一致。
|
||||
|
||||
---
|
||||
|
||||
## 8. 后续路线图(非本设计交付)
|
||||
|
||||
1. **Edge TTL / 尊重源站开关**(`proxy_cache_valid`、`proxy_ignore_headers`)
|
||||
2. **可配置旁路**(Cookie/Query)
|
||||
3. **Purge API**
|
||||
4. **Cache Rules**(有序规则 + 动作)
|
||||
5. **全局默认可缓存扩展名配置**
|
||||
|
||||
---
|
||||
|
||||
## 9. 决策记录
|
||||
|
||||
| 决策 | 选择 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 默认可缓存范围 | 开启缓存默认 `static` 扩展名表 | 对标 CF 开箱行为,降低 HTML/API 被误缓存 |
|
||||
| 旧 `url` | 映射为 `all` | 避免存量站点行为变化 |
|
||||
| HTML | 默认不在白名单 | 对齐 CF 默认不缓存 HTML |
|
||||
| 第一期不做 Edge TTL/Purge | 明确 Out of Scope | 先收敛「谁可以进缓存」再优化「存多久/怎么清」 |
|
||||
@@ -22,12 +22,14 @@ OpenFlare 适合需要统一管理多台 OpenResty 代理节点的团队,具
|
||||
| 能力 | 说明 | 详细设计/使用指南 |
|
||||
| --- | --- | --- |
|
||||
| **反代配置管理** | 以网站规则(Proxy Route)为聚合边界,支持多域名与多上游负载均衡 | [新建反代配置](../guide/proxy-config.md) |
|
||||
| **边缘缓存** | 单节点 OpenResty `proxy_cache`;开启后默认仅缓存标准静态扩展名(对标 CF 默认可缓存范围) | [边缘缓存策略设计](./edge-cache-design.md) |
|
||||
| **Zone 与域名管理** | 以可注册根域为管理入口,聚合明确域名、域名证书与反代路由 | [Zone 与域名资源设计](./zone-design.md) |
|
||||
| **配置版本控制** | 支持全局单一激活版本的预览、发布、不可变快照历史与秒级一键回滚 | [Agent 与发布模型](./agent-design.md) |
|
||||
| **WAF 安全防护** | 全局与自定义规则组,支持手动/自动/订阅型 IP 组,GeoIP 准入与 PoW CC 防护 | [WAF 设计](./waf-design.md) / [WAF 使用指南](../guide/waf-usage.md) |
|
||||
| **WAF 安全防护** | 支持可视化 DAG 编排规则、手动/自动/订阅型 IP 组、GeoIP 匹配与 PoW CC 防护 | [WAF 设计](./waf-design.md) / [WAF 可编排规则设计](./waf-orchestration-design.md) / [WAF 使用指南](../guide/waf-usage.md) |
|
||||
| **内网穿透** | 通过中继节点(Relay)与内网客户端(OpenFlared),反向穿透暴露内网 Web 服务 | [内网穿透设计](./tunnel-design.md) / [穿透使用指南](../guide/tunnel-usage.md) |
|
||||
| **Pages 静态托管** | 直接上传前端 zip 包,由边缘节点拉取并由 OpenResty 本地服务,支持 API 反代与 SPA Fallback | [Pages 静态托管设计](./pages-design.md) |
|
||||
| **TLS 证书自动续期** | 绑定 managed_domains 并通过 ACME 协议向 Let's Encrypt 申请/续期证书 | [新建反代配置](../guide/proxy-config.md) |
|
||||
| **多节点监控与观测** | 收集节点资源快照、健康事件,聚合请求指标与访问日志明细 | [系统架构](./architecture.md) |
|
||||
| **Pages 静态托管** | 直接上传前端压缩包(zip / tar.gz / tar.xz / 7z 等),由边缘节点拉取并由 OpenResty 本地服务,支持 API 反代与 SPA Fallback | [Pages 静态托管设计](./pages-design.md) |
|
||||
| **TLS 证书自动续期** | 将证书显式绑定到 Zone 域名,并通过 ACME 协议向 Let's Encrypt 申请/续期证书 | [Zone 与域名资源设计](./zone-design.md) |
|
||||
| **多节点监控与观测** | 访问日志为业务流量唯一真相;Agent 只上报明细与主机读数,Server 统一聚合;与 Zone/看板对账 | [观测数据传输模型](./observability-transport-model.md) / [边缘可观测与业务流量统计](./observability-design.md) / [上报协议与表结构](./observability-data-model.md) / [系统架构](./architecture.md) |
|
||||
|
||||
---
|
||||
|
||||
@@ -190,4 +192,3 @@ OpenFlare 已收敛为**单 monorepo**(Go 模块 `github.com/Rain-kl/Wavelet`
|
||||
* 发布、同步、回滚与 Agent 模型变化:更新 [Agent 与发布模型](./agent-design.md)。
|
||||
* 部署方式变化:更新 [部署说明](../deployment/deployment.md) 与 README。
|
||||
* 配置项变化:更新 [配置项参考](../reference/configuration.md)。
|
||||
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
# Agent 上报协议与观测落库数据模型
|
||||
|
||||
你会学到:重构后 Agent 心跳/WS 上报的 **数据结构**、Server **如何解析与写入**、ClickHouse / 关系库 **目标表结构**。
|
||||
**无协议兼容层**:Agent 以销毁重建或二进制替换升级;旧字段不解析、旧缓冲整文件丢弃。
|
||||
|
||||
本设计是 [边缘可观测与业务流量统计重构](./observability-design.md) 的 **协议与存储专章**,实现时以本文字段与 DDL 为准。
|
||||
|
||||
**先读传输全景与示例:** [观测数据传输模型](./observability-transport-model.md)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 设计目标
|
||||
|
||||
| 目标 | 说明 |
|
||||
| --- | --- |
|
||||
| Agent 只报事实 | 明细 + 主机读数 + 边缘健康瞬时态;无业务预聚合 |
|
||||
| 一张业务明细表 | 访问日志是 L1 唯一写入路径 |
|
||||
| 聚合在库内/控制面 | 小时汇总由 ClickHouse MV 或查询生成,Agent 不写汇总表 |
|
||||
| 字段不重叠 | `bytes_sent` = 已提供数据;网卡 `network_*` = 宿主机;不再有业务 `openresty_tx` |
|
||||
| 可演进 | 新字段可选;缺省数值填 0,不解析已删除的旧协议字段 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 分层与写入总览
|
||||
|
||||
```text
|
||||
Agent NodePayload (v2)
|
||||
│
|
||||
┌───────────────┼───────────────┐
|
||||
▼ ▼ ▼
|
||||
access_logs host_metrics edge_health
|
||||
(L1 明细) (L3 读数) (L2 瞬时)
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
of_node_access_logs of_node_metric_ of_node_edge_health
|
||||
│ snapshots │
|
||||
│ │ │
|
||||
▼ ▼ │
|
||||
of_access_log_hourly of_node_metric_ │
|
||||
(MV, Server 侧) capacity_hourly (MV) │
|
||||
│ │ │
|
||||
└─────── 管理端聚合 API ───────────┘
|
||||
|
||||
关系库 (PostgreSQL/SQLite):节点最新状态、Profile、健康事件(非明细湖)
|
||||
```
|
||||
|
||||
| 层 | 含义 | Agent 上报块 | ClickHouse 事实表 |
|
||||
| --- | --- | --- | --- |
|
||||
| L1 | 业务交付 | `access_logs` | `of_node_access_logs` |
|
||||
| L2 | 边缘健康 | `edge_health` | `of_node_edge_health` |
|
||||
| L3 | 宿主机资源 | `host_metrics` | `of_node_metric_snapshots` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Agent 上报数据结构(协议 v2)
|
||||
|
||||
### 3.1 顶层 `NodePayload`
|
||||
|
||||
传输:HTTP 心跳 body 与 WebSocket `status` 消息共用同一结构。
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 2,
|
||||
"node_id": "n_xxx",
|
||||
"name": "edge-1",
|
||||
"ip": "1.2.3.4",
|
||||
"version": "3.3.0",
|
||||
"ext_version": "",
|
||||
"current_version": "cfg-checksum-or-version",
|
||||
"last_error": "",
|
||||
"profile": { },
|
||||
"host_metrics": { },
|
||||
"edge_health": { },
|
||||
"access_logs": [ ],
|
||||
"buffered": [ ],
|
||||
"health_events": [ ],
|
||||
"waf_ip_group_checksums": { "1": "md5..." }
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `schema_version` | int | 建议 | 固定为 `2`(本设计) |
|
||||
| `node_id` | string | ✅ | 节点 ID |
|
||||
| `name` | string | ✅ | 显示名 |
|
||||
| `ip` | string | ✅ | 上报 IP |
|
||||
| `version` / `ext_version` | string | ✅ | Agent 版本 |
|
||||
| `current_version` | string | | 本地激活配置版本摘要 |
|
||||
| `last_error` | string | | 最近同步/运行错误,可空 |
|
||||
| `openresty_status` | string | ✅(有 OpenResty 时) | **最新健康态权威字段** → 写 PG 节点表 |
|
||||
| `openresty_message` | string | | **最新健康说明权威字段** → 写 PG 节点表(**不进 CH**) |
|
||||
| `profile` | object | | 主机概况,变化时上报(可节流) |
|
||||
| `host_metrics` | object | 建议每拍 | L3 资源快照 |
|
||||
| `edge_health` | object | 建议每拍 | L2 连接时序 + 与顶层一致的 status |
|
||||
| `access_logs` | array | | 本拍增量访问明细 |
|
||||
| `buffered` | array | | 离线补传的事实批次(见 §3.6) |
|
||||
| `health_events` | array | | 边缘健康事件 |
|
||||
| `waf_ip_group_checksums` | map | | 差分同步用,非观测湖 |
|
||||
|
||||
**已删除、Server 不再解析的字段(无兼容层):**
|
||||
|
||||
| 旧字段 | 处置 |
|
||||
| --- | --- |
|
||||
| `traffic_report` | 不存在于协议;不落库 |
|
||||
| `openresty_observation` | 不存在;连接与状态走 `edge_health` |
|
||||
| `snapshot` | 不存在;仅用 `host_metrics` |
|
||||
| `buffered_observability` | 不存在;仅用 `buffered` |
|
||||
|
||||
### 3.2 `profile` — 主机概况(低频)
|
||||
|
||||
对应关系库 `of_node_system_profiles`(或现有等价表),**不进 ClickHouse 明细湖**。
|
||||
|
||||
```json
|
||||
{
|
||||
"hostname": "edge-1",
|
||||
"os_name": "linux",
|
||||
"os_version": "...",
|
||||
"kernel_version": "...",
|
||||
"architecture": "amd64",
|
||||
"cpu_model": "...",
|
||||
"cpu_cores": 8,
|
||||
"total_memory_bytes": 16106127360,
|
||||
"total_disk_bytes": 107374182400,
|
||||
"uptime_seconds": 864000,
|
||||
"reported_at_unix": 1720000000
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 语义 |
|
||||
| --- | --- |
|
||||
| 硬件/OS 描述字段 | 事实读数 |
|
||||
| `reported_at_unix` | Agent 采集时刻(UTC 秒) |
|
||||
|
||||
### 3.3 `host_metrics` — 宿主机资源(L3)
|
||||
|
||||
**全部为读数,不做 24h 业务总量。**
|
||||
网卡/磁盘字节为 **内核累计计数器原值**(单调递增,重启可归零);CPU 为瞬时百分比;内存/磁盘占用为当前用量。
|
||||
|
||||
```json
|
||||
{
|
||||
"captured_at_unix": 1720000000,
|
||||
"cpu_usage_percent": 12.5,
|
||||
"memory_used_bytes": 4294967296,
|
||||
"memory_total_bytes": 16106127360,
|
||||
"storage_used_bytes": 50000000000,
|
||||
"storage_total_bytes": 107374182400,
|
||||
"disk_read_bytes": 9000000000,
|
||||
"disk_write_bytes": 12000000000,
|
||||
"network_rx_bytes": 500000000000,
|
||||
"network_tx_bytes": 800000000000
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 语义 | Server 如何用 |
|
||||
| --- | --- | --- | --- |
|
||||
| `captured_at_unix` | int64 | 采样时刻 | `captured_at` |
|
||||
| `cpu_usage_percent` | float | 瞬时 CPU% | 直接存;趋势取平均 |
|
||||
| `memory_*` / `storage_*` | int64 | 当前用量/总量 | 直接存;算占用率 |
|
||||
| `disk_read_bytes` / `disk_write_bytes` | int64 | **累计** IO 字节 | 存原值;查询时相邻差分 |
|
||||
| `network_rx_bytes` / `network_tx_bytes` | int64 | **累计** 网卡字节 | 存原值;查询时相邻差分 →「宿主机网卡入/出站」 |
|
||||
|
||||
> Agent **禁止** 在上报前对网卡/磁盘做「本周期增量」替换累计值(否则 Server 差分会错)。
|
||||
|
||||
### 3.4 `edge_health` — OpenResty 边缘健康(L2)
|
||||
|
||||
**仅瞬时态,不包含业务吞吐。**
|
||||
|
||||
```json
|
||||
{
|
||||
"captured_at_unix": 1720000000,
|
||||
"status": "healthy",
|
||||
"message": "",
|
||||
"connections": 42
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 语义 |
|
||||
| --- | --- | --- |
|
||||
| `status` | string | `healthy` / `unhealthy` / `unknown`(须与顶层 `openresty_status` 一致) |
|
||||
| `message` | string | 状态说明(上报可带;**仅用于回填 PG 最新态,不进 CH**) |
|
||||
| `connections` | int64 | stub_status Active connections |
|
||||
|
||||
#### 健康状态权威源(收敛)
|
||||
|
||||
| 数据 | 权威存储 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| **当前** OpenResty 是否健康 + 说明文案 | **PG 节点表** `openresty_status` / `openresty_message` | UI 徽章、列表、告警以这里为准 |
|
||||
| **时序** 健康 status + 连接数 | **CH** `of_node_edge_health`(`status`, `connections`) | 连接曲线 / 健康状态历史;**无 message 列** |
|
||||
| Agent 上报 | 顶层 status/message + `edge_health` | Server 归一化后二者 status 对齐;message **只写 PG** |
|
||||
|
||||
因此:查「现在是否 unhealthy」→ 读 PG;查「过去 24h 连接数」→ 读 CH。
|
||||
### 3.5 `access_logs[]` — 访问明细(L1,业务唯一事实)
|
||||
|
||||
Agent:tail access.log → 解析 JSON 行 → 原样字段上报(可截断 path)。
|
||||
|
||||
```json
|
||||
{
|
||||
"logged_at_unix": 1720000001,
|
||||
"remote_addr": "203.0.113.10",
|
||||
"host": "www.example.com",
|
||||
"path": "/api/v1/ping",
|
||||
"status_code": 200,
|
||||
"bytes_sent": 1024,
|
||||
"request_length": 128,
|
||||
"request_time_ms": 15,
|
||||
"user_agent": "Mozilla/5.0 ...",
|
||||
"cache_status": "HIT"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 来源(OpenResty) | 业务含义 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `logged_at_unix` | int64 | ✅ | `$time_iso8601` 解析 | 请求完成时间 |
|
||||
| `remote_addr` | string | ✅ | `$remote_addr` | 客户端 IP → UV |
|
||||
| `host` | string | ✅ | `$host` | 域名 → Zone 归属 |
|
||||
| `path` | string | ✅ | `$request_uri`,Agent 可截断 | 路径 |
|
||||
| `status_code` | int | ✅ | `$status` | 状态码 |
|
||||
| `bytes_sent` | int64 | ✅ | **`$body_bytes_sent`** | **已提供数据**(响应体) |
|
||||
| `request_length` | int64 | 建议 | `$request_length` | **接收数据** |
|
||||
| `request_time_ms` | int64 | 可选 | `$request_time * 1000` | 耗时;缺省 0 |
|
||||
| `user_agent` | string | 建议 | `$http_user_agent` | UA;可截断入库 |
|
||||
| `cache_status` | string | 建议 | **`$upstream_cache_status`** | 边缘缓存结果(见 §3.5.1) |
|
||||
|
||||
**明确不由 Agent 上报(由 Server 写入):**
|
||||
|
||||
* `region` / 国家:入库时 GeoIP 解析
|
||||
* `id` / `created_at`:Server 生成
|
||||
* `node_id`:取自 payload / 鉴权上下文
|
||||
|
||||
**明确不上报:**
|
||||
|
||||
* `upstream_addr` / 回源地址 / `origin_fetched`:不做回源端点追踪;「是否回源」仅由 `cache_status` 在控制面推导(§3.5.1)
|
||||
|
||||
### 3.5.1 `cache_status` — 缓存命中与回源(明细优先)
|
||||
|
||||
**目标(第一期):** 访问日志明细/详情能展示「是否命中缓存 / 是否回源 / 未使用缓存」。
|
||||
**口径:** 只存 OpenResty `$upstream_cache_status` 原始值;**不上报** upstream 地址。
|
||||
|
||||
#### 原始值(入库)
|
||||
|
||||
| 值 | 含义(OpenResty) |
|
||||
| --- | --- |
|
||||
| `HIT` | 命中缓存 |
|
||||
| `MISS` | 未命中,向 upstream 取内容 |
|
||||
| `BYPASS` | 跳过缓存(如 method/cookie/策略导致 `$openflare_skip_cache`) |
|
||||
| `EXPIRED` | 缓存过期后回源 |
|
||||
| `STALE` | 提供陈旧缓存(stale) |
|
||||
| `UPDATING` | 后台更新中,可能返回旧缓存 |
|
||||
| `REVALIDATED` | 协商验证后仍用缓存 |
|
||||
| `-` 或空 | 未经过 `proxy_cache`(如 Pages 本地静态、非代理 location) |
|
||||
|
||||
#### UI 三态推导(不落库)
|
||||
|
||||
控制面展示用派生枚举 `cache_outcome`,**不写 CH**:
|
||||
|
||||
| 三态 | 条件(`cache_status`) | 列表标签建议 |
|
||||
| --- | --- | --- |
|
||||
| **命中缓存** | `HIT` / `STALE` / `REVALIDATED` / `UPDATING` | 命中 |
|
||||
| **回源** | `MISS` / `EXPIRED` | 回源 |
|
||||
| **未使用缓存** | `BYPASS` / `-` / `""` | 未缓存 |
|
||||
|
||||
详情可同时显示三态 + 原始 `cache_status`。
|
||||
|
||||
#### 边界
|
||||
|
||||
* Pages 静态 / 无 `proxy_cache` 的 location:多为空或 `-` → **未使用缓存**,不得标成「命中」。
|
||||
* 第一期只做明细可见;命中率看板、hourly 维度可后续用同一列聚合。
|
||||
|
||||
**单次心跳条数建议:**
|
||||
|
||||
* 软上限例如 2000 条/拍;超出进入 `buffered` 下一批,**禁止** 在 Agent 压成 TrafficReport。
|
||||
|
||||
### 3.6 `buffered[]` — 离线补传(只装事实)
|
||||
|
||||
```json
|
||||
{
|
||||
"captured_at_unix": 1719999900,
|
||||
"host_metrics": { },
|
||||
"edge_health": { },
|
||||
"access_logs": [ ]
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `captured_at_unix` | 该批次采集/缓冲时刻,用于 ack 与去重窗口 |
|
||||
| `host_metrics` / `edge_health` / `access_logs` | 与主 payload 同结构;可省略空块 |
|
||||
|
||||
**禁止** 在 buffered 中携带 `traffic_report` 或 rx/tx 吞吐。
|
||||
|
||||
### 3.7 `health_events[]`
|
||||
|
||||
```json
|
||||
{
|
||||
"event_type": "openresty_unhealthy",
|
||||
"severity": "critical",
|
||||
"message": "...",
|
||||
"triggered_at_unix": 1720000000,
|
||||
"metadata": { }
|
||||
}
|
||||
```
|
||||
|
||||
写入关系库健康事件表(现有模型即可),不进访问日志湖。
|
||||
|
||||
### 3.8 Go 协议草图(目标)
|
||||
|
||||
```go
|
||||
// pkg/protocol/agent.go(目标形态,实现时替换旧类型)
|
||||
|
||||
type NodePayload struct {
|
||||
SchemaVersion int `json:"schema_version,omitempty"`
|
||||
NodeID string `json:"node_id"`
|
||||
Name string `json:"name"`
|
||||
IP string `json:"ip"`
|
||||
Version string `json:"version"`
|
||||
ExtVersion string `json:"ext_version"`
|
||||
CurrentVersion string `json:"current_version"`
|
||||
LastError string `json:"last_error"`
|
||||
OpenrestyStatus string `json:"openresty_status"` // PG 最新态权威
|
||||
OpenrestyMessage string `json:"openresty_message"` // PG 最新态权威;不进 CH
|
||||
Profile *NodeSystemProfile `json:"profile,omitempty"`
|
||||
HostMetrics *NodeHostMetrics `json:"host_metrics,omitempty"`
|
||||
EdgeHealth *NodeEdgeHealth `json:"edge_health,omitempty"`
|
||||
AccessLogs []NodeAccessLog `json:"access_logs,omitempty"`
|
||||
Buffered []BufferedFacts `json:"buffered,omitempty"`
|
||||
HealthEvents []NodeHealthEvent `json:"health_events"`
|
||||
WAFIPGroupChecksums map[string]string `json:"waf_ip_group_checksums,omitempty"`
|
||||
}
|
||||
|
||||
type NodeHostMetrics struct {
|
||||
CapturedAtUnix int64 `json:"captured_at_unix"`
|
||||
CPUUsagePercent float64 `json:"cpu_usage_percent"`
|
||||
MemoryUsedBytes int64 `json:"memory_used_bytes"`
|
||||
MemoryTotalBytes int64 `json:"memory_total_bytes"`
|
||||
StorageUsedBytes int64 `json:"storage_used_bytes"`
|
||||
StorageTotalBytes int64 `json:"storage_total_bytes"`
|
||||
DiskReadBytes int64 `json:"disk_read_bytes"`
|
||||
DiskWriteBytes int64 `json:"disk_write_bytes"`
|
||||
NetworkRxBytes int64 `json:"network_rx_bytes"`
|
||||
NetworkTxBytes int64 `json:"network_tx_bytes"`
|
||||
}
|
||||
|
||||
type NodeEdgeHealth struct {
|
||||
CapturedAtUnix int64 `json:"captured_at_unix"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Connections int64 `json:"connections"`
|
||||
}
|
||||
|
||||
type NodeAccessLog struct {
|
||||
LoggedAtUnix int64 `json:"logged_at_unix"`
|
||||
RemoteAddr string `json:"remote_addr"`
|
||||
Host string `json:"host"`
|
||||
Path string `json:"path"`
|
||||
UserAgent string `json:"user_agent,omitempty"`
|
||||
CacheStatus string `json:"cache_status,omitempty"` // $upstream_cache_status
|
||||
StatusCode int `json:"status_code"`
|
||||
BytesSent int64 `json:"bytes_sent"` // body_bytes_sent,已提供数据
|
||||
RequestLength int64 `json:"request_length"` // 接收数据
|
||||
RequestTimeMs int64 `json:"request_time_ms"` // 可选
|
||||
}
|
||||
|
||||
type BufferedFacts struct {
|
||||
CapturedAtUnix int64 `json:"captured_at_unix"`
|
||||
HostMetrics *NodeHostMetrics `json:"host_metrics,omitempty"`
|
||||
EdgeHealth *NodeEdgeHealth `json:"edge_health,omitempty"`
|
||||
AccessLogs []NodeAccessLog `json:"access_logs,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Server 解析与落库流程
|
||||
|
||||
### 4.1 入口
|
||||
|
||||
* HTTP:`POST /api/v1/agent/...` 心跳(现有路径)
|
||||
* WebSocket:`type=status` payload = `NodePayload`
|
||||
* 鉴权:`X-Agent-Token` → 绑定 `node_id`(payload.node_id 必须与 token 节点一致)
|
||||
|
||||
### 4.2 处理流水线(单次 payload)
|
||||
|
||||
```text
|
||||
1. 反序列化 NodePayload
|
||||
2. 归一化(normalize)
|
||||
- schema_version < 2:
|
||||
host_metrics ← snapshot
|
||||
edge_health.status ← openresty_status
|
||||
edge_health.connections ← openresty_observation.connections(若有)
|
||||
traffic_report → drop
|
||||
openresty_observation.rx/tx → drop
|
||||
buffered ← buffered_observability
|
||||
- path 再截断、status 范围钳制、负数字节 → 0
|
||||
3. 关系库事务(节点最新态)
|
||||
- 更新 node 在线时间、IP、版本、edge_health.status/message
|
||||
- upsert profile(若有)
|
||||
- insert health_events(若有)
|
||||
4. ClickHouse 异步 batch(失败记日志,不阻断心跳响应的配置下发)
|
||||
a. access_logs + buffered[].access_logs
|
||||
→ 补 region(GeoIP)
|
||||
→ 分配 snowflake id
|
||||
→ BatchInsert of_node_access_logs
|
||||
b. host_metrics + buffered[].host_metrics
|
||||
→ of_node_metric_snapshots
|
||||
c. edge_health + buffered[].edge_health
|
||||
→ of_node_edge_health(仅 connections + status 快照可选)
|
||||
5. 返回心跳响应(settings / active_config / waf 差分)
|
||||
6. 若使用 buffer ack:按 buffered.captured_at_unix 列表确认
|
||||
```
|
||||
|
||||
### 4.3 归一化规则(硬约束)
|
||||
|
||||
| 规则 | 行为 |
|
||||
| --- | --- |
|
||||
| `logged_at` 超前 now+5m | 钳制为 now 或丢弃该条(实现选定一种并单测) |
|
||||
| `logged_at` 早于 now−TTL | 仍可写入,依赖表 TTL 清理 |
|
||||
| 空 `host` | 允许,聚合进「未归属」 |
|
||||
| `bytes_sent` / `request_length` < 0 | 置 0 |
|
||||
| 单批 access_logs > N | 截断并打点监控(或只入 buffer 队列),不改为预聚合 |
|
||||
| 重复补传 | CH 允许少量重复行;查询用 sum 近似(不强制精确去重) |
|
||||
|
||||
### 4.4 字段映射表(上报 → 表)
|
||||
|
||||
| 上报路径 | 目标存储 | 列 |
|
||||
| --- | --- | --- |
|
||||
| `access_logs[]` | CH `of_node_access_logs` | 见 §5.1 |
|
||||
| `host_metrics` | CH `of_node_metric_snapshots` | 见 §5.2 |
|
||||
| `edge_health` | CH `of_node_edge_health` + PG node 最新状态 | 见 §5.3 / §5.6 |
|
||||
| `profile` | PG `of_node_system_profiles` | 现有列 |
|
||||
| `health_events` | PG 健康事件表 | 现有模型 |
|
||||
| `waf_ip_group_checksums` | 不落观测表 | 同步逻辑 |
|
||||
| `traffic_report`(旧) | **不写** | — |
|
||||
| `openresty_rx/tx`(旧) | **不写** | — |
|
||||
|
||||
### 4.5 查询侧(不落新「业务出站」列)
|
||||
|
||||
| 产品指标 | SQL 语义(示意) |
|
||||
| --- | --- |
|
||||
| 已提供数据 | `sum(bytes_sent)` |
|
||||
| 接收数据 | `sum(request_length)` |
|
||||
| 请求数 | `count()` |
|
||||
| UV | `uniqExact(remote_addr)` |
|
||||
| 5xx | `countIf(status_code >= 500)` |
|
||||
| 按域名/状态码/地区 | `GROUP BY host / status_code / region` |
|
||||
| 宿主机网卡出站 | 对 `network_tx_bytes` 按 node 时间序非负差分后 sum |
|
||||
| OpenResty 连接 | `of_node_edge_health.connections` 最新或平均 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 表结构(目标 DDL)
|
||||
|
||||
> 引擎与 TTL 与现网一致倾向:访问日志 90 天,指标 30 天。
|
||||
> `id` 使用控制面 Snowflake/唯一 UInt64。
|
||||
|
||||
### 5.1 L1 事实表:`of_node_access_logs`
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS of_node_access_logs
|
||||
(
|
||||
id UInt64,
|
||||
node_id String,
|
||||
logged_at DateTime64(3, 'UTC'),
|
||||
remote_addr String,
|
||||
region String, -- Server GeoIP 写入,Agent 不传
|
||||
host String,
|
||||
path String,
|
||||
user_agent String DEFAULT '', -- $http_user_agent
|
||||
cache_status String DEFAULT '', -- $upstream_cache_status
|
||||
status_code Int32,
|
||||
bytes_sent UInt64, -- 已提供数据(body)
|
||||
request_length UInt64 DEFAULT 0, -- 接收数据
|
||||
request_time_ms UInt32 DEFAULT 0, -- 可选
|
||||
created_at DateTime64(3, 'UTC')
|
||||
)
|
||||
ENGINE = MergeTree()
|
||||
PARTITION BY toYYYYMM(logged_at)
|
||||
ORDER BY (node_id, logged_at, host, status_code, remote_addr)
|
||||
TTL toDateTime(logged_at) + INTERVAL 90 DAY
|
||||
SETTINGS index_granularity = 8192;
|
||||
```
|
||||
|
||||
| 列 | 类型 | 来源 |
|
||||
| --- | --- | --- |
|
||||
| `id` | UInt64 | Server |
|
||||
| `node_id` | String | 鉴权/payload |
|
||||
| `logged_at` | DateTime64(3) | `logged_at_unix` |
|
||||
| `remote_addr` | String | 上报 |
|
||||
| `region` | String | Server GeoIP |
|
||||
| `host` | String | 上报 |
|
||||
| `path` | String | 上报 |
|
||||
| `user_agent` | String | 上报(可空) |
|
||||
| `cache_status` | String | 上报(可空)→ **缓存状态** |
|
||||
| `status_code` | Int32 | 上报 |
|
||||
| `bytes_sent` | UInt64 | 上报 → **已提供数据** |
|
||||
| `request_length` | UInt64 | 上报 → **接收数据** |
|
||||
| `request_time_ms` | UInt32 | 上报可选 |
|
||||
| `created_at` | DateTime64(3) | Server now |
|
||||
|
||||
**迁移:** 现表已有 `bytes_sent` / `request_length` / `request_time_ms` / `user_agent`;缓存状态新增:
|
||||
|
||||
```sql
|
||||
ALTER TABLE of_node_access_logs
|
||||
ADD COLUMN IF NOT EXISTS cache_status String DEFAULT '';
|
||||
```
|
||||
|
||||
### 5.2 L1 小时汇总(Server 侧 MV)
|
||||
|
||||
**禁止 Agent 写入。** 供看板/节点 24h 快速查询请求数、错误数、字节量。
|
||||
|
||||
**已实现选型:`SummingMergeTree` + 不含 UV 列。**
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS of_access_log_hourly
|
||||
(
|
||||
node_id String,
|
||||
hour DateTime('UTC'),
|
||||
host String,
|
||||
request_count UInt64,
|
||||
error_count UInt64,
|
||||
bytes_sent UInt64,
|
||||
request_length UInt64
|
||||
)
|
||||
ENGINE = SummingMergeTree()
|
||||
PARTITION BY toYYYYMM(hour)
|
||||
ORDER BY (node_id, hour, host)
|
||||
TTL hour + INTERVAL 90 DAY;
|
||||
|
||||
CREATE MATERIALIZED VIEW IF NOT EXISTS of_access_log_hourly_mv
|
||||
TO of_access_log_hourly
|
||||
AS
|
||||
SELECT
|
||||
node_id,
|
||||
toStartOfHour(logged_at) AS hour,
|
||||
host,
|
||||
toUInt64(count()) AS request_count,
|
||||
toUInt64(countIf(status_code >= 500)) AS error_count,
|
||||
sum(bytes_sent) AS bytes_sent,
|
||||
sum(request_length) AS request_length
|
||||
FROM of_node_access_logs
|
||||
GROUP BY node_id, hour, host;
|
||||
```
|
||||
|
||||
历史小时(MV 创建前已入库的明细)需一次性回填,见迁移 `202607180003_backfill_access_log_hourly.sql`(ANTI JOIN 防重)。
|
||||
|
||||
#### UV 策略(必须遵守)
|
||||
|
||||
| 场景 | 数据源 | 算法 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| **窗口总 UV**(看板汇总、节点卡片、Zone 汇总) | `of_node_access_logs` 明细 | `uniqExact(remote_addr)`(`TrafficSummary` / 节点聚合) | **唯一权威**;不可用小时 UV 相加 |
|
||||
| **24h 趋势折线请求/错误/字节** | `of_access_log_hourly` 优先,缺数据回落明细桶 | `sum(request_count)` 等 | 小时路径 **不填** `unique_visitor_count`(恒为 0) |
|
||||
| **24h 趋势折线分时 UV** | 仅明细桶路径 | 桶内 `uniqExact` | 走 hourly 时 UI 应展示空/0 或隐藏 UV 序列,**禁止**对小时行做 `sum(UV)` |
|
||||
|
||||
**为何 hourly 不存 UV:**
|
||||
|
||||
1. `SummingMergeTree` 只能安全合并可加和计数;`uniqExact` 跨 part 合并需要 `AggregatingMergeTree` + state,实现与查询更重。
|
||||
2. 即便存每小时 UV,对多小时窗口 **相加会严重高估**(同一 IP 跨小时重复计)。
|
||||
3. 产品「24h 独立访客」只认整窗 `uniqExact`;趋势图主序列是请求量/错误/字节,分时 UV 非主指标。
|
||||
|
||||
可选未来:若需要分时 UV 曲线,再单独加 `AggregatingMergeTree` 状态表或查询时对明细做 `uniqExact` 按小时 group(成本更高,不阻塞当前看板)。
|
||||
### 5.3 L3 事实表:`of_node_metric_snapshots`(保留,语义明确)
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS of_node_metric_snapshots
|
||||
(
|
||||
id UInt64,
|
||||
node_id String,
|
||||
captured_at DateTime64(3, 'UTC'),
|
||||
cpu_usage_percent Float64,
|
||||
memory_used_bytes Int64,
|
||||
memory_total_bytes Int64,
|
||||
storage_used_bytes Int64,
|
||||
storage_total_bytes Int64,
|
||||
disk_read_bytes Int64, -- 累计原值
|
||||
disk_write_bytes Int64,
|
||||
network_rx_bytes Int64, -- 累计原值 → 宿主机网卡入站
|
||||
network_tx_bytes Int64, -- 累计原值 → 宿主机网卡出站
|
||||
created_at DateTime64(3, 'UTC')
|
||||
)
|
||||
ENGINE = MergeTree()
|
||||
PARTITION BY toYYYYMM(captured_at)
|
||||
ORDER BY (node_id, captured_at, id)
|
||||
TTL toDateTime(captured_at) + INTERVAL 30 DAY
|
||||
SETTINGS index_granularity = 8192;
|
||||
```
|
||||
|
||||
列与现网一致;**文档与 API 必须标注 network_* 为宿主机网卡累计值**。
|
||||
|
||||
### 5.4 L3 小时汇总:`of_node_metric_capacity_hourly`(保留)
|
||||
|
||||
现有 min/max 用于累计计数器小时增量近似 + CPU/内存平均。逻辑不变:
|
||||
|
||||
* `network_tx_max - network_tx_min` ≈ 该小时宿主机出站
|
||||
* **不得** 用于「已提供数据」
|
||||
|
||||
### 5.5 L2 事实表:`of_node_edge_health`(新建,替换吞吐型 openresty 表)
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS of_node_edge_health
|
||||
(
|
||||
id UInt64,
|
||||
node_id String,
|
||||
captured_at DateTime64(3, 'UTC'),
|
||||
status LowCardinality(String), -- healthy / unhealthy / unknown
|
||||
connections Int64,
|
||||
created_at DateTime64(3, 'UTC')
|
||||
)
|
||||
ENGINE = MergeTree()
|
||||
PARTITION BY toYYYYMM(captured_at)
|
||||
ORDER BY (node_id, captured_at, id)
|
||||
TTL toDateTime(captured_at) + INTERVAL 30 DAY
|
||||
SETTINGS index_granularity = 8192;
|
||||
```
|
||||
|
||||
| 列 | 说明 |
|
||||
| --- | --- |
|
||||
| `status` | 瞬时健康(与 PG 当前态同源;用于时序,非唯一 UI 权威) |
|
||||
| `connections` | 当前连接数 |
|
||||
|
||||
**无** `message` 列(说明文案仅 PG 最新态)。
|
||||
**无** `openresty_rx_bytes` / `openresty_tx_bytes`。
|
||||
### 5.6 关系库(节点最新态,非分析湖)
|
||||
|
||||
与观测湖分离,保持「最新一份」:
|
||||
|
||||
| 表(逻辑名) | 用途 | 关键列 |
|
||||
| --- | --- | --- |
|
||||
| `of_nodes`(或现节点表) | 在线、版本、IP | `last_seen_at`, `openresty_status`, `openresty_message`, `agent_version` |
|
||||
| `of_node_system_profiles` | profile upsert | hostname, cpu_cores, total_memory_bytes, ... |
|
||||
| 健康事件表 | `health_events` | event_type, severity, message, triggered_at |
|
||||
|
||||
> 具体物理表名以仓库现有 GORM 模型为准;本设计不强制改名,只强制 **不再把业务吞吐写进节点表**。
|
||||
|
||||
### 5.7 废弃表(停止写入 → TTL 后删除)
|
||||
|
||||
| 表 | 原因 | 替代 |
|
||||
| --- | --- | --- |
|
||||
| `of_node_request_reports` | Agent 预聚合 | `of_node_access_logs` + hourly |
|
||||
| `of_node_traffic_hourly` + MV | 依赖 request_reports | `of_access_log_hourly` |
|
||||
| `of_node_obs_openresty` | 含业务 rx/tx | `of_node_edge_health` |
|
||||
| `of_node_openresty_hourly` + MV | 业务吞吐差分 | `of_access_log_hourly` 的 bytes_* |
|
||||
|
||||
Relay 专用 `of_node_obs_frps` / `of_node_obs_frpc` **保留**(非本 Agent 主路径,但同属 CH 观测)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 表与协议对照总表
|
||||
|
||||
| 产品概念 | 协议字段 | 表.列 | 聚合 |
|
||||
| --- | --- | --- | --- |
|
||||
| 已提供数据 | `access_logs[].bytes_sent` | `of_node_access_logs.bytes_sent` | `sum` |
|
||||
| 接收数据 | `access_logs[].request_length` | `...request_length` | `sum` |
|
||||
| 请求数 | 行数 | — | `count` |
|
||||
| UV(窗口总) | `remote_addr` | 同左明细 | `uniqExact`(**禁止** sum 小时 UV) |
|
||||
| Top 域名 | `host` | 同左 | `group by` |
|
||||
| 状态码分布 | `status_code` | 同左 | `group by` |
|
||||
| 来源地区 | — | `region`(Server) | `group by` |
|
||||
| 宿主机网卡出站 | `host_metrics.network_tx_bytes` | `of_node_metric_snapshots.network_tx_bytes` | 时间序差分 |
|
||||
| 宿主机网卡入站 | `network_rx_bytes` | 同左 | 差分 |
|
||||
| 磁盘读/写 | `disk_*_bytes` | 同左 | 差分 |
|
||||
| CPU/内存 | 瞬时字段 | 同左 | avg |
|
||||
| OpenResty 连接 | `edge_health.connections` | `of_node_edge_health.connections` | 最新/avg |
|
||||
| OpenResty 健康 | `edge_health.status` | 节点表 + 可选 CH | 最新 |
|
||||
|
||||
**不再存在的映射:**
|
||||
|
||||
| 旧概念 | 旧字段 | 处置 |
|
||||
| --- | --- | --- |
|
||||
| OpenResty 出站 | `openresty_tx_bytes` | 删除;用已提供数据 |
|
||||
| OpenResty 入站 | `openresty_rx_bytes` | 删除;用接收数据 |
|
||||
| 窗口请求报告 | `traffic_report` | 删除 |
|
||||
|
||||
---
|
||||
|
||||
## 7. OpenResty 日志格式(与明细对齐)
|
||||
|
||||
目标 `log_format`(保证 `bytes_sent` 键 = body;含 UA 与缓存状态):
|
||||
|
||||
```nginx
|
||||
log_format openflare_json escape=json
|
||||
'{"ts":"$time_iso8601","host":"$host","path":"$request_uri",'
|
||||
'"remote_addr":"$remote_addr","status":$status,'
|
||||
'"request_time":$request_time,'
|
||||
'"bytes_sent":$body_bytes_sent,"request_length":$request_length,'
|
||||
'"user_agent":"$http_user_agent",'
|
||||
'"cache_status":"$upstream_cache_status"}';
|
||||
```
|
||||
|
||||
Agent 解析:
|
||||
|
||||
* `ts` → `logged_at_unix`
|
||||
* `bytes_sent` → 协议 `bytes_sent`(已提供)
|
||||
* `request_length` → 协议 `request_length`
|
||||
* `request_time` → 可选 `request_time_ms = round(sec * 1000)`
|
||||
* `user_agent` → 协议 `user_agent`
|
||||
* `cache_status` → 协议 `cache_status`(原样透传,不做三态压缩)
|
||||
|
||||
---
|
||||
|
||||
## 8. 升级策略(无兼容层)
|
||||
|
||||
| 项 | 策略 |
|
||||
| --- | --- |
|
||||
| Agent 升级 | **销毁重建**优先;允许**二进制替换** |
|
||||
| 协议 | 仅 schema v2 字段;旧 JSON 字段不解析 |
|
||||
| 本地观测缓冲 | 若仍是旧格式(含 `snapshot` / `openresty_observation` / `traffic_report`)或损坏 → **整文件删除**,运行中重建 |
|
||||
| 读路径 | 业务 API **只读** access_logs(及 hourly);健康当前态读 PG;连接时序读 CH edge_health |
|
||||
| 旧 Agent | 必须升级;控制面不提供 v1 双读路径 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 示例:一次心跳的落库结果
|
||||
|
||||
**Agent 上报(节选):**
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 2,
|
||||
"node_id": "n1",
|
||||
"host_metrics": {
|
||||
"captured_at_unix": 1720000000,
|
||||
"cpu_usage_percent": 10,
|
||||
"memory_used_bytes": 1,
|
||||
"memory_total_bytes": 2,
|
||||
"storage_used_bytes": 3,
|
||||
"storage_total_bytes": 4,
|
||||
"disk_read_bytes": 100,
|
||||
"disk_write_bytes": 200,
|
||||
"network_rx_bytes": 1000,
|
||||
"network_tx_bytes": 2000
|
||||
},
|
||||
"edge_health": {
|
||||
"captured_at_unix": 1720000000,
|
||||
"status": "healthy",
|
||||
"message": "",
|
||||
"connections": 5
|
||||
},
|
||||
"access_logs": [
|
||||
{
|
||||
"logged_at_unix": 1720000001,
|
||||
"remote_addr": "1.1.1.1",
|
||||
"host": "a.example.com",
|
||||
"path": "/",
|
||||
"status_code": 200,
|
||||
"bytes_sent": 500,
|
||||
"request_length": 80
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**写入:**
|
||||
|
||||
1. PG 节点最新态:`openresty_status` / `openresty_message`(若上报)
|
||||
2. `of_node_metric_snapshots` 1 行(network_tx=2000 累计)
|
||||
3. `of_node_edge_health` 1 行(status + connections=5;**无 message**)
|
||||
4. `of_node_access_logs` 1 行(bytes_sent=500, request_length=80, region=Server 填充)
|
||||
5. MV 异步计入 `of_access_log_hourly`
|
||||
|
||||
**查询 24h 已提供数据:** `sum(bytes_sent)` → 至少 500(加历史)
|
||||
**查询宿主机出站:** 对 snapshots 差分,与 500 **无强制相等关系**。
|
||||
|
||||
---
|
||||
|
||||
## 10. 实现检查清单
|
||||
|
||||
- [x] `pkg/protocol`:仅 v2 字段,无兼容别名
|
||||
- [x] Agent:只组 `host_metrics` / `edge_health` / `access_logs` / `buffered`
|
||||
- [x] Server:无 request_reports / openresty 吞吐;健康当前态 PG、时序 CH
|
||||
- [x] CH migration:`request_length`、`request_time_ms`、`of_node_edge_health`、`of_access_log_hourly`、hourly 回填
|
||||
- [x] 看板/Zone API 统一读 access log 聚合
|
||||
- [x] UV:整窗 uniqExact;Zone 曲线标明分桶 UV;小时趋势不绘 UV
|
||||
|
||||
---
|
||||
|
||||
## 11. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
| --- | --- |
|
||||
| 2026-07-17 | 初稿:协议 v2、Server 落库流水线、CH/关系库目标表结构与废弃表清单 |
|
||||
@@ -0,0 +1,585 @@
|
||||
# 边缘可观测与业务流量统计重构设计
|
||||
|
||||
你会学到:当前观测链路为何出现「看板 OpenResty 出站」与「Zone 已提供数据」不一致、字段与聚合为何冗余,以及目标架构如何让 **Agent 只上报事实、Server 只解释事实**,业务流量以访问日志为唯一真相源。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标
|
||||
|
||||
### 1.1 要解决的问题
|
||||
|
||||
1. **双真相源**:业务吞吐同时来自访问日志聚合与 OpenResty 观测差分,数值长期对不上。
|
||||
2. **Agent 越权计算**:边缘预聚合 `TrafficReport`、吞吐累计,控制面再聚合一遍,语义难演进、难对账。
|
||||
3. **字段语义重叠**:「OpenResty 出站」与「已提供数据」对用户是同一业务问题,系统却用两套字段、两条管道。
|
||||
4. **瞬时与累计混用**:60 秒窗口计数被当成进程累计做 24h 差分,造成严重偏低。
|
||||
5. **UI 诱导错误对比**:看板与 Zone 页使用相近「流量/数据」文案,却未声明范围与口径差异。
|
||||
|
||||
### 1.2 重构目标
|
||||
|
||||
| 目标 | 说明 |
|
||||
| --- | --- |
|
||||
| **单一业务真相** | 请求数、已提供数据、UV、状态码分布、Top 域名等 **只** 从访问日志(及其 Server 侧派生汇总)得出 |
|
||||
| **Agent 只上报事实** | 明细日志 + 机器读数 + 健康瞬时态;**禁止** 业务 UV/TopN/24h 总量等预聚合 |
|
||||
| **字段收敛** | 一个业务概念对应一个权威字段;机器网卡与业务交付严格分名 |
|
||||
| **可对账** | 全局「已提供数据」≈ 各 Zone「已提供数据」之和(差仅为未绑定/未知 Host) |
|
||||
| **可演进** | 改时间窗、TopN、归属规则只改 Server,不升 Agent |
|
||||
|
||||
### 1.3 非目标(本设计不覆盖)
|
||||
|
||||
* 建成通用日志平台、全量日志长期归档或检索产品。
|
||||
* 替换 ClickHouse / 取消分析库依赖。
|
||||
* 改造 Relay / OpenFlared 的主机指标采集(可对齐原则,但不在本轮协议主路径)。
|
||||
* 实时流式告警引擎、APM 链路追踪(OpenTelemetry 服务端已有,与本业务流量模型正交)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 范围与约束
|
||||
|
||||
### 2.1 产品约束(继承)
|
||||
|
||||
* 单租户、全局单激活配置;观测不引入多租户计费隔离。
|
||||
* ClickHouse 为访问日志与时序观测的强制分析存储。
|
||||
* Agent 无入向控制、Pull 模型;离线期间本地 OpenResty 继续服务,观测可本地缓冲后补传。
|
||||
|
||||
### 2.2 工程约束
|
||||
|
||||
* Agent 保持轻量:解析日志行、读 `/proc`、健康检查;不做业务分析。
|
||||
* 控制面 API 错误仍走统一信封与 `response.Abort*`。
|
||||
* 访问日志字段变更须同时更新 OpenResty `log_format` 与 Agent 解析器;Agent 与控制面同版本发布,不保留旧协议解析。
|
||||
|
||||
---
|
||||
|
||||
## 3. 设计原则
|
||||
|
||||
### 原则 P1:Agent 上报事实,Server 解释事实
|
||||
|
||||
```text
|
||||
Agent = 采集 + 可靠投递(原始/近原始)
|
||||
Server = 入库 + 聚合 + 归属 + 趋势 + 对账
|
||||
```
|
||||
|
||||
**允许的边缘处理(采集)**
|
||||
|
||||
* 将 JSON access.log 行解析为结构化字段
|
||||
* path 长度上限、丢弃非法行、跳过观测端口自身请求
|
||||
* 读取网卡/CPU/内存等计数器 **原值**
|
||||
* 批量、压缩、离线缓冲与重试
|
||||
|
||||
**禁止的边缘处理(业务计算)**
|
||||
|
||||
* UV / Top 域名 / 状态码直方图 / 窗口 request_count 作为权威指标
|
||||
* 为看板单独维护「业务入出站累计」
|
||||
* Zone / 域名归属统计、国家分布(国家可在 Server 入库时解析)
|
||||
|
||||
### 原则 P2:业务流量唯一真相 = 访问日志
|
||||
|
||||
| 业务问题 | 唯一答案 |
|
||||
| --- | --- |
|
||||
| 提供了多少数据 | `sum(bytes_sent)` |
|
||||
| 多少请求 | `count()` |
|
||||
| 多少独立访客 | `uniqExact(remote_addr)`(或产品约定哈希) |
|
||||
| 状态码 / Top 域名 | 对日志 `group by` |
|
||||
|
||||
### 原则 P3:三层指标互不混用
|
||||
|
||||
| 层 | 名称 | 用途 | 典型字段 |
|
||||
| --- | --- | --- | --- |
|
||||
| L1 业务交付 | Business Traffic | 用户与 Zone 对账、看板业务趋势 | access log |
|
||||
| L2 边缘健康 | Edge Health | OpenResty 是否活着、当前连接 | status、connections |
|
||||
| L3 宿主机资源 | Host Capacity | 容量规划、机器是否打满 | CPU、内存、磁盘、**网卡** |
|
||||
|
||||
禁止将 L3 网卡或 L2 瞬时计数命名为「已提供数据」;禁止将 L1 与 L3 画在同一摘要卡片上却不标注语义。
|
||||
|
||||
### 原则 P4:一个业务概念一个字段
|
||||
|
||||
* **已提供数据** ≡ 响应体交付量 ≡ 历史文案中的「OpenResty 出站(业务含义)」→ **只保留 `bytes_sent` 聚合**
|
||||
* **接收数据**(可选)≡ 请求侧体量 → 日志 `request_length` 聚合
|
||||
* **宿主机出站** ≡ `network_tx` 差分,文案必须含「宿主机/网卡」
|
||||
|
||||
---
|
||||
|
||||
## 4. 现状问题(基线)
|
||||
|
||||
### 4.1 当前数据流(冗余)
|
||||
|
||||
```text
|
||||
一次 HTTP 请求
|
||||
│
|
||||
├─ access.log 一行
|
||||
│ → Agent tail → AccessLogs[]
|
||||
│ → CH of_node_access_logs
|
||||
│ → Zone「已提供数据」✅
|
||||
│
|
||||
├─ Lua shared dict 窗口/累计计数
|
||||
│ → /openflare/observability
|
||||
│ → TrafficReport + OpenrestyObservation(rx/tx)
|
||||
│ → CH request_reports / obs_openresty
|
||||
│ → 看板「OpenResty 入/出站」❌ 易与 Zone 不一致
|
||||
│
|
||||
├─ access.log 二次汇总(观测 endpoint 失败时回退)
|
||||
│ → 又一份 TrafficReport / 吞吐
|
||||
│
|
||||
└─ 宿主机 network_rx/tx
|
||||
→ Snapshot → 网络趋势中的「主机」曲线
|
||||
```
|
||||
|
||||
### 4.2 字段重叠
|
||||
|
||||
| 用户感知 | 系统字段 A | 系统字段 B | 问题 |
|
||||
| --- | --- | --- | --- |
|
||||
| 出站 / 已提供 | `openresty_tx_bytes` | `bytes_sent` | 业务语义重复 |
|
||||
| 入站 | `openresty_rx_bytes` | `request_length`(日志) | 业务语义重复 |
|
||||
| 请求数 | `TrafficReport.request_count` | `count(access_logs)` | 聚合重复且窗口易重计 |
|
||||
| 出站(机器) | `network_tx_bytes` | (无业务对应) | 应单独命名,勿与业务对账 |
|
||||
|
||||
### 4.3 典型故障模式
|
||||
|
||||
1. 窗口计数被当累计差分 → 24h 业务吞吐严重偏低。
|
||||
2. 小时 rollup `max−min` 对重置型计数失效。
|
||||
3. Zone 用日志、看板用观测 → 用户认为系统算错。
|
||||
4. 改口径需同步改 Lua、Agent 状态累计、Server 差分、前端文案。
|
||||
|
||||
---
|
||||
|
||||
## 5. 目标架构
|
||||
|
||||
### 5.1 目标数据流
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph edge [边缘节点]
|
||||
OR[OpenResty]
|
||||
LOG[access.log]
|
||||
PROC[主机 /proc 与磁盘]
|
||||
STUB[stub_status 连接数]
|
||||
AG[Agent]
|
||||
OR -->|log_format 写行| LOG
|
||||
LOG -->|仅 tail 增量明细| AG
|
||||
PROC -->|读数快照| AG
|
||||
STUB -->|瞬时连接| AG
|
||||
OR -->|健康探测| AG
|
||||
end
|
||||
|
||||
subgraph server [控制面 Server]
|
||||
HB[心跳 / WS 接收]
|
||||
CH[(ClickHouse)]
|
||||
AGG[聚合查询层]
|
||||
API[管理端 API]
|
||||
HB --> CH
|
||||
CH --> AGG
|
||||
AGG --> API
|
||||
end
|
||||
|
||||
subgraph ui [管理端]
|
||||
DASH[看板:全局业务趋势]
|
||||
ZONE[Zone:按域名过滤]
|
||||
NODE[节点:主机资源 + 健康]
|
||||
end
|
||||
|
||||
AG -->|AccessLogs + HostSnapshot + Health| HB
|
||||
API --> DASH
|
||||
API --> ZONE
|
||||
API --> NODE
|
||||
```
|
||||
|
||||
### 5.2 职责矩阵
|
||||
|
||||
| 能力 | Agent | Server | 前端 |
|
||||
| --- | --- | --- | --- |
|
||||
| 写 access.log | OpenResty | — | — |
|
||||
| 读并上报明细 | ✅ | 入库 | — |
|
||||
| sum/count/uniq/TopN | ❌ | ✅ | 展示 |
|
||||
| Zone 域名过滤 | ❌ | ✅ | 选择 Zone |
|
||||
| 主机 CPU/内存/网卡 | 读原值上报 | 差分/平均 | 节点/看板资源区 |
|
||||
| OpenResty 连接数 | 读瞬时上报 | 最近值 | 节点健康 |
|
||||
| 业务 24h 入出站 | ❌ | 日志聚合 | 统一称「已提供/接收数据」 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 指标与字段模型
|
||||
|
||||
### 6.1 权威字段表(目标)
|
||||
|
||||
#### L1 业务交付(来自访问日志)
|
||||
|
||||
| 概念 | 存储字段 | 聚合 | 展示名 |
|
||||
| --- | --- | --- | --- |
|
||||
| 请求时间 | `logged_at` | 时间窗过滤 | — |
|
||||
| 节点 | `node_id` | group | — |
|
||||
| 客户端 IP | `remote_addr` | `uniq` → UV | 唯一访问者 |
|
||||
| Host | `host` | group / Zone 映射 | 域名 |
|
||||
| 路径 | `path` | 可选 | — |
|
||||
| 状态码 | `status_code` | group | 状态码分布 |
|
||||
| **已提供数据** | **`bytes_sent`** | **`sum`** | **已提供数据** |
|
||||
| **接收数据** | **`request_length`** | **`sum`** | **接收数据**(可选展示) |
|
||||
| 地区 | `region`(Server 解析写入) | group | 来源地区 |
|
||||
|
||||
> 说明:OpenResty `log_format` 中 JSON 键名可继续叫 `bytes_sent`,值必须来自 **`$body_bytes_sent`**(与现网一致),表示响应体交付量,即「已提供数据」。
|
||||
|
||||
#### L2 边缘健康(瞬时,不做 24h 业务总量)
|
||||
|
||||
| 概念 | 字段 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| OpenResty 健康 | `openresty_status` / message | 已有 |
|
||||
| 当前连接 | `openresty_connections` | stub_status |
|
||||
| (可选)近窗 QPS 粗估 | 仅节点详情「此刻」,**不得**作为 24h 总量权威 | 若实现须标明「瞬时」 |
|
||||
|
||||
#### L3 宿主机资源
|
||||
|
||||
| 概念 | 字段 | 展示名 |
|
||||
| --- | --- | --- |
|
||||
| CPU / 内存 / 磁盘占用 | `host_metrics` | 保持 |
|
||||
| 网卡累计字节 | `network_rx_bytes` / `network_tx_bytes` | **宿主机网卡入/出站** |
|
||||
| 磁盘 IO 累计 | `disk_read_bytes` / `disk_write_bytes` | 磁盘读/写 |
|
||||
|
||||
### 6.2 已删除字段(无兼容层)
|
||||
|
||||
| 原字段 | 处置 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| `openresty_tx_bytes` / `openresty_rx_bytes` | **删除** | 业务字节以 access log 为准 |
|
||||
| `TrafficReport` 及 TopN/窗内 UV | **删除** | 边缘预聚合 |
|
||||
| Agent state 内业务 lifetime 累计 | 删除 | 违背 P1 |
|
||||
| Lua shared dict 业务吞吐/窗口请求计数 | 删除 | 非投递主路径 |
|
||||
|
||||
### 6.3 命名对照(前端文案强制)
|
||||
|
||||
| 禁止混用文案 | 正确文案 | 数据来源 |
|
||||
| --- | --- | --- |
|
||||
| OpenResty 出站(指业务量) | **已提供数据** | `sum(bytes_sent)` |
|
||||
| OpenResty 入站(指业务量) | **接收数据** | `sum(request_length)` |
|
||||
| 网络出站(未说明) | **宿主机网卡出站** | `network_tx` 差分 |
|
||||
| 已提供数据 vs 出站 两套卡片 | **只保留一套业务卡片** | 日志 |
|
||||
|
||||
---
|
||||
|
||||
## 7. Agent 设计
|
||||
|
||||
### 7.1 心跳载荷(目标协议)
|
||||
|
||||
保留并强化:
|
||||
|
||||
```text
|
||||
NodePayload
|
||||
identity / version / openresty_status / openresty_message # 最新态 → PG
|
||||
profile # 主机概况(低频)
|
||||
host_metrics # L3 资源读数(含网卡累计原值)
|
||||
edge_health # L2:status + connections(CH 时序;message 不进 CH)
|
||||
access_logs[] # L1 明细(主路径)
|
||||
health_events[]
|
||||
buffered[] # 缓冲的是上述事实,不是报表
|
||||
waf_ip_group_checksums
|
||||
```
|
||||
|
||||
协议中已删除(无兼容层):
|
||||
|
||||
```text
|
||||
traffic_report
|
||||
openresty_observation
|
||||
snapshot / buffered_observability 别名
|
||||
```
|
||||
|
||||
### 7.2 Access log 上报要求
|
||||
|
||||
每条明细至少包含:
|
||||
|
||||
| 字段 | 必填 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| `logged_at_unix` | ✅ | 请求完成时间 |
|
||||
| `remote_addr` | ✅ | UV |
|
||||
| `host` | ✅ | Zone 映射 |
|
||||
| `path` | ✅ | 可截断 |
|
||||
| `status_code` | ✅ | |
|
||||
| `bytes_sent` | ✅ | body 字节,已提供数据 |
|
||||
| `request_length` | ✅ | 接收数据 |
|
||||
|
||||
Agent 职责:
|
||||
|
||||
1. 按 offset tail `access.log`(截断/轮转时重置 offset,**只上报文件中仍存在的新行**)。
|
||||
2. 结构化解析后批量放入心跳 / WS。
|
||||
3. 离线写入本地 buffer,连通后按窗口补传。
|
||||
4. **不对明细做 sum/count/uniq。**
|
||||
|
||||
### 7.3 主机 Snapshot
|
||||
|
||||
* 继续上报网卡/磁盘 **累计计数器原值**(非业务预聚合)。
|
||||
* Server 侧对累计值做相邻采样非负差分 → 宿主机趋势。
|
||||
* 这与「已提供数据」无关,UI 必须分区展示。
|
||||
|
||||
### 7.4 OpenResty 本地观测
|
||||
|
||||
**收敛后建议:**
|
||||
|
||||
* 保留:健康检查、`stub_status` 当前连接。
|
||||
* 删除主路径依赖:`log.lua` 中对 request/status/domain/rx/tx 的 shared dict 业务计数,以及 `/openflare/observability` 作为 TrafficReport 来源。
|
||||
* 若短期内保留 endpoint 供调试,不得再写入 Server 权威分析表。
|
||||
|
||||
### 7.5 与 Agent 设计文档的关系
|
||||
|
||||
本设计强化 [Agent 与发布模型](./agent-design.md) 中的「纯粹数据落地」:
|
||||
|
||||
* 配置与证书:落地与上报应用状态。
|
||||
* 观测:只搬运事实,不搬运业务结论。
|
||||
|
||||
---
|
||||
|
||||
## 8. Server 设计
|
||||
|
||||
### 8.1 入库
|
||||
|
||||
| 输入 | 表 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `access_logs[]` | `of_node_access_logs` | 权威业务明细 |
|
||||
| `host_metrics` | `of_node_metric_snapshots` | L3;网卡/磁盘累计 |
|
||||
| `openresty_status` / `openresty_message` | **PG 节点表** | L2 **最新态权威**(message 仅此) |
|
||||
| `edge_health` | `of_node_edge_health` | L2 时序:status + connections(**无 message**) |
|
||||
|
||||
GeoIP:继续在 Server 入库路径解析 `remote_addr` → `region`,不在 Agent 做。
|
||||
|
||||
### 8.2 聚合层(统一)
|
||||
|
||||
所有业务趋势与 Zone 统计共用同一查询语义:
|
||||
|
||||
```text
|
||||
过滤:logged_at ∈ [since, until]
|
||||
可选:node_id / host IN (...)
|
||||
指标:
|
||||
request_count = count()
|
||||
unique_visitors = uniqExact(remote_addr)
|
||||
bytes_provided = sum(bytes_sent) -- 已提供数据
|
||||
bytes_received = sum(request_length) -- 接收数据
|
||||
按 hour/bucket 折叠 series
|
||||
按 status_code / host / region 分布
|
||||
```
|
||||
|
||||
实现位置:
|
||||
|
||||
* Zone:`GET .../zones/:id/stats`(已有,对齐字段命名)
|
||||
* 看板:overview 的 traffic / 业务网络趋势 **改为调用同一聚合**(全局、无 host 过滤或 Top 过滤)
|
||||
* 节点详情:业务量 = 该 `node_id` 过滤的同一聚合;主机网卡仍走 metric 差分
|
||||
|
||||
### 8.3 派生汇总(可选性能路径)
|
||||
|
||||
当明细查询在 24h 全量节点上过重时,允许 **Server 侧** 物化视图:
|
||||
|
||||
```text
|
||||
of_access_log_hourly
|
||||
(hour, node_id, host, request_count, bytes_sent, bytes_received, ...)
|
||||
```
|
||||
|
||||
约束:
|
||||
|
||||
* 仅由 CH 从 `of_node_access_logs` 派生,**禁止** Agent 直接写该表。
|
||||
* Zone / 看板优先读 rollup,缺口回退明细(与现有 metric hourly 策略类似)。
|
||||
|
||||
### 8.4 停用的分析路径
|
||||
|
||||
| 路径 | 迁移后 |
|
||||
| --- | --- |
|
||||
| `BuildNetworkTrendPoints` 对 openresty_rx/tx 差分 | 删除或仅保留 network_* 主机曲线 |
|
||||
| `of_node_obs_openresty` 吞吐字段 | 停止写入;TTL 过期后删表或缩列 |
|
||||
| `of_node_request_reports` + traffic hourly | 业务趋势不再依赖;可整表废弃 |
|
||||
| Dashboard compact 中 openresty_tx 序列 | 改为 bytes_provided 序列 |
|
||||
|
||||
---
|
||||
|
||||
## 9. API 与前端
|
||||
|
||||
### 9.1 语义统一的响应字段
|
||||
|
||||
建议在业务统计 API 中统一使用:
|
||||
|
||||
```json
|
||||
{
|
||||
"request_count": 0,
|
||||
"unique_visitors": 0,
|
||||
"bytes_provided": 0,
|
||||
"bytes_received": 0,
|
||||
"series": [
|
||||
{
|
||||
"bucket_started_at": "...",
|
||||
"request_count": 0,
|
||||
"unique_visitors": 0,
|
||||
"bytes_provided": 0,
|
||||
"bytes_received": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
API 业务字节字段使用 `bytes_provided` / `bytes_received`(访问日志聚合);不再返回 openresty 吞吐别名。
|
||||
|
||||
### 9.2 看板
|
||||
|
||||
* **业务区**:请求趋势、已提供数据、接收数据(可选)、状态码、Top 域名、来源地区 —— 全部 L1。
|
||||
* **资源区**:CPU/内存、**宿主机网卡**、磁盘 IO —— 全部 L3。
|
||||
* **禁止**:在业务区展示「OpenResty 入/出站」作为与 Zone 对账的指标。
|
||||
|
||||
「24 小时网络与磁盘趋势」建议拆分或改标题:
|
||||
|
||||
* 「24 小时业务流量」→ `bytes_provided` / `bytes_received` / 请求
|
||||
* 「24 小时宿主机网络与磁盘」→ `network_*` / `disk_*`
|
||||
|
||||
### 9.3 Zone `/websites/:id`
|
||||
|
||||
* 保持「已提供的数据总计」等卡片。
|
||||
* 数据与看板业务区 **同一聚合函数**,仅 `hosts = zone 域名列表`。
|
||||
* 文档与 UI 可注明:全局看板含全部 Host;本页仅本 Zone。
|
||||
|
||||
### 9.4 节点详情
|
||||
|
||||
* 业务吞吐:该节点 `sum(bytes_sent)` 等。
|
||||
* OpenResty:健康 + 当前连接。
|
||||
* 网卡:明确「宿主机」。
|
||||
|
||||
---
|
||||
|
||||
## 10. OpenResty 与日志格式
|
||||
|
||||
### 10.1 保持
|
||||
|
||||
现有 JSON `log_format` 核心字段:
|
||||
|
||||
```text
|
||||
ts, host, path, remote_addr, status, request_time,
|
||||
bytes_sent (= $body_bytes_sent), request_length
|
||||
```
|
||||
|
||||
### 10.2 变更
|
||||
|
||||
* 不再依赖 log phase 写入业务 shared dict 计数作为控制面输入。
|
||||
* 观测端口请求继续不写业务统计(或 access_log off)。
|
||||
|
||||
### 10.3 Agent 解析
|
||||
|
||||
* 协议 `NodeAccessLog` 增加 `request_length`。
|
||||
* 旧日志行缺字段时按 0,不阻断整批。
|
||||
|
||||
---
|
||||
|
||||
## 11. 升级与迁移(无兼容层)
|
||||
|
||||
### 11.1 阶段回顾(已落地)
|
||||
|
||||
| 阶段 | 内容 |
|
||||
| --- | --- |
|
||||
| **M1–M5** | 读路径切 access log;协议 v2;停预聚合;edge_health + access_log_hourly;删旧表与 API 兼容字段 |
|
||||
|
||||
### 11.2 升级策略
|
||||
|
||||
* **Agent:销毁重建优先**;允许二进制替换。
|
||||
* 二进制替换时:本地旧观测缓冲(含 `snapshot` / `openresty_observation` / `traffic_report`)**整文件删除**,运行后重建。
|
||||
* Server **不**解析 v1 字段,**不**双读 request_reports / openresty 吞吐。
|
||||
* 明细缺失时段:业务图为空或仅部分;**不得**用网卡或已删除的 openresty 吞吐冒充已提供数据。
|
||||
|
||||
### 11.3 数据回填
|
||||
|
||||
* 历史「已提供数据」以 access log 为准。
|
||||
* `of_access_log_hourly` 创建前历史用 goose 回填 SQL(ANTI JOIN 防重)。
|
||||
|
||||
### 11.4 健康状态权威
|
||||
|
||||
* **当前态**:PG `openresty_status` / `openresty_message`。
|
||||
* **时序**:CH `of_node_edge_health`(status + connections;无 message)。
|
||||
|
||||
### 11.5 UV
|
||||
|
||||
* **整窗独立访客**:`uniqExact(remote_addr)`(看板合计、Zone 合计)。
|
||||
* **分桶 UV**(Zone 曲线):桶内 uniq,**不可跨桶相加**;UI 须标明。
|
||||
* **小时趋势路径**:不绘 / 不填分时 UV(hourly 表不含 UV)。
|
||||
|
||||
---
|
||||
|
||||
## 12. 存储与容量
|
||||
|
||||
* 业务趋势依赖明细或 hourly rollup,需关注 `of_node_access_logs` TTL 与采样。
|
||||
* 若明细量过大:优先 **Server 侧 rollup**,而不是恢复 Agent 预聚合。
|
||||
* 可对 path 高基数场景限制明细 path 长度(已有),聚合默认不按完整 path 做全局 Top。
|
||||
|
||||
---
|
||||
|
||||
## 13. 验证标准
|
||||
|
||||
### 13.1 对账
|
||||
|
||||
在仅有单一 Zone 产生流量的环境:
|
||||
|
||||
```text
|
||||
看板「已提供数据」(24h) ≈ Zone「已提供的数据总计」(24h)
|
||||
误差仅来自时间窗对齐(整点截断)与未计入 Host
|
||||
```
|
||||
|
||||
多 Zone 时:
|
||||
|
||||
```text
|
||||
sum(各 Zone 已提供) + sum(未归属 Host) = 全局已提供
|
||||
```
|
||||
|
||||
### 13.2 回归
|
||||
|
||||
* Agent 单测:只解析与 offset,不出现业务 sum 断言为「上报契约」。
|
||||
* Server:Zone stats 与 dashboard business traffic 共用聚合测例。
|
||||
* 前端:文案快照/测试中不再出现业务含义的「OpenResty 出站」与「已提供数据」双卡片。
|
||||
|
||||
### 13.3 性能
|
||||
|
||||
* 24h 看板聚合 P95 可接受(必要时 hourly MV)。
|
||||
* 心跳 payload 体积:明细批量有上限;超限拆缓冲,不在 Agent 做摘要替代。
|
||||
|
||||
---
|
||||
|
||||
## 14. 风险与权衡
|
||||
|
||||
| 风险 | 缓解 |
|
||||
| --- | --- |
|
||||
| 明细量大导致 CH 与心跳变重 | 批量、压缩、采样策略评估;Server rollup;限制单次条数 |
|
||||
| 短暂丢失日志导致业务量偏低 | 本地 buffer 与轮转处理;监控 access log 采集滞后 |
|
||||
| 用户仍对比「网卡出站」与「已提供」 | UI 分区与文案强制「宿主机」前缀 |
|
||||
| 旧 Agent 长期在线 | **无兼容层**;必须升级/重建 Agent |
|
||||
|
||||
**为何不保留 Agent 预聚合作为优化?**
|
||||
|
||||
* 省带宽的代价是再次分裂真相、口径漂移、本次问题重演。
|
||||
* 优化应落在 Server 派生表与查询,而不是边缘业务计算。
|
||||
|
||||
---
|
||||
|
||||
## 15. 关键决策摘要
|
||||
|
||||
| 决策 | 选择 | 否决方案 |
|
||||
| --- | --- | --- |
|
||||
| 业务流量真相 | 访问日志 | OpenResty dict / TrafficReport |
|
||||
| Agent 角色 | 只上报事实 | 边缘 UV/TopN/吞吐累计 |
|
||||
| 「出站」与「已提供」 | 合并为已提供数据 | 双字段双管道长期并存 |
|
||||
| 网卡流量 | 独立 L3,单独文案 | 与业务出站并列对账 |
|
||||
| 性能 | CH rollup | Agent 预聚合 |
|
||||
| 迁移 | 先切读路径再瘦身 Agent | 先删明细依赖预聚合 |
|
||||
|
||||
---
|
||||
|
||||
## 16. 文档与代码映射(落地时)
|
||||
|
||||
| 区域 | 主要路径 |
|
||||
| --- | --- |
|
||||
| 协议 | `pkg/protocol/agent.go` |
|
||||
| Agent 采集 | `internal/apps/agent/observability/`、`heartbeat/` |
|
||||
| OpenResty 日志与 Lua | `pkg/render/openresty/`、`internal/apps/agent/nginx/observability_assets.go` |
|
||||
| Server 入库 | `internal/apps/openflare/agent/observability.go` |
|
||||
| 日志聚合 | `internal/repository/analytics/node_access_log*.go`、`internal/apps/openflare/zone/stats.go` |
|
||||
| 看板 | `internal/apps/openflare/dashboard/`、`internal/apps/openflare/observability/analytics.go` |
|
||||
| 前端 | `frontend/app/(main)/page.tsx`、`components/dashboard/*`、`websites/.../zone-overview.tsx` |
|
||||
|
||||
实现计划见:`docs/plan/20260717-observability-redesign.md`。
|
||||
|
||||
**推荐阅读顺序:**
|
||||
|
||||
1. **[观测数据传输模型](./observability-transport-model.md)**(最新:传什么、从哪采、频率、示例 JSON)
|
||||
2. [Agent 上报协议与观测落库数据模型](./observability-data-model.md)(协议字段与 DDL)
|
||||
|
||||
---
|
||||
|
||||
## 17. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
| --- | --- |
|
||||
| 2026-07-17 | 初稿:针对双真相、Agent 预聚合、字段冗余给出目标架构与迁移阶段 |
|
||||
| 2026-07-17 | 增补协议/表结构专章链接 `observability-data-model.md` |
|
||||
@@ -0,0 +1,503 @@
|
||||
# 边缘观测数据传输模型(现行目标版)
|
||||
|
||||
> **本文是「Agent ↔ Server 观测数据怎么传」的最新权威说明。**
|
||||
> 读完应能回答:传什么、从哪采、多久采一次、Server 怎么存、产品指标从哪查。
|
||||
> 协议字段与 DDL 细节另见 [观测上报协议与表结构](./observability-data-model.md);问题背景见 [边缘可观测与业务流量统计](./observability-design.md)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 先记住三层(不要混)
|
||||
|
||||
| 层 | 回答的问题 | 唯一数据来源 | 产品例子 |
|
||||
| --- | --- | --- | --- |
|
||||
| **L1 业务交付** | 提供了多少数据?多少请求? | **access.log 明细** | 已提供数据、请求数、UV、状态码、Top 域名 |
|
||||
| **L2 边缘健康** | OpenResty 活着吗?现在多少连接? | **本机 `/openflare/observability`** | 节点健康、当前连接 |
|
||||
| **L3 宿主机资源** | CPU/内存/磁盘/网卡怎样? | **操作系统读数** | 容量趋势、宿主机网卡 |
|
||||
|
||||
**三层互不对账。**
|
||||
「已提供数据」≠「当前连接」≠「宿主机网卡出站」。
|
||||
|
||||
---
|
||||
|
||||
## 1. 总览:谁采集、谁上报、谁聚合
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 边缘节点 │
|
||||
│ │
|
||||
│ 访客请求 ──► OpenResty │
|
||||
│ │ │
|
||||
│ ├─ access.log(每请求一行) ←── L1 采集点 │
|
||||
│ │ │
|
||||
│ └─ 连接状态(进程内维护) │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ GET /openflare/observability ←── L2 读快照 │
|
||||
│ (不扫日志、不重算业务量) │
|
||||
│ │
|
||||
│ 操作系统 /proc 等 ────────────────────── L3 读快照 │
|
||||
│ │
|
||||
│ ┌────────── Agent ──────────┐ │
|
||||
│ │ 默认每 3s 组一包 NodePayload │ │
|
||||
│ │ · tail access.log 增量 │ │
|
||||
│ │ · GET 本机 observability │ │
|
||||
│ │ · 读 host_metrics │ │
|
||||
│ └────────────┬──────────────┘ │
|
||||
└─────────────────────────────│──────────────────────────────────┘
|
||||
│ HTTP 心跳 或 WebSocket status
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Server(控制面) │
|
||||
│ · 明细 → ClickHouse of_node_access_logs │
|
||||
│ · 健康 → 节点最新态 + of_node_edge_health │
|
||||
│ · 主机 → of_node_metric_snapshots │
|
||||
│ · 业务趋势 / Zone 统计 = 只对 access_logs 做 sum/count/uniq │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
| 角色 | 做什么 | 不做什么 |
|
||||
| --- | --- | --- |
|
||||
| OpenResty | 写 access.log;维护连接数 | 不向控制面直接上报 |
|
||||
| Agent | **采集事实并上报** | **不算** UV/TopN/24h 已提供数据 |
|
||||
| Server | 入库 + **聚合解释** | 不信任边缘业务预汇总 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 采集频率(默认)
|
||||
|
||||
| 动作 | 默认频率 | 配置 |
|
||||
| --- | --- | --- |
|
||||
| Agent → Server 上报 | **每 3 秒** 一次完整 payload | `heartbeat_interval` / 控制面 `agent_heartbeat_interval`(毫秒,默认 `3000`) |
|
||||
| 组包时 tail access.log | **随上报**(两次上报之间的新行) | 同上 |
|
||||
| 组包时 GET `/openflare/observability` | **随上报**(读**当前**连接快照) | 同上 |
|
||||
| 组包时读主机指标 | **随上报** | 同上 |
|
||||
| OpenResty 写 access.log | **每个请求结束时** 1 行 | 与心跳无关 |
|
||||
| 连接数在进程内更新 | **连接变化时**(内核维护) | 与心跳无关 |
|
||||
| 离线补传窗口 | 默认保留约 **60 分钟** | `observability_replay_minutes` |
|
||||
| 节点离线判定 | 约 **60 秒** 无成功心跳 | `node_offline_threshold`(默认 `60000` 毫秒) |
|
||||
|
||||
**说明:**
|
||||
|
||||
- Agent **没有**单独的「采样时钟」;**采样点 = 上报点**(默认 3s)。
|
||||
- access.log 是「请求级连续写入」;Agent 只是周期性 **搬运增量行**。
|
||||
- `/openflare/observability` **不是**「被调用才开始统计业务」;对连接而言是 **读 Nginx 已有瞬时值**。
|
||||
|
||||
传输通道:
|
||||
|
||||
- **HTTP 心跳**:按间隔 POST 整包。
|
||||
- **WebSocket**:连通后按同一间隔发 `status` 消息(内容同构);此时不再走 HTTP 心跳双发。
|
||||
|
||||
---
|
||||
|
||||
## 3. Agent → Server 数据包(NodePayload v2)
|
||||
|
||||
### 3.1 结构骨架
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 2,
|
||||
"node_id": "n_01hxyz",
|
||||
"name": "edge-shanghai-1",
|
||||
"ip": "203.0.113.10",
|
||||
"version": "3.4.0",
|
||||
"ext_version": "",
|
||||
"current_version": "20260718-abc",
|
||||
"last_error": "",
|
||||
"profile": { },
|
||||
"host_metrics": { },
|
||||
"edge_health": { },
|
||||
"access_logs": [ ],
|
||||
"buffered": [ ],
|
||||
"health_events": [ ],
|
||||
"waf_ip_group_checksums": { }
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 层 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| 身份/版本/last_error | 控制 | 节点是谁、跑什么版本 |
|
||||
| `profile` | 低频概况 | 主机名、核数等(变化才报) |
|
||||
| `access_logs` | **L1** | 访问明细增量 |
|
||||
| `edge_health` | **L2** | OpenResty 健康 + 当前连接 |
|
||||
| `host_metrics` | **L3** | CPU/内存/磁盘/网卡读数 |
|
||||
| `buffered` | 补传 | 离线期间攒的事实批次 |
|
||||
| `health_events` | 事件 | 如 openresty_unhealthy |
|
||||
| `waf_ip_group_checksums` | 同步 | 非观测湖 |
|
||||
|
||||
**协议已删除(无兼容层,旧 Agent 必须升级):**
|
||||
|
||||
- `traffic_report`
|
||||
- `openresty_observation`(含 rx/tx)
|
||||
- `snapshot` / `buffered_observability`
|
||||
- 业务含义的 openresty 吞吐字段
|
||||
|
||||
---
|
||||
|
||||
## 4. L1 业务:access_logs
|
||||
|
||||
### 4.1 采集从哪里来
|
||||
|
||||
| 步骤 | 位置 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 1 | OpenResty `log_format openflare_json` | 每请求写一行 JSON 到 `access_log_path` |
|
||||
| 2 | Agent 按文件 offset **tail 增量** | 两次心跳之间的新行 |
|
||||
| 3 | 解析后放入 `access_logs[]` | 可截断过长 path;**不做 sum/count** |
|
||||
|
||||
日志格式(OpenResty 变量):
|
||||
|
||||
```text
|
||||
ts ← $time_iso8601
|
||||
host ← $host
|
||||
path ← $request_uri
|
||||
remote_addr ← $remote_addr
|
||||
status ← $status
|
||||
request_time ← $request_time
|
||||
bytes_sent ← $body_bytes_sent 【已提供数据 = 响应体字节】
|
||||
request_length← $request_length 【接收数据】
|
||||
user_agent ← $http_user_agent
|
||||
cache_status ← $upstream_cache_status 【缓存状态;UI 可推导命中/回源/未缓存】
|
||||
```
|
||||
|
||||
观测端口请求 **不写** 业务 access.log(独立 server `access_log off`)。
|
||||
|
||||
### 4.2 上报示例
|
||||
|
||||
```json
|
||||
"access_logs": [
|
||||
{
|
||||
"logged_at_unix": 1721289601,
|
||||
"remote_addr": "198.51.100.20",
|
||||
"host": "www.example.com",
|
||||
"path": "/api/v1/ping",
|
||||
"status_code": 200,
|
||||
"bytes_sent": 1024,
|
||||
"request_length": 128,
|
||||
"request_time_ms": 15,
|
||||
"user_agent": "curl/8.0",
|
||||
"cache_status": "MISS"
|
||||
},
|
||||
{
|
||||
"logged_at_unix": 1721289602,
|
||||
"remote_addr": "198.51.100.21",
|
||||
"host": "www.example.com",
|
||||
"path": "/index.html",
|
||||
"status_code": 200,
|
||||
"bytes_sent": 8192,
|
||||
"request_length": 300,
|
||||
"request_time_ms": 8,
|
||||
"user_agent": "Mozilla/5.0",
|
||||
"cache_status": "HIT"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
| 字段 | 解释 |
|
||||
| --- | --- |
|
||||
| `bytes_sent` | **已提供数据**(单请求);全局/Zone 合计 = Server `sum` |
|
||||
| `request_length` | **接收数据**(单请求) |
|
||||
| `logged_at_unix` | 请求完成时间(业务时间轴) |
|
||||
| `host` | 用于 Zone 域名过滤 |
|
||||
| `cache_status` | `$upstream_cache_status` 原样;详情/列表可推导三态(命中/回源/未缓存);**不上报** upstream 地址 |
|
||||
| 无 `region` | **Server 入库时** GeoIP 写入 |
|
||||
|
||||
### 4.3 Server 如何用(产品指标)
|
||||
|
||||
| 产品指标 | 算法(仅 L1) |
|
||||
| --- | --- |
|
||||
| 已提供数据 | `sum(bytes_sent)` |
|
||||
| 接收数据 | `sum(request_length)` |
|
||||
| 请求数 | `count()` |
|
||||
| UV | `uniqExact(remote_addr)` |
|
||||
| 状态码分布 | `group by status_code` |
|
||||
| Top 域名 | `group by host` |
|
||||
| Zone 页 | 同上 + `host IN (该 Zone 域名)` |
|
||||
| 看板业务区 | 同上,全局或 Top 过滤 |
|
||||
|
||||
落库表:`of_node_access_logs`(可选 Server 侧 `of_access_log_hourly` 加速,**Agent 不写**)。
|
||||
|
||||
### 4.4 频率再强调
|
||||
|
||||
```text
|
||||
请求发生 ──立即──► 写 access.log
|
||||
Agent 每 3s ──搬运──► 这 3s 内新行(可能 0 行,也可能很多行)
|
||||
Server ──立即/批量──► CH
|
||||
```
|
||||
|
||||
业务量正确性 **不依赖** 3s 对齐;3s 只影响「明细到达控制面的延迟」和单包条数。
|
||||
|
||||
---
|
||||
|
||||
## 5. L2 健康:edge_health 与 `/openflare/observability`
|
||||
|
||||
### 5.1 本机监测口(合并后目标)
|
||||
|
||||
**只保留一个接口:**
|
||||
|
||||
```http
|
||||
GET http://127.0.0.1:{openresty_observability_port}/openflare/observability
|
||||
```
|
||||
|
||||
默认端口:**18081**(`openresty_observability_port`)。
|
||||
|
||||
**职责:** 回答「OpenResty 此刻怎样」,**不**回答业务已提供多少数据。
|
||||
|
||||
#### 返回示例(目标 JSON)
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"captured_at_unix": 1721289600,
|
||||
"connections": {
|
||||
"active": 42,
|
||||
"reading": 0,
|
||||
"writing": 1,
|
||||
"waiting": 41
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 是否瞬时 | 从哪来 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `ok` | 当次探测 | 能返回 200 即 true | 探活 |
|
||||
| `captured_at_unix` | 采样时刻 | `ngx.time()` | 与上报对齐 |
|
||||
| `connections.active` | **瞬时** | Nginx 连接状态(原 stub_status Active) | 当前活跃连接 |
|
||||
| `reading` / `writing` / `waiting` | **瞬时** | 同上细分 | 可选但建议带 |
|
||||
|
||||
**不返回(已从目标模型删除):**
|
||||
|
||||
| 旧字段 | 原因 |
|
||||
| --- | --- |
|
||||
| `request_count` / `error_count` / UV / status_codes / top_domains | 业务窗汇总,改由 access log |
|
||||
| `openresty_rx_bytes` / `openresty_tx_bytes` | 与已提供/接收数据重复且易错 |
|
||||
| `source_countries` | 从未实现;国家走 Server GeoIP |
|
||||
| `server.accepts/handled/requests` | 进程累计 counter,易与业务请求混淆;主路径不收录 |
|
||||
|
||||
**`/openflare/stub_status`:** 合并进上述 JSON 后 **删除**(过渡期可双挂,Agent 只打合并口)。
|
||||
|
||||
### 5.2 采集机制(读快照,不是「调用才开始统计业务」)
|
||||
|
||||
```text
|
||||
Nginx 在连接建立/释放时维护 Active connections 等
|
||||
│
|
||||
Agent GET /openflare/observability
|
||||
│
|
||||
只读取「当前值」拼 JSON 返回
|
||||
```
|
||||
|
||||
- **不是** GET 一次才去扫 access.log。
|
||||
- **不是** 60 秒业务均值。
|
||||
- 是 **瞬时 gauge 快照**。
|
||||
|
||||
### 5.3 上报示例(装进 NodePayload)
|
||||
|
||||
```json
|
||||
"edge_health": {
|
||||
"captured_at_unix": 1721289600,
|
||||
"status": "healthy",
|
||||
"message": "",
|
||||
"connections": 42
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 来源 |
|
||||
| --- | --- |
|
||||
| `status` / `message` | Agent 健康探测(配置校验/进程等,可与观测口 `ok` 配合);须与顶层 `openresty_status` / `openresty_message` 对齐 |
|
||||
| `connections` | 观测口 `connections.active` |
|
||||
|
||||
**落库拆分(权威源):**
|
||||
|
||||
| 内容 | 写入 |
|
||||
| --- | --- |
|
||||
| 最新 `status` + `message` | **PG 节点表**(UI / 列表 / 告警) |
|
||||
| 时序 `status` + `connections` | **CH `of_node_edge_health`**(**无 message**) |
|
||||
|
||||
---
|
||||
|
||||
## 6. L3 主机:host_metrics
|
||||
|
||||
### 6.1 采集从哪里来
|
||||
|
||||
Agent 读本机(如 `/proc`、磁盘统计等),**每次组包时读一次**。
|
||||
|
||||
| 字段 | 语义 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `cpu_usage_percent` | 瞬时 | 当前 CPU% |
|
||||
| `memory_*` / `storage_*` | 瞬时用量/总量 | 占用率在 Server 或展示层算 |
|
||||
| `disk_read_bytes` / `disk_write_bytes` | **累计 counter** | 内核累计 IO |
|
||||
| `network_rx_bytes` / `network_tx_bytes` | **累计 counter** | **宿主机网卡**,不是已提供数据 |
|
||||
|
||||
### 6.2 上报示例
|
||||
|
||||
```json
|
||||
"host_metrics": {
|
||||
"captured_at_unix": 1721289600,
|
||||
"cpu_usage_percent": 12.5,
|
||||
"memory_used_bytes": 4294967296,
|
||||
"memory_total_bytes": 16106127360,
|
||||
"storage_used_bytes": 50000000000,
|
||||
"storage_total_bytes": 107374182400,
|
||||
"disk_read_bytes": 9000000000,
|
||||
"disk_write_bytes": 12000000000,
|
||||
"network_rx_bytes": 500000000000,
|
||||
"network_tx_bytes": 800000000000
|
||||
}
|
||||
```
|
||||
|
||||
### 6.3 Server 如何处理累计字段
|
||||
|
||||
```text
|
||||
存原值时间序列
|
||||
展示「这段时间网卡出站」时:
|
||||
delta = 本次 - 上次
|
||||
若 delta < 0 → 视为重启/计数器归零,本段增量记 0,从新基线继续
|
||||
若 delta >= 0 → 记入该时段增量
|
||||
```
|
||||
|
||||
- Agent **上报原值**,不在边缘算 24h 总量。
|
||||
- **禁止** 对累计原值做 `sum` 当业务量。
|
||||
- 文案必须是 **「宿主机网卡」**,禁止叫「已提供数据 / OpenResty 出站」。
|
||||
|
||||
落库:`of_node_metric_snapshots`(可选 capacity hourly MV)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 一次完整上报示例(拼起来)
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": 2,
|
||||
"node_id": "n_01hxyz",
|
||||
"name": "edge-shanghai-1",
|
||||
"ip": "203.0.113.10",
|
||||
"version": "3.4.0",
|
||||
"ext_version": "",
|
||||
"current_version": "20260718-abc",
|
||||
"last_error": "",
|
||||
"host_metrics": {
|
||||
"captured_at_unix": 1721289600,
|
||||
"cpu_usage_percent": 12.5,
|
||||
"memory_used_bytes": 4294967296,
|
||||
"memory_total_bytes": 16106127360,
|
||||
"storage_used_bytes": 50000000000,
|
||||
"storage_total_bytes": 107374182400,
|
||||
"disk_read_bytes": 9000000000,
|
||||
"disk_write_bytes": 12000000000,
|
||||
"network_rx_bytes": 500000000000,
|
||||
"network_tx_bytes": 800000000000
|
||||
},
|
||||
"edge_health": {
|
||||
"captured_at_unix": 1721289600,
|
||||
"status": "healthy",
|
||||
"message": "",
|
||||
"connections": 42
|
||||
},
|
||||
"access_logs": [
|
||||
{
|
||||
"logged_at_unix": 1721289595,
|
||||
"remote_addr": "198.51.100.20",
|
||||
"host": "www.example.com",
|
||||
"path": "/",
|
||||
"status_code": 200,
|
||||
"bytes_sent": 4096,
|
||||
"request_length": 200,
|
||||
"request_time_ms": 12
|
||||
}
|
||||
],
|
||||
"buffered": [],
|
||||
"health_events": [],
|
||||
"waf_ip_group_checksums": {
|
||||
"1": "d41d8cd98f00b204e9800998ecf8427e"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Server 落库示意:**
|
||||
|
||||
| payload 块 | 写入 |
|
||||
| --- | --- |
|
||||
| `access_logs[0]` | CH 一行,`bytes_sent=4096`,`region` 由 GeoIP 填 |
|
||||
| `edge_health` | 节点 `openresty_status=healthy`,connections=42 |
|
||||
| `host_metrics` | CH metric 一行累计/瞬时字段 |
|
||||
|
||||
**产品查询示意(24h):**
|
||||
|
||||
- 已提供数据 = 该节点(或全局)日志 `sum(bytes_sent)`
|
||||
- 当前连接 = 最新 `edge_health.connections`
|
||||
- 宿主机网卡出站 = metric 上 `network_tx` 非负差分之和
|
||||
|
||||
三者数字 **不必相等**。
|
||||
|
||||
---
|
||||
|
||||
## 8. 离线补传 `buffered`
|
||||
|
||||
Agent 上报失败时,把 **同一类事实** 按窗口缓存在本地(默认约 60 分钟),恢复后塞进 `buffered[]`:
|
||||
|
||||
```json
|
||||
"buffered": [
|
||||
{
|
||||
"captured_at_unix": 1721289500,
|
||||
"host_metrics": { },
|
||||
"edge_health": { },
|
||||
"access_logs": [ ]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 只装事实,不装旧 TrafficReport。
|
||||
- Server 处理逻辑与主字段相同。
|
||||
|
||||
---
|
||||
|
||||
## 9. 端到端时序(默认 3s)
|
||||
|
||||
```text
|
||||
t=0.0s 访客请求完成 → 写 access.log 一行;连接数可能变化
|
||||
t=0.1s 又一请求 → 又一行 log
|
||||
…
|
||||
t=3s Agent 心跳:
|
||||
· 读走 2 行 access_logs
|
||||
· GET observability → connections=42
|
||||
· 读 host_metrics
|
||||
· 发给 Server
|
||||
t=3s+ Server 入库;看板/Zone 查询时聚合日志
|
||||
t=6s 下一轮…
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 旧模型对照(帮助消歧)
|
||||
|
||||
| 旧做法 | 新模型 |
|
||||
| --- | --- |
|
||||
| Lua dict 60s 窗 request_count + Agent 10s 拉 + Server sum | **删除**;请求数 = 日志 count |
|
||||
| openresty_tx 当「出站」 | **删除**;已提供数据 = `sum(bytes_sent)` |
|
||||
| 两个口 observability + stub_status | **合并为一个** observability,只返回连接/探活 |
|
||||
| TrafficReport 预聚合 | **删除**;协议与 API 均无此路径 |
|
||||
| 业务与网卡混称「流量」 | **分文案、分 API、分表** |
|
||||
| 健康 status/message | **PG 最新态权威**;CH 仅 status+连接时序 |
|
||||
|
||||
---
|
||||
|
||||
## 11. 配置与实现索引
|
||||
|
||||
| 项 | 位置/键 |
|
||||
| --- | --- |
|
||||
| 心跳间隔 | Agent `heartbeat_interval`;控制面 `agent_heartbeat_interval`(默认 3000ms) |
|
||||
| 离线阈值 | 控制面 `node_offline_threshold`(默认 60000ms) |
|
||||
| 观测端口 | `openresty_observability_port`(默认 18081) |
|
||||
| access.log 路径 | `access_log_path` |
|
||||
| 补传分钟数 | `observability_replay_minutes`(默认 60) |
|
||||
| 协议类型 | `pkg/protocol/agent.go`(落地时按 v2 演进) |
|
||||
| 表结构 DDL | [observability-data-model.md](./observability-data-model.md) |
|
||||
|
||||
---
|
||||
|
||||
## 12. 修订记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
| --- | --- |
|
||||
| 2026-07-18 | 初稿:作为「最新传输模型」单页说明——三层、频率、示例 JSON、采集来源、与旧模型对照 |
|
||||
| 2026-07-18 | 默认上报间隔 3s;离线阈值 60s;补传窗口 60 分钟 |
|
||||
| 2026-07-18 | M5:edge_health 表、access_log_hourly、废弃 request_reports/obs_openresty 吞吐表 |
|
||||
| 2026-07-18 | 无兼容层:删除「兼容期可忽略」表述;健康 message 仅 PG、CH 无 message |
|
||||
+45
-27
@@ -19,11 +19,12 @@
|
||||
## 核心功能
|
||||
|
||||
Pages 静态托管子系统包含以下核心能力:
|
||||
* **Direct Upload 部署模式**:支持直接上传预构建的 `.zip` 静态资源包,省去复杂的 Git 集成和构建环境依赖。
|
||||
* **不可变部署快照**:每次上传产生一个带唯一 ID 和 SHA-256 Checksum 的不可变部署记录。历史包永久保留,支持随时激活和回滚。
|
||||
* **Direct Upload 部署模式**:支持直接上传预构建的静态资源压缩包(`zip`、`tar.gz`、`tar.xz`、`tar.bz2`、`tar`、`7z`),或填写 URL 由控制面代为下载导入(允许内网地址与自签证书),省去复杂的 Git 集成和构建环境依赖。
|
||||
* **不可变部署快照**:每次上传产生一个带唯一 ID 和 SHA-256 Checksum 的不可变部署记录。支持按系统配置保留最近 N 个历史部署,并可随时激活和回滚。
|
||||
* **SPA Fallback 支持**:支持对单页应用(SPA)进行 Fallback 路由配置,请求找不到静态文件时自动重定向到入口文件。
|
||||
* **内置 API 反代服务**:支持在 Pages 规则内一键启用 API 代理,消除跨域问题,将请求转发给指定的后端服务。
|
||||
* **安全包校验与解压缩**:内置 Zip-Slip 路径逃逸防御、防软链接劫持、文件大小/数量硬上限控制,保障节点物理安全。
|
||||
* **安全包校验与解压缩**:内置路径逃逸防御、防软链接劫持、文件大小/数量上限与可配置上传包体积控制,保障节点物理安全。
|
||||
* **可配置限额**:管理员可在运维设置中调整「部署包大小上限」与「历史部署保留数」。
|
||||
|
||||
---
|
||||
|
||||
@@ -40,7 +41,7 @@ graph TD
|
||||
|
||||
%% 控制流与心跳
|
||||
Server[OpenFlare Server 控制面] <-->|Agent API / Heartbeat| Agent[openflare-agent 进程]
|
||||
Server -.->|5. 存储 ZIP 部署包| LocalStore[(Server 本地存储)]
|
||||
Server -.->|5. 存储部署包| LocalStore[(Server 本地存储)]
|
||||
|
||||
Agent -->|1. 发现新版本| Server
|
||||
Agent -->|2. 下载部署包| Server
|
||||
@@ -65,7 +66,9 @@ graph TD
|
||||
* **Pages 部署 (`pages_deployments`)**:
|
||||
* 记录单次上传生成的不可变快照。包含:部署号 (DeploymentNumber, 递增序列)、SHA-256 Checksum 校验和、部署状态 (uploaded/active)、部署包的本地存储路径、解压后的文件数与总字节数。
|
||||
* **部署文件清单 (`pages_deployment_files`)**:
|
||||
* 存储每次部署的完整静态文件树路径、文件大小及单个文件哈希。用于审计和后续校验。
|
||||
* 存储每次部署的完整静态文件树路径与文件大小(来自压缩包声明的未压缩大小),供控制台展示与统计。
|
||||
* 不再为包内每个文件计算内容哈希;完整性由**整包** SHA-256(`pages_deployments.checksum`)保证,Agent 拉取时只校验整包 hash。
|
||||
* 控制面 inspect 通过文件句柄 / 随机访问读取归档索引(zip/7z 中央目录;tar 流式读 header 并丢弃 body),避免将整包 `ReadFile` 进内存,也避免逐文件解压算 hash。
|
||||
|
||||
### 2. 路由关联与快照
|
||||
`proxy_routes` 路由规则通过 `upstream_type = "pages"` 及 `pages_project_id` 关联 Pages 项目。当路由类型为 `pages` 且该项目存在已激活的部署时,才允许将该路由加入发布流程。
|
||||
@@ -88,21 +91,36 @@ graph TD
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 与主配置版本的双轨关系(项目锚点 + latest 拉取)
|
||||
* **主配置版本**与 **Pages 部署** 是两套独立的版本体系。
|
||||
* 主配置中 Pages 路由的稳定锚点是 **`pages_project_id`(项目 ID)**,不是某次部署 ID。
|
||||
* OpenResty `root` 使用项目级路径:`__OPENFLARE_PAGES_DIR__/projects/{project_id}/current`,激活切换时路径不变,无需为换包而重发主配置。
|
||||
* Agent 按项目请求「最新激活包」(类似 `github/release/latest`):
|
||||
* `GET /api/v1/agent/pages/projects/:project_id/latest/hash`
|
||||
* `GET /api/v1/agent/pages/projects/:project_id/latest/package`
|
||||
* 控制面根据该项目**当前激活部署**返回哈希与压缩包;Agent 不关心具体 deployment_id。
|
||||
* 因此:在项目内切换激活部署后,**不必发布主配置**;Agent 在周期性对账时轮询 latest hash,发现变化即下载并切换 `current`。
|
||||
* 快照中的 `pages_deployment` 字段仍可记录发布时元数据(入口文件、SPA/API 代理等),但不作为 Agent 拉包的版本锁定。
|
||||
|
||||
---
|
||||
|
||||
## Server 端 (控制面) 职责与生命周期
|
||||
|
||||
### 1. ZIP 包安全校验与分析
|
||||
为了避免不可信的用户上传恶意压缩包攻击服务器,控制面在 `UploadPagesDeployment` 时执行严格的流式校验:
|
||||
* **大小限制**:ZIP 压缩包不得超过 25 MiB(保守的 V1 默认值),且展开后的解压总体积不得超过 100 MiB。
|
||||
### 1. 部署包安全校验与分析
|
||||
为了避免不可信的用户上传恶意压缩包攻击服务器,控制面在 `UploadDeployment` 时执行严格校验:
|
||||
* **格式支持**:`zip`、`tar.gz` / `tgz`、`tar.xz` / `txz`、`tar.bz2` / `tbz2`、`tar`、`7z`。
|
||||
* **大小限制**:压缩包体积由系统配置 `pages_max_package_size_mb` 控制(默认 100 MiB,范围 1~2048);展开后总体积上限为「包大小 × 4」且不低于 100 MiB(按归档**声明**的未压缩大小累计,默认不流式重读每个文件内容)。
|
||||
* **数量限制**:压缩包中包含的静态文件总数不得超过 1,000 个。
|
||||
* **软链接阻断**:遍历 ZIP 文件,一旦检测到任何软链接 (`os.ModeSymlink`),立即抛出错误并拒绝上传,防御软链接劫持攻击。
|
||||
* **Zip-Slip 防御**:对每个压缩文件路径进行 `Clean` 并检查是否包含 `..` 或以 `/` 开头,防御目录跨越漏洞,防止写入系统敏感路径。
|
||||
* **入口文件校验**:项目指定的入口文件(例如 `index.html`,可在 `project.RootDir` 下)必须在 ZIP 压缩包中存在,否则拒绝上传。
|
||||
* **公共根目录去噪**:许多打包工具(如 GitHub 导出的 zip)会包含一个多余的主文件夹作为公共根前缀。控制面自动探测公共根前缀并将其安全剥离。
|
||||
* **软链接阻断**:遍历归档文件,一旦检测到任何软链接,立即抛出错误并拒绝上传,防御软链接劫持攻击。
|
||||
* **路径逃逸防御**:对每个压缩文件路径进行 `Clean` 并检查是否包含 `..` 或以 `/` 开头,防御目录跨越漏洞,防止写入系统敏感路径。
|
||||
* **入口文件校验**:项目指定的入口文件(例如 `index.html`,可在 `project.RootDir` 下)必须在部署包中存在,否则拒绝上传。
|
||||
* **公共根目录去噪**:许多打包工具会包含一个多余的主文件夹作为公共根前缀。控制面自动探测公共根前缀并将其安全剥离。
|
||||
* **整包完整性**:上传/导入时对压缩包字节计算一次 SHA-256,写入部署记录;Agent 拉包后按整包 hash 对账。包内单文件不做内容哈希。
|
||||
* **可选体积实测**:`InspectOptions.VerifySizes` 可对流式统计实际字节并与声明大小比对(仍不算 hash);默认关闭以降低上传 CPU/IO。
|
||||
* **历史保留**:系统配置 `pages_max_history_count`(默认 20,0 表示不限制)在每次上传成功后执行裁剪。语义为:**每个项目最多保留 N 条部署**;当前激活部署始终保留;其余名额按部署 ID 从新到旧填充;超出的非激活部署连同文件清单与存储对象一并删除。上传已成功时裁剪失败只记日志、不回滚上传;并发上传下可能短暂超过 N,后续上传的裁剪会收敛回 N。主配置版本回滚不依赖旧 Pages 包(见上节双轨关系)。
|
||||
|
||||
### 2. 部署包存储规划
|
||||
控制面仅将 zip 文件存储在本地存储目录 `artifacts/{project_slug}/{checksum}.zip`,并在数据库中记录路径和清单。**大体积静态包不写入 config_versions 记录和任何配置推送通道**,以保障控制面数据同步的轻量与高效。
|
||||
控制面通过统一上传框架(`upload.Ingest`)存储原始部署包,并在数据库中记录 `upload_id` 与文件清单。**大体积静态包不写入 config_versions 记录和任何配置推送通道**,以保障控制面数据同步的轻量与高效。
|
||||
|
||||
---
|
||||
|
||||
@@ -110,19 +128,19 @@ graph TD
|
||||
|
||||
Agent 运行在各边缘代理节点上,在应用配置版本前,必须先将 Pages 静态资源“原子”地拉取到节点本地。
|
||||
|
||||
### 1. 校验式增量拉取
|
||||
1. Agent 解析激活配置中的 `SourceConfigJSON`,检索出所有 `UpstreamType == "pages"` 的路由引用的部署 `DeploymentID` 和 `Checksum`。
|
||||
2. 检查本地部署目录是否存在正确的版本标记文件 `.openflare-pages.json`,且 `Checksum` 匹配。
|
||||
3. 若不匹配,通过专属接口 `GET /api/agent/pages/deployments/:id/package` 下载对应的部署包。下载请求头必须携带节点独有的 `X-Agent-Token` 用于 Server 鉴权。
|
||||
### 1. 按项目拉取 latest
|
||||
1. Agent 从激活主配置中解析 `UpstreamType == "pages"` 的路由,收集稳定锚点 **`pages_project_id`**。
|
||||
2. 对每个项目调用 `GET /api/v1/agent/pages/projects/:project_id/latest/hash` 获取控制面当前激活包哈希(类似 latest 指针)。
|
||||
3. 若本地 `projects/{project_id}/releases/{hash}` 尚未就绪,再下载 `.../latest/package`。下载后 **再次请求 hash** 与包内容 SHA-256 对齐,避免激活切换造成的竞态;不一致则有限次重试。
|
||||
4. 请求头携带节点 `X-Agent-Token`。
|
||||
|
||||
### 2. 安全解压缩与原子切换
|
||||
为了保证配置应用过程的“无缝”且能在出错时立即回滚:
|
||||
1. Agent 将下载的部署包数据写入临时目录,并重新计算 SHA-256 Checksum。如果与配置指明的 checksum 不符,立即报错并阻断发布流程。
|
||||
2. 解压部署包至临时目录 `releases/{checksum}.tmp`。解压时同样执行 Zip-Slip 目录跨越和软链接校验防御。
|
||||
3. 解压成功后,写入标记文件 `.openflare-pages.json`。
|
||||
4. 清理 `releases/{checksum}` 目录,将整个临时目录重命名为 `releases/{checksum}`。
|
||||
5. **原子切换**:建立拷贝当前部署的物理副本到目标位置 `deployments/{deployment_id}/current`。切换前先备份上一版本的 `current`,一旦重载配置失败,Agent 能够快速恢复 `current` 目录并回滚 OpenResty。
|
||||
6. **定时清理**:每次配置成功应用后,Agent 自动比对本地部署目录,将所有不活跃的(即未被当前激活版本引用的)历史部署包和文件夹进行物理删除,释放磁盘空间。
|
||||
### 2. 安全解压缩、原子切换与只保留最新
|
||||
1. 下载字节计算 SHA-256,须与「下载后再次查询」的 latest hash 一致。
|
||||
2. 解压至 `projects/{project_id}/releases/{hash}.tmp`(支持 zip / tar.* / 7z)。Agent 信任控制面业务校验,仅做路径逃逸/软链防护。
|
||||
3. 写入 `.openflare-pages.json` 后 rename 为 `releases/{hash}`。
|
||||
4. **原子切换** `projects/{project_id}/current` 指向新 release(优先 symlink,失败则拷贝)。
|
||||
5. **仅当新包已就绪且 current 切换成功后**,删除该项目下其它 `releases/*`(含 `.tmp`),**不保留历史部署包**。边缘节点每个项目永远只保留一份最新内容。
|
||||
6. 多项目对账时 **隔离失败**:单个项目失败记日志并继续其它项目,最后汇总返回错误。
|
||||
|
||||
---
|
||||
|
||||
@@ -132,13 +150,13 @@ Agent 运行在各边缘代理节点上,在应用配置版本前,必须先
|
||||
|
||||
### 1. 静态服务指令渲染
|
||||
* **`root` 与 `index`**:
|
||||
Server 根据配置将 `root` 指向 Agent 的 Pages 动态目录占位符 `__OPENFLARE_PAGES_DIR__/deployments/{deployment_id}/current`,并在此基础上追加项目的 `RootDir`。`index` 指向设置的入口文件。
|
||||
Server 将 `root` 指向项目级占位路径 `__OPENFLARE_PAGES_DIR__/projects/{project_id}/current`(可再追加 `RootDir`)。激活切换只换目录内容,路径不变,无需为换包重发主配置。
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name myapp.example.com;
|
||||
|
||||
root "/var/lib/openflare/pages/deployments/12/current";
|
||||
root "/var/lib/openflare/pages/projects/3/current";
|
||||
index "index.html";
|
||||
...
|
||||
}
|
||||
|
||||
+8
-123
@@ -1,130 +1,15 @@
|
||||
# WAF 设计文档
|
||||
# WAF 设计
|
||||
|
||||
你会学到:OpenFlare 边缘 Web 应用防火墙(WAF)的核心架构、动态 IP 组异步差分同步模型、OpenResty Lua 高性能缓存方案以及完整的请求过滤与判定逻辑。
|
||||
OpenFlare WAF 的现行规则模型是可视化 DAG。节点语义、图约束、多规则顺序、发布编译与迁移边界统一以 [WAF 可编排规则设计](./waf-orchestration-design.md) 为准。
|
||||
|
||||
---
|
||||
## 系统边界
|
||||
|
||||
## 需求分析
|
||||
Server 保存带坐标和修订号的编辑图,发布时再次校验并编译为紧凑运行图;Agent 原子写入快照并 reload OpenResty;请求热路径只遍历 Worker 内存中的不可变图。
|
||||
|
||||
在互联网公开环境中,Web 应用程序面临着各种各样的安全威胁(如扫描器踩点、刷接口、针对特定地域的恶意网络爬虫、勒索攻击及 CC 攻击等)。如果直接把恶意请求放行给源站(Origin Server),会导致:
|
||||
1. **源站负载飙升**:高频的数据库查询与 CPU 运算极易耗尽服务器资源。
|
||||
2. **敏感接口被刷**:登录、注册、短信验证码接口容易被恶意滥用导致财产损失。
|
||||
3. **数据泄露风险**:恶意的通用漏洞探测行为无法被提前拦截。
|
||||
IP 组独立于规则拓扑更新。手动、订阅和自动 IP 组由控制面维护,Agent 先原子替换 JSON、最后更新 checksum。协调 Worker 每 5 秒检查 checksum,仅变化时读取完整快照并分发给其它 Worker;失败时保留上一份有效数据。完整运行时快照上限为 20 MiB,Server 发布/同步与 Agent 落盘使用同一序列化校验;OpenResty 使用独立的 64 MiB 共享字典和非淘汰写入,容量不足时拒绝新版本而不破坏已提交快照。
|
||||
|
||||
因此,OpenFlare 需要在最前端的数据面(OpenResty)构建一套 **高性能、可弹性伸缩的 WAF 过滤引擎**。该引擎能够在最接近用户的边缘层以毫秒级的极低开销对恶意请求进行深度过滤,减轻源站压力,并提供防 CC(PoW 挑战)、IP 黑白名单与地域级别拦截等核心安全防护能力。
|
||||
地域节点使用 Country 与 City MMDB。Agent 首次启动时从程序内嵌数据库初始化缺失文件,后续按配置周期下载更新,请求处理始终读取 OpenResty 已加载的数据库。数据库不可用时地域匹配返回 `false` 并限频告警,不允许因数据损坏意外放行其它执行错误。
|
||||
|
||||
---
|
||||
## 安全顺序
|
||||
|
||||
## 核心功能
|
||||
|
||||
OpenFlare WAF 包含以下核心防护维度:
|
||||
|
||||
* **IP 级拦截(IP 黑白名单)**:支持单 IP、CIDR 网段过滤,支持将上万 IP 聚合为 IP 组进行高效比对。
|
||||
* **地域黑白名单(GeoIP 限制)**:集成 MaxMind 数据库,支持针对国家(Country)和省份/地区(Region)执行精准准入控制。
|
||||
* **自定义拦截响应**:支持针对不同的过滤规则自定义阻断状态码(如 403, 418)以及个性化的 HTML 拦截页面。
|
||||
* **人机挑战(PoW CC 防护)**:支持无感人机挑战,通过计算 Hash 碰撞防止自动化脚本和僵尸网络(Botnet)对接口进行并发冲击。
|
||||
|
||||
---
|
||||
|
||||
## IP 组设计与动态异步同步
|
||||
|
||||
IP 组是 WAF 进行高效黑白名单管控的核心容器。OpenFlare 将 IP 组根据更新频率与产生渠道分为三类:
|
||||
|
||||
### 1. IP 组类型
|
||||
* **手动 IP 组(Manual)**:由管理员在控制面板上手动输入 IP 或 CIDR 列表。主要用于静态的信任 IP 或长期的封禁。
|
||||
* **订阅 IP 组(Subscription)**:配置远程文本(按行分隔)或标准的 JSON 订阅地址。Server 侧的定时任务会周期性抓取远程订阅源并自动解析导入。主要用于集成开源的威胁情报库、云厂商的 IP 范围等。
|
||||
* **自动 IP 组(Automatic)**:**最具弹性的动态防护通道**。控制面的定时扫描任务会读取所有节点的访问日志,按照设定的 Expr 规则(例如:“5分钟内请求 `/api/login` 接口触发 401 超过 50 次”)进行聚合分析,一旦匹配,自动将该恶意源 IP 写入封禁组,并指定封禁时长。
|
||||
|
||||
### 2. 异步差分同步设计 (不触发 Nginx Reload)
|
||||
在传统的 Nginx WAF 设计中,IP 黑名单的更新通常需要重写配置并 reload。如果恶意 IP 封禁以秒级或分钟级高频触发,频繁 reload 会导致 Nginx 频繁新建 Worker 进程并销毁老进程,导致性能骤降。
|
||||
|
||||
OpenFlare 采用 **动态 IP 组异步差分同步设计**:
|
||||
|
||||
```text
|
||||
WAF IP 成员更新 (手动/订阅/自动自动触发)
|
||||
|
|
||||
v
|
||||
Server 更新数据库并计算该 IP 组的全新 MD5 Checksum
|
||||
|
|
||||
+----------------------------------------+
|
||||
| (WebSocket 实时广播) | (心跳兜底比对)
|
||||
v v
|
||||
Server 立即向所有 Agent 推送变更组的完整成员 Agent 心跳上报本地所有 IP 组的 Checksum 映射表
|
||||
| |
|
||||
| v
|
||||
| Server 发现 Checksum 不一致,下发变更的 IP 组成员
|
||||
v |
|
||||
Agent 接收成员数据,将其以 JSON 形式写入本地磁盘路径:waf_ip_groups.json
|
||||
|
|
||||
v (Lua 内存感知)
|
||||
OpenResty Lua 引擎通过 MD5 校验和秒级感知文件变化并热更新内存,无需 reload 进程
|
||||
```
|
||||
|
||||
通过这一架构,上万个高频变动的动态黑名单 IP 的落地和生效,**全程无需 reload 任何 Nginx 进程**,极大地保护了网关的高并发性能。
|
||||
|
||||
---
|
||||
|
||||
## 规则组与网站绑定
|
||||
|
||||
* **WAF 规则组(Rule Group)**:WAF 过滤政策的最小逻辑集合。一条规则组内可以包含 IP 黑白名单、IP 组引用、地域限制及防 CC 挑战配置。
|
||||
* **全局规则组(Global)**:当规则组被标记为 `is_global = true` 时,该规则组对节点上托管的**所有网站路由**默认生效。
|
||||
* **网站绑定绑定(Site Binding)**:网站路由(Proxy Route)可以绑定一个或多个非全局规则组。判定时,会执行 `全局规则组 + 绑定规则组` 的并集逻辑。
|
||||
|
||||
---
|
||||
|
||||
## 实现方案与高性能缓存
|
||||
|
||||
WAF 在 OpenResty 的 `access_by_lua` 阶段被触发,核心由 Lua 文件与本地落地的 JSON 配置构成。
|
||||
|
||||
### 1. 物理结构
|
||||
* `waf_config.json`:包含所有规则组的元数据、国家地域限制、以及网站(Site)与规则组的关联映射。
|
||||
* `waf_ip_groups.json`:包含所有同步下来的 IP 组与对应的 IP 列表。
|
||||
* `waf/runtime.lua`:WAF 规则比对的实际运行时引擎。
|
||||
* `waf/check.lua`:接入层入口,负责包引入与 check() 触发。
|
||||
|
||||
### 2. 共享内存字典 (ngx.shared) 高性能缓存设计
|
||||
在每次 Web 请求进来时都读取磁盘上的 JSON 文件并进行解码,会导致磁盘 I/O 成为严重的性能瓶颈。
|
||||
|
||||
OpenFlare 利用 **OpenResty 共享内存字典 (ngx.shared.openflare_waf_config)** 设计了二级缓存机制:
|
||||
|
||||
1. **零文件 I/O 路径**:
|
||||
在 Lua 中,每次执行 `check()` 时,首先利用 `ngx.md5` 瞬间计算本地磁盘 JSON 文件的 MD5 哈希(这一操作几乎为零耗时,因为文件已被操作系统 Page Cache 缓存)。
|
||||
2. **哈希比对与热加载**:
|
||||
比对共享内存中存储的缓存哈希键(`_config_hash`)。
|
||||
* **若哈希未发生变化**:直接从共享内存字典中读取已解码、存在内存中的 Lua Table 配置,整个校验过程完全基于**共享内存操作**,耗时在 **微秒级** 级别。
|
||||
* **若哈希不一致**:说明 Agent 刚刚落地了新的 WAF 规则或 IP 组,Lua 自动读取磁盘文件并使用 `cjson.decode` 解码,解码后的数据及全新的 MD5 写入共享内存,供后续 Worker 进程无缝读取。
|
||||
|
||||
---
|
||||
|
||||
## 应用流程与判定判定控制逻辑
|
||||
|
||||
当一个 HTTP/HTTPS 请求到达 OpenResty 后,WAF 会在 `access` 阶段按下图所示的漏斗判决链进行逐步匹配拦截:
|
||||
|
||||
### 1. WAF 判定流程图
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[请求进入 access 阶段] --> B[获取当前请求的 Site Name]
|
||||
B --> C[在共享内存中加载与此 Site 绑定的所有活跃规则组]
|
||||
C --> D{匹配到 IP 白名单 / 白名单 IP 组?}
|
||||
D -- 是 (匹配成功) --> E[放行请求 - ALLOW]
|
||||
D -- 否 --> F{匹配到国家/地区地域白名单?}
|
||||
F -- 是 (匹配成功) --> E
|
||||
F -- 否 --> G{匹配到 IP 黑名单 / 黑名单 IP 组?}
|
||||
G -- 是 (匹配成功) --> H[阻断请求 - BLOCK]
|
||||
G -- 否 --> I{匹配到国家/地区地域黑名单?}
|
||||
I -- 是 (匹配成功) --> H
|
||||
I -- 否 --> J{是否启用了防 CC PoW 验证?}
|
||||
J -- 是 --> K[转交防 CC 模块处理]
|
||||
J -- 否 --> L[无安全风险,正常放行]
|
||||
|
||||
H --> M[退出并返回规则组配置的自定义状态码与拦截响应体]
|
||||
```
|
||||
|
||||
### 2. 判决步骤细则
|
||||
1. **白名单前置**:
|
||||
为了防止误杀以及保障核心回源流量(如搜索引擎蜘蛛、CDN 回源 IP、办公区出口)的顺畅,WAF **优先匹配 IP 白名单与地域白名单**。一旦白名单匹配成功,直接绕过后续的所有黑名单检测和 CC 挑战,立刻放行。如果请求未命中白名单,则继续向下进行黑名单检测及其他后续判定。
|
||||
2. **黑名单强力阻断**:
|
||||
如果在白名单判定中未被捕获,请求将进入黑名单漏斗。一旦请求源 IP 命中 IP 黑名单、命中引用的黑名单 IP 组、或是处于被禁止的国家/地区范围内,Lua 引擎立即将 `ngx.ctx.openflare_waf_blocked` 标记设为 `true`。
|
||||
3. **输出响应**:
|
||||
命中黑名单后,Lua 提取匹配到规则组的 `block_status_code`(默认返回 418 / 403)和 `block_response_body`(拦截页面 HTML),通过 `ngx.say()` 输出响应体并执行 `ngx.exit(status)` 平滑退出请求,防止请求继续向后透传。
|
||||
启用的全局规则固定前置;路由规则按绑定 sequence 执行。阻止节点立即终止,通过节点仅结束当前规则,全部规则通过后才进入回源链路。未知节点、缺失出口或步数超限一律阻止请求。
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
# WAF 可编排规则设计
|
||||
|
||||
本文定义 OpenFlare WAF 从固定判定链重构为可视化有向无环图(DAG)的目标架构、数据模型、执行语义、发布模型与迁移边界。IP 组的来源与成员计算仍遵循 [WAF 设计](./waf-design.md),本文只改变规则如何组合和执行。
|
||||
|
||||
## 目标与边界
|
||||
|
||||
用户新增 WAF 规则时只输入名称。Server 随即创建一张合法的默认图 `开始 → 通过`,前端进入基于 React Flow 的独立编排页面。用户通过添加处理单元、配置节点并连接分支构建策略,不再填写固定顺序的黑白名单与 PoW 表单。
|
||||
|
||||
第一阶段支持以下节点:
|
||||
|
||||
| 节点 | 数量约束 | 输入 | 输出 | 配置 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 开始 | 每张图恰好一个 | 无 | `next` | 无 |
|
||||
| 通过 | 每张图恰好一个 | 一个或多个 | 无 | 无 |
|
||||
| 阻止 | 可创建多个 | 一个或多个 | 无 | HTTP 状态码、HTML 响应体 |
|
||||
| IP 匹配 | 可创建多个 | 一个或多个 | `true`、`false` | IP、CIDR、IP 组 ID |
|
||||
| 地域匹配 | 可创建多个 | 一个或多个 | `true`、`false` | 国家代码、地区代码 |
|
||||
| PoW | 可创建多个 | 一个或多个 | `next` | 算法、难度、会话 TTL、挑战 TTL |
|
||||
|
||||
IP 匹配和地域匹配不区分黑名单或白名单。`true` 只表示请求匹配节点配置,`false` 只表示未匹配;放行或阻止的业务含义完全由连线决定。PoW 验证完成后沿 `next` 继续,未完成时由挑战页面接管当前请求,不产生 `false` 分支。
|
||||
|
||||
不在第一阶段实现循环、脚本节点、任意表达式节点、子图调用和跨规则跳转。
|
||||
|
||||
## 控制面架构
|
||||
|
||||
规则图采用控制面编辑态和数据面运行态分离的双模型:
|
||||
|
||||
1. React Flow 编辑器提交版本化图 JSON,其中包含节点 ID、节点类型、显示名称、坐标、类型化配置和连线。
|
||||
2. Server 对整张图执行权威校验,通过后以单个事务保存图并递增修订号。
|
||||
3. 配置发布时,Server 再次校验所有启用规则,将图编译为不含坐标、标签等 UI 字段的紧凑运行时 DAG,并收集被引用的 IP 组 ID。
|
||||
4. Agent 原子落盘完整发布快照并 reload OpenResty。新 Worker 启动时只加载和解析一次规则 JSON。
|
||||
5. 请求热路径只遍历 Worker 内存中的不可变运行时图,不读取文件、不计算 checksum、不解析 JSON。
|
||||
|
||||
编辑态 JSON 使用明确的 `schema_version`。节点配置使用按节点类型区分的结构,不允许用无约束键值对象绕过 Server 校验。初始安全上限为每条规则 128 个节点、256 条边和 256 KiB 编辑态 JSON;这些限制由 API 和发布编译器共同执行。
|
||||
|
||||
## 图结构约束
|
||||
|
||||
规则保存与发布必须满足全部约束:
|
||||
|
||||
* 图是有向无环图,禁止自环和任意循环。
|
||||
* 恰好存在一个开始节点和一个通过节点;阻止节点可以存在多个。
|
||||
* 开始节点无入边且恰好有一个 `next` 出口;通过和阻止节点无出口。
|
||||
* IP 匹配与地域匹配的 `true`、`false` 出口必须各连接一次;PoW 的 `next` 必须连接一次。
|
||||
* 除终止节点外不得存在悬空出口;每个非开始节点至少有一条入边。
|
||||
* 所有节点都必须从开始节点可达,且从每个可执行节点出发都能抵达通过或阻止。
|
||||
* 边的源端口必须属于源节点类型;同一源端口不得连接多个目标。
|
||||
* 节点 ID 在图内唯一,边 ID 在图内唯一,所有边引用的节点必须存在。
|
||||
* 节点配置必须通过对应类型的字段、范围、引用存在性和体积校验。
|
||||
|
||||
前端提供即时校验和连线限制以改善体验,但 Server 是唯一权威校验方。删除节点时前端同步删除关联边并将规则标记为未保存;图恢复合法前禁止保存。
|
||||
|
||||
## 多规则执行语义
|
||||
|
||||
一个路由可以绑定多条自定义规则。绑定关系是有序列表,并遵循以下顺序:
|
||||
|
||||
1. 启用的全局规则固定最先执行,不参与路由侧排序。
|
||||
2. 路由绑定的启用规则按绑定顺序依次执行。
|
||||
3. 当前规则抵达阻止节点时立即输出该节点配置的响应并终止请求。
|
||||
4. 当前规则抵达通过节点时,只表示当前规则执行完成;若仍有后续规则则继续执行。
|
||||
5. 全部规则均抵达通过节点后,请求才真正放行并进入后续 OpenResty/回源链路。
|
||||
|
||||
运行时图在发布前已经过完整校验。若 Lua 执行器仍遇到未知节点、未知端口、缺失目标或超过节点步数上限,则记录限频错误并阻止请求,避免损坏的安全配置意外放行。
|
||||
|
||||
## IP 组内存刷新
|
||||
|
||||
规则拓扑只在发布并 reload OpenResty 时生效;IP 组成员仍可由手动、订阅或自动任务独立更新,不要求发布或 reload。
|
||||
|
||||
IP 组采用协调 Worker、共享快照和 Worker 本地对象的两级缓存:
|
||||
|
||||
1. 请求始终读取当前 Worker 内存中的 IP 组对象,不访问文件或共享字典中的 JSON。
|
||||
2. 每 5 秒只有一个取得共享锁的 Worker 读取轻量 checksum 文件。
|
||||
3. checksum 未变化时立即结束,不读取完整 `waf_ip_groups.json`。
|
||||
4. checksum 变化时,协调 Worker 读取并验证一次完整 JSON,再把原始快照按 checksum 写入独立的 64 MiB `ngx.shared.openflare_waf_ip_groups`,最后更新提交指针。
|
||||
5. 其他 Worker 发现共享版本变化后,从共享内存取得快照、解析并原子替换各自的本地对象,不重复读取磁盘。
|
||||
6. 刷新失败时继续使用上一份有效对象,限频记录错误,并在下一周期重试。
|
||||
|
||||
Agent 必须先原子替换 IP 组 JSON,最后原子更新 checksum,使 Worker 永远不会把半写入文件识别为新版本。Server 发布/同步和 Agent 落盘共同执行 20 MiB 聚合快照上限;共享字典使用不会强制淘汰旧键的安全写入,失败时保留当前与上一代不可变快照。
|
||||
|
||||
## API 与编辑器
|
||||
|
||||
创建接口只接受规则名称,创建成功后返回带默认图的规则详情。规则元数据、图保存和路由绑定使用独立操作,避免修改启用状态或绑定时覆盖画布。
|
||||
|
||||
图详情包含 `revision`。保存请求提交 `revision + graph`,Server 仅在修订号匹配时更新并递增修订号;不匹配时返回冲突,前端提示重新加载,禁止静默覆盖其他页面的修改。路由绑定接口接受有序规则 ID 数组。
|
||||
|
||||
React Flow 编辑页采用全宽画布和固定右侧属性栏:
|
||||
|
||||
* 顶部提供返回、规则名称、启用状态、校验状态和保存操作。
|
||||
* 画布使用紧凑高度和较小的首次适配缩放,支持缩放、平移、框选、删除、自动布局和 MiniMap/Controls 等必要导航能力;节点拖动由 React Flow 本地受控状态实时处理,拖动结束后才把坐标写回编辑图。
|
||||
* “添加处理单元”提供 IP 匹配、地域匹配、PoW 和阻止;开始与通过由默认图提供且不可删除或重复添加。
|
||||
* 选中普通节点或连线后可使用画布删除按钮或 Delete/Backspace 删除;删除节点时同步移除关联连线。
|
||||
* 右侧属性栏默认隐藏,选中节点后才显示并用于编辑配置;点击连线或画布空白处时收起。
|
||||
* 地域匹配属性使用完整国家与 ISO 3166-2 一级行政区数据;国家选项同时显示本地化名称与代码,行政区支持按国家名、行政区名或代码搜索,避免一次渲染数千个选项。
|
||||
* 离开存在未保存变更的页面前必须提示;保存冲突和 Server 校验错误应定位到相关节点或边。
|
||||
|
||||
WAF 列表展示规则名称、启用状态、节点数量、应用路由数量和更新时间。新建规则的对话框只有名称字段,成功后立即导航到编排页面。
|
||||
|
||||
## 持久化与迁移
|
||||
|
||||
规则记录增加版本化图 JSON 与修订号;绑定记录增加执行顺序。图作为一个聚合整体保存,不拆成节点表和边表,以保证编辑操作的事务边界,并让新增节点类型不必频繁扩展数据库 Schema。
|
||||
|
||||
升级现有安装时:
|
||||
|
||||
* 保留规则名称、全局标记、启用状态及路由绑定关系。
|
||||
* 所有规则图重置为 `开始 → 通过`,不迁移旧 IP/地域名单、PoW 或拦截响应配置。
|
||||
* 现有绑定按稳定顺序写入顺序字段;全局规则仍固定前置。
|
||||
* 新图和运行时稳定后移除旧规则字段、固定顺序编译逻辑和旧前端表单,不长期维护双执行器。
|
||||
|
||||
该迁移会让旧防护配置停止生效,升级说明必须显著提示管理员在发布下一版本前重新编排规则。
|
||||
|
||||
## 发布、失败与回滚
|
||||
|
||||
规则图只在配置发布时生效。发布前校验或编译失败时拒绝发布,当前活动版本保持不变。Agent 写入、OpenResty 配置检查或 reload 失败时,应用流程失败并恢复上一份有效发布版本。
|
||||
|
||||
新 Worker 只接受完整且可解析的规则运行态配置。旧 Worker 在 OpenResty 优雅 reload 期间继续使用旧内存图,新 Worker 使用新图,因此请求不会观察到半更新状态。
|
||||
|
||||
地域数据库不可用时,地域匹配返回 `false` 并限频告警,保持现有行为。IP 组刷新失败时保留旧内存快照。PoW 未完成由挑战模块接管请求,不视为执行错误;PoW 节点配置先以短期键写入 OpenResty 共享内存,再通过 `ngx.exec` 的显式参数传给内部挑战处理器,不能依赖内部重定向保留 `ngx.ctx` 或隐式继承请求参数。发布快照中的空规则绑定必须编码为 JSON 空数组;运行时将旧快照中的 `null` 可选数组按空数组处理,禁止因 `cjson` 的 `ngx.null` userdata 中断请求。
|
||||
|
||||
## 测试与验收
|
||||
|
||||
* Go 单元测试覆盖图结构、端口、可达性、终止性、节点配置、体积限制、编译结果、修订冲突和绑定顺序。
|
||||
* 数据库测试覆盖 PostgreSQL/SQLite 迁移、默认图、旧绑定稳定排序和回滚。
|
||||
* Lua 测试覆盖所有节点出口、多规则顺序、全局规则前置、多个阻止响应、PoW 接管和损坏运行时图保护。
|
||||
* Agent/OpenResty 测试覆盖发布 reload、加载一次、失败回滚、IP 组五秒 checksum 刷新和旧快照保留。
|
||||
* 前端测试覆盖创建后导航、特殊节点唯一性、连线限制、属性编辑、即时校验、未保存提示和并发冲突。
|
||||
* 集成测试从控制面创建并编排规则,发布后用真实请求验证放行、阻止、PoW 和 IP 组热刷新。
|
||||
* API 变更后运行 `make swagger`;完成实现后运行前端检查与构建以及 `make code-check`。
|
||||
@@ -0,0 +1,100 @@
|
||||
# Zone 与域名资源设计
|
||||
|
||||
## 目标
|
||||
|
||||
将“网站”重构为以可注册根域为入口的 Zone 管理体验。`example.com` 之类的 Zone 是稳定的管理边界;用户通过稳定 ID 路径进入该 Zone,查看并维护其中明确声明的域名、域名所绑定的反代路由和证书,以及路由级 WAF、Pages 等能力。
|
||||
|
||||
本设计替代 `managed_domains` 的概念、表与 API。它不引入权威 DNS 解析记录管理。
|
||||
|
||||
## 范围与约束
|
||||
|
||||
* Zone 根域使用 Public Suffix List 解析,例如 `api.example.co.uk` 归属 `example.co.uk`。
|
||||
* URL 使用 ID:列表为 `/websites`,详情为 `/websites/:zoneId`;不使用域名作为 URL 参数。
|
||||
* Zone 域名必须是明确的 FQDN,禁止录入 `*.example.com`。TLS 证书可仍含通配符 SAN,并用于覆盖明确的 Zone 域名。
|
||||
* 一个 Zone 域名至多关联一条反代路由;一条反代路由可关联多个 Zone 域名,因而可跨 Zone 共享同一套上游、缓存、限流、WAF 与 Pages 配置。
|
||||
* 不新增 DNS 记录、边缘函数、预览子域或租户隔离能力。
|
||||
|
||||
## 核心模型
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
ZONES ||--o{ ZONE_DOMAINS : contains
|
||||
PROXY_ROUTES ||--o{ ZONE_DOMAINS : serves
|
||||
TLS_CERTIFICATES ||--o{ ZONE_DOMAINS : secures
|
||||
PROXY_ROUTES ||--o{ WAF_RULE_GROUP_BINDINGS : applies
|
||||
PAGES_PROJECTS ||--o{ PROXY_ROUTES : backs
|
||||
|
||||
ZONES {
|
||||
uint id PK
|
||||
string domain UK
|
||||
}
|
||||
ZONE_DOMAINS {
|
||||
uint id PK
|
||||
uint zone_id
|
||||
uint proxy_route_id
|
||||
string domain UK
|
||||
uint cert_id
|
||||
}
|
||||
```
|
||||
|
||||
### `of_zones`
|
||||
|
||||
保存根域、创建时间与更新时间。根域全局唯一且创建后不可原地修改;需要变更时新建 Zone 并迁移域名。删除 Zone 前必须先清空其 Zone 域名。
|
||||
|
||||
### `of_zone_domains`
|
||||
|
||||
保存 `zone_id`、明确 `domain`、可空的 `proxy_route_id`、可空的 `cert_id` 及时间戳。`domain` 全局唯一;所有关系字段建立索引但不建立物理外键。`proxy_route_id` 允许为空,以承接已准备证书但尚未配置反代的历史域名。
|
||||
|
||||
`of_proxy_routes` 逐步移除 `domain`、`domains`、`cert_id`、`cert_ids` 与 `domain_cert_ids` 等域名/证书冗余列。路由不得再指定任何 TLS 证书;路由名称 `site_name` 成为稳定的人类可读标识,编译器从关联的 Zone 域名读取 `server_name` 与其 `cert_id`。这使每个明确域名的证书只有一个来源。
|
||||
|
||||
## 业务与 API
|
||||
|
||||
管理端新增 Zone 资源:
|
||||
|
||||
* `GET/POST /api/v1/d/zones`
|
||||
* `GET/POST /api/v1/d/zones/:id/update`
|
||||
* `POST /api/v1/d/zones/:id/delete`
|
||||
* `GET/POST /api/v1/d/zones/:id/domains`
|
||||
* `POST /api/v1/d/zones/:id/domains/:domainID/update`
|
||||
* `POST /api/v1/d/zones/:id/domains/:domainID/delete`
|
||||
* `GET /api/v1/d/zones/:id/overview`
|
||||
|
||||
反代路由的创建、更新请求改用 `zone_domain_ids`,不再提交 `domains`、`cert_id`、`cert_ids` 或 `domain_cert_ids`。服务端在事务中验证域名归属、全局唯一性和证书 SAN 覆盖;失败通过 `response.Abort*` 统一返回。删除已绑定路由的 Zone 域名必须先解除或删除该路由;删除仍有域名的 Zone 必须拒绝。
|
||||
|
||||
WAF、Pages、上游与发布版本仍属于 `proxy_routes`。Zone 概览只聚合展示其域名关联的路由状态,不复制或重新定义这些配置。
|
||||
|
||||
## 前端体验
|
||||
|
||||
`/websites` 只展示 Zone 根域,显示已配置域名数、路由数与状态,并提供搜索、创建和操作菜单。点击进入 `/websites/:zoneId`。
|
||||
|
||||
详情页包含:
|
||||
|
||||
* 概览:域名、路由和有效证书统计;域名—路由—证书摘要;路由级 WAF 与 Pages 摘要。
|
||||
* 域名:明确 FQDN 的列表、证书选择和关联路由;不显示或接受通配符域名。
|
||||
* 路由:筛选到当前 Zone 的路由并链接到既有路由详情。
|
||||
* 证书:当前 Zone 域名实际引用的证书。
|
||||
* 设置:Zone 备注和受保护的删除操作。
|
||||
|
||||
新增路由时从 Zone 域名中选择;用户也可以先在 Zone 中登记域名,再绑定路由。全局反代路由入口保留,但改用同一套 Zone 域名选择器。
|
||||
|
||||
## 数据迁移
|
||||
|
||||
本次改造分两个发布阶段,以免 SQL 用错误的“末两段域名”规则处理多级公共后缀。操作细则见 [Zone 域名迁移与发布验收](../guide/zone-domain-migration.md)。
|
||||
|
||||
1. **第一阶段 DDL**:PostgreSQL 与 SQLite 同版本 Goose 创建 `of_zones` / `of_zone_domains`;暂时保留 `of_managed_domains` 与路由冗余列。
|
||||
2. **数据导入(自动)**:Server 启动时 `migrator.Migrate()` 先应用 goose SQL 至 `202607120002`,再自动导入旧路由域名 / `managed_domains`(`publicsuffix` 解析注册根域,写入 `cert_id` 与 `proxy_route_id`),最后继续后续 SQL。冲突时启动失败;修复后重启可幂等重试。无需手动命令。
|
||||
3. **代码切换**:控制面 API、配置快照、渲染、前端均以 Zone 域名为唯一来源;路由写入仅使用 `zone_domain_ids`。
|
||||
4. **第二阶段清理**:Goose SQL `202607130001_drop_legacy_route_domain_columns` 删除 `of_managed_domains` 与 `of_proxy_routes` 冗余列。Down 仅恢复开发库空结构,不回填历史数据。
|
||||
|
||||
### 运行时模型边界
|
||||
|
||||
* 持久化:域名与证书只存在于 `of_zone_domains`;`of_proxy_routes` 仅保存路由策略(上游、缓存、限流、WAF 绑定键等)。
|
||||
* 渲染:配置快照在内存中组装临时 `Domains` / `DomainCertIDs` 供 OpenResty 渲染,不写回数据库。
|
||||
* 结构迁移仅使用 `internal/db/migrator/goose/{postgres,sqlite}/*.sql`;启动时自动导入历史域名,第二阶段后旧列不存在则为空操作。
|
||||
|
||||
## 验证
|
||||
|
||||
* 单元测试:Public Suffix List 分组、FQDN / 通配符拒绝、跨 Zone 路由、证书 SAN 覆盖、删除保护及迁移幂等性;清理后断言旧列/旧表不存在。
|
||||
* 集成测试:Zone、Zone 域名与路由 API 的成功与失败响应;现有路由迁移后生成相同 OpenResty 域名与证书配置。
|
||||
* 前端测试:Zone 列表、ID 路由、详情加载 / 错误 / 空状态、域名选择器与 API 负载。
|
||||
* 手动验证:迁移前后比较激活配置快照中的 `server_name` 和证书路径,发布后使用根域及各子域请求验证路由。
|
||||
+1888
-937
File diff suppressed because it is too large
Load Diff
+9
-8
@@ -11,14 +11,15 @@ OpenFlare 是一套自托管的 OpenResty 控制面。它把反向代理网站
|
||||
1. [快速开始](./quick-start.md):用 Docker Compose 启动 Server,登录管理端,并接入第一个 Agent。
|
||||
2. [发布第一份配置](./first-site.md):快速新建一条最基础的 HTTP 反代站点规则,并验证节点生效状态。
|
||||
3. [新建反代配置](./proxy-config.md):一步一步了解如何从证书导入与申请开始,配置 HTTPS 加密与上游源站管理。
|
||||
4. [Pages 静态托管使用](./pages-usage.md):了解静态项目 ZIP 上传限制、SPA Fallback、以及内置 API 反向代理配置。
|
||||
5. [内网穿透与隧道使用](./tunnel-usage.md):部署 Relay 与 Client,实现安全、无公网 IP 反向穿透。
|
||||
6. [WAF 安全防护使用](./waf-usage.md):配置 WAF 规则组,掌握 IP 黑白名单、自动/订阅 IP 组、地域限制与 PoW CC 防护。
|
||||
7. [WAF 自动 IP 组语法](./waf-ip-group-expr.md):编写自动 IP 组 Expr 规则,了解关键字含义和预设规则。
|
||||
8. [Uptime Kuma 监控同步](./uptime-kuma.md):配置并使用 Uptime Kuma 自动差分同步和监控范围控制。
|
||||
9. [SSO 登录配置](./sso.md):配置 GitHub 或 OIDC 实现第三方单点登录 (SSO) 接入。
|
||||
10. [故障排查](./troubleshooting.md):按症状排查登录、数据库、节点同步、OpenResty 应用和前端构建问题。
|
||||
11. [引用与致谢](./credits.md):查看系统依赖的优秀开源项目与社区致谢清单。
|
||||
4. [Zone 域名迁移](./zone-domain-migration.md):从旧托管域名/路由内嵌域名升级到 Zone 模型(goose 自动导入),含备份、验收与回滚说明。
|
||||
5. [Pages 静态托管使用](./pages-usage.md):了解静态项目 ZIP 上传限制、SPA Fallback、以及内置 API 反向代理配置。
|
||||
6. [内网穿透与隧道使用](./tunnel-usage.md):部署 Relay 与 Client,实现安全、无公网 IP 反向穿透。
|
||||
7. [WAF 安全防护使用](./waf-usage.md):配置 WAF 规则组,掌握 IP 黑白名单、自动/订阅 IP 组、地域限制与 PoW CC 防护。
|
||||
8. [WAF 自动 IP 组语法](./waf-ip-group-expr.md):编写自动 IP 组 Expr 规则,了解关键字含义和预设规则。
|
||||
9. [Uptime Kuma 监控同步](./uptime-kuma.md):配置并使用 Uptime Kuma 自动差分同步和监控范围控制。
|
||||
10. [SSO 登录配置](./sso.md):配置 GitHub 或 OIDC 实现第三方单点登录 (SSO) 接入。
|
||||
11. [故障排查](./troubleshooting.md):按症状排查登录、数据库、节点同步、OpenResty 应用和前端构建问题。
|
||||
12. [引用与致谢](./credits.md):查看系统依赖的优秀开源项目与社区致谢清单。
|
||||
|
||||
## 按角色查找
|
||||
|
||||
|
||||
+36
-17
@@ -30,6 +30,14 @@ Agent 统一通过 OpenResty 二进制控制运行时。本地部署需要节点
|
||||
|
||||
为了保证异步任务队列(Asynq 框架)及可观测流量看板功能完整运行,快速开始推荐采用 **PostgreSQL + Redis + ClickHouse** 经典单机版编排。
|
||||
|
||||
先拉取 ClickHouse 服务端性能配置到 `./config/clickhouse`,并以单文件方式挂载:
|
||||
|
||||
```bash
|
||||
mkdir -p ./config/clickhouse
|
||||
curl -fsSL -o ./config/clickhouse/performance.xml \
|
||||
https://raw.githubusercontent.com/Rain-kl/OpenFlare/refs/heads/main/config/clickhouse/performance.xml
|
||||
```
|
||||
|
||||
在空目录中创建 `docker-compose.yaml`:
|
||||
|
||||
```yaml
|
||||
@@ -37,26 +45,26 @@ version: '3.8'
|
||||
|
||||
services:
|
||||
openflare:
|
||||
image: ghcr.io/rain-kl/openflare-server:latest
|
||||
image: ghcr.io/rain-kl/openflare:latest
|
||||
container_name: openflare-server
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./uploads:/app/uploads
|
||||
- openflare_uploads:/app/uploads
|
||||
environment:
|
||||
TZ: Asia/Shanghai
|
||||
APP_SESSION_SECRET: 'replace-with-a-long-random-string' # 生产环境请替换为长随机字符串
|
||||
DB_ENABLED: "true"
|
||||
DB_HOST: "postgres"
|
||||
DB_PORT: "5432"
|
||||
DB_USERNAME: "openflare"
|
||||
DB_PASSWORD: "replace-with-strong-password"
|
||||
DB_NAME: "openflare"
|
||||
DB_USERNAME: "${DB_USERNAME:-openflare}"
|
||||
DB_PASSWORD: "${DB_PASSWORD:-replace-with-strong-password}"
|
||||
DB_NAME: "${DB_NAME:-openflare}"
|
||||
REDIS_ENABLED: "true"
|
||||
REDIS_ADDRS: "redis:6379"
|
||||
REDIS_ADDR: "redis:6379"
|
||||
CLICKHOUSE_ENABLED: "true"
|
||||
CLICKHOUSE_HOSTS: "clickhouse:9000"
|
||||
CLICKHOUSE_HOST: "clickhouse:9000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -69,13 +77,13 @@ services:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: openflare
|
||||
POSTGRES_USER: openflare
|
||||
POSTGRES_PASSWORD: replace-with-strong-password
|
||||
POSTGRES_DB: ${DB_NAME:-openflare}
|
||||
POSTGRES_USER: ${DB_USERNAME:-openflare}
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD:-replace-with-strong-password}
|
||||
volumes:
|
||||
- ./data/postgres_data:/var/lib/postgresql/data
|
||||
- openflare_postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U openflare -d openflare"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-openflare} -d ${DB_NAME:-openflare}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
@@ -85,7 +93,7 @@ services:
|
||||
restart: unless-stopped
|
||||
command: ["valkey-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- ./data/valkey:/data
|
||||
- openflare_redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "valkey-cli", "ping"]
|
||||
interval: 10s
|
||||
@@ -98,17 +106,28 @@ services:
|
||||
environment:
|
||||
CLICKHOUSE_DB: openflare
|
||||
CLICKHOUSE_USER: default
|
||||
CLICKHOUSE_PASSWORD: 123456
|
||||
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}
|
||||
CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1
|
||||
TZ: Asia/Shanghai
|
||||
ulimits:
|
||||
nofile:
|
||||
soft: 262144
|
||||
hard: 262144
|
||||
volumes:
|
||||
- ./data/clickhouse_data:/var/lib/clickhouse
|
||||
- openflare_clickhouse_data:/var/lib/clickhouse
|
||||
- ./config/clickhouse/performance.xml:/etc/clickhouse-server/config.d/performance.xml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "clickhouse-client", "--query", "SELECT 1"]
|
||||
test: ["CMD", "clickhouse-client", "--user", "default", "--password", "${CLICKHOUSE_PASSWORD:-replace-with-clickhouse-password}", "--query", "SELECT 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
volumes:
|
||||
openflare_uploads:
|
||||
openflare_postgres_data:
|
||||
openflare_redis_data:
|
||||
openflare_clickhouse_data:
|
||||
```
|
||||
|
||||
启动服务:
|
||||
@@ -134,7 +153,7 @@ http://localhost:3000
|
||||
|
||||
| 用户名 | 密码 |
|
||||
| --- | --- |
|
||||
| `root` | `123456` |
|
||||
| `admin` | `12345678` |
|
||||
|
||||
> [!WARNING]
|
||||
> 为了你的系统安全,首次登录后请立即修改默认密码。
|
||||
|
||||
@@ -79,7 +79,7 @@ NEXT_DEV_BACKEND_URL=http://127.0.0.1:3000 pnpm dev
|
||||
|
||||
## 默认账号无法登录
|
||||
|
||||
默认账号是 `root` / `123456`。首次登录后如果已经修改密码,应使用修改后的密码。
|
||||
默认账号是 `admin` / `12345678`。首次登录后如果已经修改密码,应使用修改后的密码。
|
||||
|
||||
排查步骤:
|
||||
|
||||
@@ -90,7 +90,7 @@ NEXT_DEV_BACKEND_URL=http://127.0.0.1:3000 pnpm dev
|
||||
|
||||
### 应急重置管理员密码
|
||||
|
||||
如果忘记了 `root` 账户的密码,可以通过直接更新数据库中的密码哈希值将其重置为 `123456`(登录后请务必立即修改):
|
||||
如果忘记了 `admin` 账户的密码,可以通过直接更新数据库中的密码哈希值将其重置为 `12345678`(登录后请务必立即修改):
|
||||
|
||||
#### 1. 若使用 SQLite 数据库
|
||||
停止 Server 运行,使用 sqlite3 客户端打开数据库文件:
|
||||
@@ -99,16 +99,16 @@ sqlite3 /path/to/openflare.db
|
||||
```
|
||||
执行以下 SQL 语句:
|
||||
```sql
|
||||
UPDATE users SET password_hash = '$2a$10$wN9aE3zTz83rO7R1uKlhuehJtA3c604pX4Z12B/9.5c0X337t1L4m' WHERE username = 'root';
|
||||
UPDATE users SET password = '$2a$10$eXpE9i/6S3gPT94/G0mu0.B8ser66ARETFz5NWYSYcrQ4JmtSrMXu' WHERE username = 'admin';
|
||||
```
|
||||
输入 `.exit` 退出并重新启动 Server。
|
||||
|
||||
#### 2. 若使用 PostgreSQL 数据库
|
||||
通过您的数据库连接工具(如 psql、pgAdmin 或 DBeaver)连接到 PostgreSQL 实例,选择对应的 `openflare` 数据库,执行以下 SQL 语句:
|
||||
```sql
|
||||
UPDATE users SET password_hash = '$2a$10$wN9aE3zTz83rO7R1uKlhuehJtA3c604pX4Z12B/9.5c0X337t1L4m' WHERE username = 'root';
|
||||
UPDATE users SET password = '$2a$10$eXpE9i/6S3gPT94/G0mu0.B8ser66ARETFz5NWYSYcrQ4JmtSrMXu' WHERE username = 'admin';
|
||||
```
|
||||
执行成功后即可使用默认密码 `123456` 重新登录管理后台。
|
||||
执行成功后即可使用默认密码 `12345678` 重新登录管理后台。
|
||||
|
||||
## Agent 无法注册或一直离线
|
||||
|
||||
|
||||
+18
-163
@@ -1,176 +1,31 @@
|
||||
# WAF 安全防护使用
|
||||
|
||||
你会学到:OpenFlare 边缘 Web 应用防火墙 (WAF) 的工作原理、防护维度,如何管理与引用三类 IP 组(手动、订阅与基于 Expr 的自动 IP 组),配置防 CC 挑战(PoW 人机验证)与地域级拦截,以及如何在不 reload 进程的情况下实现 IP 组成员的秒级热更新。
|
||||
OpenFlare WAF 使用可视化有向无环图编排规则。新建规则时只填写名称,系统创建默认的“开始 → 通过”图并进入编辑器。
|
||||
|
||||
---
|
||||
## 节点与连线
|
||||
|
||||
## 核心概念
|
||||
- **开始**:每条规则唯一,沿 `next` 进入图。
|
||||
- **通过**:结束当前规则;若路由仍有后续规则则继续执行。
|
||||
- **阻止**:立即按配置的状态码和 HTML 响应终止请求。
|
||||
- **IP 匹配**:配置 IP、CIDR 或 IP 组,分别连接 `true`、`false`。
|
||||
- **地域匹配**:按国家或 ISO 3166-2 一级行政区代码分支;国家列表同时显示中文名称与代码,行政区可按国家名、行政区名或代码搜索。Country 与 City MMDB 缺失时由 Agent 从程序内嵌数据库初始化,并按配置周期更新。City MMDB 不可用时按未匹配处理。
|
||||
- **PoW**:未完成挑战时接管请求,验证通过后沿 `next` 继续。
|
||||
|
||||
在配置安全策略前,你需要理解 WAF 的几个核心组成部分:
|
||||
服务端会拒绝循环、悬空出口、不可达节点、重复端口连接和无效配置。保存时携带页面加载得到的 `revision`;发生 409 冲突时应重新加载,避免覆盖他人修改。
|
||||
|
||||
| 概念 | 说明 | 作用范围与生效方式 |
|
||||
| --- | --- | --- |
|
||||
| **WAF 规则组 (Rule Group)** | 安全规则的逻辑集合。包括:IP 黑白名单(直接录入或引用 IP 组)、国家/地区地域限制、防 CC 挑战(PoW)以及自定义拦截响应。 | 支持全局生效或绑定到单个/多个网站。**修改规则组定义必须发布并激活配置版本**。 |
|
||||
| **IP 组 (IP Group)** | 存放单个 IP 或 CIDR 网段的列表容器。分为**手动**、**订阅**与**自动**三类。WAF 规则组可通过 ID 引用 IP 组。 | 属于动态资源。**IP 组成员的增减支持 WebSocket 秒级无缝热同步,无需 reload 进程**。 |
|
||||
| **人机挑战 (CC PoW)** | 基于 Proof of Work (工作量证明) 的人机验证挑战。通过让浏览器计算特定难度的哈希碰撞,静默阻断恶意刷接口的自动化脚本与 Bot,保障正常用户体验。 | 位于规则组内的配置 Tab。**修改 PoW 参数必须发布并激活配置版本**。 |
|
||||
选中普通节点或连线后,可点击画布右上角的删除按钮,或按 Delete/Backspace 删除。删除节点会同时删除关联连线;唯一的“开始”和“通过”节点不可删除。拖动节点只在松开时记录最终坐标,不会在移动过程中反复重建画布状态。
|
||||
|
||||
---
|
||||
右侧节点属性栏默认隐藏,点击节点后显示;点击连线或画布空白区域后自动收起。
|
||||
|
||||
## 推荐配置顺序
|
||||
编排区默认使用较紧凑的高度和较小的首次缩放比例,仍可通过滚轮或画布 Controls 自由缩放。
|
||||
|
||||
配置网站的安全防护时,推荐按这个顺序进行:
|
||||
## 绑定与生效
|
||||
|
||||
1. 进入左侧菜单 **「安全性」->「IP 组」**,创建所需的 **手动 IP 组** (如开发者白名单) 或 **自动 IP 组** (如根据 404 扫描自动封禁的 IP)。
|
||||
2. 创建或编辑 **WAF 规则组**(菜单路径 **「安全性」->「WAF」**):
|
||||
* 绑定需要引用或阻断的 IP 组。
|
||||
* 配置国家或省份的地域黑白名单限制。
|
||||
* (可选) 在 `PoW` 标签页配置人机挑战参数。
|
||||
* 在 `拦截返回` 标签页设定自定义状态码(如 403, 418)和 HTML 拦截页。
|
||||
3. 将规则组关联到对应的 **路由规则**(在 **「规则管理」** 页面编辑对应规则,并在「WAF」选项卡中勾选关联规则组)。
|
||||
4. 发布并激活配置版本,使边缘节点 (Agent) 开始应用 WAF 规则过滤流量。
|
||||
启用的全局规则固定最先执行;路由绑定的自定义规则严格按列表顺序执行。调整顺序后需要发布配置版本,规则拓扑才会随 OpenResty reload 生效。
|
||||
|
||||
---
|
||||
IP 组成员是动态资源。Agent 每 5 秒检查 checksum,变化后在 Worker 间更新内存快照,无需重新发布规则或 reload。手动、订阅与自动 IP 组均可被 IP 匹配节点引用。单次完整 IP 组运行时快照最多 20 MiB;超过上限时发布或同步会返回错误,并继续使用上一份有效快照。
|
||||
|
||||
## 详细步骤指南
|
||||
> [!IMPORTANT]
|
||||
> 从旧固定黑白名单/地域/PoW 表单升级时,规则图会重置为“开始 → 通过”,旧策略字段不会迁移。请在发布新版本前逐条重新编排并验证规则。
|
||||
|
||||
### 第一步:管理与配置 IP 组
|
||||
|
||||
IP 组是进行大批量 IP 过滤的基石。OpenFlare 提供了极富弹性的三类 IP 组:
|
||||
|
||||
#### 1. 手动 IP 组 (Manual)
|
||||
* **用途**:静态维护一些确定受信任或确定需长期拦截的 IP/网段。
|
||||
* **配置**:点击「创建 IP 组」-> 类型选择「手动」-> 按行直接填入 IP 或 CIDR 格式(例如 `192.168.1.100` 或 `10.0.0.0/24`)。
|
||||
|
||||
#### 2. 订阅 IP 组 (Subscription)
|
||||
* **用途**:接入第三方开源威胁情报库、云厂商公布的官方网段(如 Cloudflare, GitHub Action IP 列表),或团队内部统一维护的动态 IP 源。
|
||||
* **配置参数**:
|
||||
* **订阅 URL**:必须是合法的 `http` 或 `https` 链接。
|
||||
* **订阅格式**:支持 `Text` 与 `JSON` 两种数据格式:
|
||||
* **Text 格式**:纯文本格式。按行分隔读取 IP/CIDR,会自动过滤掉以 `#` 开头的注释行和空白行。
|
||||
* **JSON 格式**:当订阅源是一个结构化的 JSON 响应时,需要编写 **映射规则 (Mapping Rule)** 从 JSON 数据中提取 IP 列表。
|
||||
* **映射规则**:使用类似 JSONPath 的轻量点语法定位 IP 数组,支持以 `[]` 展开数组。例如:
|
||||
* 若 JSON 结构为 `{"data": {"ips": ["1.1.1.1", "2.2.2.2"]}}`,则映射规则填写 `$.data.ips[]`(或 `data.ips[]`)。
|
||||
* 若 JSON 根节点本身即为字符串数组(如 `["1.1.1.1", "2.2.2.2"]`),映射规则留空或填写 `$` 即可。
|
||||
* **同步间隔 (分钟)**:该订阅组自动同步的周期,默认为 `1440` 分钟(24小时),允许范围为 `5` 至 `43200` 分钟。
|
||||
* **安全限额与同步频率**:
|
||||
* 为防止恶意或超大订阅源造成系统负担,单次抓取上限限制为 **2 MiB**,网络拉取超时为 15 秒。
|
||||
* Server 默认每 5 分钟在后台扫描一次到期的订阅 IP 组并拉取同步。
|
||||
|
||||
> [!TIP]
|
||||
> 关于 WAF 的动态 IP 组异步差分同步模型(WebSocket 实时热同步、不触发 Nginx Reload 机制)以及高性能 Lua 缓存方案等底层设计细节,请参阅 [WAF 设计](../design/waf-design.md)。
|
||||
|
||||
#### 3. 自动 IP 组 (Automatic)
|
||||
* **用途**:**最具杀伤力的防扫描、防爆破自动通道**。
|
||||
* **配置**:类型选择「自动」-> 编写 Expr 日志聚合逻辑。你可以直接引用系统内置的预设:
|
||||
* **单 IP 404 高频扫描**:`request_count > 100 && StatusRatio(404) >= 0.8` (单个 IP 最近一小时请求超 100 次且 404 响应占比超 80%)。
|
||||
* **单 IP 直连访问异常**:`ip_host_count > 50 && ip_host_ratio > 0.5` (绕过域名直接通过 IP 地址进行高频请求)。
|
||||
* **测试与立即执行**:保存前可点击 **「测试规则」** 按钮预览当前日志窗口被命中的 IP。保存后可点击 **「立即执行」** 直接聚合日志并生成封禁名单。
|
||||
|
||||
> [!TIP]
|
||||
> 自动 IP 组的详细语法和可用指标请参阅 [WAF 自动 IP 组规则语法](./waf-ip-group-expr.md)。
|
||||
|
||||
---
|
||||
|
||||
### 第二步:创建与配置 WAF 规则组
|
||||
|
||||
1. 导航至左侧菜单 **「安全性」->「WAF」**,点击 **「创建规则组」**。
|
||||
2. 填写规则组名称(如 `production-api-shield`),选择是否为「全局规则组」。
|
||||
3. 进入规则组详情,在下方几个配置 Tab 中依次设置:
|
||||
|
||||
#### 1. 黑白名单配置 (Allow / Block Lists)
|
||||
* **直录 IP**:可直接在框内按行填入临时需要白名单放行或黑名单阻断的单个 IP 或网段。
|
||||
* **IP 组引用**:点击「绑定 IP 组」,选择你在第一步中配置好的手动、自动或订阅 IP 组。白名单引用会直接放行,黑名单引用则直接阻断。
|
||||
|
||||
#### 2. 地域限制 (GeoIP)
|
||||
* **说明**:OpenFlare 集成了 GeoIP 地理位置解析。
|
||||
* **配置**:可开启地域限制开关,模式可选择「仅允许」或「禁止」。
|
||||
* * 例如,若你的服务只服务于国内,可以将模式设为「仅允许」,并在国家列表中勾选 `中国`。
|
||||
* * 支持细化到具体省份/地区(Region),一键拦截特定地理区域的恶意流量。
|
||||
|
||||
#### 3. 人机挑战配置 (PoW CC 防护)
|
||||
* **说明**:开启防 CC 的人机挑战。当请求触发防CC机制时,浏览器会渲染一个静默挑战页面,并在几百毫秒内完成数学计算(哈希碰撞)。通过后会被写入 Cookie,后续访问直接放行。此过程对真实用户几乎无感,但能完美拦截不支持 JS/不具备计算能力的爆破脚本与 CC 僵尸工具。
|
||||
* **核心参数**:
|
||||
* **开启状态**:启用/禁用。
|
||||
* **哈希难度**:控制碰撞难度(建议设定为 `4` 或 `5`)。
|
||||
* **Cookie 有效期**:挑战通过后,在多长时间内免验证(例如 `3600` 秒)。
|
||||
* **自定义挑战 HTML**:可定制挑战中的 Loading 页面风格,让其融入你的业务设计。
|
||||
|
||||
#### 4. 拦截返回 (Block Response)
|
||||
* **说明**:设定 WAF 规则拦截恶意请求时的返回行为。
|
||||
* **配置**:
|
||||
* **拦截状态码**:可自定义拦截响应的 HTTP 状态码,例如标准的 `403`,或带有趣味性质的 `418 (I'm a teapot)`。
|
||||
* **拦截响应体**:可在此输入自定义的 HTML 内容,展示给被拦截的攻击者(如:“WAF 拦截:你的请求已被记录”)。
|
||||
|
||||
---
|
||||
|
||||
### 第三步:将规则组关联到路由规则
|
||||
|
||||
规则组配置完成后,并不会自动生效,你需要将其与具体的路由规则绑定。
|
||||
|
||||
* **关联配置步骤**:进入 **「规则管理」** 页面,点击进入对应反代或静态托管规则的详情,切换到 **「WAF」** 选项卡,勾选并绑定刚才创建的 WAF 规则组。
|
||||
|
||||
> [!NOTE]
|
||||
> 如果规则组被标记为 **「全局规则组 (is_global)」**,它将自动应用到网关上托管的**所有网站**,无需手动执行绑定。
|
||||
|
||||
---
|
||||
|
||||
### 第四步:发布并生效配置
|
||||
|
||||
1. 如果你修改了 **规则组定义**、**GeoIP 范围**、**PoW 防CC难度** 或 **网站的绑定关系**:
|
||||
* 你需要点击管理端右上角的 **「配置预览」** -> **「发布并激活」**。
|
||||
* Agent 拉取并校验新版本后,将重写本地 OpenResty 核心配置文件(`waf_config.json` 等)并平滑重载进程使策略生效。
|
||||
2. 如果你只是更新了 **IP 组的成员名单**(如:在手动 IP 组中删减了一个 IP,或者自动 IP 组定时聚合出了一批新的封禁 IP):
|
||||
* **不需要做任何发布操作!**
|
||||
* Server 会在数据库更新后立即计算 IP 组全新的 Checksum 摘要。
|
||||
* 控制面会通过 **WebSocket 长连接实时向所有在线的 Agent 广播** 变更的 IP 组成员,Agent 接收后会增量覆写到本地的运行时磁盘文件 `waf_ip_groups.json`。
|
||||
* OpenResty Lua 引擎在处理新请求时,会在微秒级计算文件哈希,若发现 Checksum 变更则实时重载入内存字典(`ngx.shared`),**整个过程全程不需要 reload 任何 Nginx 服务,对线上高并发业务毫无影响**。
|
||||
* 即使 WebSocket 连接意外中断,Agent 也会在每周期心跳中上报本地 Checksum,由 Server 差分补齐下发,确保万无一失。
|
||||
|
||||
---
|
||||
|
||||
## WAF 判定逻辑 (过滤漏斗)
|
||||
|
||||
当一个外部请求到达 OpenResty 数据面时,WAF 运行时引擎会以微秒级的极速开销进行如下判决流检测。只要判定出明确结果,即不再向下执行:
|
||||
|
||||
```text
|
||||
请求进入 access 阶段
|
||||
│
|
||||
▼
|
||||
获取当前请求绑定的所有规则组 (全局规则组 + 自定义规则组)
|
||||
│
|
||||
▼
|
||||
1. 匹配 IP 白名单 / 白名单 IP 组? ──────(是)─────► [ 放行 (ALLOW) ]
|
||||
│ (否)
|
||||
▼
|
||||
2. 匹配国家 / 省份地域白名单? ────────(是)─────► [ 放行 (ALLOW) ]
|
||||
│ (否)
|
||||
▼
|
||||
3. 匹配 IP 黑名单 / 黑名单 IP 组? ──────(是)─────► [ 拦截 (BLOCK) ] ──► 返回自定义状态码与HTML拦截页
|
||||
│ (否)
|
||||
▼
|
||||
4. 匹配国家 / 省份地域黑名单? ────────(是)─────► [ 拦截 (BLOCK) ] ──► 返回自定义状态码与HTML拦截页
|
||||
│ (否)
|
||||
▼
|
||||
5. 该站点是否启用了 PoW CC 防护?
|
||||
├───(是)───► [ 校验 PoW Cookie ] ──(验证通过)──► [ 放行 (ALLOW) ]
|
||||
│ │
|
||||
│ (未通过)
|
||||
│ ▼
|
||||
│ [ 渲染 PoW 挑战页 ] ──(计算正确)──► 写入 Cookie 并放行
|
||||
▼
|
||||
6. 未触发任何策略,属于正常业务流量 ───────────────► [ 放行 (ALLOW) ]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 最佳实践与调优建议
|
||||
|
||||
* **白名单放行语义**:一旦某个生效规则组配置了 IP 白名单、白名单 IP 组或地域白名单,且请求命中了其中至少一条白名单规则,该请求将被直接放行,并优先绕过后续的黑名单与 PoW 检查;未命中的请求则会继续进行黑名单等后续防护校验。
|
||||
* **白名单前置与保护**:在部署高强度黑名单或地域屏蔽前,建议首先创建一个「受信任 IP 组」,放入你团队的办公室出口 IP、本地开发 IP 以及可能访问你的第三方回调源站 IP(如微信、支付宝支付回调地址),并在规则组的**白名单**中优先引入。这可以有效防止误杀,确保信任的 IP 即使命中黑名单或 CC 限制也能无阻碍访问。
|
||||
* **合理微调 PoW 难度**:人机 CC 挑战的哈希碰撞计算(`challenge_difficulty`)是一把双刃剑。
|
||||
* 难度值 `3`:几乎瞬间完成计算,防 CC 强度低。
|
||||
* 难度值 `4`:普通手机/低端浏览器在 100~300ms 内完成计算,防护性能良好。
|
||||
* 难度值 `5`:需要 500ms~2s,防护性强,但低配端可能会感觉稍显卡顿。
|
||||
* 难度值 `6` 及以上:计算量呈指数级上升,可能导致移动端用户浏览器 CPU 持续打满卡死。**因此强烈建议在生产环境选用 `4` 或 `5`**。
|
||||
* **善用“测试规则”**:对于自动 IP 组,在点击保存之前务必点击 **「测试规则」**。通过分析当前窗口内被命中的 IP 列表,确认你的 Expr 表达式阈值(如请求数、404占比等)配置是否过宽或过紧,防止由于阈值配置不合理导致大面积误封正常用户。
|
||||
* **分离静态与动态黑名单**:不要将需要长期封禁的静态恶意 IP 填入自动封禁组(因为自动聚合的名单随时会被新的执行窗口覆盖)。应该将确定的恶意 IP 录入到一个专门的「手动封禁 IP 组」中,并让规则组同时引用该手动组与自动组。
|
||||
架构、图校验和失败回滚细节见 [WAF 可编排规则设计](../design/waf-orchestration-design.md)。
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Zone 域名迁移与发布验收
|
||||
|
||||
从旧版 `managed_domains` / 反代路由内嵌域名列迁移到 Zone + Zone 域名模型时,数据导入与表结构升级均由 **Server 启动时的 goose 自动迁移**完成,无需单独执行导入命令。
|
||||
|
||||
## 升级时发生了什么
|
||||
|
||||
启动(或滚动升级)包含 Zone 改造的 Server 版本时,**无需手动命令**,`migrator.Migrate()` 自动:
|
||||
|
||||
1. 应用 goose SQL:创建 `of_zones` / `of_zone_domains`(若尚未存在)。
|
||||
2. **自动导入**旧路由域名列(及无路由域名时的 `of_managed_domains`)为 Zone / Zone 域名,并绑定 `proxy_route_id` / `cert_id`(公共后缀列表解析注册根域)。
|
||||
3. 继续 goose SQL:删除 `of_managed_domains` 与 `of_proxy_routes` 冗余域名/证书列。
|
||||
|
||||
导入幂等:已存在的域名会跳过或补绑路由。
|
||||
|
||||
**若历史数据无法解析(冲突域名、无效根域、证书不存在等),启动失败。** 修复数据或恢复备份后再次启动即可重试。
|
||||
|
||||
## 建议操作
|
||||
|
||||
### 1. 升级前备份
|
||||
|
||||
```bash
|
||||
# PostgreSQL 示例
|
||||
pg_dump "$DATABASE_URL" > openflare-pre-zone-$(date +%Y%m%d).sql
|
||||
|
||||
# 或复制备份卷 / 快照;SQLite 则复制 data 目录中的库文件
|
||||
```
|
||||
|
||||
可选:在管理端记下当前**激活配置版本号**与 checksum,便于配置回滚对比。
|
||||
|
||||
### 2. 升级并启动 Server
|
||||
|
||||
部署新版本并启动即可。观察启动日志中的 goose 成功信息;若出现「迁移 Zone 失败(N 个冲突)」则按日志中的冲突项修复源数据后重启。
|
||||
|
||||
### 3. 升级后检查
|
||||
|
||||
1. 管理端 **网站** `/websites`:Zone 根域与域名计数是否合理。
|
||||
2. Zone 详情:域名、证书、关联路由 ID。
|
||||
3. **反代路由**:域名绑定来自 Zone 域名,而非旧手写字段。
|
||||
|
||||
### 4. 配置预览与发布
|
||||
|
||||
1. 在管理端查看配置差异 / 预览。
|
||||
2. **逐路由**核对:`server_name` 集合、证书路径、WAF Route ID、Pages 引用。
|
||||
3. **允许**旧快照 JSON 中路由上的冗余 `domain` / `domains` / `cert_ids` 消失。
|
||||
4. **不允许**数据面语义变化。
|
||||
5. 预览通过后发布;需要时在配置版本中激活升级前版本做配置回滚。数据库回退请使用升级前备份(Down 迁移不回填业务域名数据)。
|
||||
|
||||
## 相关文档
|
||||
|
||||
* [Zone 与域名资源设计](../design/zone-design.md)
|
||||
* [新建反代配置](./proxy-config.md)
|
||||
* [发布第一份配置](./first-site.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
# ClickHouse P0–P3 修复计划
|
||||
|
||||
> 状态: 已完成(已合并主工作区,`make code-check` 通过)
|
||||
> 策略: 4 个互不干扰 worktree 并行,最后由主代理合并
|
||||
|
||||
## 任务拆分
|
||||
|
||||
| ID | Worktree 主题 | 范围 | 禁止改动 |
|
||||
|----|---------------|------|----------|
|
||||
| WT1 | P0 清理语义 C1 | cleanup maintenance / delete / tasks | chwriter、dashboard、DDL 新 MV |
|
||||
| WT2 | 写路径 C2+H1+H2+H3 | chwriter、batchwriter、risk_control、model store 分层、status 指标 | goose 迁移、dashboard 读逻辑 |
|
||||
| WT3 | 读路径 H4+H5 | 最新快照查询、metric/openresty 小时 MV + 读路径 | chwriter、cleanup |
|
||||
| WT4 | P3 打磨 | 连接池/async_insert、traffic hourly TTL、UV 语义 | model store 分层、cleanup |
|
||||
|
||||
## 合并顺序
|
||||
|
||||
1. WT1 → 2. WT2 → 3. WT3 → 4. WT4
|
||||
(迁移文件时间戳已错开,changelog 由主代理统一写)
|
||||
|
||||
## 验收
|
||||
|
||||
各 worktree: 相关 `go test` + 可运行部分;合并后 `make code-check`。
|
||||
@@ -0,0 +1,491 @@
|
||||
# Zone 与域名资源重构 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 以稳定 ID 的 Zone 管理入口和正规化 Zone 域名替代 `managed_domains` 及反代路由中的域名/证书冗余字段,同时保持配置发布后的 OpenResty 行为不变。
|
||||
|
||||
**Architecture:** `of_zones` 管理可注册根域;`of_zone_domains` 是明确 FQDN、证书和反代路由之间的唯一关联来源。反代路由保留路由策略,配置快照在控制面联查 Zone 域名与证书后生成现有 OpenResty 配置格式。第一发布阶段保留旧列供可重复执行的历史数据导入读取;生产快照对比通过后才执行第二阶段清理。
|
||||
|
||||
**Tech Stack:** Go 1.25、Gin、GORM、goose(PostgreSQL/SQLite)、`golang.org/x/net/publicsuffix`、Next.js App Router、TypeScript、TanStack Query、shadcn/ui。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
* Zone URL 必须为 `/websites/:zoneId`,不得使用域名作为路由参数。
|
||||
* Zone 根域由 `publicsuffix.EffectiveTLDPlusOne` 解析;Zone 域名只接受明确 FQDN,拒绝 `*.`。
|
||||
* TLS 证书可含通配符 SAN;证书只能由 `of_zone_domains.cert_id` 指定,`of_proxy_routes` 不再保存证书字段。
|
||||
* `of_zone_domains.domain` 全局唯一;同一 Zone 域名至多绑定一条反代路由,路由可关联多个 Zone 的域名。
|
||||
* 不建立物理数据库外键;所有关联列必须建立显式索引。
|
||||
* 所有 HTTP 路由仅通过 `internal/router/v1/openflare/` 的管理端注册器委派;Handler 使用 `response.Abort*` 报错并补全 Swagger。
|
||||
* 不新增 DNS 记录管理、边缘函数、预览子域或多租户能力。
|
||||
* 每次 API 变更运行 `make swagger`;每个实现任务结束运行对应测试;完成前必须运行 `make code-check`。
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| 路径 | 职责 |
|
||||
| --- | --- |
|
||||
| `internal/db/migrator/goose/{postgres,sqlite}/202607120001_create_zone_domain_tables.sql` | 第一阶段 Zone/ZoneDomain DDL 与索引。 |
|
||||
| `internal/model/openflare_zone.go` | Zone、ZoneDomain 模型及数据访问。 |
|
||||
| `internal/apps/openflare/zone/{logics.go,routers.go,errs.go,legacy_import.go}` | Zone CRUD、概览、输入验证和历史导入。 |
|
||||
| `internal/cmd/migrate_zones.go` | 显式、可重复运行的历史 Zone 数据导入命令。 |
|
||||
| `internal/router/v1/openflare/register_zone.go` | `/api/v1/d/zones` 路由注册。 |
|
||||
| `internal/apps/openflare/proxy_route/*` | 以 `zone_domain_ids` 取代域名与证书输入。 |
|
||||
| `internal/apps/openflare/config_version/*`、`pkg/render/openresty/*` | 快照与 OpenResty 渲染改为使用 Zone 域名。 |
|
||||
| `frontend/lib/services/openflare/{zone.service.ts,types.ts,index.ts}` | Zone API 类型和服务。 |
|
||||
| `frontend/vitest.config.ts`、`frontend/tests/zone/*.test.tsx` | Zone 页面与域名选择器的最小前端测试运行环境。 |
|
||||
| `frontend/app/(main)/websites/*` | Zone 列表、`[zoneId]` 动态详情页和局部组件。 |
|
||||
| `frontend/app/(main)/proxy-routes/*` | Zone 域名选择器替换旧域名/证书编辑器。 |
|
||||
| `internal/db/migrator/goose/{postgres,sqlite}/202607130001_drop_legacy_route_domain_columns.sql` | 第二阶段删除旧表、列与索引。 |
|
||||
|
||||
### Task 1: 第一阶段 Schema、模型与迁移测试
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/db/migrator/goose/postgres/202607120001_create_zone_domain_tables.sql`
|
||||
- Create: `internal/db/migrator/goose/sqlite/202607120001_create_zone_domain_tables.sql`
|
||||
- Create: `internal/model/openflare_zone.go`
|
||||
- Create: `internal/model/openflare_zone_test.go`
|
||||
- Modify: `internal/model/openflare_proxy_route.go`
|
||||
- Test: `internal/db/migrator/migrator_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `model.Zone`, `model.ZoneDomain`, `ListZoneDomainsByRouteID(ctx, routeID)`, `ReplaceZoneDomainRouteBindings(ctx, routeID, domainIDs)`.
|
||||
- Consumes: existing `model.ProxyRoute` and `model.TLSCertificate` IDs; no physical FK.
|
||||
|
||||
- [x] **Step 1: 写失败的模型与迁移测试**
|
||||
|
||||
```go
|
||||
func TestReplaceZoneDomainRouteBindingsRejectsForeignDomain(t *testing.T) {
|
||||
// Create zones and domains, then assert a domain cannot be bound twice.
|
||||
}
|
||||
```
|
||||
|
||||
Run: `go test ./internal/model ./internal/db/migrator -run 'Zone|Migrat' -count=1`
|
||||
|
||||
Expected: FAIL,因为 Zone 模型和 goose 文件尚不存在。
|
||||
|
||||
- [x] **Step 2: 新建双方言 DDL**
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS of_zones (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
domain VARCHAR(255) NOT NULL,
|
||||
remark VARCHAR(255) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_of_zones_domain ON of_zones (domain);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS of_zone_domains (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
zone_id BIGINT NOT NULL,
|
||||
proxy_route_id BIGINT,
|
||||
domain VARCHAR(255) NOT NULL,
|
||||
cert_id BIGINT,
|
||||
remark VARCHAR(255) NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_of_zone_domains_domain ON of_zone_domains (domain);
|
||||
CREATE INDEX IF NOT EXISTS idx_of_zone_domains_zone_id ON of_zone_domains (zone_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_of_zone_domains_proxy_route_id ON of_zone_domains (proxy_route_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_of_zone_domains_cert_id ON of_zone_domains (cert_id);
|
||||
```
|
||||
|
||||
SQLite 使用 `INTEGER PRIMARY KEY AUTOINCREMENT`、`DATETIME`,字段/索引语义完全对齐。此任务不得删除旧列或旧表。
|
||||
|
||||
- [x] **Step 3: 实现模型和受事务保护的绑定替换**
|
||||
|
||||
```go
|
||||
type Zone struct { ID uint; Domain string; Remark string; CreatedAt time.Time; UpdatedAt time.Time }
|
||||
type ZoneDomain struct { ID uint; ZoneID uint; ProxyRouteID *uint; Domain string; CertID *uint; Remark string; CreatedAt time.Time; UpdatedAt time.Time }
|
||||
|
||||
func ReplaceZoneDomainRouteBindings(ctx context.Context, routeID uint, domainIDs []uint) error
|
||||
```
|
||||
|
||||
实现先锁定/读取请求域名,拒绝已绑定到其他路由的记录,再把当前路由已绑定但不在 `domainIDs` 的记录置空,最后将请求记录写为 `routeID`;所有动作放在同一 `db.DB(ctx).Transaction` 内。
|
||||
|
||||
- [x] **Step 4: 运行模型与迁移测试**
|
||||
|
||||
Run: `go test ./internal/model ./internal/db/migrator -run 'Zone|Migrat' -count=1`
|
||||
|
||||
Expected: PASS,空 SQLite 库可应用迁移,唯一域名和绑定排他性受保护。
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add internal/db/migrator/goose internal/model
|
||||
git commit -m "feat(zone): add normalized zone domain schema"
|
||||
```
|
||||
|
||||
### Task 2: Zone 领域逻辑、历史导入命令与管理 API
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/apps/openflare/zone/{logics.go,routers.go,errs.go,legacy_import.go,logics_test.go}`
|
||||
- Create: `internal/cmd/migrate_zones.go`
|
||||
- Create: `internal/router/v1/openflare/register_zone.go`
|
||||
- Modify: `internal/cmd/root.go`
|
||||
- Modify: `internal/router/v1/openflare/register_tls.go`
|
||||
- Test: `internal/apps/openflare/integration/security_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `zone.Create`, `zone.Update`, `zone.GetOverview`, `zone.ImportLegacy(ctx) (ImportReport, error)` and Zone REST handlers.
|
||||
- Consumes: Task 1 models; legacy `managed_domains` and proxy-route columns only inside `ImportLegacy`.
|
||||
|
||||
- [x] **Step 1: 写失败的逻辑与 API 测试**
|
||||
|
||||
```go
|
||||
func TestCreateZoneDomainRejectsWildcard(t *testing.T) { _, err := CreateDomain(ctx, zoneID, DomainInput{Domain: "*.example.com"}); require.EqualError(t, err, errDomainWildcardUnsupported) }
|
||||
func TestLegacyImportUsesEffectiveTLDPlusOne(t *testing.T) {
|
||||
root, err := zoneRoot("api.example.co.uk")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "example.co.uk", root)
|
||||
}
|
||||
```
|
||||
|
||||
集成测试请求 `POST /api/v1/d/zones/`、`POST /api/v1/d/zones/:id/domains`,并断言错误响应使用 400 信封。
|
||||
|
||||
- [x] **Step 2: 实现精确域名和 Zone 归属验证**
|
||||
|
||||
```go
|
||||
func zoneRoot(domain string) (string, error) { return publicsuffix.EffectiveTLDPlusOne(strings.ToLower(strings.TrimSpace(domain))) }
|
||||
func CreateDomain(ctx context.Context, zoneID uint, input DomainInput) (*model.ZoneDomain, error)
|
||||
```
|
||||
|
||||
拒绝空值、协议、路径和 `*`;要求 `zoneRoot(input.Domain) == zone.Domain`;若 `cert_id` 非空,验证 TLS 证书存在。Zone 根域创建也必须经 `EffectiveTLDPlusOne` 验证且输入等于结果。
|
||||
|
||||
- [x] **Step 3: 实现显式导入命令**
|
||||
|
||||
```go
|
||||
var migrateZonesCmd = &cobra.Command{Use: "migrate-zones", RunE: func(_ *cobra.Command, _ []string) error {
|
||||
report, err := zone.ImportLegacy(context.Background())
|
||||
return report.LogAndReturn(err)
|
||||
}}
|
||||
```
|
||||
|
||||
导入以事务执行:用 `routeidentity.DecodeDomains(route.Domains, route.Domain)` 读取旧路由;按 `domain_cert_ids` 的同一索引写入 `zone_domains.cert_id`;只在无路由域名时导入旧 `managed_domains`。发现无效根域、通配符记录或全局域名冲突时回滚并输出全部冲突项。重复执行不得生成重复 Zone/ZoneDomain。
|
||||
|
||||
- [x] **Step 4: 注册 API 并删除旧 managed-domain 路由**
|
||||
|
||||
```go
|
||||
zoneGroup := apiGroup.Group("/zones")
|
||||
zoneGroup.Use(apiutil.AdminMiddlewares()...)
|
||||
zoneGroup.GET("/", zone.ListHandler)
|
||||
zoneGroup.POST("/", zone.CreateHandler)
|
||||
zoneGroup.GET("/:id/overview", zone.GetOverviewHandler)
|
||||
```
|
||||
|
||||
把 `managed-domains` 路由块从 `register_tls.go` 移除;每个 Handler 使用 `apiutil.BindJSON` 和 `response.AbortBadRequest/AbortNotFound/AbortConflict`。
|
||||
|
||||
- [x] **Step 5: 验证并 Commit**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/zone ./internal/apps/openflare/integration -count=1 && make swagger`
|
||||
|
||||
Expected: PASS,Swagger 不再含 `/managed-domains` 且包含 `/zones`。
|
||||
|
||||
```bash
|
||||
git add internal/apps/openflare/zone internal/cmd internal/router/v1/openflare docs
|
||||
git commit -m "feat(zone): add zone management api and legacy importer"
|
||||
```
|
||||
|
||||
### Task 3: 反代路由改用 ZoneDomain 关联
|
||||
|
||||
**Files:**
|
||||
- Modify: `internal/apps/openflare/proxy_route/{logics.go,helpers.go,build_helpers.go,routers.go,errs.go,logics_test.go}`
|
||||
- Modify: `internal/model/openflare_proxy_route.go`
|
||||
- Modify: `internal/apps/openflare/tls/logics.go`
|
||||
- Modify: `internal/apps/openflare/origin/logics.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `zone_domain_ids []uint` and Task 1 binding API.
|
||||
- Produces: `proxy_route.Input{ZoneDomainIDs []uint}`, `proxy_route.View{ZoneDomains []ZoneDomainView}`.
|
||||
|
||||
- [x] **Step 1: 写失败的路由逻辑测试**
|
||||
|
||||
```go
|
||||
input := Input{SiteName: "api", ZoneDomainIDs: []uint{domainA.ID, domainB.ID}, EnableHTTPS: true}
|
||||
view, err := CreateProxyRoute(ctx, input)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []uint{domainA.ID, domainB.ID}, view.ZoneDomainIDs)
|
||||
```
|
||||
|
||||
同时覆盖:空 `zone_domain_ids`、重复 ID、其他路由已占用域名、HTTPS 域名无证书、证书 SAN 不覆盖。
|
||||
|
||||
- [x] **Step 2: 删除路由输入/视图中的旧域名与证书字段**
|
||||
|
||||
```go
|
||||
type ZoneDomainBindingInput struct {
|
||||
ZoneDomainIDs []uint `json:"zone_domain_ids"`
|
||||
}
|
||||
type ZoneDomainView struct { ID uint `json:"id"`; ZoneID uint `json:"zone_id"`; Domain string `json:"domain"`; CertID *uint `json:"cert_id"` }
|
||||
```
|
||||
|
||||
移除 `Input.Domain`、`Input.Domains`、`Input.CertID`、`Input.CertIDs`、`Input.DomainCertIDs` 及对应 View 字段;删除旧证书派生辅助函数与 `WebsiteService.match` 所需后端逻辑。
|
||||
|
||||
- [x] **Step 3: 用关联记录验证并构建路由**
|
||||
|
||||
在 `buildProxyRoute` 中读取所有 `ZoneDomainIDs`,对每个 HTTPS 域名调用现有 `validateCertificateCoverage`,再调用 `ReplaceZoneDomainRouteBindings`。更新/删除路由也必须在事务内同步解除关联。来源、证书删除检查和 Origin 路由摘要改从 `zone_domains` 查询域名/证书。
|
||||
|
||||
- [x] **Step 4: 运行路由和 TLS 回归测试**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/proxy_route ./internal/apps/openflare/tls ./internal/apps/openflare/origin -count=1`
|
||||
|
||||
Expected: PASS;任一证书已被 Zone 域名引用时,删除证书被拒绝。
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add internal/apps/openflare/proxy_route internal/apps/openflare/tls internal/apps/openflare/origin internal/model
|
||||
git commit -m "refactor(proxy): bind routes through zone domains"
|
||||
```
|
||||
|
||||
### Task 4: 配置快照、渲染与关联消费者
|
||||
|
||||
**Files:**
|
||||
- Modify: `internal/apps/openflare/config_version/{snapshot.go,helpers.go,logics.go,logics_test.go,certificate_snapshot_test.go,pages_snapshot.go}`
|
||||
- Modify: `pkg/render/openresty/{types.go,render.go,render_route.go,render_test.go}`
|
||||
- Modify: `internal/apps/openflare/{flared/logics.go,uptimekuma/sync.go}`
|
||||
- Modify: `internal/apps/openflare/routeidentity/identity.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: snapshot/render `Route{SiteName, Domains, DomainCertIDs}` built transiently from ZoneDomain rows; neither DB model nor API stores those fields.
|
||||
|
||||
- [x] **Step 1: 写快照等价性失败测试**
|
||||
|
||||
```go
|
||||
func TestBuildSnapshotReadsZoneDomainCertificates(t *testing.T) {
|
||||
// Two explicit ZoneDomains with different certs must render two TLS server blocks.
|
||||
}
|
||||
```
|
||||
|
||||
加入 Pages、Tunnel、WAF 绑定测试,断言 Route ID 与 `site_name` 未改变。
|
||||
|
||||
- [x] **Step 2: 在快照边界联查并生成临时渲染字段**
|
||||
|
||||
```go
|
||||
domains, err := model.ListZoneDomainsByRouteID(ctx, route.ID)
|
||||
snapshotRoute.Domains = maps.Values(domainNames)
|
||||
snapshotRoute.DomainCertIDs = certIDsInDomainOrder(domains)
|
||||
```
|
||||
|
||||
`pkg/render/openresty.Route` 可继续保留 `Domains` 与 `DomainCertIDs`,因为它是不可变配置快照的渲染输入;移除其中持久化主域/证书回退逻辑,所有错误消息改用 `SiteName`。
|
||||
|
||||
- [x] **Step 3: 移除旧字段回退路径**
|
||||
|
||||
删除 `routeidentity.DecodeDomains` 对持久化 `route.Domain` 的依赖;Flared、Uptime Kuma、配置 diff、WAF 文档和 Pages 错误信息都从 snapshot/ZoneDomain 查询的明确域名获取显示文本。
|
||||
|
||||
- [x] **Step 4: 运行数据面测试**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/config_version ./pkg/render/openresty ./internal/apps/openflare/flared ./internal/apps/openflare/uptimekuma -count=1`
|
||||
|
||||
Expected: PASS;迁移后的路由产生的 `server_name`、证书支持文件和 WAF RouteID 绑定与迁移前一致。
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add internal/apps/openflare/config_version internal/apps/openflare/flared internal/apps/openflare/uptimekuma internal/apps/openflare/routeidentity pkg/render/openresty
|
||||
git commit -m "refactor(config): render routes from zone domains"
|
||||
```
|
||||
|
||||
### Task 5: Zone 前端服务与 ID 动态页面
|
||||
|
||||
**Files:**
|
||||
- Create: `frontend/lib/services/openflare/zone.service.ts`
|
||||
- Create: `frontend/vitest.config.ts`
|
||||
- Create: `frontend/tests/zone/{websites-page.test.tsx,zone-page.test.tsx}`
|
||||
- Modify: `frontend/lib/services/openflare/{types.ts,index.ts}`
|
||||
- Modify: `frontend/lib/services/index.ts`
|
||||
- Modify: `frontend/app/(main)/websites/page.tsx`
|
||||
- Create: `frontend/app/(main)/websites/[zoneId]/page.tsx`
|
||||
- Create: `frontend/app/(main)/websites/[zoneId]/components/{zone-overview.tsx,zone-domains-table.tsx,zone-route-summary.tsx,zone-editor-dialog.tsx,zone-domain-dialog.tsx}`
|
||||
- Delete: `frontend/app/(main)/websites/detail/page.tsx`
|
||||
- Delete: `frontend/app/(main)/websites/detail/page-client.tsx`
|
||||
- Delete: legacy Website/managed-domain-only components after imports are removed.
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `ZoneService.list/getOverview/create/update/delete`, `ZoneDomainService.create/update/delete` and `ZoneOverview` TypeScript types.
|
||||
|
||||
- [x] **Step 1: 写服务与页面行为测试**
|
||||
|
||||
先安装仅用于本次页面测试的开发依赖:
|
||||
|
||||
```bash
|
||||
cd frontend && pnpm add -D vitest @testing-library/react @testing-library/jest-dom jsdom
|
||||
```
|
||||
|
||||
```ts
|
||||
expect(ZoneService.getOverview).toHaveBeenCalledWith(42)
|
||||
expect(screen.getByRole('heading', {name: 'example.com'})).toBeVisible()
|
||||
```
|
||||
|
||||
覆盖 `/websites/42` 的加载、404、空域名、搜索列表和从列表点击 ID 链接。
|
||||
|
||||
- [x] **Step 2: 实现类型化服务与查询键**
|
||||
|
||||
```ts
|
||||
export interface ZoneDomainItem { id: number; zone_id: number; proxy_route_id: number | null; domain: string; cert_id: number | null; remark: string }
|
||||
export class ZoneService extends OpenFlareBaseService { protected static override basePath = '/api/v1/d/zones' }
|
||||
export const zoneQueryKey = ['openflare', 'zones'] as const
|
||||
```
|
||||
|
||||
所有 React Query 回调使用箭头函数,避免静态 service `this` 丢失。
|
||||
|
||||
- [x] **Step 3: 用 Next 动态段实现 Zone 详情**
|
||||
|
||||
```tsx
|
||||
export default async function ZonePage({params}: PageProps<'/websites/[zoneId]'>) {
|
||||
const {zoneId} = await params
|
||||
return <ZonePageClient zoneId={Number(zoneId)} />
|
||||
}
|
||||
```
|
||||
|
||||
遵循本地 Next 文档:动态 `params` 是 Promise;无效或非正整数 ID 显示既有 `EmptyStateWithBorder`,不把域名写入 URL。主页面只维护页面骨架和 Tabs,具体 Tab 放入同目录组件。
|
||||
|
||||
- [x] **Step 4: 实现列表和详情交互**
|
||||
|
||||
列表仅渲染 Zone 根域及计数;详情使用概览、域名、路由、证书、设置 Tabs。域名弹窗拒绝 `*.`,但证书选择器不限制其 SAN。删除 Zone/域名使用确认对话框和服务端错误文案。
|
||||
|
||||
- [x] **Step 5: 验证并 Commit**
|
||||
|
||||
Run: `cd frontend && pnpm exec vitest run && pnpm lint`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
```bash
|
||||
git add frontend/lib/services frontend/app/'(main)'/websites
|
||||
git commit -m "feat(web): add zone-based website management"
|
||||
```
|
||||
|
||||
### Task 6: 反代路由前端切换到 Zone 域名选择器
|
||||
|
||||
**Files:**
|
||||
- Create: `frontend/app/(main)/proxy-routes/components/zone-domain-selector.tsx`
|
||||
- Create: `frontend/tests/zone/zone-domain-selector.test.tsx`
|
||||
- Modify: `frontend/app/(main)/proxy-routes/{components/proxy-route-create-sheet.tsx,components/helpers.ts,page-client.tsx}`
|
||||
- Modify: `frontend/app/(main)/proxy-routes/detail/{helpers.ts,page-client.tsx,components/domain-section.tsx}`
|
||||
- Delete: `frontend/app/(main)/proxy-routes/detail/components/domain-list-input.tsx`
|
||||
- Modify: `frontend/lib/services/openflare/types.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ZoneDomainItem[]` and route `zone_domain_ids: number[]`.
|
||||
- Produces: selector values with explicit domain/Zone/证书信息;不发送任何旧域名或证书字段。
|
||||
|
||||
- [x] **Step 1: 写失败的选择器测试**
|
||||
|
||||
```tsx
|
||||
render(<ZoneDomainSelector value={[7]} onChange={onChange} domains={[apiDomain]} />)
|
||||
expect(screen.getByText('api.example.com')).toBeVisible()
|
||||
expect(onChange).toHaveBeenCalledWith([7])
|
||||
```
|
||||
|
||||
覆盖搜索、跨 Zone 多选、已被其他路由占用的禁用项和 HTTPS 缺少证书的表单错误。
|
||||
|
||||
- [x] **Step 2: 移除旧前端负载与自动匹配**
|
||||
|
||||
从 `ProxyRouteItem`/`ProxyRouteMutationPayload` 删除 `domain`、`domains`、`primary_domain`、`cert_id`、`cert_ids`、`domain_cert_ids`;删除 `WebsiteService.match` 及 `DomainListInput` 自动填证书交互。
|
||||
|
||||
- [x] **Step 3: 实现 Zone 域名选择和保存负载**
|
||||
|
||||
```ts
|
||||
mutationFn: (payload) => ProxyRouteService.update(route.id, {
|
||||
...payload,
|
||||
zone_domain_ids: selectedDomainIDs,
|
||||
})
|
||||
```
|
||||
|
||||
展示每个选择项的 FQDN、所属 Zone 与证书;路由详情的“域名”区只编辑关联关系,证书链接跳转 Zone 详情而非路由内编辑。
|
||||
|
||||
- [x] **Step 4: 运行前端类型和交互测试**
|
||||
|
||||
Run: `cd frontend && pnpm exec tsc --noEmit`
|
||||
|
||||
Expected: PASS;不存在旧持久化域名/证书字段的 TypeScript 引用。
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/app/'(main)'/proxy-routes frontend/lib/services/openflare/types.ts
|
||||
git commit -m "refactor(web): select route domains from zones"
|
||||
```
|
||||
|
||||
### Task 7: 第一发布阶段验证、文档与发布前数据检查
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/design/zone-design.md`
|
||||
- Modify: `docs/changelog/index.md`
|
||||
- Modify: generated `docs/{docs.go,swagger.json,swagger.yaml}`
|
||||
- Create: `docs/guide/zone-domain-migration.md`
|
||||
|
||||
- [x] **Step 1: 为导入命令写可操作迁移指南**
|
||||
|
||||
文档写明备份、执行 `wavelet migrate-zones`、读取导入报告、发布预览、比较 `server_name`/证书支持文件、发布激活和回滚步骤;不允许在报告有冲突时继续。
|
||||
|
||||
- [x] **Step 2: 生成 Swagger 和更新未发布变更**
|
||||
|
||||
Run: `make swagger`
|
||||
|
||||
在 `[Unreleased]` 记录 Zone 管理、反代路由域名正规化和移除 managed-domain API。
|
||||
|
||||
- [x] **Step 3: 运行全量质量门禁**
|
||||
|
||||
Run: `go test ./... && make code-check`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
- [x] **Step 4: 做快照等价性验收**
|
||||
|
||||
在升级前导出活动版本,在导入后生成预览;逐个比较所有路由的明确 `server_name` 集合、证书路径、WAF RouteID 绑定与 Pages 部署引用。只允许旧快照的域名/证书冗余 JSON 消失,不允许数据面语义变化。
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add docs
|
||||
git commit -m "docs(zone): add migration and release verification guide"
|
||||
```
|
||||
|
||||
### Task 8: 第二发布阶段——删除旧表和冗余列
|
||||
|
||||
**Precondition:** 已在生产环境完成 Task 7 的导入、预览对比和至少一次发布/回滚验证;`migrate-zones` 报告无冲突。
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/db/migrator/goose/postgres/202607130001_drop_legacy_route_domain_columns.sql`
|
||||
- Create: `internal/db/migrator/goose/sqlite/202607130001_drop_legacy_route_domain_columns.sql`
|
||||
- Delete: `internal/model/openflare_managed_domain.go`
|
||||
- Delete: `internal/apps/openflare/tls/managed_domain.go`
|
||||
- Delete: `internal/apps/openflare/tls/helpers.go` 中仅用于旧路由证书数组的函数
|
||||
- Modify: legacy迁移相关测试、模型测试与 `docs/design/zone-design.md`
|
||||
|
||||
- [x] **Step 1: 写空库与升级库清理失败测试**
|
||||
|
||||
```go
|
||||
func TestLegacyRouteColumnsAreAbsentAfterCleanup(t *testing.T) {
|
||||
require.False(t, db.DB(ctx).Migrator().HasColumn(&model.ProxyRoute{}, "domain"))
|
||||
}
|
||||
```
|
||||
|
||||
- [x] **Step 2: 编写双方言清理 DDL**
|
||||
|
||||
PostgreSQL 删除旧唯一索引和 `domain`、`domains`、`cert_id`、`cert_ids`、`domain_cert_ids`,再删除 `of_managed_domains`;SQLite 使用重建 `of_proxy_routes` 表的迁移方式保留所有非旧字段与索引。Down 仅在开发数据库恢复旧结构,不回填历史数据。
|
||||
|
||||
- [x] **Step 3: 删除旧读取代码与测试 fixture**
|
||||
|
||||
删除所有 `route.Domain`、`route.Domains`、`route.CertID`、`route.CertIDs`、`route.DomainCertIDs` 的持久化引用;让编译器、Uptime Kuma、Flared、来源摘要及 API 只使用 ZoneDomain 查询结果。
|
||||
|
||||
- [x] **Step 4: 验证升级和完整回归**
|
||||
|
||||
Run: `go test ./internal/db/migrator ./internal/model ./internal/apps/openflare/... ./pkg/render/openresty -count=1 && make code-check`
|
||||
|
||||
Expected: PASS;全仓搜索不再发现旧 `ManagedDomain` 业务代码、`ProxyRoute` 持久化字段或管理端 API;渲染快照中的临时 `DomainCertIDs` 类型允许保留。
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add internal/db/migrator internal/model internal/apps frontend docs
|
||||
git commit -m "refactor(zone): remove legacy route domain storage"
|
||||
```
|
||||
|
||||
## Plan Self-Review
|
||||
|
||||
* Spec coverage: Tasks 1–4 交付正规化数据模型、API、迁移与数据面;Tasks 5–6 交付 ID 路由和 Zone 交互;Tasks 7–8 覆盖质量门禁与旧表清理。
|
||||
* Placeholder scan: 无待定标记或未定义的实现步骤;所有删除动作在明确的生产验证前置条件后执行。
|
||||
* Type consistency: 路由写入统一使用 `zone_domain_ids`,持久化关系统一为 `ZoneDomain.ProxyRouteID`,渲染边界仅使用临时 `Domains`/`DomainCertIDs`。
|
||||
@@ -0,0 +1,639 @@
|
||||
# WAF 可编排规则实现计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 将固定顺序的 WAF 规则组重构为可用 React Flow 编辑、发布时编译、OpenResty 内存执行的有序 DAG 规则系统。
|
||||
|
||||
**Architecture:** 控制面以带修订号的版本化 JSON 保存整张编辑态图,Server 保存与发布时执行同一套强校验并编译为精简运行态 DAG。规则仅随配置发布和 OpenResty reload 加载一次;动态 IP 组由协调 Worker 每 5 秒检查 checksum,变化时更新共享快照和各 Worker 本地内存对象。
|
||||
|
||||
**Tech Stack:** Go 1.25、Gin、GORM、goose、PostgreSQL/SQLite、OpenResty Lua、Next.js 16 App Router、React 19、TypeScript、`@xyflow/react`、TanStack Query、shadcn/ui、Vitest。
|
||||
|
||||
## 实现状态(2026-07-13)
|
||||
|
||||
Tasks 1–11 已实现,包含三段数据库迁移、图模型与编译器、规则 API、发布快照、OpenResty 内存执行器、IP 组协调刷新、React Flow 编辑器、有序绑定、GeoLite2 City/Country 支持以及中文文档与 Swagger 更新。React Flow 画布使用本地受控节点状态处理拖动,并支持显式或键盘删除普通节点与连线。Country 与 City MMDB 均随 Agent 内嵌,缺失文件在启动时从程序内初始化,网络仅用于后续周期更新。地域属性栏使用完整国家与 ISO 3166-2 一级行政区数据,国家同时展示中文名称与代码,行政区支持按名称或代码搜索。发布器保证空规则绑定编码为 `[]`,Lua 运行时兼容旧快照中的 `null` 数组,避免未启用或空绑定规则导致请求 500。PoW 节点通过共享内存暂存配置,并以 `ngx.exec` 显式参数把配置键传入内部挑战处理器,避免内部重定向丢失请求上下文后误报节点未执行。
|
||||
|
||||
当前工作区已完成 `go test ./...`、前端全量 Vitest(56 项)、`make swagger`、`make code-check` 与 `git diff --check` 验证。Next.js 生产构建在本机持续停留于 Turbopack 的 `Creating an optimized production build ...`,未返回编译错误或成功状态,故不计为通过。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 每张图恰好一个 `start` 和一个 `allow`;`block` 可多个;图必须无环、无悬空、无不可达节点,所有路径必须抵达 `allow` 或 `block`。
|
||||
- `ip_match` 与 `geo_match` 只输出 `true`/`false`,分别表示匹配与未匹配;`pow` 只输出 `next`。
|
||||
- 全局规则固定前置;路由自定义规则按绑定 `sequence` 升序执行;当前规则 `allow` 后继续下一条,`block` 立即终止。
|
||||
- 规则运行态 JSON 仅在 OpenResty reload 后由 Worker 加载一次;请求路径禁止文件 I/O、checksum 和 JSON 解码。
|
||||
- IP 组请求路径始终读取 Worker 本地对象;整个实例每 5 秒最多一个 Worker 检查 checksum。
|
||||
- 迁移只保留规则名称、全局标记、启用状态和绑定关系,旧策略统一重置为 `开始 → 通过`。
|
||||
- 所有 HTTP 路由仅在 `internal/router/router.go` 的既有分发体系中通过 `internal/router/v1/openflare/register_waf.go` 注册;API 失败使用 `response.Abort*`。
|
||||
- API Handler 变化后运行 `make swagger`;代码完成后运行 `make code-check`;代码变更写入 `docs/changelog/index.md` 的 `[Unreleased]`。
|
||||
- 前端不得删除 `frontend/node_modules`;使用 shadcn variant 与全局 CSS 变量,页面根容器保持 `w-full py-6 px-1`。
|
||||
- 实现前阅读 `.agent/skills/database-migration/SKILL.md`、`.agent/skills/new-api/SKILL.md`、`.agent/skills/shadcn/SKILL.md` 以及 `frontend/node_modules/next/dist/docs/01-app/03-api-reference/03-file-conventions/page.md` 等匹配的 Next.js 本地文档。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与背景
|
||||
|
||||
当前 `OpenFlareWAFRuleGroup` 把 IP/地域黑白名单、PoW 与阻止响应平铺为固定字段,Lua 按硬编码顺序判断,无法表达用户自定义分支。本次交付包含图模型、强校验、API、迁移、发布编译、Lua DAG 执行、有序绑定、IP 组五秒内存刷新和 React Flow 编辑器;不包含循环、脚本节点、表达式节点、子图和跨规则跳转。
|
||||
|
||||
## 2. 数据与控制流
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[React Flow 编辑态图] -->|revision + graph| API[Server 校验与保存]
|
||||
API --> DB[(规则 graph JSON)]
|
||||
DB --> PUB[发布编译器]
|
||||
PUB --> SNAP[运行态 DAG 快照]
|
||||
SNAP --> AGENT[Agent 原子落盘]
|
||||
AGENT -->|reload| LUA[OpenResty Worker 内存]
|
||||
IPS[IP 组异步更新] -->|JSON 后 checksum| TIMER[5 秒协调定时器]
|
||||
TIMER --> SHM[ngx.shared 原始快照]
|
||||
SHM --> LUA
|
||||
```
|
||||
|
||||
## 3. 文件结构与职责
|
||||
|
||||
- `internal/apps/openflare/waf/graph_types.go`:编辑态图、节点配置、运行态图和默认图类型。
|
||||
- `internal/apps/openflare/waf/graph_validate.go`:结构、端口、配置、引用、可达性和终止性校验。
|
||||
- `internal/apps/openflare/waf/graph_compile.go`:删除 UI 字段、编译索引化 DAG、收集 IP 组引用。
|
||||
- `internal/apps/openflare/waf/rule_logics.go`:规则元数据、修订保存和有序绑定逻辑;从现有过大的 `logics.go` 中抽离规则职责。
|
||||
- `internal/apps/openflare/waf/rule_routers.go`:规则 API Handler 与 Swagger;IP 组 Handler 留在现有文件或后续独立拆分。
|
||||
- `internal/apps/agent/nginx/waf_assets.go`:只负责嵌入 Lua 文件;实际 Lua 拆到 `internal/apps/agent/nginx/waf_runtime.lua` 与 `waf_ip_groups.lua` 并使用 `go:embed`,避免继续膨胀 Go 字符串。
|
||||
- `frontend/app/(main)/waf/page.tsx`:规则/IP 组列表和仅名称创建流程。
|
||||
- `frontend/app/(main)/waf/rules/editor/page.tsx`:静态可导出的编辑器路由入口,通过查询参数读取规则 ID,避免 Next 静态导出的动态参数限制。
|
||||
- `frontend/app/(main)/waf/rules/editor/components/`:画布、节点、节点库、属性栏和校验提示,单文件保持低于 600 行。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 数据库迁移与持久化模型
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/db/migrator/goose/postgres/202607150001_orchestrate_waf_rules.sql`
|
||||
- Create: `internal/db/migrator/goose/sqlite/202607150001_orchestrate_waf_rules.sql`
|
||||
- Create: `internal/db/migrator/goose/postgres/202607150002_reset_waf_rule_graphs.sql`
|
||||
- Create: `internal/db/migrator/goose/sqlite/202607150002_reset_waf_rule_graphs.sql`
|
||||
- Modify: `internal/model/openflare_waf.go`
|
||||
- Create: `internal/model/openflare_waf_graph_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `Graph string`, `Revision uint64`, `Sequence int`;`UpdateOpenFlareWAFRuleGraph(ctx, id, revision, graph) (uint64, error)`;绑定查询按 `sequence, id` 排序。
|
||||
- Consumes: 现有 `OpenFlareWAFRuleGroup` 与 `OpenFlareWAFRuleGroupBinding`。
|
||||
|
||||
- [ ] **Step 1: 阅读数据库迁移 Skill 并写迁移失败测试**
|
||||
|
||||
测试建立旧 Schema、插入两个规则和无序绑定、执行迁移后断言图统一为默认图、`revision = 1`、绑定顺序稳定。测试核心断言:
|
||||
|
||||
```go
|
||||
require.JSONEq(t, `{"schema_version":1,"nodes":[{"id":"start","type":"start","position":{"x":0,"y":0},"config":{}},{"id":"allow","type":"allow","position":{"x":320,"y":0},"config":{}}],"edges":[{"id":"start-allow","source":"start","source_handle":"next","target":"allow"}]}`, group.Graph)
|
||||
assert.Equal(t, uint64(1), group.Revision)
|
||||
assert.Equal(t, []int{0, 1}, []int{bindings[0].Sequence, bindings[1].Sequence})
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行模型测试确认失败**
|
||||
|
||||
Run: `go test ./internal/model -run 'TestOpenFlareWAFGraph|TestReplaceOpenFlareWAFRuleGroupBindings' -count=1`
|
||||
|
||||
Expected: FAIL,缺少新字段或迁移列。
|
||||
|
||||
- [ ] **Step 3: 编写 PostgreSQL 与 SQLite goose 迁移**
|
||||
|
||||
`202607150001` 只执行 DDL:两端都增加 `graph TEXT NOT NULL`、`revision BIGINT/INTEGER NOT NULL DEFAULT 1`、`sequence INTEGER NOT NULL DEFAULT 0`。`202607150002` 只执行 DML:用确定性的 `id` 顺序为每个 `proxy_route_id` 回填 sequence,并将所有 graph 重置为同一默认 JSON。Down 分别恢复数据语义与旧列结构;不要创建物理外键,禁止把 DDL 与 DML 放入同一个迁移文件。
|
||||
|
||||
- [ ] **Step 4: 实现乐观锁与有序绑定模型方法**
|
||||
|
||||
```go
|
||||
var ErrWAFRuleRevisionConflict = errors.New("waf rule revision conflict")
|
||||
|
||||
func UpdateOpenFlareWAFRuleGraph(ctx context.Context, id uint, revision uint64, graph string) (uint64, error) {
|
||||
result := db.DB(ctx).Model(&OpenFlareWAFRuleGroup{}).
|
||||
Where("id = ? AND revision = ?", id, revision).
|
||||
Updates(map[string]any{"graph": graph, "revision": gorm.Expr("revision + 1")})
|
||||
if result.Error != nil { return 0, result.Error }
|
||||
if result.RowsAffected != 1 { return 0, ErrWAFRuleRevisionConflict }
|
||||
return revision + 1, nil
|
||||
}
|
||||
```
|
||||
|
||||
绑定替换在事务中按输入下标写 `Sequence: index`;查询显式 `Order("sequence asc").Order("id asc")`。
|
||||
|
||||
- [ ] **Step 5: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/model ./internal/db/migrator/... -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(waf): add graph persistence and binding order`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 图类型、默认图和强校验器
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/apps/openflare/waf/graph_types.go`
|
||||
- Create: `internal/apps/openflare/waf/graph_validate.go`
|
||||
- Create: `internal/apps/openflare/waf/graph_validate_test.go`
|
||||
- Modify: `internal/apps/openflare/waf/errs.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `RuleGraph`, `RuleNode`, `RuleEdge`, `DefaultRuleGraph() RuleGraph`, `ValidateRuleGraph(ctx context.Context, graph RuleGraph, ipGroupExists func(context.Context, uint) (bool, error)) error`。
|
||||
- Consumes: Task 1 的 JSON 持久化字段。
|
||||
|
||||
- [ ] **Step 1: 写表驱动失败测试**
|
||||
|
||||
覆盖合法默认图、重复 start/allow、环、不可达节点、悬空端口、错误 handle、同 handle 多目标、无终止路径、未知类型、无效 IP/CIDR、缺失 IP 组、非法国家/地区、PoW 范围和超限图。
|
||||
|
||||
```go
|
||||
tests := []struct{name string; mutate func(*RuleGraph); want string}{
|
||||
{"cycle", addCycle, "规则图不能包含循环"},
|
||||
{"missing false edge", removeFalseEdge, "节点 match-1 的 false 出口未连接"},
|
||||
{"unreachable", addUnreachableNode, "节点 orphan 无法从开始节点到达"},
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/waf -run TestValidateRuleGraph -count=1`
|
||||
|
||||
Expected: FAIL,类型和校验函数不存在。
|
||||
|
||||
- [ ] **Step 3: 定义带判别联合的图类型**
|
||||
|
||||
```go
|
||||
type RuleNodeType string
|
||||
const (
|
||||
RuleNodeStart RuleNodeType = "start"
|
||||
RuleNodeAllow RuleNodeType = "allow"
|
||||
RuleNodeBlock RuleNodeType = "block"
|
||||
RuleNodeIPMatch RuleNodeType = "ip_match"
|
||||
RuleNodeGeoMatch RuleNodeType = "geo_match"
|
||||
RuleNodePoW RuleNodeType = "pow"
|
||||
)
|
||||
type RuleGraph struct { SchemaVersion int `json:"schema_version"`; Nodes []RuleNode `json:"nodes"`; Edges []RuleEdge `json:"edges"` }
|
||||
type RuleEdge struct { ID, Source, SourceHandle, Target string }
|
||||
```
|
||||
|
||||
`RuleNode.Config` 先用 `json.RawMessage` 解码到明确的 `IPMatchConfig`、`GeoMatchConfig`、`PoWNodeConfig`、`BlockNodeConfig`,禁止透传未知字段。
|
||||
|
||||
- [ ] **Step 4: 实现结构和 DFS/Kahn 校验**
|
||||
|
||||
先检查大小、ID、类型、端口和配置,再用 Kahn 检测环,用从 start 的 DFS 检测可达性,用反向图从所有终止节点遍历检测终止性。错误文案携带节点/边 ID,供前端定位。
|
||||
|
||||
- [ ] **Step 5: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/waf -run 'Test(DefaultRuleGraph|ValidateRuleGraph)' -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(waf): validate composable rule graphs`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 运行态图编译器
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/apps/openflare/waf/graph_compile.go`
|
||||
- Create: `internal/apps/openflare/waf/graph_compile_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `CompileRuleGraph(graph RuleGraph) (RuntimeRuleGraph, error)`、`ReferencedIPGroupIDs(graph RuleGraph) []uint`。
|
||||
- Consumes: Task 2 的已校验图类型。
|
||||
|
||||
- [ ] **Step 1: 写编译快照测试**
|
||||
|
||||
断言位置和显示名不进入 JSON、节点通过 ID map O(1) 查找、出口按 handle 编译、IP 组 ID 去重排序。
|
||||
|
||||
```go
|
||||
compiled, err := CompileRuleGraph(graph)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "start", compiled.Entry)
|
||||
assert.Equal(t, "allow", compiled.Nodes["match"].Next["true"])
|
||||
assert.Equal(t, []uint{2, 7}, ReferencedIPGroupIDs(graph))
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/waf -run 'TestCompileRuleGraph|TestReferencedIPGroupIDs' -count=1`
|
||||
|
||||
Expected: FAIL,编译接口不存在。
|
||||
|
||||
- [ ] **Step 3: 实现确定性编译**
|
||||
|
||||
输出结构只保留 `entry`、按节点 ID 索引的类型化运行配置和 handle→target 映射;序列化前对可排序切片排序,确保相同图生成相同快照和 checksum。
|
||||
|
||||
- [ ] **Step 4: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/waf -run 'TestCompileRuleGraph|TestReferencedIPGroupIDs' -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(waf): compile rule graphs for runtime`
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 规则 API、修订冲突与有序绑定
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/apps/openflare/waf/rule_logics.go`
|
||||
- Create: `internal/apps/openflare/waf/rule_routers.go`
|
||||
- Create: `internal/apps/openflare/waf/rule_logics_test.go`
|
||||
- Modify: `internal/apps/openflare/waf/logics.go`
|
||||
- Modify: `internal/apps/openflare/waf/routers.go`
|
||||
- Modify: `internal/router/v1/openflare/register_waf.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `CreateRuleInput{Name string}`、`SaveRuleGraphInput{Revision uint64; Graph RuleGraph}`、`UpdateRuleMetaInput{Name string; Enabled bool}`;创建、详情、元数据、图保存、删除和有序绑定 API。
|
||||
- Consumes: Tasks 1–3 的模型、默认图和校验器。
|
||||
|
||||
- [ ] **Step 1: 阅读 new-api Skill,写逻辑与 Handler 失败测试**
|
||||
|
||||
覆盖只传名称创建默认图、空名 400、图非法 400、revision 冲突 409、绑定顺序往返不变、全局规则不能被路由绑定排序覆盖。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/waf ./internal/router/v1/openflare -run 'Test(CreateRule|SaveRuleGraph|ReplaceSiteRuleGroups)' -count=1`
|
||||
|
||||
Expected: FAIL,API 输入与路由尚未实现。
|
||||
|
||||
- [ ] **Step 3: 实现 logic 与安全错误映射**
|
||||
|
||||
```go
|
||||
func SaveRuleGraph(ctx context.Context, id uint, input SaveRuleGraphInput) (*RuleView, error) {
|
||||
if err := ValidateRuleGraph(ctx, input.Graph, ipGroupExists); err != nil { return nil, err }
|
||||
raw, err := json.Marshal(input.Graph)
|
||||
if err != nil { return nil, err }
|
||||
if _, err = model.UpdateOpenFlareWAFRuleGraph(ctx, id, input.Revision, string(raw)); err != nil { return nil, err }
|
||||
return GetRule(ctx, id)
|
||||
}
|
||||
```
|
||||
|
||||
数据库/编码错误用 `pkg/logger` 记录后映射 `AbortInternal`;校验错误用 `AbortBadRequest`;revision 冲突用 `AbortConflict`。
|
||||
|
||||
- [ ] **Step 4: 注册路由并补全 Swagger**
|
||||
|
||||
保留 `/rule-groups` 路径以减少前端与兼容面变化,但将创建 payload 改为仅名称,新增 `POST /rule-groups/:id/graph` 与 `POST /rule-groups/:id/meta`。所有 `@Failure 400/404/409/500` 与统一 response envelope 完整声明。
|
||||
|
||||
- [ ] **Step 5: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/waf ./internal/router/v1/openflare -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(api): expose orchestrated waf rules`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: 发布快照与规则顺序
|
||||
|
||||
**Files:**
|
||||
- Modify: `internal/apps/openflare/config_version/snapshot.go`
|
||||
- Modify: `internal/apps/openflare/config_version/logics_test.go`
|
||||
- Create: `internal/apps/openflare/config_version/waf_graph_snapshot_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: 发布快照中的 `rule_groups[].graph` 运行态 DAG、按 sequence 排序的 `bindings[].rule_group_ids`、图引用 IP 组集合。
|
||||
- Consumes: Task 3 编译器与 Task 1 有序绑定。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
建立全局规则和两个自定义图,绑定顺序 `[customB, customA]`,断言快照保持该顺序、运行图无 position、只包含图引用的 IP 组;非法启用图阻止预览/发布。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/config_version -run 'TestWAFGraphSnapshot|TestBuildSnapshotRejectsInvalidWAFGraph' -count=1`
|
||||
|
||||
Expected: FAIL,快照仍输出旧固定字段并按 ID 排序。
|
||||
|
||||
- [ ] **Step 3: 替换固定字段快照编译**
|
||||
|
||||
删除 `snapshotWAFRuleGroup` 的旧黑白名单/PoW 字段,加入 `Graph waf.RuntimeRuleGraph`;`buildSnapshotWAFIPGroups` 从所有编辑图的 `ReferencedIPGroupIDs` 聚合;绑定不再按 group ID 排序。
|
||||
|
||||
- [ ] **Step 4: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/config_version ./internal/apps/openflare/integration -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(waf): publish ordered runtime graphs`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: OpenResty 内存 DAG 执行器
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/apps/agent/nginx/waf_runtime.lua`
|
||||
- Create: `internal/apps/agent/nginx/waf_runtime_spec.lua`
|
||||
- Modify: `internal/apps/agent/nginx/waf_assets.go`
|
||||
- Modify: `internal/apps/agent/nginx/waf_assets_test.go`
|
||||
- Modify: `internal/apps/agent/nginx/manager.go`
|
||||
- Modify: `internal/apps/agent/nginx/manager_test.go`
|
||||
- Modify: `internal/apps/agent/nginx/pow_assets.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `require("waf.runtime").check()`,模块加载时读取一次规则配置,请求时执行内存 DAG。
|
||||
- Consumes: Task 5 的运行态快照;现有 PoW challenge/session 代码。
|
||||
|
||||
- [ ] **Step 1: 写 Lua 执行器失败测试**
|
||||
|
||||
用 stub `ngx` 覆盖 IP true/false、地域 true/false、PoW 接管/完成、多个 block 响应、全局前置、自定义顺序、未知节点 fail-closed、请求期间 `io.open` 调用次数为 0。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/agent/nginx -run 'TestWAFRuntime' -count=1`
|
||||
|
||||
Expected: FAIL,运行时仍为固定链且每次请求读取配置。
|
||||
|
||||
- [ ] **Step 3: 将规则加载移到 Lua 模块初始化**
|
||||
|
||||
```lua
|
||||
local rules_config = assert(load_json_once(runtime_dir .. "/waf_config.json"))
|
||||
|
||||
function _M.check()
|
||||
local rules = active_rules_for_site(rules_config, ngx.var.openflare_waf_site or "")
|
||||
for _, rule in ipairs(rules) do
|
||||
local decision = execute_graph(rule.graph)
|
||||
if decision.kind == "block" then return render_block(decision.config) end
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
在 `manager.go` 生成的 `http` 块中显式加入 `init_worker_by_lua_block { require("waf.runtime").init() }`,使新 Worker 在 reload 启动阶段完成读取与解析,而不是推迟到首个请求。模块缓存使每个 Worker 只解析一次;执行器设置最大步数为节点数,任何损坏图都记录限频错误并返回阻止响应。
|
||||
|
||||
- [ ] **Step 4: 将 PoW 变为节点执行接口**
|
||||
|
||||
抽取现有 PoW runtime 为 `pow.evaluate(config)`:完成返回 `true`,未完成直接输出/重定向挑战并返回接管标记。移除“按站点选择第一个 pow_enabled 规则”的旧扫描逻辑。
|
||||
|
||||
- [ ] **Step 5: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/apps/agent/nginx ./internal/apps/agent/sync -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(agent): execute waf graphs from worker memory`
|
||||
|
||||
---
|
||||
|
||||
### Task 7: IP 组 checksum 与五秒内存刷新
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/apps/agent/nginx/waf_ip_groups.lua`
|
||||
- Create: `internal/apps/agent/nginx/waf_ip_groups_spec.lua`
|
||||
- Modify: `internal/apps/agent/sync/service.go`
|
||||
- Modify: `internal/apps/agent/sync/service_test.go`
|
||||
- Modify: `internal/apps/agent/nginx/waf_assets.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `waf_ip_groups.json.checksum`;Lua `ip_groups.current()` 返回 Worker 本地对象;协调刷新间隔固定 5 秒。
|
||||
- Consumes: 现有 Agent IP 组同步 payload 与独立的 `ngx.shared.openflare_waf_ip_groups`(64 MiB);完整运行时快照上限为 20 MiB。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
断言 Agent 先原子替换 JSON、最后原子替换 checksum;Lua 稳定状态 15 秒只读取 checksum 3 次且不读 JSON;变化时全实例只读一次 JSON;非法新 JSON 保留旧对象。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/agent/sync ./internal/apps/agent/nginx -run 'TestWAFIPGroup(Checksum|Refresh)' -count=1`
|
||||
|
||||
Expected: FAIL,checksum sidecar 和定时器不存在。
|
||||
|
||||
- [ ] **Step 3: Agent 写 checksum sidecar**
|
||||
|
||||
checksum 使用 Agent 已有快照 checksum;写入采用同目录临时文件、fsync/close、rename 的现有原子文件工具。严格顺序为 JSON rename 成功后 checksum rename。
|
||||
|
||||
- [ ] **Step 4: 实现协调 Worker 刷新**
|
||||
|
||||
```lua
|
||||
local function tick(premature)
|
||||
if premature then return end
|
||||
local ok = shared:add("ip_refresh_lock", true, 4)
|
||||
if ok then refresh_from_checksum() end
|
||||
adopt_shared_snapshot_if_changed()
|
||||
end
|
||||
ngx.timer.every(5, tick)
|
||||
```
|
||||
|
||||
协调 Worker 变化时把 raw JSON 和 checksum 写共享字典;每个 Worker 只在 shared version 变化时 decode 到模块局部 `current_groups`。请求只调用 `ip_groups.current()`。
|
||||
|
||||
- [ ] **Step 5: 运行测试并提交**
|
||||
|
||||
Run: `go test ./internal/apps/agent/nginx ./internal/apps/agent/sync -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `perf(waf): refresh ip groups by checksum timer`
|
||||
|
||||
---
|
||||
|
||||
### Task 8: 前端类型、Service 与创建流程
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/package.json`
|
||||
- Modify: `frontend/pnpm-lock.yaml`
|
||||
- Modify: `frontend/lib/services/openflare/types.ts`
|
||||
- Modify: `frontend/lib/services/openflare/waf.service.ts`
|
||||
- Modify: `frontend/app/(main)/waf/page.tsx`
|
||||
- Create: `frontend/app/(main)/waf/components/create-rule-dialog.tsx`
|
||||
- Modify: `frontend/app/(main)/waf/components/rule-groups-table.tsx`
|
||||
- Delete after replacement: `frontend/app/(main)/waf/components/rule-group-sheet.tsx`
|
||||
- Test: `frontend/tests/unit/waf-rule-service.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: TypeScript 判别联合 `WAFRuleNode`、`WAFRuleGraph`、`WAFRule`;`WafService.createRule({name})`、`saveRuleGraph(id, {revision, graph})`。
|
||||
- Consumes: Task 4 API。
|
||||
|
||||
- [ ] **Step 1: 阅读 shadcn 与 Next 本地文档,安装 React Flow**
|
||||
|
||||
Run: `cd frontend && pnpm add @xyflow/react`
|
||||
|
||||
Expected: `package.json` 与 lockfile 增加同一版本的 `@xyflow/react`。
|
||||
|
||||
- [ ] **Step 2: 写 Service 与创建流程失败测试**
|
||||
|
||||
断言创建 payload 只有 `{name}`,保存包含 revision,创建成功导航到 `/waf/rules/editor?id=<id>`,不再打开旧规则大表单。
|
||||
|
||||
- [ ] **Step 3: 运行测试确认失败**
|
||||
|
||||
Run: `cd frontend && pnpm vitest run tests/unit/waf-rule-service.test.ts`
|
||||
|
||||
Expected: FAIL,旧 payload 仍要求固定字段。
|
||||
|
||||
- [ ] **Step 4: 实现类型、Service 和名称对话框**
|
||||
|
||||
```ts
|
||||
export type WAFRuleNode =
|
||||
| {id: string; type: 'start'; position: XYPosition; config: Record<string, never>}
|
||||
| {id: string; type: 'ip_match'; position: XYPosition; config: IPMatchConfig}
|
||||
| {id: string; type: 'geo_match'; position: XYPosition; config: GeoMatchConfig}
|
||||
| {id: string; type: 'pow'; position: XYPosition; config: PoWNodeConfig}
|
||||
| {id: string; type: 'allow'; position: XYPosition; config: Record<string, never>}
|
||||
| {id: string; type: 'block'; position: XYPosition; config: BlockNodeConfig};
|
||||
```
|
||||
|
||||
静态方法作为 React Query 回调时继续用箭头函数包裹。列表创建成功后 `router.push('/waf/rules/editor?id=' + rule.id)`。
|
||||
|
||||
- [ ] **Step 5: 运行测试并提交**
|
||||
|
||||
Run: `cd frontend && pnpm vitest run tests/unit/waf-rule-service.test.ts && pnpm lint`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `feat(frontend): create orchestrated waf rules`
|
||||
|
||||
---
|
||||
|
||||
### Task 9: React Flow 编排器与固定属性栏
|
||||
|
||||
**Files:**
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/page.tsx`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/rule-flow-canvas.tsx`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/rule-node.tsx`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/node-library.tsx`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/node-properties.tsx`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/graph-validation.ts`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/graph-validation.test.ts`
|
||||
- Create: `frontend/app/(main)/waf/rules/editor/components/unsaved-changes.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: 全宽 React Flow 编辑器;前端 `validateGraph(graph): GraphIssue[]`;Server 错误节点定位。
|
||||
- Consumes: Task 8 类型与 Service。
|
||||
|
||||
- [ ] **Step 1: 写前端图校验失败测试**
|
||||
|
||||
覆盖唯一 start/allow、必需 handle、禁止环、不可达、终止性以及删除节点同步删边。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `cd frontend && pnpm vitest run 'app/(main)/waf/rules/editor/components/graph-validation.test.ts'`
|
||||
|
||||
Expected: FAIL,校验器不存在。
|
||||
|
||||
- [ ] **Step 3: 实现页面骨架和数据状态**
|
||||
|
||||
`page.tsx` 直接维护 query、mutation、React Flow nodes/edges、dirty、selection 和右侧栏状态,不创建同名中转容器。根节点使用 `w-full py-6 px-1`,标题严格使用既定图标和 `h1` 规范。
|
||||
|
||||
- [ ] **Step 4: 实现节点、handle 和连线约束**
|
||||
|
||||
`start/pow` 只显示 `next` source handle,`ip_match/geo_match` 显示 `true`、`false`,`allow/block` 只显示 target handle。`isValidConnection` 阻止错误端口、同端口重复连接和形成环;start/allow 禁止删除。
|
||||
|
||||
- [ ] **Step 5: 实现固定右侧属性栏**
|
||||
|
||||
属性栏按节点判别联合渲染 IP/CIDR 与 IP 组多选、国家/地区多选、PoW 配置、阻止状态码与 HTML。颜色和阴影通过节点组件 variant/CSS 变量集中定义,不在业务调用点硬编码。
|
||||
|
||||
- [ ] **Step 6: 实现保存、冲突和未保存提示**
|
||||
|
||||
仅图合法时启用保存;409 显示“规则已在其他页面更新,请重新加载”;Server 返回节点/边 ID 时选中并聚焦;浏览器离开和应用内返回均提示未保存变更。
|
||||
|
||||
- [ ] **Step 7: 运行测试、构建并提交**
|
||||
|
||||
Run: `cd frontend && pnpm vitest run && pnpm lint && pnpm build`
|
||||
|
||||
Expected: PASS;静态导出包含 `/waf/rules/editor`。
|
||||
|
||||
Commit: `feat(frontend): add visual waf rule composer`
|
||||
|
||||
---
|
||||
|
||||
### Task 10: 路由绑定排序 UI 与旧界面清理
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/app/(main)/waf/components/site-binding-sheet.tsx`
|
||||
- Modify: `frontend/app/(main)/proxy-routes/detail/components/waf-section.tsx`
|
||||
- Modify: `frontend/app/(main)/waf/components/helpers.ts`(删除仅旧规则表单使用的导出;若清空则删除文件)
|
||||
- Delete: `frontend/app/(main)/waf/components/pow-config-panel.tsx`
|
||||
- Delete: `frontend/app/(main)/waf/components/rule-entry-dialog.tsx`
|
||||
- Delete: `frontend/app/(main)/waf/components/rule-list-section.tsx`
|
||||
- Test: `frontend/tests/unit/waf-binding-order.test.tsx`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: 拖拽或上下移动的有序绑定列表,提交 ID 顺序不被排序。
|
||||
- Consumes: Task 4 有序绑定 API 和 Task 8 Service。
|
||||
|
||||
- [ ] **Step 1: 写绑定顺序失败测试**
|
||||
|
||||
选择规则 A/B/C,移动为 C/A/B,断言 API payload 为 `{ids:[C,A,B]}`;全局规则单独展示为固定前置且不可拖动。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `cd frontend && pnpm vitest run tests/unit/waf-binding-order.test.tsx`
|
||||
|
||||
Expected: FAIL,当前 UI 只表达集合。
|
||||
|
||||
- [ ] **Step 3: 实现排序并删除旧固定表单组件**
|
||||
|
||||
复用项目现有 `@dnd-kit/sortable`;为键盘用户提供上移/下移操作。清理旧字段、旧 PoW 面板和不再引用的 helper,保留 IP 组管理组件。
|
||||
|
||||
- [ ] **Step 4: 运行测试并提交**
|
||||
|
||||
Run: `cd frontend && pnpm vitest run && pnpm lint && pnpm build`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Commit: `refactor(frontend): order waf bindings and remove legacy editor`
|
||||
|
||||
---
|
||||
|
||||
### Task 11: 旧后端字段清理、Swagger、中文文档与端到端验证
|
||||
|
||||
**Files:**
|
||||
- Create: `internal/db/migrator/goose/postgres/202607150003_drop_legacy_waf_rule_fields.sql`
|
||||
- Create: `internal/db/migrator/goose/sqlite/202607150003_drop_legacy_waf_rule_fields.sql`
|
||||
- Modify: `internal/model/openflare_waf.go`
|
||||
- Modify: `internal/apps/openflare/waf/logics_test.go`
|
||||
- Modify: `docs/design/waf-design.md`
|
||||
- Modify: `docs/guide/waf-usage.md`
|
||||
- Modify: `docs/changelog/index.md`
|
||||
- Generated: `docs/docs.go`, `docs/swagger.json`, `docs/swagger.yaml`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: 无旧固定策略字段的最终 Schema 与中文使用文档。
|
||||
- Consumes: Tasks 1–10 的完整替代实现。
|
||||
|
||||
- [ ] **Step 1: 写迁移与集成失败测试**
|
||||
|
||||
断言最终表不再包含 `block_status_code`、`ip_whitelist`、`ip_blacklist`、地域名单、`pow_enabled`、`pow_config`;端到端图分别产生 allow、block、PoW 接管,IP 组变化在 5–10 秒内生效。
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `go test ./internal/apps/openflare/integration ./internal/model -run 'TestOrchestratedWAF|TestLegacyWAFColumnsRemoved' -count=1`
|
||||
|
||||
Expected: FAIL,旧列仍存在。
|
||||
|
||||
- [ ] **Step 3: 删除旧列和旧代码路径**
|
||||
|
||||
PostgreSQL 直接 `DROP COLUMN`;SQLite 使用项目支持版本的 `DROP COLUMN` 或重建表迁移并复制 `id/name/enabled/is_global/graph/revision/timestamps`。删除 Go model/view/input 中的旧字段和固定链 helper,确保仓库中业务代码不再引用它们。
|
||||
|
||||
- [ ] **Step 4: 更新中文文档与 changelog**
|
||||
|
||||
`waf-design.md` 删除固定链作为现行设计的表述,链接可编排设计;`waf-usage.md` 写创建、节点语义、绑定顺序、发布生效和迁移警告;`[Unreleased]` 增加 WAF 可视编排、发布加载和 IP 组刷新条目。
|
||||
|
||||
- [ ] **Step 5: 生成 Swagger 并运行全量验证**
|
||||
|
||||
Run: `make swagger`
|
||||
|
||||
Expected: PASS,生成文件包含新 graph/meta API 与 409 response。
|
||||
|
||||
Run: `go test ./... -count=1`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Run: `cd frontend && pnpm vitest run && pnpm lint && pnpm build`
|
||||
|
||||
Expected: PASS。
|
||||
|
||||
Run: `make code-check`
|
||||
|
||||
Expected: PASS,无格式、lint、测试或生成文件差异。
|
||||
|
||||
- [ ] **Step 6: 最终人工数据面验收**
|
||||
|
||||
创建规则并编排 `开始 → IP 匹配 → true:通过 / false:地域匹配 → true:阻止A / false:PoW → 通过`,绑定到测试路由并发布。用命中/未命中 IP、不同 GeoIP 和无 PoW cookie 请求验证三个分支;更新引用 IP 组后不发布,确认 5–10 秒内结果变化且 OpenResty 未 reload。
|
||||
|
||||
- [ ] **Step 7: 提交**
|
||||
|
||||
Commit: `feat(waf): complete composable rule orchestration`
|
||||
|
||||
## 4. 最终验收标准
|
||||
|
||||
- 用户新增规则时只输入名称并立即进入 React Flow 编排器。
|
||||
- 默认规则为 `开始 → 通过`;特殊节点与处理节点满足设计约束。
|
||||
- Server 和前端均拒绝非法图,发布再次校验,revision 冲突返回 409。
|
||||
- 全局规则固定前置,自定义规则严格按绑定顺序执行。
|
||||
- OpenResty 请求路径对规则与 IP 组均为纯内存读取。
|
||||
- 规则只在发布 reload 时加载;IP 组每 5 秒 checksum 检查且仅变化时读取完整 JSON。
|
||||
- PostgreSQL、SQLite、Go、Lua、前端、Swagger、构建与 `make code-check` 全部通过。
|
||||
@@ -0,0 +1,99 @@
|
||||
# 边缘可观测与业务流量统计重构 — 实现计划
|
||||
|
||||
说明:本计划对应设计文档 [observability-design.md](../design/observability-design.md)。重大架构重构,按阶段交付,避免一次大爆炸。
|
||||
|
||||
---
|
||||
|
||||
## 0. 落地进度(2026-07-18)
|
||||
|
||||
* [x] M1 看板业务趋势改读 access log;网络图文案改为已提供/接收 + 宿主机网卡
|
||||
* [x] M2 协议 v2 字段(host_metrics/edge_health/request_length);CH 列 `request_length`/`request_time_ms`
|
||||
* [x] M3 Agent:观测口仅健康连接;payload 不再发 TrafficReport;access_logs 带 request_length
|
||||
* [x] M4 Server:停写 TrafficReport;openresty 仅存 connections;明细入库带 request_length
|
||||
* [x] 分布图 status/top domains + 节点行请求/UV 改 access log;24h UV 用 uniqExact;API bytes_provided/received
|
||||
* [x] M5:`of_node_edge_health`、`of_access_log_hourly`(+MV);删除 request_reports/traffic_hourly/openresty_hourly/obs_openresty;写入/查询改道
|
||||
* [x] 收尾:清 openresty hourly / request_report 死路径;edge_health 写全 status;cleanup 命名 `node_edge_health`;hourly 回填 SQL + UV 策略文档
|
||||
* [x] 协议/API 去兼容层(Agent 销毁重建):删除 TrafficReport / openresty_observation / snapshot 别名 / request_reports API 字段 / openresty_rx|tx
|
||||
* [x] 前端 UV 文案:24h/查询窗口独立访客;趋势图不绘分时 UV
|
||||
* [ ] 真实环境 ClickHouse 迁移 + `202607180003` 回填(本机 Docker 未起时需运维执行)
|
||||
|
||||
## 1. 目标与背景 (Goal & Context)
|
||||
|
||||
* **需求背景**:看板「OpenResty 入/出站」与 Zone「已提供数据」不一致;Agent 预聚合与访问日志双轨;`openresty_tx` 与 `bytes_sent` 业务语义重复。
|
||||
* **开发范围 (Scope)**:
|
||||
* **必做**:业务趋势统一为访问日志聚合;UI 字段与文案收敛;协议补齐 `request_length`;停用预聚合作为权威源;Agent 瘦身。
|
||||
* **后续**:废弃 CH 表清理、hourly rollup 性能优化、Relay 指标对齐。
|
||||
* **Out of Scope**:通用日志平台、替换 ClickHouse、APM。
|
||||
|
||||
---
|
||||
|
||||
## 2. 设计与决策 (Design & Decisions)
|
||||
|
||||
* **核心对象**:以 `of_node_access_logs` 为 L1 权威;主机 snapshot 为 L3;OpenResty 仅健康/连接为 L2。
|
||||
* **传输模型(示例与频率)**:见 [observability-transport-model.md](../design/observability-transport-model.md)。
|
||||
* **协议与表结构**:见 [observability-data-model.md](../design/observability-data-model.md)(NodePayload v2、落库流水线、DDL、废弃表)。
|
||||
* **API**:看板与 Zone 共用聚合语义;`bytes_provided` / `bytes_received`(兼容 `bytes_sent` 别名)。
|
||||
* **数据流**:见 [observability-design.md](../design/observability-design.md) §5。
|
||||
* **权衡**:性能用 Server 侧 rollup,不恢复 Agent 预聚合。
|
||||
|
||||
---
|
||||
|
||||
## 3. 阶段与修改清单 (Proposed Changes)
|
||||
|
||||
### 阶段 M1 — 读路径切换(优先对账)
|
||||
|
||||
* #### [MODIFY] `internal/apps/openflare/dashboard/*`、`observability/analytics.go`
|
||||
* 业务 24h 趋势改为 access log 聚合(全局)。
|
||||
* 网络趋势中业务曲线与主机网卡分离。
|
||||
* #### [MODIFY] 前端 dashboard 组件与文案
|
||||
* 「OpenResty 出站/入站」→「已提供数据/接收数据」或拆卡片。
|
||||
* #### [MODIFY] Zone stats 字段对齐(如需别名)
|
||||
* **验收**:单 Zone 流量时看板已提供 ≈ Zone 已提供。
|
||||
|
||||
### 阶段 M2 — 协议与入库补齐
|
||||
|
||||
* #### [MODIFY] `pkg/protocol/agent.go` — `NodeAccessLog.request_length`
|
||||
* #### [MODIFY] Agent 解析与 CH 写入列
|
||||
* #### [MODIFY] goose ClickHouse migration(如缺列)
|
||||
|
||||
### 阶段 M3 — 停写预聚合权威路径
|
||||
|
||||
* #### [MODIFY] Server persist:TrafficReport / openresty rx/tx 不再驱动看板
|
||||
* 可选:直接停写以减 CH 压力
|
||||
|
||||
### 阶段 M4 — Agent 瘦身
|
||||
|
||||
* #### [MODIFY] 移除 TrafficReport 构建主路径、Lua 业务 dict 计数、state 内业务累计
|
||||
* #### [MODIFY] 心跳仅明细 + snapshot + 连接/健康
|
||||
|
||||
### 阶段 M5 — 清理
|
||||
|
||||
* 删除废弃 API 字段、前端类型、CH 表/MV、相关测试夹具
|
||||
* 更新 agent-design / changelog(代码变更时)
|
||||
|
||||
---
|
||||
|
||||
## 4. 验证计划 (Verification Plan)
|
||||
|
||||
### 自动化
|
||||
|
||||
* `go test`:zone stats、dashboard 聚合、agent access log 解析
|
||||
* 前端:zone / dashboard 文案与字段测试
|
||||
|
||||
### 手动
|
||||
|
||||
* 制造已知大小响应,对比 Zone 与看板 24h 已提供数据
|
||||
* 确认宿主机网卡曲线与业务已提供数据分区展示、数值可不一致且文案不诱导对账
|
||||
|
||||
### 质量门禁
|
||||
|
||||
* `make swagger`(若 API 变更)
|
||||
* `make code-check`
|
||||
* `make prettier`
|
||||
|
||||
---
|
||||
|
||||
## 5. 依赖与风险
|
||||
|
||||
* 明细量大时 M1 需同步评估 hourly rollup(仍 Server 侧)。
|
||||
* 旧 Agent 无 `request_length` 时接收数据为空,需 UI 降级。
|
||||
@@ -0,0 +1,63 @@
|
||||
# 访问日志 cache_status 明细可见 — 实现计划
|
||||
|
||||
说明:对应设计 [observability-data-model.md §3.5.1](../design/observability-data-model.md)。第一期只做明细可见,不上报 upstream 地址。
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标与背景
|
||||
|
||||
* **需求背景**:访问日志无法判断请求是否命中边缘缓存、是否回源。
|
||||
* **开发范围 (Scope)**:
|
||||
* **必做**:OpenResty 日志输出 `$upstream_cache_status`;Agent 上报;CH 入库;列表/详情展示三态标签。
|
||||
* **Out of Scope**:命中率看板、hourly 维度、`upstream_addr`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 设计与决策
|
||||
|
||||
* **唯一字段**:`cache_status` string(原始值)。
|
||||
* **UI 三态(不落库)**:
|
||||
* 命中:`HIT` / `STALE` / `REVALIDATED` / `UPDATING`
|
||||
* 回源:`MISS` / `EXPIRED`
|
||||
* 未缓存:`BYPASS` / `-` / 空
|
||||
* **数据流**:log_format → Agent parse → protocol → Server model → CH → API → 前端明细。
|
||||
|
||||
---
|
||||
|
||||
## 3. 修改清单
|
||||
|
||||
### 边缘 / 协议
|
||||
|
||||
* `pkg/render/openresty/types.go`、`internal/model/openflare_option.go`:`log_format` 增加 `cache_status`
|
||||
* `internal/apps/agent/observability/traffic.go`:解析与映射
|
||||
* `pkg/protocol/agent.go`:`NodeAccessLog.CacheStatus`
|
||||
|
||||
### Server / CH
|
||||
|
||||
* goose:`202607180005_access_log_cache_status.sql`
|
||||
* `internal/model/analytics/node_access_log.go`、writer、list/scan、store 映射
|
||||
* `internal/model/openflare_observability.go`、agent build records
|
||||
* API `AccessLogView` + list 响应带 `cache_status`
|
||||
|
||||
### 前端
|
||||
|
||||
* types / 明细列表标签 / 详情字段
|
||||
* 三态 helper:`resolveCacheOutcome(cache_status)`
|
||||
|
||||
---
|
||||
|
||||
## 4. 验证
|
||||
|
||||
* `go test ./internal/apps/agent/observability/ ./internal/repository/analytics/ ./internal/apps/openflare/agent/`
|
||||
* `make swagger`(若 Handler 响应结构变更)
|
||||
* `make code-check` / `make prettier`
|
||||
|
||||
---
|
||||
|
||||
## 5. 落地进度
|
||||
|
||||
* [x] log_format + protocol + agent parse
|
||||
* [x] CH migration + 写入/读取
|
||||
* [x] API + 前端明细展示
|
||||
* [x] 缓冲去重 key 含 cache_status;保留 `-` 原始值
|
||||
* [x] 测试与提交
|
||||
@@ -0,0 +1,38 @@
|
||||
# 边缘缓存默认 static 策略 — 实现计划
|
||||
|
||||
对应设计:[edge-cache-design.md](../design/edge-cache-design.md)
|
||||
|
||||
## 目标
|
||||
|
||||
路由开启缓存后,**新建推荐**仅缓存标准静态扩展名(`static`);存量 `url`/空策略映射为 `all`,不收窄缓存范围。
|
||||
|
||||
## 兼容规则(评审后定稿)
|
||||
|
||||
| 场景 | 行为 |
|
||||
| --- | --- |
|
||||
| 已启用 + `''` / `url` | 读 API / 快照 / 渲染 → **`all`** |
|
||||
| 写入时 enabled 且 policy 为空 | 规范为 **`all`**(旧客户端兼容) |
|
||||
| UI 新建/推荐默认 | **显式提交** `static` |
|
||||
| 关闭缓存 | policy 存 `''`,rules 清空 |
|
||||
|
||||
## 修改清单
|
||||
|
||||
1. **渲染** `pkg/render/openresty/render.go`:`static` 内置扩展名;空/`url`/`all` 无路径限制
|
||||
2. **校验/展示** `proxy_route/helpers.go`:`normalizeCachePolicy` + `displayCachePolicy`
|
||||
3. **快照** `config_version/logics.go`:`normalizeSnapshotCachePolicy`
|
||||
4. **前端** `cache-section.tsx` + helpers:存量 empty/url→`all`;关闭时提交 `''`;新建默认 `static`
|
||||
5. **测试** render + proxy_route
|
||||
6. **设计/changelog** 同步兼容说明
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
go test ./pkg/render/openresty/ ./internal/apps/openflare/proxy_route/ ./internal/apps/openflare/config_version/
|
||||
# 已通过(2026-07-18)
|
||||
```
|
||||
|
||||
## 状态
|
||||
|
||||
- [x] 功能实现 + 评审修复(empty→all,禁止静默收窄)
|
||||
- [ ] 提交 `fix(cache): ...`(待用户确认)
|
||||
- [ ] 合并 / 发布后需重新发布节点配置
|
||||
@@ -0,0 +1,71 @@
|
||||
# ClickHouse 观测表迁移与小时汇总回填(运维手册)
|
||||
|
||||
适用:M5 观测存储(`of_node_edge_health`、`of_access_log_hourly`、删旧表)及历史小时回填。
|
||||
|
||||
## 前提
|
||||
|
||||
* 控制面 `config.yaml` / 环境变量中 ClickHouse 已启用,账号可写 `openflare` 库。
|
||||
* 备份策略已就绪(可选:对 `of_node_access_logs` 做快照)。
|
||||
* **Agent 升级策略为销毁重建**;勿混跑旧 Agent(旧协议字段已从 Server 删除)。
|
||||
|
||||
## 1. 自动迁移(推荐)
|
||||
|
||||
进程启动时 `migrator.MigrateClickHouse()` 会按 goose 顺序执行:
|
||||
|
||||
| 版本 | 作用 |
|
||||
| --- | --- |
|
||||
| `202607180001` | access log 增加 `request_length` / `request_time_ms` |
|
||||
| `202607180002` | 建 `of_node_edge_health`、`of_access_log_hourly`(+MV);删 request_reports / openresty 吞吐表 |
|
||||
| `202607180003` | 从明细 ANTI JOIN 回填近 90 天 `of_access_log_hourly` |
|
||||
|
||||
启动 API / all 模式一次即可:
|
||||
|
||||
```bash
|
||||
# 示例:本地
|
||||
./bin/openflare api
|
||||
# 或
|
||||
make run # 以项目实际入口为准
|
||||
```
|
||||
|
||||
查看 goose 版本表(ClickHouse)确认三版本均已应用。
|
||||
|
||||
## 2. 仅回填(迁移已执行、MV 创建前缺历史)
|
||||
|
||||
若只需重跑回填 SQL:
|
||||
|
||||
```bash
|
||||
clickhouse-client --host 127.0.0.1 --port 9000 \
|
||||
--user default --password "$CLICKHOUSE_PASSWORD" \
|
||||
--database openflare \
|
||||
--multiquery < internal/db/migrator/goose/clickhouse/202607180003_backfill_access_log_hourly.sql
|
||||
```
|
||||
|
||||
(goose 文件含 `+goose Up` 注释,若 client 报错可去掉注释行后执行 INSERT 主体。)
|
||||
|
||||
回填可重复:`ANTI JOIN` 跳过已有 `(node_id, hour, host)`。
|
||||
|
||||
## 3. 验收
|
||||
|
||||
```sql
|
||||
-- 新表存在
|
||||
SHOW TABLES FROM openflare LIKE 'of_node_edge_health';
|
||||
SHOW TABLES FROM openflare LIKE 'of_access_log_hourly';
|
||||
|
||||
-- 旧表应不存在
|
||||
SHOW TABLES FROM openflare LIKE 'of_node_request_reports';
|
||||
SHOW TABLES FROM openflare LIKE 'of_node_obs_openresty';
|
||||
|
||||
-- 小时汇总有数据(有历史访问时)
|
||||
SELECT count() FROM of_access_log_hourly;
|
||||
SELECT min(hour), max(hour), sum(request_count) FROM of_access_log_hourly;
|
||||
```
|
||||
|
||||
看板 24h 请求趋势应优先走 hourly;UV 卡片为整窗独立访客,**不等于**小时 UV 之和。
|
||||
|
||||
## 4. 本机执行记录
|
||||
|
||||
| 日期 | 环境 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 2026-07-18 | 开发机 | Docker daemon 未启动,未能 live 迁移;SQL 与 goose 文件已入库 |
|
||||
|
||||
运维在目标环境按 §1–§3 执行后更新本表。
|
||||
@@ -0,0 +1,161 @@
|
||||
# 访问日志 IP 明细 Tab — 实现计划
|
||||
|
||||
## 1. 目标与背景 (Goal & Context)
|
||||
|
||||
* **需求背景**:运维需要按 IP 维度快速查看时间窗内的访问量与流量,并下钻单 IP 情报;原先 IP 分析嵌在「单条访问日志详情」中,入口弱、列表能力缺失。
|
||||
* **开发范围 (Scope) V1**:
|
||||
* 访问日志页新增第三 Tab **「IP 明细」**(`?tab=ips`)。
|
||||
* IP 列表:时间筛选(快捷 24h/7d/15d/30d + 自定义 since/until)、分页、按请求数 / 入站 / 出站 / 最后访问 / 2xx 比例排序。
|
||||
* 列表列:IP、地区、请求数、2xx 比例(2xx 数 / 总请求)、入站流量、出站流量、最后访问。
|
||||
* 行详情:弹窗展示完整 **IP 情报**(分析 + 趋势 + Top 分布 + 加入 WAF IP 组)。
|
||||
* **日志明细详情弹窗仅展示单条请求字段**,不再内嵌 IP 情报;如需分析请到 IP 明细。
|
||||
* **Out of Scope(V1 不做)**:
|
||||
* 独立 `/access-logs/ip` 子路由全页。
|
||||
* IP 列表 UI 暴露节点 / host 筛选(后端可保留兼容参数,前端首版不放)。
|
||||
* 入/出站带宽时间序列(趋势图仍为请求数)。
|
||||
* 实时 GeoIP 二次查询(沿用入库 `region`)。
|
||||
|
||||
## 2. 设计与决策 (Design & Decisions)
|
||||
|
||||
### 2.1 页面与交互
|
||||
|
||||
| Tab | URL | 内容 |
|
||||
| --- | --- | --- |
|
||||
| 概览 | `/access-logs` | 不变 |
|
||||
| IP 明细 | `/access-logs?tab=ips` | 新 |
|
||||
| 日志明细 | `/access-logs?tab=list` | 不变;详情弹窗瘦身 |
|
||||
|
||||
* **时间筛选(IP 明细)**:
|
||||
* 快捷:`hours` ∈ {24, 168, 360, 720},默认 168(7d)。
|
||||
* 自定义:`since` + `until`(RFC3339);**同时提供时覆盖 hours**。
|
||||
* **详情形态**:留在列表页的 Dialog(非独立子页)。
|
||||
* **日志详情瘦身**:`access-log-detail-dialog` 只渲染请求字段(时间、节点、IP、地区、host、path、UA、cache、status 等)及必要操作;删除 analysis/trend/WAF 组内嵌区块。WAF「按 IP 加入组」仅保留在 IP 详情弹窗。
|
||||
|
||||
### 2.2 API 设计(扩展现有端点,不新建)
|
||||
|
||||
**`GET /api/v1/d/access-logs/ip-summary`**
|
||||
|
||||
| 参数 | 说明 |
|
||||
| --- | --- |
|
||||
| `hours` | 1–720;默认 168;在无 since/until 时生效 |
|
||||
| `since` / `until` | 可选 RFC3339;同时有效时优先于 hours |
|
||||
| `sort_by` | `total_requests`(默认)\| `request_length`(入站)\| `bytes_sent`(出站)\| `last_seen_at` \| `success_ratio` |
|
||||
| `sort_order` | `asc` \| `desc` |
|
||||
| `p` / `page_size` | 分页,page_size 上限 200 |
|
||||
| `remote_addr` / `node_id` / `host` | 兼容保留;V1 UI 可不暴露 |
|
||||
|
||||
**响应行字段(扩展)**
|
||||
|
||||
```text
|
||||
remote_addr string
|
||||
region string // 窗内 argMax(region, logged_at) 或等价
|
||||
total_requests uint64
|
||||
success_2xx_count uint64 // status_code 200–299
|
||||
success_ratio float64 // success_2xx_count / total_requests;total=0 时为 0
|
||||
bytes_received uint64 // sum(request_length) 入站
|
||||
bytes_sent uint64 // sum(bytes_sent) 出站
|
||||
last_seen_at time
|
||||
```
|
||||
|
||||
* `recent_requests`:可停止计算或固定返回 0;**UI 不展示**。避免与可配置时间窗语义冲突。
|
||||
* 详情下钻仍用现有:
|
||||
* `GET .../ip-summary/analysis?remote_addr=&hours=`(或 since/until,若后续扩展;V1 将列表当前窗映射为 hours 或 since/until 与后端约定一致)
|
||||
* `GET .../ip-summary/trend?remote_addr=&hours=&bucket_minutes=`
|
||||
|
||||
**分析/趋势时间窗对齐**:打开 IP 详情时,将列表当前时间窗传入 analysis/trend(优先 since/until;仅有 hours 则传 hours)。
|
||||
|
||||
### 2.3 数据层(ClickHouse)
|
||||
|
||||
* 表:`of_node_access_logs`(已有 `bytes_sent`、`request_length`、`status_code`、`region`)。
|
||||
* 聚合:`GROUP BY remote_addr`,在 `NodeAccessLogFilter.Since/Until` 上过滤。
|
||||
* 2xx:`countIf(status_code >= 200 AND status_code < 300)`。
|
||||
* region:`argMax(region, logged_at)`。
|
||||
* 排序:服务端 ORDER BY 对应表达式;`success_ratio` 注意除零(`if(total=0,0,ratio)`)。
|
||||
|
||||
### 2.4 设计决策权衡
|
||||
|
||||
| 选项 | 结论 |
|
||||
| --- | --- |
|
||||
| 扩展 `/ip-summary` vs 新 `/ip-list` | **扩展现有**,前端 service 已有 `listIPSummaries` |
|
||||
| 详情弹窗 vs 子页 | **弹窗**,与现有明细交互一致 |
|
||||
| IP 情报放日志详情 vs 独立 IP 详情 | **仅 IP 明细详情**;日志详情只展示请求信息 |
|
||||
| 时间:仅快捷 vs 仅自定义 | **两者都要**,自定义优先 |
|
||||
|
||||
### 2.5 数据流(示意)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI_IP[IP 明细 Tab] --> API_List[GET /ip-summary]
|
||||
API_List --> CH[(of_node_access_logs)]
|
||||
UI_IP --> UI_Dlg[IP 详情 Dialog]
|
||||
UI_Dlg --> API_A[GET /ip-summary/analysis]
|
||||
UI_Dlg --> API_T[GET /ip-summary/trend]
|
||||
API_A --> CH
|
||||
API_T --> CH
|
||||
UI_List[日志明细 Tab] --> API_Logs[GET /access-logs]
|
||||
UI_List --> UI_LogDlg[日志详情 Dialog]
|
||||
UI_LogDlg -.->|不请求 IP 分析| X[仅请求字段]
|
||||
```
|
||||
|
||||
## 3. 具体修改文件清单 (Proposed Changes)
|
||||
|
||||
### 后端 Server
|
||||
|
||||
* #### [MODIFY] `internal/repository/analytics/node_access_log_stats.go`(及 filter 如有)
|
||||
* `IPSummariesNodeAccessLogs`:时间窗、sum 入/出、2xx count、ratio、region、扩展 sort。
|
||||
* #### [MODIFY] `internal/apps/openflare/observability/access_log_logics.go`
|
||||
* Query/View 类型扩展;解析 hours/since/until;去掉或忽略 recent 3h 硬编码。
|
||||
* #### [MODIFY] `internal/apps/openflare/observability/routers.go` / handler
|
||||
* 绑定新 query;Swagger 注释。
|
||||
* #### [MODIFY] 相关单元测试(logics / repository 若有)
|
||||
|
||||
### 前端 Web
|
||||
|
||||
* #### [MODIFY] `frontend/app/(main)/access-logs/page.tsx`
|
||||
* 第三 Tab `ips`;`resolveTab` / `handleTabChange`。
|
||||
* #### [NEW] `frontend/app/(main)/access-logs/components/ip-tab.tsx`
|
||||
* 列表、时间筛选、排序、分页、打开详情。
|
||||
* #### [NEW] `frontend/app/(main)/access-logs/components/ip-detail-dialog.tsx`
|
||||
* IP 入口详情壳。
|
||||
* #### [NEW] `frontend/app/(main)/access-logs/components/ip-analysis-panel.tsx`
|
||||
* 从现有 `access-log-detail-dialog` **迁出** 分析/趋势/排行/WAF IP 组逻辑。
|
||||
* #### [MODIFY] `frontend/app/(main)/access-logs/components/access-log-detail-dialog.tsx`
|
||||
* **删除** IP 情报相关 UI 与 `getIPAnalysis` / `getIPTrend` 请求;仅请求日志字段展示。
|
||||
* #### [MODIFY] `frontend/app/(main)/access-logs/components/access-log-utils.ts`
|
||||
* tab 类型、IP 排序选项、时间筛选辅助。
|
||||
* #### [MODIFY] `frontend/lib/services/openflare/access-log.service.ts` + `types.ts`
|
||||
* `listIPSummaries` 参数与 `AccessLogIPSummaryItem` 字段同步。
|
||||
|
||||
### 文档
|
||||
|
||||
* #### [MODIFY] `docs/changelog/index.md` — `[Unreleased]` 用户可见说明
|
||||
* #### [MODIFY] `docs/design/observability-design.md` 或 data-model(如有访问日志 UI 约定)— 补充 IP 明细 Tab 与 API 字段(中文)
|
||||
* #### [MODIFY] `docs/plan/index.md` — 挂上本计划链接
|
||||
|
||||
## 4. 验证计划 (Verification Plan)
|
||||
|
||||
### 自动化
|
||||
|
||||
```bash
|
||||
go test ./internal/apps/openflare/observability/ ./internal/repository/analytics/
|
||||
# 前端:相关 tsc / 页面无类型错误
|
||||
make code-check # 完成后按项目门禁
|
||||
make prettier
|
||||
make swagger # API 注释变更后
|
||||
```
|
||||
|
||||
### 手动
|
||||
|
||||
1. `/access-logs?tab=ips` 默认 7d 列表有数据;切换 24h/自定义区间结果变化。
|
||||
2. 分别按请求数、入站、出站、2xx 比例、最后访问排序正确。
|
||||
3. 2xx 比例 = 2xx/总数;0 请求不出现 NaN/Infinity。
|
||||
4. 点 IP 打开详情:指标/趋势/Top/WAF 组可用;时间窗与列表一致。
|
||||
5. 日志明细 → 详情:仅请求信息,**无** IP 分析/趋势区块。
|
||||
6. 概览 Tab 行为无回归。
|
||||
|
||||
## 5. 状态
|
||||
|
||||
- [x] 需求澄清与方案确认
|
||||
- [x] 实现(后端 ip-summary 扩展 + 前端 IP 明细 Tab + 日志详情瘦身)
|
||||
- [x] 测试与 changelog(`go test` 相关包通过;changelog 已更新)
|
||||
- [ ] 提交合并
|
||||
@@ -0,0 +1,47 @@
|
||||
# ClickHouse CPU 性能优化计划
|
||||
|
||||
> PLAN_ID: `63ba981b`
|
||||
> 状态: 已完成(含 Phase 2 遗留治理)
|
||||
> 目标: 完成 P0–P2 优化,降低 ClickHouse CPU 占用
|
||||
|
||||
## 背景
|
||||
|
||||
ClickHouse CPU 偏高由写入侧(小 part 频繁 flush、心跳同步 DELETE mutation)与查询侧(无 LIMIT 全表扫、高频轮询、WAF 全量拉日志)叠加导致。
|
||||
|
||||
## PR Plan
|
||||
|
||||
### PR 1: 写入路径 P0 优化
|
||||
|
||||
- **Description:** 移除心跳路径同步 `ALTER DELETE`;为 `batchwriter` 增加 `MinBatchSize`;调大可观测 writer 批次与 flush 间隔;为 openresty/frps/frpc 补全去重。
|
||||
- **Files/components affected:** `internal/apps/openflare/agent/observability.go`, `internal/db/batchwriter/`, `internal/apps/openflare/chwriter/`, `internal/db/batchwriter/*_test.go`
|
||||
- **Dependencies:** None
|
||||
|
||||
### PR 2: ClickHouse 客户端与配置 P1
|
||||
|
||||
- **Description:** 启用 `async_insert` 等写入优化 settings;提高 `block_buffer_size` 默认值;更新 `config.example.yaml` 与配置模型注释。
|
||||
- **Files/components affected:** `internal/db/clickhouse.go`, `internal/config/model.go`, `internal/config/config.go`, `config.example.yaml`
|
||||
- **Dependencies:** None
|
||||
|
||||
### PR 3: Dashboard 与可观测查询 P0
|
||||
|
||||
- **Description:** 消除 `limit=0` 无界查询;复用已有限制数据构建趋势;增加服务端短 TTL 缓存;降低前端轮询频率。
|
||||
- **Files/components affected:** `internal/apps/openflare/dashboard/logics.go`, `internal/apps/openflare/observability/node_logics.go`, `frontend/app/(main)/page.tsx`, `frontend/app/(main)/nodes/components/node-observability.tsx`
|
||||
- **Dependencies:** None
|
||||
|
||||
### PR 4: 访问日志与 WAF 查询 P0/P1
|
||||
|
||||
- **Description:** WAF IP 同步改为 ClickHouse 侧聚合;IP 汇总与折叠日志 SQL 分页;消除 count 重复全量扫描;列表 API 强制默认时间窗口。
|
||||
- **Files/components affected:** `internal/apps/openflare/waf/ip_group_sync.go`, `internal/repository/analytics/node_access_log_stats.go`, `internal/model/openflare_access_log.go`, `internal/apps/openflare/observability/access_log_logics.go`, `internal/repository/analytics/access_log_stats.go`
|
||||
- **Dependencies:** None
|
||||
|
||||
### PR 5: ClickHouse DDL 与数据规范化 P1
|
||||
|
||||
- **Description:** 为 7 张分析表添加 TTL;收窄 `of_node_access_logs` ORDER BY;插入时规范化 `remote_addr`(去 trim 查询);将可观测 obs 三表纳入自动清理。
|
||||
- **Files/components affected:** `internal/db/migrator/goose/clickhouse/`, `internal/repository/analytics/node_access_log_writer.go`, `internal/apps/openflare/tasks/database_cleanup.go`, `internal/model/analytics/`
|
||||
- **Dependencies:** PR 1
|
||||
|
||||
### PR 6: 基础设施与审计减负 P2
|
||||
|
||||
- **Description:** Docker ClickHouse 服务端基础调优;审计日志 headers 截断/精简;更新 changelog。
|
||||
- **Files/components affected:** `docker-compose.yaml`, `docker/clickhouse/` (if needed), `internal/apps/risk_control/middleware.go`, `docs/changelog/index.md`
|
||||
- **Dependencies:** None
|
||||
+8
-1
@@ -11,7 +11,14 @@
|
||||
|
||||
## 正在进行的计划
|
||||
|
||||
当前暂无正在进行的开发计划或 AI 接手计划。所有历史迁移与重构项目(如后端/前端向 Wavelet 平台的迁移、边缘运行时重构等)均已完成开发并上线,对应的临时计划文档已归档清理。
|
||||
当前进行中的开发计划:
|
||||
|
||||
* [Zone 与域名资源重构](./20260712-zone-domain-refactor.md):以 Zone 和正规化 Zone 域名替代托管域名及反代路由中的域名/证书冗余字段。
|
||||
* [WAF 可编排规则](./20260713-waf-orchestration.md):使用 React Flow 编辑 DAG 规则,发布时编译并由 OpenResty 纯内存执行。
|
||||
* [边缘可观测与业务流量统计重构](./20260717-observability-redesign.md):访问日志为业务唯一真相;Agent 只上报明细与主机读数;收敛「出站/已提供」双字段。
|
||||
* [访问日志 cache_status 明细可见](./20260718-access-log-cache-status.md):上报 `$upstream_cache_status`,明细展示命中/回源/未缓存三态。
|
||||
* [边缘缓存默认 static 策略](./20260718-edge-cache-static-default.md):开启缓存默认仅静态扩展名;存量 url→all。
|
||||
* [访问日志 IP 明细 Tab](./20260719-access-log-ip-tab.md):第三 Tab 按 IP 聚合列表(时间窗/流量/2xx 比例);IP 情报迁入独立详情;日志详情仅请求字段。
|
||||
|
||||
## 使用建议
|
||||
|
||||
|
||||
@@ -40,6 +40,14 @@ GOCACHE=/tmp/openflare-go-cache go test ./...
|
||||
make code-check
|
||||
```
|
||||
|
||||
自动格式化后端 Go 与前端 TypeScript、JavaScript、CSS 等源码:
|
||||
|
||||
```bash
|
||||
make prettier
|
||||
```
|
||||
|
||||
该命令使用 `gofmt` 格式化后端,并使用项目固定版本的 Prettier 格式化 `frontend/` 源码;构建产物、依赖、公开静态资源和锁文件会被忽略。
|
||||
|
||||
## Frontend
|
||||
|
||||
开发:
|
||||
@@ -155,4 +163,4 @@ pnpm dev
|
||||
```bash
|
||||
cd docs
|
||||
pnpm build:embed
|
||||
```
|
||||
```
|
||||
|
||||
@@ -97,15 +97,24 @@ Server 的所有核心基础配置定义在 `config.yaml` 中,且均支持环
|
||||
| `redis.db` | `REDIS_DB` | Redis 逻辑数据库编号 | `0` |
|
||||
| `redis.key_prefix` | `REDIS_KEY_PREFIX` | 系统在 Redis 中使用的键前缀 | `openflare:` |
|
||||
| `redis.pool_size` | `REDIS_POOL_SIZE` | Redis 连接池大小 | `100` |
|
||||
| `redis.maint_notifications` | `REDIS_MAINT_NOTIFICATIONS` | 启动时是否启用 Redis maintenance notifications 自动协商;兼容性不明时保持关闭,修改后需重启 | `false` |
|
||||
|
||||
### 4. ClickHouse 配置 (`clickhouse:`)
|
||||
|
||||
> **说明**:下列为 OpenFlare **客户端**连接参数。ClickHouse **服务端**小规格调优:将 `performance.xml` curl 到 `./config/clickhouse/`,再以单文件方式挂载至容器的 `config.d/performance.xml`,详见 [启动 Server](../deployment/server.md)。
|
||||
|
||||
| 配置文件 YAML 路径 | 对应覆盖环境变量 | 作用说明 | 默认值 |
|
||||
| --- | --- | --- | --- |
|
||||
| `clickhouse.enabled` | `CLICKHOUSE_ENABLED` | 是否启用 ClickHouse。**系统节点指标与访问日志在此进行海量写入** | `true` |
|
||||
| `clickhouse.hosts` | `CLICKHOUSE_HOST` | ClickHouse 集群连接地址数组(环境变量仅设置单地址) | `["127.0.0.1:9000"]` |
|
||||
| `clickhouse.username` | `CLICKHOUSE_USERNAME` | ClickHouse 账号用户名 | `default` |
|
||||
| `clickhouse.password` | `CLICKHOUSE_PASSWORD` | ClickHouse 密码 | `123456` |
|
||||
| `clickhouse.password` | `CLICKHOUSE_PASSWORD` | ClickHouse 密码 | `replace-with-clickhouse-password` |
|
||||
| `clickhouse.database` | `CLICKHOUSE_NAME` | ClickHouse 存储的数据库名称 | `openflare` |
|
||||
| `clickhouse.max_idle_conn` | - | 客户端空闲连接数(小规格默认偏低) | `8` |
|
||||
| `clickhouse.max_open_conn` | - | 客户端最大打开连接数 | `16` |
|
||||
| `clickhouse.conn_max_lifetime` | - | 连接最大存活时间(秒) | `3600` |
|
||||
| `clickhouse.dial_timeout` | - | 建连超时(秒) | `5` |
|
||||
| `clickhouse.block_buffer_size` | - | 原生协议 block 缓冲行数 | `32` |
|
||||
|
||||
### 5. 系统日志配置 (`log:`)
|
||||
| 配置文件 YAML 路径 | 对应覆盖环境变量 | 作用说明 | 默认值 |
|
||||
@@ -161,7 +170,7 @@ Server 的所有核心基础配置定义在 `config.yaml` 中,且均支持环
|
||||
### 2. 人机安全校验 (PoW Captcha)
|
||||
| 配置键 (Key) | 数据类型 | 作用说明 | 默认值 |
|
||||
| --- | --- | --- | --- |
|
||||
| `cap_login_enabled` | `bool` | 是否在登录界面强制要求进行本地 PoW 算力防爆破人机验证 | `true` |
|
||||
| `cap_login_enabled` | `bool` | 是否在登录界面强制要求进行本地 PoW 算力防爆破人机验证 | `false` |
|
||||
| `cap_auto_solve` | `bool` | 打开页面后是否由浏览器自动开始后台背景计算算力(无需用户手动点击)| `true` |
|
||||
| `cap_challenge_count` | `int` | 人机验证所需的计算难题数。数量越大,计算要求时间越长(推荐 1~5) | `1` |
|
||||
| `cap_challenge_difficulty`| `int`| 每次计算所需的 PoW 哈希前缀匹配难度。推荐数值在 3-5 之间 | `4` |
|
||||
@@ -183,9 +192,9 @@ Server 的所有核心基础配置定义在 `config.yaml` 中,且均支持环
|
||||
| 配置键 (Key) | 数据类型 | 作用说明 | 默认值 |
|
||||
| --- | --- | --- | --- |
|
||||
| `agent_discovery_token` | `string` | 新节点首次一键接入并自动注册的全局通用验证发现 Token | 无(系统初始化生成) |
|
||||
| `agent_heartbeat_interval`| `int` | 控制并向所有接入 Agent 周期下发的标准心跳检测间隔(毫秒) | `10000` (10s) |
|
||||
| `agent_heartbeat_interval`| `int` | 控制并向所有接入 Agent 周期下发的标准心跳检测间隔(毫秒) | `3000` (3s) |
|
||||
| `agent_websocket_upgrade_enabled` | `bool` | 是否授权 Agent 在 HTTP 心跳握手成功后升级建立持久 WebSocket 实时连接 | `true` |
|
||||
| `node_offline_threshold` | `int` | 在管理后台中判定节点失去心跳并标注为离线状态的无响应阈值(毫秒) | `120000` (120s) |
|
||||
| `node_offline_threshold` | `int` | 在管理后台中判定节点失去心跳并标注为离线状态的无响应阈值(毫秒) | `60000` (60s) |
|
||||
| `agent_update_repo` | `string` | Agent 节点更新下载自身二进制的 Release 仓库源 | `Rain-kl/OpenFlare` |
|
||||
| `geoip_provider` | `string` | GeoIP 提供商,支持 `maxmind` 等,用于 WAF 防护时地域分析 | `ipinfo` |
|
||||
| `database_auto_cleanup_enabled` | `bool` | 是否在每天凌晨 3:00 自动清理过期观测历史日志(降低数据库空间) | `true` |
|
||||
@@ -278,6 +287,8 @@ Server 的所有核心基础配置定义在 `config.yaml` 中,且均支持环
|
||||
| `OPENFLARE_MMDB_PATH` | WAF GeoIP mmdb 路径,可覆盖 `agent.json` | 空 |
|
||||
| `OPENFLARE_MMDB_UPDATE_INTERVAL` | WAF GeoIP mmdb 更新间隔,可覆盖 `agent.json` | 空 |
|
||||
| `OPENFLARE_MMDB_DOWNLOAD_URL` | WAF GeoIP mmdb 下载地址,可覆盖 `agent.json` | 空 |
|
||||
| `OPENFLARE_CITY_MMDB_PATH` | WAF 地区匹配 City MMDB 路径,可覆盖 `agent.json` | 空 |
|
||||
| `OPENFLARE_CITY_MMDB_DOWNLOAD_URL` | WAF City MMDB 下载地址,可覆盖 `agent.json` | 空 |
|
||||
|
||||
---
|
||||
|
||||
@@ -307,12 +318,14 @@ Server 的所有核心基础配置定义在 `config.yaml` 中,且均支持环
|
||||
| `runtime_config_dir` | Agent 运行时配置写入目录,如 `pow_config.json` | 否 | `data_dir/etc/openflare` |
|
||||
| `pages_dir` | Pages 静态部署包解压与当前部署目录 | 否 | `data_dir/var/lib/openflare/pages` |
|
||||
| `mmdb_path` | WAF GeoIP mmdb 文件路径 | 否 | `data_dir/etc/openflare/GeoLite2-Country.mmdb` |
|
||||
| `city_mmdb_path` | WAF 地区匹配 City MMDB 文件路径 | 否 | `data_dir/etc/openflare/GeoLite2-City.mmdb` |
|
||||
| `mmdb_update_interval` | WAF GeoIP mmdb 更新间隔 | 否 | `86400000` 毫秒 (24h) |
|
||||
| `mmdb_download_url` | WAF GeoIP mmdb 下载地址 | 否 | 内置 GeoLite2 Country 下载地址 |
|
||||
| `mmdb_download_url` | WAF GeoIP mmdb 周期更新地址 | 否 | GeoLite2 Country 更新地址;首次缺失时从程序内嵌数据库初始化 |
|
||||
| `city_mmdb_download_url` | WAF City MMDB 周期更新地址 | 否 | GeoLite2 City 更新地址;首次缺失时从程序内嵌数据库初始化 |
|
||||
| `observability_buffer_path` | 观测补报缓冲文件路径 | 否 | `data_dir/var/lib/openflare/observability-buffer.json` |
|
||||
| `observability_replay_minutes` | 自动补传最近观测窗口分钟数 | 否 | `15` |
|
||||
| `observability_replay_minutes` | 自动补传最近观测窗口分钟数 | 否 | `60` |
|
||||
| `state_path` | Agent 本地状态文件路径 | 否 | `data_dir/var/lib/openflare/agent-state.json` |
|
||||
| `heartbeat_interval` | 心跳间隔 | 否 | `10000` 毫秒 |
|
||||
| `heartbeat_interval` | 心跳间隔 | 否 | `3000` 毫秒 |
|
||||
| `request_timeout` | HTTP 请求超时 | 否 | `10000` 毫秒 |
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Zone 域名重构规格
|
||||
|
||||
已确认的设计:
|
||||
|
||||
* `/websites` 展示可注册根域 Zone;详情 URL 使用 `/websites/:zoneId`。
|
||||
* `managed_domains` 将被彻底替换为 `of_zones` 与 `of_zone_domains`。
|
||||
* Zone 域名是 `of_proxy_routes` 域名与证书的规范化来源;一个域名至多连接一条路由,一条路由可含多个 Zone 的域名。
|
||||
* `of_proxy_routes` 移除 `cert_id`、`cert_ids` 与 `domain_cert_ids`,不再指定证书;配置编译只从关联 Zone 域名的 `cert_id` 查询证书。
|
||||
* Zone 域名只允许明确 FQDN;允许把含 `*.example.com` SAN 的 TLS 证书绑定到明确域名,但不允许通配符域名记录。
|
||||
* 路由仍拥有上游、缓存、限流、WAF 与 Pages;Zone 只提供聚合管理和展示。
|
||||
* 迁移先建新表、用 Public Suffix List 回填和验证,再在后续独立发布中移除旧表及冗余列。
|
||||
|
||||
完整设计、API、迁移与验证策略见 [Zone 与域名资源设计](../../design/zone-design.md)。
|
||||
+1888
-937
File diff suppressed because it is too large
Load Diff
+1217
-626
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
.next/
|
||||
node_modules/
|
||||
out/
|
||||
coverage/
|
||||
public/
|
||||
next-env.d.ts
|
||||
pnpm-lock.yaml
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"printWidth": 80,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"bracketSpacing": true,
|
||||
"bracketSameLine": false,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"proseWrap": "preserve"
|
||||
}
|
||||
@@ -22,11 +22,13 @@ Modern frontend application for the Wavelet scaffold framework.
|
||||
### Installation
|
||||
|
||||
1. Install dependencies:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
2. Run the development server:
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
@@ -22,11 +22,13 @@ Wavelet 脚手架系统的现代化前端应用。
|
||||
### 安装
|
||||
|
||||
1. 安装依赖:
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
2. 运行开发服务器:
|
||||
|
||||
```bash
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {Suspense} from "react"
|
||||
import {LoginPage} from "@/components/auth/login-page"
|
||||
import { Suspense } from 'react';
|
||||
import { LoginPage } from '@/components/auth/login-page';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Suspense>
|
||||
<LoginPage />
|
||||
</Suspense>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {Suspense} from "react"
|
||||
import {RegisterPage} from "@/components/auth/register-page"
|
||||
import { Suspense } from 'react';
|
||||
import { RegisterPage } from '@/components/auth/register-page';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<Suspense>
|
||||
<RegisterPage />
|
||||
</Suspense>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import {LegalPageLayout} from "@/components/common/docs/legal-page-layout";
|
||||
import {apiSections, DOCS_LAST_UPDATED} from "@/components/common/docs/api";
|
||||
import { LegalPageLayout } from '@/components/common/docs/legal-page-layout';
|
||||
import { apiSections, DOCS_LAST_UPDATED } from '@/components/common/docs/api';
|
||||
|
||||
export default function ApiDocPage() {
|
||||
return (
|
||||
<LegalPageLayout
|
||||
title="API 接口文档"
|
||||
title='API 接口文档'
|
||||
lastUpdated={DOCS_LAST_UPDATED}
|
||||
sections={apiSections}
|
||||
description={
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
OpenFlare 提供简单、强大的 API 接口,支持多种编程语言和开发环境。通过标准化的 RESTful 接口,您可以轻松地与后端服务进行集成与二次开发。
|
||||
<p className='text-muted-foreground text-sm leading-relaxed'>
|
||||
OpenFlare 提供简单、强大的 API
|
||||
接口,支持多种编程语言和开发环境。通过标准化的 RESTful
|
||||
接口,您可以轻松地与后端服务进行集成与二次开发。
|
||||
</p>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import {LegalPageLayout} from "@/components/common/docs/legal-page-layout";
|
||||
import {howToUseSections} from "@/components/common/docs/how-to-use";
|
||||
import {DOCS_LAST_UPDATED} from "@/components/common/docs/api";
|
||||
import { LegalPageLayout } from '@/components/common/docs/legal-page-layout';
|
||||
import { howToUseSections } from '@/components/common/docs/how-to-use';
|
||||
import { DOCS_LAST_UPDATED } from '@/components/common/docs/api';
|
||||
|
||||
export default function HowToUsePage() {
|
||||
return (
|
||||
<LegalPageLayout
|
||||
title="平台使用指南"
|
||||
title='平台使用指南'
|
||||
lastUpdated={DOCS_LAST_UPDATED}
|
||||
sections={howToUseSections}
|
||||
description={
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
欢迎使用 OpenFlare 管理平台。本文档将引导您快速了解平台的核心组件、角色权限设计及二次开发流程,帮助您快速上手开发。
|
||||
<p className='text-muted-foreground text-sm leading-relaxed'>
|
||||
欢迎使用 OpenFlare
|
||||
管理平台。本文档将引导您快速了解平台的核心组件、角色权限设计及二次开发流程,帮助您快速上手开发。
|
||||
</p>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import {LegalPageLayout} from "@/components/common/docs/legal-page-layout"
|
||||
import {privacySections} from "@/components/common/docs/privacy"
|
||||
import {TERMS_LAST_UPDATED} from "@/components/common/docs/terms"
|
||||
import { LegalPageLayout } from '@/components/common/docs/legal-page-layout';
|
||||
import { privacySections } from '@/components/common/docs/privacy';
|
||||
import { TERMS_LAST_UPDATED } from '@/components/common/docs/terms';
|
||||
|
||||
export default function PrivacyPolicyPage() {
|
||||
return (
|
||||
<LegalPageLayout
|
||||
title="隐私政策 (Privacy)"
|
||||
title='隐私政策 (Privacy)'
|
||||
lastUpdated={TERMS_LAST_UPDATED}
|
||||
sections={privacySections}
|
||||
description={
|
||||
<span>
|
||||
我们非常重视您的隐私保护。本政策将向您透明地展示我们如何收集、使用、存储您的个人信息,
|
||||
<br className="hidden md:block" />
|
||||
<br className='hidden md:block' />
|
||||
以及您享有的相关权利。
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import {LegalPageLayout} from "@/components/common/docs/legal-page-layout"
|
||||
import {TERMS_LAST_UPDATED, termsSections} from "@/components/common/docs/terms"
|
||||
import { LegalPageLayout } from '@/components/common/docs/legal-page-layout';
|
||||
import {
|
||||
TERMS_LAST_UPDATED,
|
||||
termsSections,
|
||||
} from '@/components/common/docs/terms';
|
||||
|
||||
export default function TermsOfServicePage() {
|
||||
return (
|
||||
<LegalPageLayout
|
||||
title="服务协议 (Terms)"
|
||||
title='服务协议 (Terms)'
|
||||
lastUpdated={TERMS_LAST_UPDATED}
|
||||
sections={termsSections}
|
||||
description={
|
||||
<span>
|
||||
为了保障您的合法权益,请您仔细阅读以下条款。
|
||||
</span>
|
||||
}
|
||||
description={<span>为了保障您的合法权益,请您仔细阅读以下条款。</span>}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import type { AccessLogItem } from '@/lib/services/openflare';
|
||||
import { formatDateTime } from '@/lib/utils';
|
||||
import { formatBytes } from '@/lib/utils/metrics';
|
||||
|
||||
import { cacheOutcomeLabel, resolveCacheOutcome } from './access-log-utils';
|
||||
|
||||
function DetailField({
|
||||
label,
|
||||
value,
|
||||
mono,
|
||||
full,
|
||||
}: {
|
||||
label: string;
|
||||
value: React.ReactNode;
|
||||
mono?: boolean;
|
||||
full?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={full ? 'sm:col-span-2 space-y-1' : 'space-y-1'}>
|
||||
<p className='text-[11px] uppercase tracking-wider text-muted-foreground'>
|
||||
{label}
|
||||
</p>
|
||||
<div
|
||||
className={`text-sm break-all ${mono ? 'font-mono text-xs' : 'text-foreground'}`}
|
||||
>
|
||||
{value}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatRequestTimeMs(value: number | undefined | null) {
|
||||
if (value == null || !Number.isFinite(value) || value < 0) {
|
||||
return '—';
|
||||
}
|
||||
if (value < 1000) {
|
||||
return `${Math.round(value)} ms`;
|
||||
}
|
||||
return `${(value / 1000).toFixed(2)} s`;
|
||||
}
|
||||
|
||||
export function AccessLogDetailDialog({
|
||||
open,
|
||||
item,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
item: AccessLogItem | null;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
// Keep last selected item while the dialog closes to avoid empty-state flash.
|
||||
const [displayItem, setDisplayItem] = useState<AccessLogItem | null>(item);
|
||||
if (item && item !== displayItem) {
|
||||
setDisplayItem(item);
|
||||
}
|
||||
const activeItem = item ?? displayItem;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='max-h-[90vh] sm:max-w-2xl overflow-y-auto hide-scrollbar'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>访问日志详情</DialogTitle>
|
||||
<DialogDescription>
|
||||
本条请求的全部业务字段。IP 访问分析请前往「IP 明细」。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{activeItem ? (
|
||||
<div className='grid gap-4 sm:grid-cols-2'>
|
||||
<DetailField label='日志 ID' value={activeItem.id || '—'} mono />
|
||||
<DetailField
|
||||
label='请求时间'
|
||||
value={formatDateTime(activeItem.logged_at)}
|
||||
/>
|
||||
<DetailField
|
||||
label='入库时间'
|
||||
value={
|
||||
activeItem.created_at
|
||||
? formatDateTime(activeItem.created_at)
|
||||
: '—'
|
||||
}
|
||||
/>
|
||||
<DetailField
|
||||
label='节点'
|
||||
value={activeItem.node_name || activeItem.node_id || '—'}
|
||||
/>
|
||||
<DetailField
|
||||
label='节点 ID'
|
||||
value={activeItem.node_id || '—'}
|
||||
mono
|
||||
/>
|
||||
<DetailField
|
||||
label='客户端 IP'
|
||||
value={activeItem.remote_addr || '—'}
|
||||
mono
|
||||
/>
|
||||
<DetailField label='地区' value={activeItem.region || '—'} />
|
||||
<DetailField label='域名' value={activeItem.host || '—'} />
|
||||
<DetailField
|
||||
label='状态码'
|
||||
value={
|
||||
<Badge variant='outline' className='text-[10px]'>
|
||||
{activeItem.status_code}
|
||||
</Badge>
|
||||
}
|
||||
/>
|
||||
<DetailField
|
||||
label='缓存'
|
||||
value={
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
<Badge variant='outline' className='text-[10px]'>
|
||||
{cacheOutcomeLabel(
|
||||
resolveCacheOutcome(activeItem.cache_status),
|
||||
)}
|
||||
</Badge>
|
||||
<span className='font-mono text-xs text-muted-foreground'>
|
||||
{activeItem.cache_status || '—'}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<DetailField
|
||||
label='出站流量'
|
||||
value={formatBytes(activeItem.bytes_sent ?? 0)}
|
||||
/>
|
||||
<DetailField
|
||||
label='入站流量'
|
||||
value={formatBytes(activeItem.request_length ?? 0)}
|
||||
/>
|
||||
<DetailField
|
||||
label='请求耗时'
|
||||
value={formatRequestTimeMs(activeItem.request_time_ms)}
|
||||
/>
|
||||
<DetailField
|
||||
label='路径'
|
||||
value={activeItem.path || '—'}
|
||||
full
|
||||
mono
|
||||
/>
|
||||
<DetailField
|
||||
label='User-Agent'
|
||||
value={activeItem.user_agent || '—'}
|
||||
full
|
||||
mono
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,29 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {Search} from "lucide-react"
|
||||
import { Search } from 'lucide-react';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
|
||||
import type {AccessLogTab, SearchDraft} from "./access-log-utils"
|
||||
import {PAGE_SIZE_OPTIONS} from "./access-log-utils"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { SearchDraft } from './access-log-utils';
|
||||
import { PAGE_SIZE_OPTIONS } from './access-log-utils';
|
||||
|
||||
interface AccessLogFiltersProps {
|
||||
tab: AccessLogTab
|
||||
draft: SearchDraft
|
||||
pageSize: number
|
||||
onDraftChange: (draft: SearchDraft) => void
|
||||
onPageSizeChange: (pageSize: number) => void
|
||||
onSearch: () => void
|
||||
onReset: () => void
|
||||
draft: SearchDraft;
|
||||
pageSize: number;
|
||||
onDraftChange: (draft: SearchDraft) => void;
|
||||
onPageSizeChange: (pageSize: number) => void;
|
||||
onSearch: () => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
|
||||
export function AccessLogFilters({
|
||||
tab,
|
||||
draft,
|
||||
pageSize,
|
||||
onDraftChange,
|
||||
@@ -27,78 +31,76 @@ export function AccessLogFilters({
|
||||
onSearch,
|
||||
onReset,
|
||||
}: AccessLogFiltersProps) {
|
||||
const showPath = tab === "list" || tab === "folds"
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground">节点 ID</p>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-2.5 size-3.5 text-muted-foreground" />
|
||||
<div className='space-y-3'>
|
||||
<div className='grid gap-3 md:grid-cols-2 xl:grid-cols-4'>
|
||||
<div className='space-y-1.5'>
|
||||
<p className='text-xs font-medium text-muted-foreground'>节点 ID</p>
|
||||
<div className='relative'>
|
||||
<Search className='absolute left-2.5 top-2.5 size-3.5 text-muted-foreground' />
|
||||
<Input
|
||||
value={draft.nodeId}
|
||||
onChange={(e) =>
|
||||
onDraftChange({ ...draft, nodeId: e.target.value })
|
||||
}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onSearch()
|
||||
if (e.key === 'Enter') onSearch();
|
||||
}}
|
||||
placeholder="按 node_id 搜索"
|
||||
className="pl-8 h-9 text-xs"
|
||||
placeholder='按 node_id 搜索'
|
||||
className='pl-8 h-9 text-xs'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground">来源 IP</p>
|
||||
<div className='space-y-1.5'>
|
||||
<p className='text-xs font-medium text-muted-foreground'>来源 IP</p>
|
||||
<Input
|
||||
value={draft.remoteAddr}
|
||||
onChange={(e) =>
|
||||
onDraftChange({ ...draft, remoteAddr: e.target.value })
|
||||
}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onSearch()
|
||||
if (e.key === 'Enter') onSearch();
|
||||
}}
|
||||
placeholder="按 IP 搜索"
|
||||
className="h-9 text-xs"
|
||||
placeholder='按 IP 搜索'
|
||||
className='h-9 text-xs'
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground">访问域名</p>
|
||||
<div className='space-y-1.5'>
|
||||
<p className='text-xs font-medium text-muted-foreground'>访问域名</p>
|
||||
<Input
|
||||
value={draft.host}
|
||||
onChange={(e) => onDraftChange({ ...draft, host: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onSearch()
|
||||
if (e.key === 'Enter') onSearch();
|
||||
}}
|
||||
placeholder="按域名搜索"
|
||||
className="h-9 text-xs"
|
||||
placeholder='按域名搜索'
|
||||
className='h-9 text-xs'
|
||||
/>
|
||||
</div>
|
||||
<div className='space-y-1.5'>
|
||||
<p className='text-xs font-medium text-muted-foreground'>请求路径</p>
|
||||
<Input
|
||||
value={draft.path}
|
||||
onChange={(e) => onDraftChange({ ...draft, path: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') onSearch();
|
||||
}}
|
||||
placeholder='按路径搜索'
|
||||
className='h-9 text-xs'
|
||||
/>
|
||||
</div>
|
||||
{showPath ? (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium text-muted-foreground">请求路径</p>
|
||||
<Input
|
||||
value={draft.path}
|
||||
onChange={(e) => onDraftChange({ ...draft, path: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") onSearch()
|
||||
}}
|
||||
placeholder="按路径搜索"
|
||||
className="h-9 text-xs"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div className="space-y-1.5 w-full sm:max-w-[180px]">
|
||||
<p className="text-xs font-medium text-muted-foreground">每页条数</p>
|
||||
<div className='flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between'>
|
||||
<div className='space-y-1.5 w-full sm:max-w-[180px]'>
|
||||
<p className='text-xs font-medium text-muted-foreground'>每页条数</p>
|
||||
<Select
|
||||
value={String(pageSize)}
|
||||
onValueChange={(value) => onPageSizeChange(Number.parseInt(value, 10))}
|
||||
onValueChange={(value) =>
|
||||
onPageSizeChange(Number.parseInt(value, 10))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-9 text-xs">
|
||||
<SelectTrigger className='h-9 text-xs'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -110,15 +112,15 @@ export function AccessLogFilters({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" onClick={onSearch}>
|
||||
<div className='flex gap-2'>
|
||||
<Button size='sm' onClick={onSearch}>
|
||||
筛选
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={onReset}>
|
||||
<Button variant='outline' size='sm' onClick={onReset}>
|
||||
清空
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,48 +1,110 @@
|
||||
export type AccessLogTab = "list" | "folds" | "ip-summary" | "ip-trend"
|
||||
export type AccessLogTab = 'overview' | 'ips' | 'list';
|
||||
|
||||
export type SearchDraft = {
|
||||
nodeId: string
|
||||
remoteAddr: string
|
||||
host: string
|
||||
path: string
|
||||
}
|
||||
nodeId: string;
|
||||
remoteAddr: string;
|
||||
host: string;
|
||||
path: string;
|
||||
};
|
||||
|
||||
export const PAGE_SIZE_OPTIONS = [20, 50, 100, 200]
|
||||
export type OverviewRangeHours = 24 | 168 | 360 | 720;
|
||||
|
||||
export const PAGE_SIZE_OPTIONS = [20, 50, 100, 200];
|
||||
|
||||
export const OVERVIEW_RANGE_OPTIONS: {
|
||||
value: OverviewRangeHours;
|
||||
label: string;
|
||||
}[] = [
|
||||
{ value: 24, label: '24 小时' },
|
||||
{ value: 168, label: '7 天' },
|
||||
{ value: 360, label: '15 天' },
|
||||
{ value: 720, label: '30 天' },
|
||||
];
|
||||
|
||||
export const DETAIL_SORT_OPTIONS = [
|
||||
{ value: "logged_at:desc", label: "时间从新到旧" },
|
||||
{ value: "logged_at:asc", label: "时间从旧到新" },
|
||||
{ value: "status_code:desc", label: "状态码从高到低" },
|
||||
{ value: "status_code:asc", label: "状态码从低到高" },
|
||||
{ value: "remote_addr:asc", label: "IP 正序" },
|
||||
{ value: "remote_addr:desc", label: "IP 倒序" },
|
||||
]
|
||||
|
||||
export const FOLD_SORT_OPTIONS = [
|
||||
{ value: "bucket_started_at:desc", label: "时间桶从新到旧" },
|
||||
{ value: "bucket_started_at:asc", label: "时间桶从旧到新" },
|
||||
{ value: "request_count:desc", label: "访问次数从高到低" },
|
||||
{ value: "request_count:asc", label: "访问次数从低到高" },
|
||||
]
|
||||
{ value: 'logged_at:desc', label: '时间从新到旧' },
|
||||
{ value: 'logged_at:asc', label: '时间从旧到新' },
|
||||
{ value: 'status_code:desc', label: '状态码从高到低' },
|
||||
{ value: 'status_code:asc', label: '状态码从低到高' },
|
||||
{ value: 'remote_addr:asc', label: 'IP 正序' },
|
||||
{ value: 'remote_addr:desc', label: 'IP 倒序' },
|
||||
];
|
||||
|
||||
export const IP_SORT_OPTIONS = [
|
||||
{ value: "total_requests:desc", label: "总访问次数从高到低" },
|
||||
{ value: "total_requests:asc", label: "总访问次数从低到高" },
|
||||
{ value: "recent_requests:desc", label: "3 小时访问次数从高到低" },
|
||||
{ value: "last_seen_at:desc", label: "最后访问时间从新到旧" },
|
||||
]
|
||||
{ value: 'total_requests:desc', label: '请求数从高到低' },
|
||||
{ value: 'total_requests:asc', label: '请求数从低到高' },
|
||||
{ value: 'request_length:desc', label: '入站从高到低' },
|
||||
{ value: 'request_length:asc', label: '入站从低到高' },
|
||||
{ value: 'bytes_sent:desc', label: '出站从高到低' },
|
||||
{ value: 'bytes_sent:asc', label: '出站从低到高' },
|
||||
{ value: 'success_ratio:desc', label: '2xx 比例从高到低' },
|
||||
{ value: 'success_ratio:asc', label: '2xx 比例从低到高' },
|
||||
{ value: 'last_seen_at:desc', label: '最后访问从新到旧' },
|
||||
{ value: 'last_seen_at:asc', label: '最后访问从旧到新' },
|
||||
];
|
||||
|
||||
export function parseSortValue(value: string) {
|
||||
const [sortBy = "logged_at", sortOrder = "desc"] = value.split(":")
|
||||
const [sortBy = 'logged_at', sortOrder = 'desc'] = value.split(':');
|
||||
return {
|
||||
sortBy,
|
||||
sortOrder: sortOrder === "asc" ? ("asc" as const) : ("desc" as const),
|
||||
}
|
||||
sortOrder: sortOrder === 'asc' ? ('asc' as const) : ('desc' as const),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatCompactNumber(value: number) {
|
||||
return new Intl.NumberFormat("zh-CN", {
|
||||
notation: value >= 10000 ? "compact" : "standard",
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
notation: value >= 10000 ? 'compact' : 'standard',
|
||||
maximumFractionDigits: 1,
|
||||
}).format(value)
|
||||
}
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function formatOverviewRangeHint(hours: number) {
|
||||
if (hours <= 24) return '近 24 小时';
|
||||
if (hours % 24 === 0) return `近 ${hours / 24} 天`;
|
||||
return `近 ${hours} 小时`;
|
||||
}
|
||||
|
||||
export function formatOverviewTrendLabel(value: string, hours: number) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return '—';
|
||||
}
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0');
|
||||
const day = `${date.getDate()}`.padStart(2, '0');
|
||||
const hour = `${date.getHours()}`.padStart(2, '0');
|
||||
if (hours <= 24) {
|
||||
return `${hour}:00`;
|
||||
}
|
||||
return `${month}/${day} ${hour}:00`;
|
||||
}
|
||||
|
||||
export type CacheOutcome = 'hit' | 'origin' | 'uncached';
|
||||
|
||||
export function resolveCacheOutcome(
|
||||
cacheStatus: string | undefined | null,
|
||||
): CacheOutcome {
|
||||
const status = (cacheStatus ?? '').trim().toUpperCase();
|
||||
if (
|
||||
status === 'HIT' ||
|
||||
status === 'STALE' ||
|
||||
status === 'REVALIDATED' ||
|
||||
status === 'UPDATING'
|
||||
) {
|
||||
return 'hit';
|
||||
}
|
||||
if (status === 'MISS' || status === 'EXPIRED') {
|
||||
return 'origin';
|
||||
}
|
||||
return 'uncached';
|
||||
}
|
||||
|
||||
export function cacheOutcomeLabel(outcome: CacheOutcome) {
|
||||
switch (outcome) {
|
||||
case 'hit':
|
||||
return '命中';
|
||||
case 'origin':
|
||||
return '回源';
|
||||
default:
|
||||
return '未缓存';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useState} from "react"
|
||||
import {Loader2} from "lucide-react"
|
||||
import { useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -11,19 +11,25 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Label} from "@/components/ui/label"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
|
||||
const CLEANUP_PRESETS = [3, 7, 30]
|
||||
const CLEANUP_PRESETS = [3, 7, 30];
|
||||
|
||||
interface CleanupDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onConfirm: (retentionDays: number) => void
|
||||
loading: boolean
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onConfirm: (retentionDays: number) => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export function CleanupDialog({
|
||||
@@ -32,24 +38,24 @@ export function CleanupDialog({
|
||||
onConfirm,
|
||||
loading,
|
||||
}: CleanupDialogProps) {
|
||||
const [mode, setMode] = useState<string>("7")
|
||||
const [customDays, setCustomDays] = useState("14")
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [mode, setMode] = useState<string>('7');
|
||||
const [customDays, setCustomDays] = useState('14');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleConfirm = () => {
|
||||
const retentionDays =
|
||||
mode === "custom"
|
||||
mode === 'custom'
|
||||
? Number.parseInt(customDays, 10)
|
||||
: Number.parseInt(mode, 10)
|
||||
: Number.parseInt(mode, 10);
|
||||
|
||||
if (!Number.isFinite(retentionDays) || retentionDays < 1) {
|
||||
setError("保留天数必须大于 0")
|
||||
return
|
||||
setError('保留天数必须大于 0');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null)
|
||||
onConfirm(retentionDays)
|
||||
}
|
||||
setError(null);
|
||||
onConfirm(retentionDays);
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -61,8 +67,8 @@ export function CleanupDialog({
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
<div className='space-y-3'>
|
||||
<div className='space-y-1.5'>
|
||||
<Label>保留策略</Label>
|
||||
<Select value={mode} onValueChange={setMode}>
|
||||
<SelectTrigger>
|
||||
@@ -74,17 +80,17 @@ export function CleanupDialog({
|
||||
保留最近 {days} 天
|
||||
</SelectItem>
|
||||
))}
|
||||
<SelectItem value="custom">自定义天数</SelectItem>
|
||||
<SelectItem value='custom'>自定义天数</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{mode === "custom" ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="customDays">自定义保留天数</Label>
|
||||
{mode === 'custom' ? (
|
||||
<div className='space-y-1.5'>
|
||||
<Label htmlFor='customDays'>自定义保留天数</Label>
|
||||
<Input
|
||||
id="customDays"
|
||||
type="number"
|
||||
id='customDays'
|
||||
type='number'
|
||||
min={1}
|
||||
value={customDays}
|
||||
onChange={(e) => setCustomDays(e.target.value)}
|
||||
@@ -93,23 +99,27 @@ export function CleanupDialog({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? <p className="text-xs text-destructive">{error}</p> : null}
|
||||
{error ? <p className='text-xs text-destructive'>{error}</p> : null}
|
||||
</div>
|
||||
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={loading}>取消</AlertDialogCancel>
|
||||
<Button variant="destructive" onClick={handleConfirm} disabled={loading}>
|
||||
<Button
|
||||
variant='destructive'
|
||||
onClick={handleConfirm}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin mr-1" />
|
||||
<Loader2 className='size-4 animate-spin mr-1' />
|
||||
清理中...
|
||||
</>
|
||||
) : (
|
||||
"确认清理"
|
||||
'确认清理'
|
||||
)}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Eye } from 'lucide-react';
|
||||
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import type { AccessLogItem, AccessLogList } from '@/lib/services/openflare';
|
||||
import { formatDateTime } from '@/lib/utils';
|
||||
|
||||
import { AccessLogDetailDialog } from './access-log-detail-dialog';
|
||||
import {
|
||||
cacheOutcomeLabel,
|
||||
DETAIL_SORT_OPTIONS,
|
||||
resolveCacheOutcome,
|
||||
type CacheOutcome,
|
||||
} from './access-log-utils';
|
||||
|
||||
function cacheOutcomeVariant(
|
||||
outcome: CacheOutcome,
|
||||
): 'default' | 'secondary' | 'outline' | 'destructive' {
|
||||
switch (outcome) {
|
||||
case 'hit':
|
||||
return 'default';
|
||||
case 'origin':
|
||||
return 'secondary';
|
||||
default:
|
||||
return 'outline';
|
||||
}
|
||||
}
|
||||
|
||||
function PaginationBar({
|
||||
page,
|
||||
hasMore,
|
||||
loading,
|
||||
onPrev,
|
||||
onNext,
|
||||
}: {
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
loading: boolean;
|
||||
onPrev: () => void;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className='flex items-center justify-between px-4 py-3 border-t border-dashed'>
|
||||
<p className='text-xs text-muted-foreground'>当前第 {page + 1} 页</p>
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={loading || page <= 0}
|
||||
onClick={onPrev}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={loading || !hasMore}
|
||||
onClick={onNext}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DetailTab({
|
||||
data,
|
||||
loading,
|
||||
error,
|
||||
page,
|
||||
detailSort,
|
||||
onDetailSortChange,
|
||||
onRetry,
|
||||
onPrevPage,
|
||||
onNextPage,
|
||||
isFetching,
|
||||
}: {
|
||||
data?: AccessLogList;
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
page: number;
|
||||
detailSort: string;
|
||||
onDetailSortChange: (value: string) => void;
|
||||
onRetry: () => void;
|
||||
onPrevPage: () => void;
|
||||
onNextPage: () => void;
|
||||
isFetching: boolean;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<AccessLogItem | null>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='rounded-lg border border-dashed overflow-hidden bg-background'>
|
||||
<div className='flex items-center justify-between px-4 py-3 border-b border-dashed'>
|
||||
<p className='text-sm font-medium'>日志明细</p>
|
||||
<Select value={detailSort} onValueChange={onDetailSortChange}>
|
||||
<SelectTrigger className='h-8 w-44 text-xs'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DETAIL_SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{error ? (
|
||||
<div className='p-4'>
|
||||
<ErrorInline
|
||||
message={error.message || '加载失败'}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<LoadingStateWithBorder />
|
||||
) : (data?.items ?? []).length === 0 ? (
|
||||
<EmptyStateWithBorder title='暂无访问日志' />
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader className='bg-muted/40'>
|
||||
<TableRow className='border-dashed hover:bg-transparent'>
|
||||
<TableHead className='text-xs'>时间</TableHead>
|
||||
<TableHead className='text-xs'>节点</TableHead>
|
||||
<TableHead className='text-xs'>IP</TableHead>
|
||||
<TableHead className='text-xs'>域名</TableHead>
|
||||
<TableHead className='text-xs'>路径</TableHead>
|
||||
<TableHead className='text-xs'>缓存</TableHead>
|
||||
<TableHead className='text-xs'>状态码</TableHead>
|
||||
<TableHead className='w-12 text-center text-xs' />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(data?.items ?? []).map((item) => {
|
||||
const outcome = resolveCacheOutcome(item.cache_status);
|
||||
return (
|
||||
<TableRow key={item.id} className='border-dashed'>
|
||||
<TableCell className='text-xs'>
|
||||
{formatDateTime(item.logged_at)}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs'>
|
||||
{item.node_name || item.node_id}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs'>
|
||||
<div className='flex flex-col gap-0.5'>
|
||||
<span className='font-mono'>{item.remote_addr}</span>
|
||||
{item.region ? (
|
||||
<span className='text-[10px] text-muted-foreground'>
|
||||
{item.region}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className='text-xs'>{item.host}</TableCell>
|
||||
<TableCell className='text-xs max-w-48 truncate'>
|
||||
{item.path}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant={cacheOutcomeVariant(outcome)}
|
||||
className='text-[10px]'
|
||||
title={item.cache_status || undefined}
|
||||
>
|
||||
{cacheOutcomeLabel(outcome)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant='outline' className='text-[10px]'>
|
||||
{item.status_code}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className='text-center'>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='h-6 w-6 text-muted-foreground hover:text-foreground'
|
||||
onClick={() => {
|
||||
setSelected(item);
|
||||
setDetailOpen(true);
|
||||
}}
|
||||
>
|
||||
<Eye className='size-3' />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side='top' className='text-xs'>
|
||||
查看详情
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
<PaginationBar
|
||||
page={page}
|
||||
hasMore={data?.has_more ?? false}
|
||||
loading={isFetching}
|
||||
onPrev={onPrevPage}
|
||||
onNext={onNextPage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AccessLogDetailDialog
|
||||
open={detailOpen}
|
||||
item={selected}
|
||||
onOpenChange={setDetailOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from 'recharts';
|
||||
import { Loader2, ShieldPlus, Trash2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { RankChart } from '@/components/data/rank-chart';
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
ChartConfig,
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
} from '@/components/ui/chart';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import {
|
||||
AccessLogService,
|
||||
type DistributionItem,
|
||||
type WAFIPGroup,
|
||||
WafService,
|
||||
} from '@/lib/services/openflare';
|
||||
import { formatBytes, formatCompactNumber } from '@/lib/utils/metrics';
|
||||
|
||||
import { buildIPGroupPayloadFromGroup } from '../../waf/components/helpers';
|
||||
import {
|
||||
formatOverviewRangeHint,
|
||||
formatOverviewTrendLabel,
|
||||
OVERVIEW_RANGE_OPTIONS,
|
||||
type OverviewRangeHours,
|
||||
} from './access-log-utils';
|
||||
|
||||
const trendChartConfig = {
|
||||
requests: { label: '请求数', color: 'hsl(var(--primary))' },
|
||||
} satisfies ChartConfig;
|
||||
|
||||
function resolveBucketMinutes(hours: number) {
|
||||
if (hours <= 24) return 30;
|
||||
return 60;
|
||||
}
|
||||
|
||||
function groupsContainingIp(groups: WAFIPGroup[], ip: string) {
|
||||
const target = ip.trim();
|
||||
if (!target) return [];
|
||||
return groups.filter((group) =>
|
||||
(group.ip_list ?? []).some((entry) => entry.trim() === target),
|
||||
);
|
||||
}
|
||||
|
||||
function toRankItems(items: DistributionItem[] | undefined) {
|
||||
return (items ?? []).map((item) => ({
|
||||
label: item.key,
|
||||
value: item.value,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Clamp analysis/trend window to API limits (1–720 hours). */
|
||||
function clampAnalysisHours(hours: number): number {
|
||||
if (!Number.isFinite(hours) || hours <= 0) return 24;
|
||||
return Math.min(720, Math.max(1, Math.round(hours)));
|
||||
}
|
||||
|
||||
function isOverviewPreset(hours: number): hours is OverviewRangeHours {
|
||||
return hours === 24 || hours === 168 || hours === 360 || hours === 720;
|
||||
}
|
||||
|
||||
function MetricCard({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className='rounded-lg border border-dashed px-3 py-2.5'>
|
||||
<p className='text-[10px] uppercase tracking-wider text-muted-foreground'>
|
||||
{label}
|
||||
</p>
|
||||
<p className='mt-1 text-lg font-semibold tracking-tight'>{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MiniRankCard({
|
||||
title,
|
||||
items,
|
||||
color,
|
||||
}: {
|
||||
title: string;
|
||||
items: { label: string; value: number }[];
|
||||
color: string;
|
||||
}) {
|
||||
return (
|
||||
<div className='rounded-lg border border-dashed p-3'>
|
||||
<p className='mb-2 text-sm font-medium'>{title}</p>
|
||||
<RankChart
|
||||
items={items}
|
||||
color={color}
|
||||
className='!h-[220px]'
|
||||
emptyMessage={`暂无 ${title} 数据`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddToIPGroupPanel({
|
||||
ip,
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
ip: string;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const [selectedGroupId, setSelectedGroupId] = useState<string>('');
|
||||
|
||||
const groupsQuery = useQuery({
|
||||
queryKey: ['openflare', 'waf', 'ip-groups'],
|
||||
queryFn: () => WafService.listIPGroups(),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
const groups = useMemo(() => groupsQuery.data ?? [], [groupsQuery.data]);
|
||||
const matchedGroups = useMemo(
|
||||
() => groupsContainingIp(groups, ip),
|
||||
[groups, ip],
|
||||
);
|
||||
const manualGroups = useMemo(
|
||||
() =>
|
||||
groups.filter(
|
||||
(group) => group.type === 'manual' && group.enabled !== false,
|
||||
),
|
||||
[groups],
|
||||
);
|
||||
const addableGroups = useMemo(
|
||||
() =>
|
||||
manualGroups.filter(
|
||||
(group) =>
|
||||
!(group.ip_list ?? []).some((entry) => entry.trim() === ip.trim()),
|
||||
),
|
||||
[manualGroups, ip],
|
||||
);
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
group,
|
||||
nextList,
|
||||
}: {
|
||||
group: WAFIPGroup;
|
||||
nextList: string[];
|
||||
}) =>
|
||||
WafService.updateIPGroup(
|
||||
group.id,
|
||||
buildIPGroupPayloadFromGroup(group, nextList),
|
||||
),
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['openflare', 'waf', 'ip-groups'],
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleAdd = async () => {
|
||||
const groupId = Number.parseInt(selectedGroupId, 10);
|
||||
const group = addableGroups.find((item) => item.id === groupId);
|
||||
if (!group) {
|
||||
toast.error('请选择要加入的 IP 组');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateMutation.mutateAsync({
|
||||
group,
|
||||
nextList: [...(group.ip_list ?? []), ip.trim()],
|
||||
});
|
||||
toast.success(`已将 ${ip} 加入 IP 组「${group.name}」`);
|
||||
setSelectedGroupId('');
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : '加入 IP 组失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemove = async (group: WAFIPGroup) => {
|
||||
try {
|
||||
await updateMutation.mutateAsync({
|
||||
group,
|
||||
nextList: (group.ip_list ?? []).filter(
|
||||
(entry) => entry.trim() !== ip.trim(),
|
||||
),
|
||||
});
|
||||
toast.success(`已从 IP 组「${group.name}」移除 ${ip}`);
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : '移除失败');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) {
|
||||
setSelectedGroupId('');
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className='max-w-lg'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>将 IP 加入 IP 组</DialogTitle>
|
||||
<DialogDescription>
|
||||
目标 IP:
|
||||
<span className='font-mono text-foreground'>{ip}</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{groupsQuery.isLoading ? (
|
||||
<LoadingStateWithBorder title='加载 IP 组' />
|
||||
) : groupsQuery.isError ? (
|
||||
<ErrorInline
|
||||
message={
|
||||
groupsQuery.error instanceof Error
|
||||
? groupsQuery.error.message
|
||||
: '加载 IP 组失败'
|
||||
}
|
||||
onRetry={() => void groupsQuery.refetch()}
|
||||
/>
|
||||
) : (
|
||||
<div className='space-y-4'>
|
||||
{matchedGroups.length > 0 ? (
|
||||
<div className='space-y-2 rounded-lg border border-dashed p-3'>
|
||||
<p className='text-sm font-medium text-foreground'>
|
||||
该 IP 已存在于以下 IP 组
|
||||
</p>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
可选择删除,或继续添加到其他 IP 组。
|
||||
</p>
|
||||
<div className='space-y-2'>
|
||||
{matchedGroups.map((group) => (
|
||||
<div
|
||||
key={group.id}
|
||||
className='flex items-center justify-between gap-2 rounded-md border px-3 py-2'
|
||||
>
|
||||
<div className='min-w-0'>
|
||||
<p className='truncate text-sm font-medium'>
|
||||
{group.name}
|
||||
</p>
|
||||
<p className='text-[11px] text-muted-foreground'>
|
||||
{group.type} · {group.ip_list?.length ?? 0} 条
|
||||
</p>
|
||||
</div>
|
||||
{group.type === 'manual' ? (
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8 shrink-0 text-destructive'
|
||||
disabled={updateMutation.isPending}
|
||||
onClick={() => void handleRemove(group)}
|
||||
>
|
||||
{updateMutation.isPending ? (
|
||||
<Loader2 className='size-3.5 animate-spin' />
|
||||
) : (
|
||||
<>
|
||||
<Trash2 className='mr-1 size-3.5' />
|
||||
删除
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Badge variant='outline' className='text-[10px]'>
|
||||
不可手动删除
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
该 IP 尚未加入任何 IP 组。
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className='space-y-2'>
|
||||
<p className='text-sm font-medium'>添加到其他 IP 组</p>
|
||||
{addableGroups.length === 0 ? (
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
没有可写入的手动 IP 组(或已全部包含该 IP)。
|
||||
</p>
|
||||
) : (
|
||||
<Select
|
||||
value={selectedGroupId}
|
||||
onValueChange={setSelectedGroupId}
|
||||
>
|
||||
<SelectTrigger className='h-9 text-xs'>
|
||||
<SelectValue placeholder='选择手动 IP 组' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{addableGroups.map((group) => (
|
||||
<SelectItem key={group.id} value={String(group.id)}>
|
||||
{group.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant='outline' onClick={onClose}>
|
||||
关闭
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => void handleAdd()}
|
||||
disabled={
|
||||
!selectedGroupId ||
|
||||
updateMutation.isPending ||
|
||||
addableGroups.length === 0
|
||||
}
|
||||
>
|
||||
{updateMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className='mr-1 size-3.5 animate-spin' />
|
||||
处理中...
|
||||
</>
|
||||
) : (
|
||||
'加入所选 IP 组'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function IpAnalysisPanel({
|
||||
ip,
|
||||
enabled,
|
||||
initialHours = 24,
|
||||
}: {
|
||||
ip: string;
|
||||
enabled: boolean;
|
||||
/**
|
||||
* Exact analysis window in hours (1–720), aligned with list filter duration.
|
||||
* Remount with key={ip} when switching IPs so this re-initializes.
|
||||
*/
|
||||
initialHours?: number;
|
||||
}) {
|
||||
const [ipGroupOpen, setIpGroupOpen] = useState(false);
|
||||
const [rangeHours, setRangeHours] = useState(() =>
|
||||
clampAnalysisHours(initialHours),
|
||||
);
|
||||
|
||||
const bucketMinutes = resolveBucketMinutes(rangeHours);
|
||||
const rangeHint = isOverviewPreset(rangeHours)
|
||||
? formatOverviewRangeHint(rangeHours)
|
||||
: `近 ${rangeHours} 小时`;
|
||||
|
||||
const trendQuery = useQuery({
|
||||
queryKey: [
|
||||
'openflare',
|
||||
'access-logs',
|
||||
'ip-trend',
|
||||
ip,
|
||||
rangeHours,
|
||||
bucketMinutes,
|
||||
],
|
||||
queryFn: () =>
|
||||
AccessLogService.getIPTrend({
|
||||
remote_addr: ip,
|
||||
hours: rangeHours,
|
||||
bucket_minutes: bucketMinutes,
|
||||
}),
|
||||
enabled: enabled && ip !== '',
|
||||
});
|
||||
|
||||
const analysisQuery = useQuery({
|
||||
queryKey: ['openflare', 'access-logs', 'ip-analysis', ip, rangeHours],
|
||||
queryFn: () =>
|
||||
AccessLogService.getIPAnalysis({
|
||||
remote_addr: ip,
|
||||
hours: rangeHours,
|
||||
}),
|
||||
enabled: enabled && ip !== '',
|
||||
});
|
||||
|
||||
const trendChartData = useMemo(() => {
|
||||
return (trendQuery.data?.points ?? []).map((point) => ({
|
||||
label: formatOverviewTrendLabel(point.bucket_started_at, rangeHours),
|
||||
requests: point.request_count,
|
||||
}));
|
||||
}, [rangeHours, trendQuery.data?.points]);
|
||||
|
||||
const analysis = analysisQuery.data;
|
||||
const isLoadingIP = trendQuery.isLoading || analysisQuery.isLoading;
|
||||
const isFetchingIP = trendQuery.isFetching || analysisQuery.isFetching;
|
||||
|
||||
if (!ip) {
|
||||
return <EmptyStateWithBorder description='没有有效 IP。' />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='space-y-4'>
|
||||
<div className='flex flex-wrap items-center justify-between gap-2'>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='outline'
|
||||
onClick={() => setIpGroupOpen(true)}
|
||||
>
|
||||
<ShieldPlus className='mr-1 size-3.5' />将 IP 加入到 IP 组
|
||||
</Button>
|
||||
<ToggleGroup
|
||||
type='single'
|
||||
value={isOverviewPreset(rangeHours) ? String(rangeHours) : ''}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
setRangeHours(clampAnalysisHours(Number.parseInt(value, 10)));
|
||||
}}
|
||||
variant='outline'
|
||||
size='sm'
|
||||
>
|
||||
{OVERVIEW_RANGE_OPTIONS.map((option) => (
|
||||
<ToggleGroupItem
|
||||
key={option.value}
|
||||
value={String(option.value)}
|
||||
className='px-2.5 text-xs'
|
||||
>
|
||||
{option.label}
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
{isLoadingIP ? (
|
||||
<LoadingStateWithBorder title='加载 IP 分析' />
|
||||
) : (
|
||||
<div className='space-y-4'>
|
||||
{analysisQuery.isError ? (
|
||||
<ErrorInline
|
||||
message={
|
||||
analysisQuery.error instanceof Error
|
||||
? analysisQuery.error.message
|
||||
: '加载 IP 分析失败'
|
||||
}
|
||||
onRetry={() => void analysisQuery.refetch()}
|
||||
/>
|
||||
) : analysis ? (
|
||||
<div className='grid gap-3 sm:grid-cols-2 lg:grid-cols-3'>
|
||||
<MetricCard
|
||||
label='总请求'
|
||||
value={formatCompactNumber(analysis.summary.total_requests)}
|
||||
/>
|
||||
<MetricCard
|
||||
label='错误数'
|
||||
value={formatCompactNumber(analysis.summary.error_count)}
|
||||
/>
|
||||
<MetricCard
|
||||
label='已提供带宽'
|
||||
value={formatBytes(analysis.summary.bandwidth_served)}
|
||||
/>
|
||||
<MetricCard
|
||||
label='接收数据'
|
||||
value={formatBytes(analysis.summary.bytes_received)}
|
||||
/>
|
||||
<MetricCard
|
||||
label='独立域名'
|
||||
value={formatCompactNumber(analysis.summary.unique_hosts)}
|
||||
/>
|
||||
<MetricCard
|
||||
label='独立路径'
|
||||
value={formatCompactNumber(analysis.summary.unique_paths)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className='space-y-3 rounded-lg border border-dashed p-4'>
|
||||
<div className='flex items-center justify-between gap-2'>
|
||||
<div>
|
||||
<p className='text-sm font-medium'>IP 请求趋势</p>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
{ip} · {rangeHint} · {bucketMinutes} 分钟桶
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size='sm'
|
||||
variant='ghost'
|
||||
disabled={isFetchingIP}
|
||||
onClick={() => {
|
||||
void trendQuery.refetch();
|
||||
void analysisQuery.refetch();
|
||||
}}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{trendQuery.isError ? (
|
||||
<ErrorInline
|
||||
message={
|
||||
trendQuery.error instanceof Error
|
||||
? trendQuery.error.message
|
||||
: '加载趋势失败'
|
||||
}
|
||||
onRetry={() => void trendQuery.refetch()}
|
||||
/>
|
||||
) : trendChartData.every((point) => point.requests === 0) ? (
|
||||
<EmptyStateWithBorder
|
||||
description={`该 IP 在${rangeHint}内没有访问记录。`}
|
||||
/>
|
||||
) : (
|
||||
<ChartContainer
|
||||
config={trendChartConfig}
|
||||
className='h-56 w-full'
|
||||
>
|
||||
<AreaChart data={trendChartData}>
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis
|
||||
dataKey='label'
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
fontSize={10}
|
||||
minTickGap={24}
|
||||
/>
|
||||
<YAxis
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
fontSize={10}
|
||||
width={40}
|
||||
tickFormatter={(value) =>
|
||||
formatCompactNumber(Number(value))
|
||||
}
|
||||
/>
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Area
|
||||
type='monotone'
|
||||
dataKey='requests'
|
||||
stroke='var(--color-requests)'
|
||||
fill='var(--color-requests)'
|
||||
fillOpacity={0.2}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{analysis ? (
|
||||
<div className='grid gap-3 md:grid-cols-2'>
|
||||
<MiniRankCard
|
||||
title='Top Paths'
|
||||
color='#a78bfa'
|
||||
items={toRankItems(analysis.top_paths)}
|
||||
/>
|
||||
<MiniRankCard
|
||||
title='Top Hosts'
|
||||
color='#34d399'
|
||||
items={toRankItems(analysis.top_hosts)}
|
||||
/>
|
||||
<MiniRankCard
|
||||
title='Status Codes'
|
||||
color='#f59e0b'
|
||||
items={toRankItems(analysis.status_codes)}
|
||||
/>
|
||||
<MiniRankCard
|
||||
title='Top User-Agents'
|
||||
color='#818cf8'
|
||||
items={toRankItems(analysis.top_user_agents)}
|
||||
/>
|
||||
<MiniRankCard
|
||||
title='Device Types'
|
||||
color='#38bdf8'
|
||||
items={toRankItems(analysis.device_types)}
|
||||
/>
|
||||
<MiniRankCard
|
||||
title='Top Browsers'
|
||||
color='#22c55e'
|
||||
items={toRankItems(analysis.top_browsers)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AddToIPGroupPanel
|
||||
ip={ip}
|
||||
open={ipGroupOpen}
|
||||
onClose={() => setIpGroupOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
import { IpAnalysisPanel } from './ip-analysis-panel';
|
||||
|
||||
export function IpDetailDialog({
|
||||
open,
|
||||
remoteAddr,
|
||||
region,
|
||||
initialHours,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean;
|
||||
remoteAddr: string | null;
|
||||
region?: string;
|
||||
initialHours?: number;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const [displayAddr, setDisplayAddr] = useState<string | null>(remoteAddr);
|
||||
const [displayRegion, setDisplayRegion] = useState(region);
|
||||
if (remoteAddr && remoteAddr !== displayAddr) {
|
||||
setDisplayAddr(remoteAddr);
|
||||
setDisplayRegion(region);
|
||||
}
|
||||
const ip = remoteAddr ?? displayAddr ?? '';
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className='max-h-[90vh] sm:max-w-6xl md:max-w-6xl overflow-y-auto hide-scrollbar'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>IP 详情</DialogTitle>
|
||||
<DialogDescription>
|
||||
<span className='font-mono text-foreground'>{ip || '—'}</span>
|
||||
{displayRegion ? (
|
||||
<span className='text-muted-foreground'> · {displayRegion}</span>
|
||||
) : null}
|
||||
。查看该 IP 的访问趋势、分布与 WAF IP 组操作。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<IpAnalysisPanel
|
||||
key={ip}
|
||||
ip={ip}
|
||||
enabled={open && ip !== ''}
|
||||
initialHours={initialHours}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Eye } from 'lucide-react';
|
||||
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import type {
|
||||
AccessLogIPSummaryItem,
|
||||
AccessLogIPSummaryList,
|
||||
} from '@/lib/services/openflare';
|
||||
import { formatDateTime } from '@/lib/utils';
|
||||
import { formatBytes, formatCompactNumber } from '@/lib/utils/metrics';
|
||||
|
||||
import {
|
||||
formatOverviewRangeHint,
|
||||
IP_SORT_OPTIONS,
|
||||
OVERVIEW_RANGE_OPTIONS,
|
||||
PAGE_SIZE_OPTIONS,
|
||||
type OverviewRangeHours,
|
||||
} from './access-log-utils';
|
||||
import { IpDetailDialog } from './ip-detail-dialog';
|
||||
|
||||
export function toLocalInputValue(date: Date) {
|
||||
const pad = (n: number) => `${n}`.padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** Default local range ending now, spanning `hours`. */
|
||||
export function defaultLocalRangeForHours(hours: number) {
|
||||
const until = new Date();
|
||||
const since = new Date(until.getTime() - hours * 3_600_000);
|
||||
return {
|
||||
since: toLocalInputValue(since),
|
||||
until: toLocalInputValue(until),
|
||||
};
|
||||
}
|
||||
|
||||
function localInputToRFC3339(value: string) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
const MAX_CUSTOM_RANGE_MS = 30 * 24 * 3_600_000;
|
||||
|
||||
/** Validate custom local datetime-local range; returns error message or null. */
|
||||
export function validateCustomTimeRange(
|
||||
sinceLocal: string,
|
||||
untilLocal: string,
|
||||
): string | null {
|
||||
if (!sinceLocal.trim() || !untilLocal.trim()) {
|
||||
return '请填写开始与结束时间';
|
||||
}
|
||||
const sinceMs = new Date(sinceLocal).getTime();
|
||||
const untilMs = new Date(untilLocal).getTime();
|
||||
if (Number.isNaN(sinceMs) || Number.isNaN(untilMs)) {
|
||||
return '时间格式无效';
|
||||
}
|
||||
if (untilMs <= sinceMs) {
|
||||
return '结束时间必须晚于开始时间';
|
||||
}
|
||||
if (untilMs - sinceMs > MAX_CUSTOM_RANGE_MS) {
|
||||
return '时间范围不能超过 30 天';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatRatio(ratio: number) {
|
||||
if (!Number.isFinite(ratio) || ratio < 0) return '0%';
|
||||
return `${(ratio * 100).toFixed(1)}%`;
|
||||
}
|
||||
|
||||
/** Exact hours for analysis API (1–720), matching list window duration. */
|
||||
export function resolveAnalysisHours(input: {
|
||||
timeMode: IpTabTimeMode;
|
||||
hours: OverviewRangeHours;
|
||||
customSince: string;
|
||||
customUntil: string;
|
||||
}): number {
|
||||
if (input.timeMode === 'custom' && input.customSince && input.customUntil) {
|
||||
const ms =
|
||||
new Date(input.customUntil).getTime() -
|
||||
new Date(input.customSince).getTime();
|
||||
if (Number.isFinite(ms) && ms > 0) {
|
||||
return Math.min(720, Math.max(1, Math.ceil(ms / 3_600_000)));
|
||||
}
|
||||
}
|
||||
return input.hours;
|
||||
}
|
||||
|
||||
function PaginationBar({
|
||||
page,
|
||||
hasMore,
|
||||
loading,
|
||||
totalIp,
|
||||
onPrev,
|
||||
onNext,
|
||||
}: {
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
loading: boolean;
|
||||
totalIp?: number;
|
||||
onPrev: () => void;
|
||||
onNext: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className='flex items-center justify-between px-4 py-3 border-t border-dashed'>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
当前第 {page + 1} 页
|
||||
{typeof totalIp === 'number' ? ` · 共 ${totalIp} 个 IP` : ''}
|
||||
</p>
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={loading || page <= 0}
|
||||
onClick={onPrev}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={loading || !hasMore}
|
||||
onClick={onNext}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type IpTabTimeMode = 'preset' | 'custom';
|
||||
|
||||
export function IpTab({
|
||||
data,
|
||||
loading,
|
||||
error,
|
||||
page,
|
||||
pageSize,
|
||||
sort,
|
||||
hours,
|
||||
timeMode,
|
||||
customSince,
|
||||
customUntil,
|
||||
onHoursChange,
|
||||
onTimeModeChange,
|
||||
onApplyCustomRange,
|
||||
onPageSizeChange,
|
||||
onSortChange,
|
||||
onRetry,
|
||||
onPrevPage,
|
||||
onNextPage,
|
||||
isFetching,
|
||||
}: {
|
||||
data?: AccessLogIPSummaryList;
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
sort: string;
|
||||
hours: OverviewRangeHours;
|
||||
timeMode: IpTabTimeMode;
|
||||
/** Applied custom range (local datetime-local strings). */
|
||||
customSince: string;
|
||||
customUntil: string;
|
||||
onHoursChange: (hours: OverviewRangeHours) => void;
|
||||
onTimeModeChange: (mode: IpTabTimeMode) => void;
|
||||
/** Commit validated custom range for list query. */
|
||||
onApplyCustomRange: (since: string, until: string) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
onSortChange: (value: string) => void;
|
||||
onRetry: () => void;
|
||||
onPrevPage: () => void;
|
||||
onNextPage: () => void;
|
||||
isFetching: boolean;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<AccessLogIPSummaryItem | null>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
const [draftSince, setDraftSince] = useState(customSince);
|
||||
const [draftUntil, setDraftUntil] = useState(customUntil);
|
||||
const [customError, setCustomError] = useState<string | null>(null);
|
||||
|
||||
const defaultCustomRange = useMemo(
|
||||
() => defaultLocalRangeForHours(hours),
|
||||
[hours],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (timeMode !== 'custom') {
|
||||
setCustomError(null);
|
||||
return;
|
||||
}
|
||||
// Sync draft from applied range when entering custom or after apply.
|
||||
setDraftSince(customSince || defaultCustomRange.since);
|
||||
setDraftUntil(customUntil || defaultCustomRange.until);
|
||||
setCustomError(null);
|
||||
}, [timeMode, customSince, customUntil, defaultCustomRange]);
|
||||
|
||||
const analysisHours = resolveAnalysisHours({
|
||||
timeMode,
|
||||
hours,
|
||||
customSince,
|
||||
customUntil,
|
||||
});
|
||||
|
||||
const rangeHint =
|
||||
timeMode === 'custom' && customSince && customUntil
|
||||
? '自定义区间'
|
||||
: timeMode === 'custom'
|
||||
? '自定义(未应用)'
|
||||
: formatOverviewRangeHint(hours);
|
||||
|
||||
const handleApplyCustom = () => {
|
||||
const message = validateCustomTimeRange(draftSince, draftUntil);
|
||||
if (message) {
|
||||
setCustomError(message);
|
||||
return;
|
||||
}
|
||||
setCustomError(null);
|
||||
onApplyCustomRange(draftSince, draftUntil);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='space-y-4'>
|
||||
<div className='rounded-lg border border-dashed bg-background p-4 space-y-3'>
|
||||
<div className='flex flex-wrap items-center justify-between gap-3'>
|
||||
<div className='space-y-1'>
|
||||
<p className='text-sm font-medium'>时间范围</p>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
当前:{rangeHint}
|
||||
{data?.total_ip != null
|
||||
? ` · ${formatCompactNumber(data.total_ip)} 个 IP`
|
||||
: ''}
|
||||
</p>
|
||||
</div>
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
<ToggleGroup
|
||||
type='single'
|
||||
value={timeMode === 'preset' ? String(hours) : ''}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
onTimeModeChange('preset');
|
||||
onHoursChange(
|
||||
Number.parseInt(value, 10) as OverviewRangeHours,
|
||||
);
|
||||
}}
|
||||
variant='outline'
|
||||
size='sm'
|
||||
>
|
||||
{OVERVIEW_RANGE_OPTIONS.map((option) => (
|
||||
<ToggleGroupItem
|
||||
key={option.value}
|
||||
value={String(option.value)}
|
||||
className='px-2.5 text-xs'
|
||||
>
|
||||
{option.label}
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
<Button
|
||||
size='sm'
|
||||
variant={timeMode === 'custom' ? 'default' : 'outline'}
|
||||
className='h-8 text-xs'
|
||||
onClick={() => onTimeModeChange('custom')}
|
||||
>
|
||||
自定义
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{timeMode === 'custom' ? (
|
||||
<div className='space-y-2'>
|
||||
<div className='flex flex-wrap items-end gap-3'>
|
||||
<div className='space-y-1'>
|
||||
<p className='text-xs text-muted-foreground'>开始</p>
|
||||
<Input
|
||||
type='datetime-local'
|
||||
className='h-9 w-52 text-xs'
|
||||
value={draftSince || defaultCustomRange.since}
|
||||
onChange={(e) => {
|
||||
setDraftSince(e.target.value);
|
||||
setCustomError(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className='space-y-1'>
|
||||
<p className='text-xs text-muted-foreground'>结束</p>
|
||||
<Input
|
||||
type='datetime-local'
|
||||
className='h-9 w-52 text-xs'
|
||||
value={draftUntil || defaultCustomRange.until}
|
||||
onChange={(e) => {
|
||||
setDraftUntil(e.target.value);
|
||||
setCustomError(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size='sm'
|
||||
className='h-9 text-xs'
|
||||
onClick={handleApplyCustom}
|
||||
>
|
||||
应用
|
||||
</Button>
|
||||
</div>
|
||||
{customError ? (
|
||||
<p className='text-xs text-destructive'>{customError}</p>
|
||||
) : (
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
修改时间后点击「应用」再查询;详情分析窗口与列表时长对齐。
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className='flex flex-wrap items-center gap-3'>
|
||||
<div className='space-y-1'>
|
||||
<p className='text-xs text-muted-foreground'>排序</p>
|
||||
<Select value={sort} onValueChange={onSortChange}>
|
||||
<SelectTrigger className='h-8 w-48 text-xs'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{IP_SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className='space-y-1'>
|
||||
<p className='text-xs text-muted-foreground'>每页</p>
|
||||
<Select
|
||||
value={String(pageSize)}
|
||||
onValueChange={(value) =>
|
||||
onPageSizeChange(Number.parseInt(value, 10))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className='h-8 w-24 text-xs'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{PAGE_SIZE_OPTIONS.map((size) => (
|
||||
<SelectItem key={size} value={String(size)}>
|
||||
{size}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='rounded-lg border border-dashed overflow-hidden bg-background'>
|
||||
<div className='flex items-center justify-between px-4 py-3 border-b border-dashed'>
|
||||
<p className='text-sm font-medium'>IP 明细</p>
|
||||
</div>
|
||||
{error ? (
|
||||
<div className='p-4'>
|
||||
<ErrorInline
|
||||
message={error.message || '加载失败'}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<LoadingStateWithBorder />
|
||||
) : (data?.items ?? []).length === 0 ? (
|
||||
<EmptyStateWithBorder title='暂无 IP 数据' />
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader className='bg-muted/40'>
|
||||
<TableRow className='border-dashed hover:bg-transparent'>
|
||||
<TableHead className='text-xs'>IP</TableHead>
|
||||
<TableHead className='text-xs'>地区</TableHead>
|
||||
<TableHead className='text-xs text-right'>请求数</TableHead>
|
||||
<TableHead className='text-xs text-right'>2xx 比例</TableHead>
|
||||
<TableHead className='text-xs text-right'>入站</TableHead>
|
||||
<TableHead className='text-xs text-right'>出站</TableHead>
|
||||
<TableHead className='text-xs'>最后访问</TableHead>
|
||||
<TableHead className='w-12 text-center text-xs' />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(data?.items ?? []).map((item) => (
|
||||
<TableRow key={item.remote_addr} className='border-dashed'>
|
||||
<TableCell className='font-mono text-xs'>
|
||||
{item.remote_addr}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-muted-foreground'>
|
||||
{item.region || '—'}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-right tabular-nums'>
|
||||
{formatCompactNumber(item.total_requests)}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-right tabular-nums'>
|
||||
<span
|
||||
title={`${item.success_2xx_count}/${item.total_requests}`}
|
||||
>
|
||||
{formatRatio(item.success_ratio)}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-right tabular-nums'>
|
||||
{formatBytes(item.bytes_received)}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-right tabular-nums'>
|
||||
{formatBytes(item.bytes_sent)}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs'>
|
||||
{formatDateTime(item.last_seen_at)}
|
||||
</TableCell>
|
||||
<TableCell className='text-center'>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='h-6 w-6 text-muted-foreground hover:text-foreground'
|
||||
onClick={() => {
|
||||
setSelected(item);
|
||||
setDetailOpen(true);
|
||||
}}
|
||||
>
|
||||
<Eye className='size-3' />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side='top' className='text-xs'>
|
||||
查看 IP 详情
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
<PaginationBar
|
||||
page={page}
|
||||
hasMore={data?.has_more ?? false}
|
||||
loading={isFetching}
|
||||
totalIp={data?.total_ip}
|
||||
onPrev={onPrevPage}
|
||||
onNext={onNextPage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<IpDetailDialog
|
||||
open={detailOpen}
|
||||
remoteAddr={selected?.remote_addr ?? null}
|
||||
region={selected?.region}
|
||||
initialHours={analysisHours}
|
||||
onOpenChange={setDetailOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Build list API time params from IP tab state (applied values only). */
|
||||
export function buildIpSummaryTimeParams(input: {
|
||||
timeMode: IpTabTimeMode;
|
||||
hours: OverviewRangeHours;
|
||||
customSince: string;
|
||||
customUntil: string;
|
||||
}): { hours?: number; since?: string; until?: string } | null {
|
||||
if (input.timeMode === 'custom') {
|
||||
if (validateCustomTimeRange(input.customSince, input.customUntil)) {
|
||||
return null;
|
||||
}
|
||||
const since = localInputToRFC3339(input.customSince);
|
||||
const until = localInputToRFC3339(input.customUntil);
|
||||
if (!since || !until) {
|
||||
return null;
|
||||
}
|
||||
return { since, until };
|
||||
}
|
||||
return { hours: input.hours };
|
||||
}
|
||||
@@ -0,0 +1,775 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import ReactECharts from 'echarts-for-react';
|
||||
import { ChevronDown, Filter, Loader2, X } from 'lucide-react';
|
||||
import { Cell, Pie, PieChart } from 'recharts';
|
||||
|
||||
import { RankCard } from '@/components/data/rank-card';
|
||||
import { TrendChart } from '@/components/data/trend-chart';
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import {
|
||||
ChartContainer,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
type ChartConfig,
|
||||
} from '@/components/ui/chart';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import {
|
||||
ZoneService,
|
||||
zoneQueryKey,
|
||||
type AccessLogOverview,
|
||||
type DistributionItem,
|
||||
} from '@/lib/services/openflare';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { formatBytes, formatCompactNumber } from '@/lib/utils/metrics';
|
||||
|
||||
import {
|
||||
formatOverviewRangeHint,
|
||||
formatOverviewTrendLabel,
|
||||
OVERVIEW_RANGE_OPTIONS,
|
||||
type OverviewRangeHours,
|
||||
} from './access-log-utils';
|
||||
|
||||
const DEVICE_COLORS = [
|
||||
'#38bdf8',
|
||||
'#34d399',
|
||||
'#f59e0b',
|
||||
'#a78bfa',
|
||||
'#f472b6',
|
||||
'#94a3b8',
|
||||
];
|
||||
|
||||
function SparklineMetricCard({
|
||||
title,
|
||||
value,
|
||||
hint,
|
||||
color,
|
||||
fillColor,
|
||||
labels,
|
||||
values,
|
||||
valueFormatter,
|
||||
}: {
|
||||
title: string;
|
||||
value: string;
|
||||
hint: string;
|
||||
color: string;
|
||||
fillColor: string;
|
||||
labels: string[];
|
||||
values: number[];
|
||||
valueFormatter?: (value: number) => string;
|
||||
}) {
|
||||
const option = useMemo<EChartsOption>(
|
||||
() => ({
|
||||
animationDuration: 400,
|
||||
grid: {
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 8,
|
||||
bottom: 0,
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
show: false,
|
||||
boundaryGap: false,
|
||||
data: labels,
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
show: false,
|
||||
min: 0,
|
||||
},
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
backgroundColor: 'rgba(15, 23, 42, 0.92)',
|
||||
borderWidth: 0,
|
||||
textStyle: {
|
||||
color: '#e2e8f0',
|
||||
fontSize: 12,
|
||||
},
|
||||
formatter: (params: unknown) => {
|
||||
const items = Array.isArray(params) ? params : [];
|
||||
const item = items[0] as
|
||||
{ axisValueLabel?: string; value?: number } | undefined;
|
||||
if (!item) return '';
|
||||
const raw = typeof item.value === 'number' ? item.value : 0;
|
||||
const formatted = valueFormatter
|
||||
? valueFormatter(raw)
|
||||
: formatCompactNumber(raw);
|
||||
return `${item.axisValueLabel ?? ''}<br/>${formatted}`;
|
||||
},
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'line',
|
||||
data: values,
|
||||
smooth: true,
|
||||
showSymbol: false,
|
||||
lineStyle: {
|
||||
color,
|
||||
width: 2,
|
||||
},
|
||||
areaStyle: {
|
||||
color: fillColor,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
[color, fillColor, labels, valueFormatter, values],
|
||||
);
|
||||
|
||||
return (
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardContent className='p-4'>
|
||||
<div className='flex items-start justify-between gap-3'>
|
||||
<div className='min-w-0 space-y-1'>
|
||||
<p className='text-[10px] uppercase tracking-wider text-muted-foreground'>
|
||||
{title}
|
||||
</p>
|
||||
<p className='text-2xl font-semibold tracking-tight'>{value}</p>
|
||||
<p className='text-[11px] text-muted-foreground'>{hint}</p>
|
||||
</div>
|
||||
<div className='h-16 w-28 shrink-0 sm:w-36'>
|
||||
{labels.length > 0 ? (
|
||||
<ReactECharts
|
||||
option={option}
|
||||
notMerge
|
||||
lazyUpdate
|
||||
style={{ height: '100%', width: '100%' }}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function toRankItems(items: DistributionItem[] | undefined) {
|
||||
return (items ?? []).map((item) => ({
|
||||
label: item.key,
|
||||
value: item.value,
|
||||
}));
|
||||
}
|
||||
|
||||
function PieDistributionCard({
|
||||
title,
|
||||
description,
|
||||
items,
|
||||
emptyMessage,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
items: DistributionItem[];
|
||||
emptyMessage: string;
|
||||
}) {
|
||||
const chartData = useMemo(
|
||||
() =>
|
||||
items.map((item, index) => ({
|
||||
name: item.key,
|
||||
value: item.value,
|
||||
fill: DEVICE_COLORS[index % DEVICE_COLORS.length],
|
||||
})),
|
||||
[items],
|
||||
);
|
||||
|
||||
const chartConfig = useMemo(() => {
|
||||
const config: ChartConfig = {};
|
||||
chartData.forEach((item) => {
|
||||
config[item.name] = {
|
||||
label: item.name,
|
||||
color: item.fill,
|
||||
};
|
||||
});
|
||||
return config;
|
||||
}, [chartData]);
|
||||
|
||||
return (
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader className='pb-3'>
|
||||
<CardTitle className='text-sm font-semibold text-foreground'>
|
||||
{title}
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs text-muted-foreground'>
|
||||
{description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className='pt-0'>
|
||||
{chartData.length === 0 ? (
|
||||
<div className='flex h-[300px] items-center justify-center rounded-md border border-dashed bg-muted/20 text-sm text-muted-foreground'>
|
||||
{emptyMessage}
|
||||
</div>
|
||||
) : (
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className='mx-auto h-[300px] w-full'
|
||||
>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={chartData}
|
||||
dataKey='value'
|
||||
nameKey='name'
|
||||
cx='50%'
|
||||
cy='46%'
|
||||
innerRadius={50}
|
||||
outerRadius={80}
|
||||
paddingAngle={2}
|
||||
>
|
||||
{chartData.map((entry) => (
|
||||
<Cell key={entry.name} fill={entry.fill} />
|
||||
))}
|
||||
</Pie>
|
||||
<ChartTooltip
|
||||
cursor={false}
|
||||
content={
|
||||
<ChartTooltipContent
|
||||
hideLabel
|
||||
formatter={(value, name) => (
|
||||
<>
|
||||
<span className='text-muted-foreground'>{name}</span>
|
||||
<span className='ml-auto font-mono font-medium tabular-nums text-foreground'>
|
||||
{formatCompactNumber(Number(value ?? 0))}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<ChartLegend
|
||||
content={<ChartLegendContent nameKey='name' />}
|
||||
className='flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-[11px]'
|
||||
/>
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type ManagedZoneDomains = {
|
||||
zoneId: number;
|
||||
zoneName: string;
|
||||
domains: string[];
|
||||
};
|
||||
|
||||
function useManagedZoneDomains(enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: [...zoneQueryKey, 'zone-domain-tree'],
|
||||
enabled,
|
||||
staleTime: 60_000,
|
||||
queryFn: async (): Promise<ManagedZoneDomains[]> => {
|
||||
const zones = await ZoneService.list();
|
||||
const overviews = await Promise.all(
|
||||
zones.map((zone) => ZoneService.getOverview(zone.id)),
|
||||
);
|
||||
return overviews
|
||||
.map((overview) => {
|
||||
const domainSet = new Set<string>();
|
||||
for (const item of overview.domains ?? []) {
|
||||
const domain = item.domain?.trim();
|
||||
if (domain) domainSet.add(domain);
|
||||
}
|
||||
return {
|
||||
zoneId: overview.zone.id,
|
||||
zoneName: overview.zone.domain || `Zone #${overview.zone.id}`,
|
||||
domains: Array.from(domainSet).sort((a, b) => a.localeCompare(b)),
|
||||
};
|
||||
})
|
||||
.filter((zone) => zone.domains.length > 0)
|
||||
.sort((a, b) => a.zoneName.localeCompare(b.zoneName));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function OverviewHostFilter({
|
||||
hosts,
|
||||
onHostsChange,
|
||||
}: {
|
||||
hosts: string[];
|
||||
onHostsChange: (hosts: string[]) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [expandedZones, setExpandedZones] = useState<Record<number, boolean>>(
|
||||
{},
|
||||
);
|
||||
const zonesQuery = useManagedZoneDomains(open);
|
||||
const zones = useMemo(() => zonesQuery.data ?? [], [zonesQuery.data]);
|
||||
const selectedSet = useMemo(() => new Set(hosts), [hosts]);
|
||||
const filteredZones = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return zones;
|
||||
return zones
|
||||
.map((zone) => {
|
||||
const zoneMatched = zone.zoneName.toLowerCase().includes(q);
|
||||
const domains = zoneMatched
|
||||
? zone.domains
|
||||
: zone.domains.filter((domain) => domain.toLowerCase().includes(q));
|
||||
return { ...zone, domains };
|
||||
})
|
||||
.filter((zone) => zone.domains.length > 0);
|
||||
}, [query, zones]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || zones.length === 0) return;
|
||||
setExpandedZones((prev) => {
|
||||
const next = { ...prev };
|
||||
let changed = false;
|
||||
for (const zone of zones) {
|
||||
if (next[zone.zoneId] === undefined) {
|
||||
next[zone.zoneId] = true;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
}, [open, zones]);
|
||||
|
||||
useEffect(() => {
|
||||
const q = query.trim();
|
||||
if (!q || filteredZones.length === 0) return;
|
||||
setExpandedZones((prev) => {
|
||||
const next = { ...prev };
|
||||
for (const zone of filteredZones) {
|
||||
next[zone.zoneId] = true;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [filteredZones, query]);
|
||||
|
||||
const toggleHost = (domain: string, checked: boolean | 'indeterminate') => {
|
||||
if (checked === true) {
|
||||
if (selectedSet.has(domain)) return;
|
||||
onHostsChange([...hosts, domain]);
|
||||
return;
|
||||
}
|
||||
onHostsChange(hosts.filter((item) => item !== domain));
|
||||
};
|
||||
|
||||
const toggleZone = (
|
||||
zoneDomains: string[],
|
||||
checked: boolean | 'indeterminate',
|
||||
) => {
|
||||
if (checked === true) {
|
||||
const next = new Set(hosts);
|
||||
for (const domain of zoneDomains) next.add(domain);
|
||||
onHostsChange(Array.from(next));
|
||||
return;
|
||||
}
|
||||
onHostsChange(hosts.filter((item) => !zoneDomains.includes(item)));
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next);
|
||||
if (!next) setQuery('');
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='icon'
|
||||
className={cn(
|
||||
'size-8 shrink-0',
|
||||
hosts.length > 0 ? 'border-primary text-primary' : undefined,
|
||||
)}
|
||||
title={
|
||||
hosts.length > 0 ? `已筛选 ${hosts.length} 个域名` : '按域名筛选'
|
||||
}
|
||||
aria-label={
|
||||
hosts.length > 0 ? `已筛选 ${hosts.length} 个域名` : '按域名筛选'
|
||||
}
|
||||
>
|
||||
<Filter className='size-3.5' />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align='end' className='w-96 space-y-3 p-3'>
|
||||
<div className='flex items-center justify-between gap-2'>
|
||||
<p className='text-sm font-medium'>筛选域名</p>
|
||||
{hosts.length > 0 ? (
|
||||
<Button
|
||||
type='button'
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='h-7 px-2 text-xs'
|
||||
onClick={() => onHostsChange([])}
|
||||
>
|
||||
<X className='mr-1 size-3' />
|
||||
清除
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder='搜索 Zone 或域名'
|
||||
className='h-8 text-xs'
|
||||
/>
|
||||
<div className='max-h-72 space-y-2 overflow-y-auto hide-scrollbar'>
|
||||
{zonesQuery.isLoading ? (
|
||||
<div className='flex items-center justify-center gap-2 py-6 text-xs text-muted-foreground'>
|
||||
<Loader2 className='size-3.5 animate-spin' />
|
||||
加载域名…
|
||||
</div>
|
||||
) : zonesQuery.isError ? (
|
||||
<div className='space-y-2 py-2'>
|
||||
<p className='text-xs text-destructive'>加载域名失败</p>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
onClick={() => void zonesQuery.refetch()}
|
||||
>
|
||||
重试
|
||||
</Button>
|
||||
</div>
|
||||
) : filteredZones.length === 0 ? (
|
||||
<p className='py-6 text-center text-xs text-muted-foreground'>
|
||||
{zones.length === 0 ? '暂无已登记域名' : '没有匹配的域名'}
|
||||
</p>
|
||||
) : (
|
||||
filteredZones.map((zone) => {
|
||||
const selectedCount = zone.domains.filter((domain) =>
|
||||
selectedSet.has(domain),
|
||||
).length;
|
||||
const allSelected = selectedCount === zone.domains.length;
|
||||
const partialSelected =
|
||||
selectedCount > 0 && selectedCount < zone.domains.length;
|
||||
const expanded = expandedZones[zone.zoneId] ?? true;
|
||||
return (
|
||||
<Collapsible
|
||||
key={zone.zoneId}
|
||||
open={expanded}
|
||||
onOpenChange={(next) =>
|
||||
setExpandedZones((prev) => ({
|
||||
...prev,
|
||||
[zone.zoneId]: next,
|
||||
}))
|
||||
}
|
||||
className='rounded-md border border-dashed'
|
||||
>
|
||||
<div className='flex items-center gap-1 px-2 py-1.5'>
|
||||
<Checkbox
|
||||
checked={
|
||||
allSelected
|
||||
? true
|
||||
: partialSelected
|
||||
? 'indeterminate'
|
||||
: false
|
||||
}
|
||||
onCheckedChange={(checked) =>
|
||||
toggleZone(zone.domains, checked)
|
||||
}
|
||||
aria-label={`选择 Zone ${zone.zoneName}`}
|
||||
/>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type='button'
|
||||
className='flex min-w-0 flex-1 items-center gap-1 rounded-md px-1 py-0.5 text-left text-xs font-medium hover:bg-accent'
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'size-3.5 shrink-0 text-muted-foreground transition-transform',
|
||||
expanded ? 'rotate-0' : '-rotate-90',
|
||||
)}
|
||||
/>
|
||||
<span className='min-w-0 flex-1 truncate'>
|
||||
{zone.zoneName}
|
||||
</span>
|
||||
<span className='text-[10px] text-muted-foreground'>
|
||||
{selectedCount}/{zone.domains.length}
|
||||
</span>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
</div>
|
||||
<CollapsibleContent>
|
||||
<div className='space-y-0.5 border-t border-dashed px-2 py-1.5'>
|
||||
{zone.domains.map((domain) => {
|
||||
const selected = selectedSet.has(domain);
|
||||
return (
|
||||
<label
|
||||
key={domain}
|
||||
className={cn(
|
||||
'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-accent',
|
||||
selected ? 'bg-accent/50' : undefined,
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
onCheckedChange={(checked) =>
|
||||
toggleHost(domain, checked)
|
||||
}
|
||||
aria-label={`选择域名 ${domain}`}
|
||||
/>
|
||||
<span className='min-w-0 flex-1 truncate font-mono'>
|
||||
{domain}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
function OverviewToolbar({
|
||||
hours,
|
||||
hosts,
|
||||
onHoursChange,
|
||||
onHostsChange,
|
||||
}: {
|
||||
hours: OverviewRangeHours;
|
||||
hosts: string[];
|
||||
onHoursChange: (hours: OverviewRangeHours) => void;
|
||||
onHostsChange: (hosts: string[]) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className='flex flex-wrap items-center justify-end gap-2'>
|
||||
{hosts.length > 0 ? (
|
||||
<Badge variant='secondary' className='max-w-[260px] truncate'>
|
||||
{hosts.length === 1 ? hosts[0] : `已选 ${hosts.length} 个域名`}
|
||||
</Badge>
|
||||
) : null}
|
||||
<OverviewHostFilter hosts={hosts} onHostsChange={onHostsChange} />
|
||||
<ToggleGroup
|
||||
type='single'
|
||||
value={String(hours)}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
onHoursChange(Number.parseInt(value, 10) as OverviewRangeHours);
|
||||
}}
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='justify-end'
|
||||
>
|
||||
{OVERVIEW_RANGE_OPTIONS.map((option) => (
|
||||
<ToggleGroupItem
|
||||
key={option.value}
|
||||
value={String(option.value)}
|
||||
className='px-2.5 text-xs'
|
||||
>
|
||||
{option.label}
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function OverviewTab({
|
||||
data,
|
||||
loading,
|
||||
error,
|
||||
hours,
|
||||
hosts,
|
||||
onHoursChange,
|
||||
onHostsChange,
|
||||
onRetry,
|
||||
}: {
|
||||
data?: AccessLogOverview;
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
hours: OverviewRangeHours;
|
||||
hosts: string[];
|
||||
onHoursChange: (hours: OverviewRangeHours) => void;
|
||||
onHostsChange: (hosts: string[]) => void;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
<OverviewToolbar
|
||||
hours={hours}
|
||||
hosts={hosts}
|
||||
onHoursChange={onHoursChange}
|
||||
onHostsChange={onHostsChange}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<LoadingStateWithBorder
|
||||
title='加载访问概览'
|
||||
description='正在聚合请求量、访问量与带宽趋势...'
|
||||
/>
|
||||
) : error ? (
|
||||
<ErrorInline
|
||||
message={error.message || '加载访问概览失败'}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
) : !data ? (
|
||||
<EmptyStateWithBorder
|
||||
title='暂无概览数据'
|
||||
description='当前时间范围内没有可展示的访问统计。'
|
||||
/>
|
||||
) : (
|
||||
<OverviewContent data={data} hours={hours} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OverviewContent({
|
||||
data,
|
||||
hours,
|
||||
}: {
|
||||
data: AccessLogOverview;
|
||||
hours: number;
|
||||
}) {
|
||||
const requestLabels = data.trends.requests.map((point) =>
|
||||
formatOverviewTrendLabel(point.bucket_started_at, hours),
|
||||
);
|
||||
const requestValues = data.trends.requests.map((point) => point.value);
|
||||
const visitValues = data.trends.visits.map((point) => point.value);
|
||||
const bandwidthValues = data.trends.bandwidth.map((point) => point.value);
|
||||
const hint = formatOverviewRangeHint(hours);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='grid gap-4 lg:grid-cols-3'>
|
||||
<SparklineMetricCard
|
||||
title='Total Requests'
|
||||
value={formatCompactNumber(data.summary.total_requests)}
|
||||
hint={hint}
|
||||
color='#f59e0b'
|
||||
fillColor='rgba(245, 158, 11, 0.18)'
|
||||
labels={requestLabels}
|
||||
values={requestValues}
|
||||
/>
|
||||
<SparklineMetricCard
|
||||
title='Total Visits'
|
||||
value={formatCompactNumber(data.summary.total_visits)}
|
||||
hint={`${hint} · 独立访客`}
|
||||
color='#38bdf8'
|
||||
fillColor='rgba(56, 189, 248, 0.16)'
|
||||
labels={requestLabels}
|
||||
values={visitValues}
|
||||
/>
|
||||
<SparklineMetricCard
|
||||
title='Bandwidth Served'
|
||||
value={formatBytes(data.summary.bandwidth_served)}
|
||||
hint={`${hint} · 已提供数据`}
|
||||
color='#34d399'
|
||||
fillColor='rgba(52, 211, 153, 0.16)'
|
||||
labels={requestLabels}
|
||||
values={bandwidthValues}
|
||||
valueFormatter={formatBytes}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
Requests over time
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs'>
|
||||
观察请求量是否出现异常抬升或回落。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<TrendChart
|
||||
labels={requestLabels}
|
||||
height={280}
|
||||
showSummary={false}
|
||||
series={[
|
||||
{
|
||||
label: '请求量',
|
||||
color: '#f59e0b',
|
||||
fillColor: 'rgba(245, 158, 11, 0.18)',
|
||||
variant: 'area',
|
||||
values: requestValues,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className='grid gap-6 xl:grid-cols-2'>
|
||||
<PieDistributionCard
|
||||
title='Requests by device type'
|
||||
description='按设备类型统计请求占比。'
|
||||
items={data.device_types ?? []}
|
||||
emptyMessage='暂无设备类型数据'
|
||||
/>
|
||||
<PieDistributionCard
|
||||
title='Status code'
|
||||
description='按 HTTP 状态码统计请求占比。'
|
||||
items={data.status_codes ?? []}
|
||||
emptyMessage='暂无状态码分布数据'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='grid gap-6 xl:grid-cols-3'>
|
||||
<RankCard
|
||||
title='Top Paths'
|
||||
description='访问量最高的请求路径。'
|
||||
items={toRankItems(data.top_paths)}
|
||||
/>
|
||||
<RankCard
|
||||
title='Top Hosts'
|
||||
description='流量集中的访问域名。'
|
||||
items={toRankItems(data.top_hosts)}
|
||||
/>
|
||||
<RankCard
|
||||
title='Top IPs'
|
||||
description='请求次数最多的来源 IP。'
|
||||
items={toRankItems(data.top_ips)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='grid gap-6 xl:grid-cols-3'>
|
||||
<RankCard
|
||||
title='Top browsers'
|
||||
description='按浏览器聚合的请求排行。'
|
||||
items={toRankItems(data.top_browsers)}
|
||||
/>
|
||||
<RankCard
|
||||
title='Top Operating System'
|
||||
description='按操作系统聚合的请求排行。'
|
||||
items={toRankItems(data.top_operating_systems)}
|
||||
/>
|
||||
<RankCard
|
||||
title='Top User-Agent'
|
||||
description='原始 User-Agent 请求排行。'
|
||||
items={toRankItems(data.top_user_agents)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +1,110 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useCallback, useEffect, useMemo, useState} from "react"
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query"
|
||||
import {Area, AreaChart, CartesianGrid, XAxis, YAxis} from "recharts"
|
||||
import {RefreshCw, ScrollText, Trash2} from "lucide-react"
|
||||
import {toast} from "sonner"
|
||||
import { Suspense, useCallback, useEffect, useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { RefreshCw, ScrollText, Trash2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import {EmptyStateWithBorder} from "@/components/layout/empty"
|
||||
import {ErrorInline} from "@/components/layout/error"
|
||||
import {LoadingStateWithBorder} from "@/components/layout/loading"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent,} from "@/components/ui/chart"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow,} from "@/components/ui/table"
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
|
||||
import {AccessLogService} from "@/lib/services/openflare"
|
||||
import {formatDateTime} from "@/lib/utils"
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { AccessLogService } from '@/lib/services/openflare';
|
||||
|
||||
import {AccessLogFilters} from "./components/access-log-filters"
|
||||
import { AccessLogFilters } from './components/access-log-filters';
|
||||
import {
|
||||
type AccessLogTab,
|
||||
DETAIL_SORT_OPTIONS,
|
||||
FOLD_SORT_OPTIONS,
|
||||
formatCompactNumber,
|
||||
IP_SORT_OPTIONS,
|
||||
type OverviewRangeHours,
|
||||
parseSortValue,
|
||||
type SearchDraft,
|
||||
} from "./components/access-log-utils"
|
||||
import {CleanupDialog} from "./components/cleanup-dialog"
|
||||
|
||||
const trendChartConfig = {
|
||||
requests: { label: "请求数", color: "hsl(var(--primary))" },
|
||||
} satisfies ChartConfig
|
||||
} from './components/access-log-utils';
|
||||
import { CleanupDialog } from './components/cleanup-dialog';
|
||||
import { DetailTab } from './components/detail-tab';
|
||||
import {
|
||||
buildIpSummaryTimeParams,
|
||||
defaultLocalRangeForHours,
|
||||
IpTab,
|
||||
type IpTabTimeMode,
|
||||
} from './components/ip-tab';
|
||||
import { OverviewTab } from './components/overview-tab';
|
||||
|
||||
const emptyDraft: SearchDraft = {
|
||||
nodeId: "",
|
||||
remoteAddr: "",
|
||||
host: "",
|
||||
path: "",
|
||||
nodeId: '',
|
||||
remoteAddr: '',
|
||||
host: '',
|
||||
path: '',
|
||||
};
|
||||
|
||||
function resolveTab(value: string | null): AccessLogTab {
|
||||
if (value === 'list') return 'list';
|
||||
if (value === 'ips') return 'ips';
|
||||
return 'overview';
|
||||
}
|
||||
|
||||
function PaginationBar({
|
||||
page,
|
||||
hasMore,
|
||||
loading,
|
||||
onPrev,
|
||||
onNext,
|
||||
}: {
|
||||
page: number
|
||||
hasMore: boolean
|
||||
loading: boolean
|
||||
onPrev: () => void
|
||||
onNext: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-4 py-3 border-t border-dashed">
|
||||
<p className="text-xs text-muted-foreground">当前第 {page + 1} 页</p>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" disabled={loading || page <= 0} onClick={onPrev}>
|
||||
上一页
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" disabled={loading || !hasMore} onClick={onNext}>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
function AccessLogsPageContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const tab = resolveTab(searchParams.get('tab'));
|
||||
const [draft, setDraft] = useState<SearchDraft>(emptyDraft);
|
||||
const [filters, setFilters] = useState<SearchDraft>(emptyDraft);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [page, setPage] = useState(0);
|
||||
const [detailSort, setDetailSort] = useState('logged_at:desc');
|
||||
const [ipSort, setIpSort] = useState('total_requests:desc');
|
||||
const [ipPageSize, setIpPageSize] = useState(20);
|
||||
const [ipPage, setIpPage] = useState(0);
|
||||
const [ipHours, setIpHours] = useState<OverviewRangeHours>(168);
|
||||
const [ipTimeMode, setIpTimeMode] = useState<IpTabTimeMode>('preset');
|
||||
const [ipCustomSince, setIpCustomSince] = useState('');
|
||||
const [ipCustomUntil, setIpCustomUntil] = useState('');
|
||||
const [overviewHours, setOverviewHours] = useState<OverviewRangeHours>(24);
|
||||
const [overviewHosts, setOverviewHosts] = useState<string[]>([]);
|
||||
const [cleanupOpen, setCleanupOpen] = useState(false);
|
||||
|
||||
export default function AccessLogsPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const [tab, setTab] = useState<AccessLogTab>("list")
|
||||
const [draft, setDraft] = useState<SearchDraft>(emptyDraft)
|
||||
const [filters, setFilters] = useState<SearchDraft>(emptyDraft)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
const [page, setPage] = useState(0)
|
||||
const [detailSort, setDetailSort] = useState("logged_at:desc")
|
||||
const [foldSort, setFoldSort] = useState("bucket_started_at:desc")
|
||||
const [ipSort, setIpSort] = useState("total_requests:desc")
|
||||
const [foldMinutes, setFoldMinutes] = useState<3 | 5>(3)
|
||||
const [trendIp, setTrendIp] = useState("")
|
||||
const [appliedTrendIp, setAppliedTrendIp] = useState("")
|
||||
const [cleanupOpen, setCleanupOpen] = useState(false)
|
||||
const detailSortState = parseSortValue(detailSort);
|
||||
const ipSortState = parseSortValue(ipSort);
|
||||
const ipTimeParams = buildIpSummaryTimeParams({
|
||||
timeMode: ipTimeMode,
|
||||
hours: ipHours,
|
||||
customSince: ipCustomSince,
|
||||
customUntil: ipCustomUntil,
|
||||
});
|
||||
const ipQueryEnabled = tab === 'ips' && ipTimeParams != null;
|
||||
|
||||
const detailSortState = parseSortValue(detailSort)
|
||||
const foldSortState = parseSortValue(foldSort)
|
||||
const ipSortState = parseSortValue(ipSort)
|
||||
const handleTabChange = (value: string) => {
|
||||
const next = resolveTab(value);
|
||||
router.replace(
|
||||
next === 'overview' ? '/access-logs' : `/access-logs?tab=${next}`,
|
||||
);
|
||||
};
|
||||
|
||||
const overviewQuery = useQuery({
|
||||
queryKey: [
|
||||
'openflare',
|
||||
'access-logs',
|
||||
'overview',
|
||||
overviewHours,
|
||||
overviewHosts,
|
||||
],
|
||||
queryFn: () =>
|
||||
AccessLogService.getOverview({
|
||||
hours: overviewHours,
|
||||
hosts: overviewHosts.length > 0 ? overviewHosts : undefined,
|
||||
}),
|
||||
enabled: tab === 'overview',
|
||||
});
|
||||
|
||||
const listQuery = useQuery({
|
||||
queryKey: ["openflare", "access-logs", "list", filters, page, pageSize, detailSort],
|
||||
queryKey: [
|
||||
'openflare',
|
||||
'access-logs',
|
||||
'list',
|
||||
filters,
|
||||
page,
|
||||
pageSize,
|
||||
detailSort,
|
||||
],
|
||||
queryFn: () =>
|
||||
AccessLogService.list({
|
||||
node_id: filters.nodeId || undefined,
|
||||
@@ -101,95 +116,44 @@ export default function AccessLogsPage() {
|
||||
sort_by: detailSortState.sortBy,
|
||||
sort_order: detailSortState.sortOrder,
|
||||
}),
|
||||
enabled: tab === "list",
|
||||
})
|
||||
enabled: tab === 'list',
|
||||
});
|
||||
|
||||
const foldsQuery = useQuery({
|
||||
queryKey: ["openflare", "access-logs", "folds", filters, page, pageSize, foldSort, foldMinutes],
|
||||
queryFn: () =>
|
||||
AccessLogService.listFolds({
|
||||
node_id: filters.nodeId || undefined,
|
||||
remote_addr: filters.remoteAddr || undefined,
|
||||
host: filters.host || undefined,
|
||||
path: filters.path || undefined,
|
||||
p: page,
|
||||
page_size: pageSize,
|
||||
sort_by: foldSortState.sortBy,
|
||||
sort_order: foldSortState.sortOrder,
|
||||
fold_minutes: foldMinutes,
|
||||
}),
|
||||
enabled: tab === "folds",
|
||||
})
|
||||
|
||||
const ipSummaryQuery = useQuery({
|
||||
queryKey: ["openflare", "access-logs", "ip-summary", filters, page, pageSize, ipSort],
|
||||
const ipQuery = useQuery({
|
||||
queryKey: [
|
||||
'openflare',
|
||||
'access-logs',
|
||||
'ip-summary',
|
||||
ipTimeParams,
|
||||
ipPage,
|
||||
ipPageSize,
|
||||
ipSort,
|
||||
],
|
||||
queryFn: () =>
|
||||
AccessLogService.listIPSummaries({
|
||||
node_id: filters.nodeId || undefined,
|
||||
remote_addr: filters.remoteAddr || undefined,
|
||||
host: filters.host || undefined,
|
||||
p: page,
|
||||
page_size: pageSize,
|
||||
...(ipTimeParams as NonNullable<typeof ipTimeParams>),
|
||||
p: ipPage,
|
||||
page_size: ipPageSize,
|
||||
sort_by: ipSortState.sortBy,
|
||||
sort_order: ipSortState.sortOrder,
|
||||
}),
|
||||
enabled: tab === "ip-summary",
|
||||
})
|
||||
|
||||
const ipTrendQuery = useQuery({
|
||||
queryKey: ["openflare", "access-logs", "ip-trend", filters, appliedTrendIp],
|
||||
queryFn: () =>
|
||||
AccessLogService.getIPTrend({
|
||||
node_id: filters.nodeId || undefined,
|
||||
remote_addr: appliedTrendIp,
|
||||
host: filters.host || undefined,
|
||||
hours: 24,
|
||||
bucket_minutes: 30,
|
||||
}),
|
||||
enabled: tab === "ip-trend" && appliedTrendIp !== "",
|
||||
})
|
||||
enabled: ipQueryEnabled,
|
||||
});
|
||||
|
||||
const cleanupMutation = useMutation({
|
||||
mutationFn: (retentionDays: number) =>
|
||||
AccessLogService.cleanup({ retention_days: retentionDays }),
|
||||
onSuccess: async (result) => {
|
||||
toast.success(`已清理 ${result.deleted_count} 条日志`)
|
||||
setCleanupOpen(false)
|
||||
await queryClient.invalidateQueries({ queryKey: ["openflare", "access-logs"] })
|
||||
toast.success(`已清理 ${result.deleted_count} 条日志`);
|
||||
setCleanupOpen(false);
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: ['openflare', 'access-logs'],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error instanceof Error ? error.message : "清理失败")
|
||||
toast.error(error instanceof Error ? error.message : '清理失败');
|
||||
},
|
||||
})
|
||||
|
||||
const activeSummary = useMemo(() => {
|
||||
if (tab === "list" && listQuery.data) {
|
||||
return {
|
||||
totalRecord: listQuery.data.total_record,
|
||||
totalIp: listQuery.data.total_ip,
|
||||
}
|
||||
}
|
||||
if (tab === "folds" && foldsQuery.data) {
|
||||
return {
|
||||
totalRecord: foldsQuery.data.total_record,
|
||||
totalIp: foldsQuery.data.total_ip,
|
||||
}
|
||||
}
|
||||
if (tab === "ip-summary" && ipSummaryQuery.data) {
|
||||
return {
|
||||
totalRecord: 0,
|
||||
totalIp: ipSummaryQuery.data.total_ip,
|
||||
}
|
||||
}
|
||||
return { totalRecord: 0, totalIp: 0 }
|
||||
}, [tab, listQuery.data, foldsQuery.data, ipSummaryQuery.data])
|
||||
|
||||
const trendChartData = useMemo(() => {
|
||||
return (ipTrendQuery.data?.points ?? []).map((point) => ({
|
||||
label: formatDateTime(point.bucket_started_at).slice(5),
|
||||
requests: point.request_count,
|
||||
}))
|
||||
}, [ipTrendQuery.data?.points])
|
||||
});
|
||||
|
||||
const handleSearch = useCallback(() => {
|
||||
setFilters({
|
||||
@@ -197,383 +161,163 @@ export default function AccessLogsPage() {
|
||||
remoteAddr: draft.remoteAddr.trim(),
|
||||
host: draft.host.trim(),
|
||||
path: draft.path.trim(),
|
||||
})
|
||||
setPage(0)
|
||||
}, [draft])
|
||||
});
|
||||
setPage(0);
|
||||
}, [draft]);
|
||||
|
||||
const handleReset = () => {
|
||||
setDraft(emptyDraft)
|
||||
setFilters(emptyDraft)
|
||||
setPage(0)
|
||||
setTrendIp("")
|
||||
setAppliedTrendIp("")
|
||||
}
|
||||
setDraft(emptyDraft);
|
||||
setFilters(emptyDraft);
|
||||
setPage(0);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setPage(0)
|
||||
}, [tab, pageSize])
|
||||
setPage(0);
|
||||
}, [tab, pageSize]);
|
||||
|
||||
useEffect(() => {
|
||||
setIpPage(0);
|
||||
}, [
|
||||
tab,
|
||||
ipPageSize,
|
||||
ipHours,
|
||||
ipTimeMode,
|
||||
ipCustomSince,
|
||||
ipCustomUntil,
|
||||
ipSort,
|
||||
]);
|
||||
|
||||
const refreshActive = () => {
|
||||
if (tab === "list") void listQuery.refetch()
|
||||
if (tab === "folds") void foldsQuery.refetch()
|
||||
if (tab === "ip-summary") void ipSummaryQuery.refetch()
|
||||
if (tab === "ip-trend") void ipTrendQuery.refetch()
|
||||
}
|
||||
if (tab === 'overview') void overviewQuery.refetch();
|
||||
if (tab === 'list') void listQuery.refetch();
|
||||
if (tab === 'ips') void ipQuery.refetch();
|
||||
};
|
||||
|
||||
const isFetching =
|
||||
listQuery.isFetching ||
|
||||
foldsQuery.isFetching ||
|
||||
ipSummaryQuery.isFetching ||
|
||||
ipTrendQuery.isFetching
|
||||
overviewQuery.isFetching || listQuery.isFetching || ipQuery.isFetching;
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ScrollText className="size-5 text-primary" />
|
||||
<div className='py-6 px-1 space-y-6'>
|
||||
<div className='flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<ScrollText className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">访问日志</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
按节点、IP、域名与路径检索,支持时间折叠、IP 汇总与趋势分析。
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>访问日志</h1>
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
查看访问概览、IP 明细与请求日志。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={refreshActive} disabled={isFetching}>
|
||||
<RefreshCw className={`size-3.5 mr-1 ${isFetching ? "animate-spin" : ""}`} />
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={refreshActive}
|
||||
disabled={isFetching}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`size-3.5 mr-1 ${isFetching ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
刷新
|
||||
</Button>
|
||||
<Button variant="destructive" size="sm" onClick={() => setCleanupOpen(true)}>
|
||||
<Trash2 className="size-3.5 mr-1" />
|
||||
<Button
|
||||
variant='destructive'
|
||||
size='sm'
|
||||
onClick={() => setCleanupOpen(true)}
|
||||
>
|
||||
<Trash2 className='size-3.5 mr-1' />
|
||||
清理日志
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
{[
|
||||
{ label: "访问记录", value: formatCompactNumber(activeSummary.totalRecord) },
|
||||
{ label: "来源 IP", value: formatCompactNumber(activeSummary.totalIp) },
|
||||
{
|
||||
label: "当前视图",
|
||||
value:
|
||||
tab === "list"
|
||||
? "明细日志"
|
||||
: tab === "folds"
|
||||
? "时间折叠"
|
||||
: tab === "ip-summary"
|
||||
? "IP 汇总"
|
||||
: "IP 趋势",
|
||||
},
|
||||
].map((item) => (
|
||||
<div key={item.label} className="rounded-lg border border-dashed px-4 py-3">
|
||||
<p className="text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
{item.label}
|
||||
</p>
|
||||
<p className="mt-1 text-lg font-semibold">{item.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Tabs value={tab} onValueChange={(value) => setTab(value as AccessLogTab)}>
|
||||
<TabsList className="grid w-full grid-cols-2 lg:grid-cols-4">
|
||||
<TabsTrigger value="list">明细列表</TabsTrigger>
|
||||
<TabsTrigger value="folds">时间折叠</TabsTrigger>
|
||||
<TabsTrigger value="ip-summary">IP 汇总</TabsTrigger>
|
||||
<TabsTrigger value="ip-trend">IP 趋势</TabsTrigger>
|
||||
<Tabs value={tab} onValueChange={handleTabChange}>
|
||||
<TabsList className='grid w-full max-w-lg grid-cols-3'>
|
||||
<TabsTrigger value='overview'>概览</TabsTrigger>
|
||||
<TabsTrigger value='ips'>IP 明细</TabsTrigger>
|
||||
<TabsTrigger value='list'>日志明细</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<div className="mt-4 rounded-lg border border-dashed bg-background p-4">
|
||||
<AccessLogFilters
|
||||
tab={tab}
|
||||
draft={draft}
|
||||
pageSize={pageSize}
|
||||
onDraftChange={setDraft}
|
||||
onPageSizeChange={setPageSize}
|
||||
onSearch={handleSearch}
|
||||
onReset={handleReset}
|
||||
<TabsContent value='overview' className='mt-4'>
|
||||
<OverviewTab
|
||||
data={overviewQuery.data}
|
||||
loading={overviewQuery.isLoading}
|
||||
error={
|
||||
overviewQuery.error instanceof Error ? overviewQuery.error : null
|
||||
}
|
||||
hours={overviewHours}
|
||||
hosts={overviewHosts}
|
||||
onHoursChange={setOverviewHours}
|
||||
onHostsChange={setOverviewHosts}
|
||||
onRetry={() => void overviewQuery.refetch()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<TabsContent value="list" className="mt-4">
|
||||
<div className="rounded-lg border border-dashed overflow-hidden bg-background">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-dashed">
|
||||
<p className="text-sm font-medium">明细日志</p>
|
||||
<Select value={detailSort} onValueChange={setDetailSort}>
|
||||
<SelectTrigger className="h-8 w-44 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DETAIL_SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{listQuery.isError ? (
|
||||
<div className="p-4">
|
||||
<ErrorInline
|
||||
message={listQuery.error instanceof Error ? listQuery.error.message : "加载失败"}
|
||||
onRetry={() => void listQuery.refetch()}
|
||||
/>
|
||||
</div>
|
||||
) : listQuery.isLoading ? (
|
||||
<LoadingStateWithBorder />
|
||||
) : (listQuery.data?.items ?? []).length === 0 ? (
|
||||
<EmptyStateWithBorder title="暂无访问日志" />
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow className="border-dashed hover:bg-transparent">
|
||||
<TableHead className="text-xs">时间</TableHead>
|
||||
<TableHead className="text-xs">节点</TableHead>
|
||||
<TableHead className="text-xs">IP</TableHead>
|
||||
<TableHead className="text-xs">域名</TableHead>
|
||||
<TableHead className="text-xs">路径</TableHead>
|
||||
<TableHead className="text-xs">状态码</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(listQuery.data?.items ?? []).map((item) => (
|
||||
<TableRow key={item.id} className="border-dashed">
|
||||
<TableCell className="text-xs">{formatDateTime(item.logged_at)}</TableCell>
|
||||
<TableCell className="text-xs">{item.node_name || item.node_id}</TableCell>
|
||||
<TableCell className="text-xs font-mono">{item.remote_addr}</TableCell>
|
||||
<TableCell className="text-xs">{item.host}</TableCell>
|
||||
<TableCell className="text-xs max-w-48 truncate">{item.path}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="text-[10px]">
|
||||
{item.status_code}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
<PaginationBar
|
||||
page={page}
|
||||
hasMore={listQuery.data?.has_more ?? false}
|
||||
loading={listQuery.isFetching}
|
||||
onPrev={() => setPage((p) => Math.max(0, p - 1))}
|
||||
onNext={() => setPage((p) => p + 1)}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="folds" className="mt-4">
|
||||
<div className="rounded-lg border border-dashed overflow-hidden bg-background">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 px-4 py-3 border-b border-dashed">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">时间折叠</p>
|
||||
<Select
|
||||
value={String(foldMinutes)}
|
||||
onValueChange={(value) => setFoldMinutes(Number(value) as 3 | 5)}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-36 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="3">3 分钟桶</SelectItem>
|
||||
<SelectItem value="5">5 分钟桶</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Select value={foldSort} onValueChange={setFoldSort}>
|
||||
<SelectTrigger className="h-8 w-44 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{FOLD_SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{foldsQuery.isError ? (
|
||||
<div className="p-4">
|
||||
<ErrorInline
|
||||
message={
|
||||
foldsQuery.error instanceof Error
|
||||
? foldsQuery.error.message
|
||||
: "加载失败"
|
||||
}
|
||||
onRetry={() => void foldsQuery.refetch()}
|
||||
/>
|
||||
</div>
|
||||
) : foldsQuery.isLoading ? (
|
||||
<LoadingStateWithBorder />
|
||||
) : (foldsQuery.data?.items ?? []).length === 0 ? (
|
||||
<EmptyStateWithBorder title="暂无折叠数据" />
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow className="border-dashed hover:bg-transparent">
|
||||
<TableHead className="text-xs">时间桶</TableHead>
|
||||
<TableHead className="text-xs">请求数</TableHead>
|
||||
<TableHead className="text-xs">独立 IP</TableHead>
|
||||
<TableHead className="text-xs">独立域名</TableHead>
|
||||
<TableHead className="text-xs">2xx</TableHead>
|
||||
<TableHead className="text-xs">4xx</TableHead>
|
||||
<TableHead className="text-xs">5xx</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(foldsQuery.data?.items ?? []).map((item) => (
|
||||
<TableRow key={item.bucket_started_at} className="border-dashed">
|
||||
<TableCell className="text-xs">
|
||||
{formatDateTime(item.bucket_started_at)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs">{item.request_count}</TableCell>
|
||||
<TableCell className="text-xs">{item.unique_ip_count}</TableCell>
|
||||
<TableCell className="text-xs">{item.unique_host_count}</TableCell>
|
||||
<TableCell className="text-xs">{item.success_count}</TableCell>
|
||||
<TableCell className="text-xs">{item.client_error_count}</TableCell>
|
||||
<TableCell className="text-xs">{item.server_error_count}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
<PaginationBar
|
||||
page={page}
|
||||
hasMore={foldsQuery.data?.has_more ?? false}
|
||||
loading={foldsQuery.isFetching}
|
||||
onPrev={() => setPage((p) => Math.max(0, p - 1))}
|
||||
onNext={() => setPage((p) => p + 1)}
|
||||
/>
|
||||
</div>
|
||||
<TabsContent value='ips' className='mt-4'>
|
||||
<IpTab
|
||||
data={ipQuery.data}
|
||||
loading={ipQueryEnabled && ipQuery.isLoading}
|
||||
error={ipQuery.error instanceof Error ? ipQuery.error : null}
|
||||
page={ipPage}
|
||||
pageSize={ipPageSize}
|
||||
sort={ipSort}
|
||||
hours={ipHours}
|
||||
timeMode={ipTimeMode}
|
||||
customSince={ipCustomSince}
|
||||
customUntil={ipCustomUntil}
|
||||
onHoursChange={(next) => {
|
||||
setIpTimeMode('preset');
|
||||
setIpHours(next);
|
||||
}}
|
||||
onTimeModeChange={(mode) => {
|
||||
setIpTimeMode(mode);
|
||||
if (
|
||||
mode === 'custom' &&
|
||||
(!ipCustomSince.trim() || !ipCustomUntil.trim())
|
||||
) {
|
||||
const range = defaultLocalRangeForHours(ipHours);
|
||||
setIpCustomSince(range.since);
|
||||
setIpCustomUntil(range.until);
|
||||
}
|
||||
}}
|
||||
onApplyCustomRange={(since, until) => {
|
||||
setIpCustomSince(since);
|
||||
setIpCustomUntil(until);
|
||||
setIpTimeMode('custom');
|
||||
setIpPage(0);
|
||||
}}
|
||||
onPageSizeChange={setIpPageSize}
|
||||
onSortChange={setIpSort}
|
||||
onRetry={() => void ipQuery.refetch()}
|
||||
onPrevPage={() => setIpPage((p) => Math.max(0, p - 1))}
|
||||
onNextPage={() => setIpPage((p) => p + 1)}
|
||||
isFetching={ipQuery.isFetching}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="ip-summary" className="mt-4">
|
||||
<div className="rounded-lg border border-dashed overflow-hidden bg-background">
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-dashed">
|
||||
<p className="text-sm font-medium">IP 汇总</p>
|
||||
<Select value={ipSort} onValueChange={setIpSort}>
|
||||
<SelectTrigger className="h-8 w-52 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{IP_SORT_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
{ipSummaryQuery.isError ? (
|
||||
<div className="p-4">
|
||||
<ErrorInline
|
||||
message={
|
||||
ipSummaryQuery.error instanceof Error
|
||||
? ipSummaryQuery.error.message
|
||||
: "加载失败"
|
||||
}
|
||||
onRetry={() => void ipSummaryQuery.refetch()}
|
||||
/>
|
||||
</div>
|
||||
) : ipSummaryQuery.isLoading ? (
|
||||
<LoadingStateWithBorder />
|
||||
) : (ipSummaryQuery.data?.items ?? []).length === 0 ? (
|
||||
<EmptyStateWithBorder title="暂无 IP 汇总数据" />
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow className="border-dashed hover:bg-transparent">
|
||||
<TableHead className="text-xs">IP</TableHead>
|
||||
<TableHead className="text-xs">总请求数</TableHead>
|
||||
<TableHead className="text-xs">近 3 小时</TableHead>
|
||||
<TableHead className="text-xs">最后访问</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(ipSummaryQuery.data?.items ?? []).map((item) => (
|
||||
<TableRow key={item.remote_addr} className="border-dashed">
|
||||
<TableCell className="text-xs font-mono">{item.remote_addr}</TableCell>
|
||||
<TableCell className="text-xs">{item.total_requests}</TableCell>
|
||||
<TableCell className="text-xs">{item.recent_requests}</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
{formatDateTime(item.last_seen_at)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
<PaginationBar
|
||||
page={page}
|
||||
hasMore={ipSummaryQuery.data?.has_more ?? false}
|
||||
loading={ipSummaryQuery.isFetching}
|
||||
onPrev={() => setPage((p) => Math.max(0, p - 1))}
|
||||
onNext={() => setPage((p) => p + 1)}
|
||||
<TabsContent value='list' className='mt-4 space-y-4'>
|
||||
<div className='rounded-lg border border-dashed bg-background p-4'>
|
||||
<AccessLogFilters
|
||||
draft={draft}
|
||||
pageSize={pageSize}
|
||||
onDraftChange={setDraft}
|
||||
onPageSizeChange={setPageSize}
|
||||
onSearch={handleSearch}
|
||||
onReset={handleReset}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="ip-trend" className="mt-4 space-y-4">
|
||||
<div className="rounded-lg border border-dashed bg-background p-4 flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div className="space-y-1.5 flex-1">
|
||||
<p className="text-xs font-medium text-muted-foreground">趋势 IP</p>
|
||||
<input
|
||||
className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 text-xs"
|
||||
value={trendIp}
|
||||
onChange={(e) => setTrendIp(e.target.value)}
|
||||
placeholder="输入要分析趋势的 IP 地址"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setAppliedTrendIp(trendIp.trim())}
|
||||
disabled={!trendIp.trim()}
|
||||
>
|
||||
查看趋势
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-dashed overflow-hidden bg-background p-4">
|
||||
{!appliedTrendIp ? (
|
||||
<EmptyStateWithBorder description="请输入 IP 地址后查看 24 小时访问趋势。" />
|
||||
) : ipTrendQuery.isLoading ? (
|
||||
<LoadingStateWithBorder />
|
||||
) : ipTrendQuery.isError ? (
|
||||
<ErrorInline
|
||||
message={
|
||||
ipTrendQuery.error instanceof Error
|
||||
? ipTrendQuery.error.message
|
||||
: "加载失败"
|
||||
}
|
||||
onRetry={() => void ipTrendQuery.refetch()}
|
||||
/>
|
||||
) : trendChartData.length === 0 ? (
|
||||
<EmptyStateWithBorder description="该 IP 在选定时间范围内没有访问记录。" />
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium">
|
||||
{appliedTrendIp} · 近 {ipTrendQuery.data?.hours ?? 24} 小时
|
||||
</p>
|
||||
<ChartContainer config={trendChartConfig} className="h-64 w-full">
|
||||
<AreaChart data={trendChartData}>
|
||||
<CartesianGrid vertical={false} />
|
||||
<XAxis dataKey="label" tickLine={false} axisLine={false} fontSize={10} />
|
||||
<YAxis tickLine={false} axisLine={false} fontSize={10} width={40} />
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="requests"
|
||||
stroke="var(--color-requests)"
|
||||
fill="var(--color-requests)"
|
||||
fillOpacity={0.2}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DetailTab
|
||||
data={listQuery.data}
|
||||
loading={listQuery.isLoading}
|
||||
error={listQuery.error instanceof Error ? listQuery.error : null}
|
||||
page={page}
|
||||
detailSort={detailSort}
|
||||
onDetailSortChange={setDetailSort}
|
||||
onRetry={() => void listQuery.refetch()}
|
||||
onPrevPage={() => setPage((p) => Math.max(0, p - 1))}
|
||||
onNextPage={() => setPage((p) => p + 1)}
|
||||
isFetching={listQuery.isFetching}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
@@ -584,5 +328,20 @@ export default function AccessLogsPage() {
|
||||
loading={cleanupMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export default function AccessLogsPage() {
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<LoadingStateWithBorder
|
||||
title='加载访问日志'
|
||||
description='正在准备页面...'
|
||||
/>
|
||||
}
|
||||
>
|
||||
<AccessLogsPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useCallback, useEffect, useState} from "react"
|
||||
import {toast} from "sonner"
|
||||
import {HardDrive, RefreshCw, Trash2} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { HardDrive, RefreshCw, Trash2 } from 'lucide-react';
|
||||
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Skeleton} from "@/components/ui/skeleton"
|
||||
import {Label} from "@/components/ui/label"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Switch} from "@/components/ui/switch"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -18,183 +24,205 @@ import {
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import type {CacheStatus} from "@/lib/services/admin"
|
||||
import services from "@/lib/services"
|
||||
} from '@/components/ui/dialog';
|
||||
import type { CacheStatus } from '@/lib/services/admin';
|
||||
import services from '@/lib/services';
|
||||
|
||||
/**
|
||||
* 格式化字节大小
|
||||
*/
|
||||
const formatBytes = (bytes: number) => {
|
||||
if (bytes === 0) return "0 Bytes"
|
||||
const k = 1024
|
||||
const sizes = ["Bytes", "KB", "MB", "GB", "TB"]
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
|
||||
}
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
/**
|
||||
* 格式化数字,每3位加逗号
|
||||
*/
|
||||
const formatNumber = (num: number | string) => {
|
||||
if (num === undefined || num === null) return "0"
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ",")
|
||||
}
|
||||
if (num === undefined || num === null) return '0';
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ',');
|
||||
};
|
||||
|
||||
interface CacheManagerProps {
|
||||
refreshTrigger: number
|
||||
refreshTrigger: number;
|
||||
}
|
||||
|
||||
export function CacheManager({ refreshTrigger }: CacheManagerProps) {
|
||||
const [cacheStatus, setCacheStatus] = useState<CacheStatus | null>(null)
|
||||
const [loadingCache, setLoadingCache] = useState<boolean>(true)
|
||||
const [savingConfig, setSavingConfig] = useState<boolean>(false)
|
||||
const [clearingCache, setClearingCache] = useState<boolean>(false)
|
||||
const [showClearConfirm, setShowClearConfirm] = useState<boolean>(false)
|
||||
const [cacheStatus, setCacheStatus] = useState<CacheStatus | null>(null);
|
||||
const [loadingCache, setLoadingCache] = useState<boolean>(true);
|
||||
const [savingConfig, setSavingConfig] = useState<boolean>(false);
|
||||
const [clearingCache, setClearingCache] = useState<boolean>(false);
|
||||
const [showClearConfirm, setShowClearConfirm] = useState<boolean>(false);
|
||||
|
||||
// 策略配置表单状态
|
||||
const [maxSizeMB, setMaxSizeMB] = useState<string>("100")
|
||||
const [ttlMinutes, setTtlMinutes] = useState<string>("60")
|
||||
const [lruEnabled, setLruEnabled] = useState<boolean>(true)
|
||||
const [maxSizeMB, setMaxSizeMB] = useState<string>('100');
|
||||
const [ttlMinutes, setTtlMinutes] = useState<string>('60');
|
||||
const [lruEnabled, setLruEnabled] = useState<boolean>(true);
|
||||
|
||||
// 获取磁盘缓存状态
|
||||
const fetchCacheStatus = useCallback(async (isSilent = false) => {
|
||||
if (!isSilent) setLoadingCache(true)
|
||||
if (!isSilent) setLoadingCache(true);
|
||||
try {
|
||||
const data = await services.adminCache.getCacheStatus()
|
||||
setCacheStatus(data)
|
||||
setMaxSizeMB(data.max_size_mb.toString())
|
||||
setTtlMinutes(data.ttl_minutes.toString())
|
||||
setLruEnabled(data.lru_enabled)
|
||||
const data = await services.adminCache.getCacheStatus();
|
||||
setCacheStatus(data);
|
||||
setMaxSizeMB(data.max_size_mb.toString());
|
||||
setTtlMinutes(data.ttl_minutes.toString());
|
||||
setLruEnabled(data.lru_enabled);
|
||||
} catch (err) {
|
||||
toast.error("获取磁盘缓存状态失败", {
|
||||
description: err instanceof Error ? err.message : "未知错误",
|
||||
})
|
||||
toast.error('获取磁盘缓存状态失败', {
|
||||
description: err instanceof Error ? err.message : '未知错误',
|
||||
});
|
||||
} finally {
|
||||
setLoadingCache(false)
|
||||
setLoadingCache(false);
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
// 保存配置
|
||||
const handleSaveConfig = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
const size = parseInt(maxSizeMB, 10)
|
||||
const ttl = parseInt(ttlMinutes, 10)
|
||||
e.preventDefault();
|
||||
const size = parseInt(maxSizeMB, 10);
|
||||
const ttl = parseInt(ttlMinutes, 10);
|
||||
if (isNaN(size) || size < 1) {
|
||||
toast.error("保存失败", { description: "最大容量限制必须是大于等于 1 的整数" })
|
||||
return
|
||||
toast.error('保存失败', {
|
||||
description: '最大容量限制必须是大于等于 1 的整数',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (isNaN(ttl) || ttl < 0) {
|
||||
toast.error("保存失败", { description: "默认过期时间必须是大于等于 0 的整数" })
|
||||
return
|
||||
toast.error('保存失败', {
|
||||
description: '默认过期时间必须是大于等于 0 的整数',
|
||||
});
|
||||
return;
|
||||
}
|
||||
setSavingConfig(true)
|
||||
setSavingConfig(true);
|
||||
try {
|
||||
await services.adminCache.updateCacheConfig({
|
||||
max_size_mb: size,
|
||||
ttl_minutes: ttl,
|
||||
lru_enabled: lruEnabled,
|
||||
})
|
||||
toast.success("保存成功", { description: "磁盘缓存策略已热更新" })
|
||||
await fetchCacheStatus(true)
|
||||
});
|
||||
toast.success('保存成功', { description: '磁盘缓存策略已热更新' });
|
||||
await fetchCacheStatus(true);
|
||||
} catch (err) {
|
||||
toast.error("保存配置失败", {
|
||||
description: err instanceof Error ? err.message : "未知错误",
|
||||
})
|
||||
toast.error('保存配置失败', {
|
||||
description: err instanceof Error ? err.message : '未知错误',
|
||||
});
|
||||
} finally {
|
||||
setSavingConfig(false)
|
||||
setSavingConfig(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 清空磁盘缓存数据
|
||||
const handleClearCache = async () => {
|
||||
setClearingCache(true)
|
||||
setClearingCache(true);
|
||||
try {
|
||||
await services.adminCache.clearCache()
|
||||
toast.success("清空成功", { description: "缓存数据已全部清除" })
|
||||
setShowClearConfirm(false)
|
||||
await fetchCacheStatus(true)
|
||||
await services.adminCache.clearCache();
|
||||
toast.success('清空成功', { description: '缓存数据已全部清除' });
|
||||
setShowClearConfirm(false);
|
||||
await fetchCacheStatus(true);
|
||||
} catch (err) {
|
||||
toast.error("清空缓存失败", {
|
||||
description: err instanceof Error ? err.message : "未知错误",
|
||||
})
|
||||
toast.error('清空缓存失败', {
|
||||
description: err instanceof Error ? err.message : '未知错误',
|
||||
});
|
||||
} finally {
|
||||
setClearingCache(false)
|
||||
setClearingCache(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 初始化拉取
|
||||
useEffect(() => {
|
||||
fetchCacheStatus()
|
||||
}, [fetchCacheStatus])
|
||||
fetchCacheStatus();
|
||||
}, [fetchCacheStatus]);
|
||||
|
||||
// 当外部刷新触发器改变时自动刷新
|
||||
useEffect(() => {
|
||||
fetchCacheStatus(true)
|
||||
}, [refreshTrigger, fetchCacheStatus])
|
||||
fetchCacheStatus(true);
|
||||
}, [refreshTrigger, fetchCacheStatus]);
|
||||
|
||||
return (
|
||||
<Card className="border-border/40 bg-card/50 backdrop-blur-sm shadow-sm">
|
||||
<CardHeader className="pb-3 border-b border-dashed flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<HardDrive className="size-4 text-primary animate-pulse" />
|
||||
<CardTitle className="text-sm font-semibold">缓存管理</CardTitle>
|
||||
<Card className='border-border/40 bg-card/50 backdrop-blur-sm shadow-sm'>
|
||||
<CardHeader className='pb-3 border-b border-dashed flex flex-col md:flex-row md:items-center md:justify-between gap-4'>
|
||||
<div className='space-y-0.5'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<HardDrive className='size-4 text-primary animate-pulse' />
|
||||
<CardTitle className='text-sm font-semibold'>缓存管理</CardTitle>
|
||||
</div>
|
||||
<CardDescription className="text-[11px]">管理和监控系统级磁盘缓存的资源占用、生命周期及淘汰策略</CardDescription>
|
||||
<CardDescription className='text-[11px]'>
|
||||
管理和监控系统级磁盘缓存的资源占用、生命周期及淘汰策略
|
||||
</CardDescription>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 gap-1.5 text-xs self-start md:self-auto"
|
||||
size='sm'
|
||||
variant='secondary'
|
||||
className='h-8 gap-1.5 text-xs self-start md:self-auto'
|
||||
onClick={() => fetchCacheStatus(true)}
|
||||
disabled={loadingCache}
|
||||
>
|
||||
<RefreshCw className={`size-3 ${loadingCache ? "animate-spin" : ""}`} />
|
||||
<RefreshCw
|
||||
className={`size-3 ${loadingCache ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
刷新状态
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-4">
|
||||
<CardContent className='pt-4'>
|
||||
{loadingCache && !cacheStatus ? (
|
||||
<div className="space-y-3 py-6">
|
||||
<Skeleton className="h-6 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className='space-y-3 py-6'>
|
||||
<Skeleton className='h-6 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
</div>
|
||||
) : cacheStatus ? (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
|
||||
<div className='grid grid-cols-1 lg:grid-cols-5 gap-6'>
|
||||
{/* 左边:状态区 (2/5 cols) */}
|
||||
<div className="lg:col-span-2 space-y-4">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">运行状态</h4>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className='lg:col-span-2 space-y-4'>
|
||||
<h4 className='text-xs font-semibold text-muted-foreground uppercase tracking-wider'>
|
||||
运行状态
|
||||
</h4>
|
||||
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
|
||||
{/* 已占空间 */}
|
||||
<div className="p-4 rounded-xl border border-border/40 bg-background/30 backdrop-blur-xs hover:border-primary/20 transition-all duration-300">
|
||||
<p className="text-[10px] text-muted-foreground font-medium mb-1">已用空间</p>
|
||||
<p className="text-xl font-bold tracking-tight text-foreground">
|
||||
<div className='p-4 rounded-xl border border-border/40 bg-background/30 backdrop-blur-xs hover:border-primary/20 transition-all duration-300'>
|
||||
<p className='text-[10px] text-muted-foreground font-medium mb-1'>
|
||||
已用空间
|
||||
</p>
|
||||
<p className='text-xl font-bold tracking-tight text-foreground'>
|
||||
{formatBytes(cacheStatus.total_size)}
|
||||
</p>
|
||||
</div>
|
||||
{/* Key数量 */}
|
||||
<div className="p-4 rounded-xl border border-border/40 bg-background/30 backdrop-blur-xs hover:border-primary/20 transition-all duration-300">
|
||||
<p className="text-[10px] text-muted-foreground font-medium mb-1">缓存键数量</p>
|
||||
<p className="text-xl font-bold tracking-tight text-foreground">
|
||||
{formatNumber(cacheStatus.keys_count)} <span className="text-xs text-muted-foreground font-normal">个文件</span>
|
||||
<div className='p-4 rounded-xl border border-border/40 bg-background/30 backdrop-blur-xs hover:border-primary/20 transition-all duration-300'>
|
||||
<p className='text-[10px] text-muted-foreground font-medium mb-1'>
|
||||
缓存键数量
|
||||
</p>
|
||||
<p className='text-xl font-bold tracking-tight text-foreground'>
|
||||
{formatNumber(cacheStatus.keys_count)}{' '}
|
||||
<span className='text-xs text-muted-foreground font-normal'>
|
||||
个文件
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 存储路径 */}
|
||||
<div className="p-4 rounded-xl border border-border/40 bg-background/30 backdrop-blur-xs hover:border-primary/20 transition-all duration-300">
|
||||
<p className="text-[10px] text-muted-foreground font-medium mb-1.5">缓存基准目录</p>
|
||||
<code className="text-xs font-mono bg-muted/60 px-2 py-1 rounded-md block truncate" title={cacheStatus.base_path}>
|
||||
<div className='p-4 rounded-xl border border-border/40 bg-background/30 backdrop-blur-xs hover:border-primary/20 transition-all duration-300'>
|
||||
<p className='text-[10px] text-muted-foreground font-medium mb-1.5'>
|
||||
缓存基准目录
|
||||
</p>
|
||||
<code
|
||||
className='text-xs font-mono bg-muted/60 px-2 py-1 rounded-md block truncate'
|
||||
title={cacheStatus.base_path}
|
||||
>
|
||||
{cacheStatus.base_path}
|
||||
</code>
|
||||
</div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="h-8 text-xs font-medium w-full"
|
||||
variant='secondary'
|
||||
size='sm'
|
||||
className='h-8 text-xs font-medium w-full'
|
||||
onClick={() => setShowClearConfirm(true)}
|
||||
>
|
||||
立即清空缓存
|
||||
@@ -202,111 +230,125 @@ export function CacheManager({ refreshTrigger }: CacheManagerProps) {
|
||||
</div>
|
||||
|
||||
{/* 右边:配置区 (3/5 cols) */}
|
||||
<div className="lg:col-span-3 border-t lg:border-t-0 lg:border-l border-border/40 pt-6 lg:pt-0 lg:pl-6 space-y-4">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">策略配置</h4>
|
||||
<form onSubmit={handleSaveConfig} className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="maxSizeMB" className="text-xs font-medium">最大容量限制 (MB)</Label>
|
||||
<div className='lg:col-span-3 border-t lg:border-t-0 lg:border-l border-border/40 pt-6 lg:pt-0 lg:pl-6 space-y-4'>
|
||||
<h4 className='text-xs font-semibold text-muted-foreground uppercase tracking-wider'>
|
||||
策略配置
|
||||
</h4>
|
||||
<form onSubmit={handleSaveConfig} className='space-y-4'>
|
||||
<div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
|
||||
<div className='space-y-1.5'>
|
||||
<Label htmlFor='maxSizeMB' className='text-xs font-medium'>
|
||||
最大容量限制 (MB)
|
||||
</Label>
|
||||
<Input
|
||||
id="maxSizeMB"
|
||||
type="number"
|
||||
min="1"
|
||||
id='maxSizeMB'
|
||||
type='number'
|
||||
min='1'
|
||||
value={maxSizeMB}
|
||||
onChange={(e) => setMaxSizeMB(e.target.value)}
|
||||
className="h-8 text-xs bg-background/50 border-border/40"
|
||||
placeholder="例如 100"
|
||||
className='h-8 text-xs bg-background/50 border-border/40'
|
||||
placeholder='例如 100'
|
||||
required
|
||||
/>
|
||||
<p className="text-[9px] text-muted-foreground">当总大小超出该值时,自动触发淘汰算法</p>
|
||||
<p className='text-[9px] text-muted-foreground'>
|
||||
当总大小超出该值时,自动触发淘汰算法
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ttlMinutes" className="text-xs font-medium">生存时间限制 (分钟)</Label>
|
||||
<div className='space-y-1.5'>
|
||||
<Label htmlFor='ttlMinutes' className='text-xs font-medium'>
|
||||
生存时间限制 (分钟)
|
||||
</Label>
|
||||
<Input
|
||||
id="ttlMinutes"
|
||||
type="number"
|
||||
min="0"
|
||||
id='ttlMinutes'
|
||||
type='number'
|
||||
min='0'
|
||||
value={ttlMinutes}
|
||||
onChange={(e) => setTtlMinutes(e.target.value)}
|
||||
className="h-8 text-xs bg-background/50 border-border/40"
|
||||
placeholder="例如 60,0 表示永不过期"
|
||||
className='h-8 text-xs bg-background/50 border-border/40'
|
||||
placeholder='例如 60,0 表示永不过期'
|
||||
required
|
||||
/>
|
||||
<p className="text-[9px] text-muted-foreground">缓存项的最长存活时间,超期后将失效被清理</p>
|
||||
<p className='text-[9px] text-muted-foreground'>
|
||||
缓存项的最长存活时间,超期后将失效被清理
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between p-4 rounded-xl border border-border/40 bg-background/20">
|
||||
<div className="space-y-1 pr-4">
|
||||
<Label htmlFor="lruEnabled" className="text-xs font-semibold block cursor-pointer">
|
||||
<div className='flex items-start justify-between p-4 rounded-xl border border-border/40 bg-background/20'>
|
||||
<div className='space-y-1 pr-4'>
|
||||
<Label
|
||||
htmlFor='lruEnabled'
|
||||
className='text-xs font-semibold block cursor-pointer'
|
||||
>
|
||||
启用 LRU 淘汰机制
|
||||
</Label>
|
||||
<span className="text-[10px] text-muted-foreground block">
|
||||
<span className='text-[10px] text-muted-foreground block'>
|
||||
在到达最大容量限制时,自动移除最久未被访问的缓存项。关闭该功能仅清理过期项。
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
id="lruEnabled"
|
||||
id='lruEnabled'
|
||||
checked={lruEnabled}
|
||||
onCheckedChange={setLruEnabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end pt-2">
|
||||
<div className='flex justify-end pt-2'>
|
||||
<Button
|
||||
type="submit"
|
||||
type='submit'
|
||||
disabled={savingConfig}
|
||||
className="h-8 text-xs px-4"
|
||||
className='h-8 text-xs px-4'
|
||||
>
|
||||
{savingConfig ? "正在保存..." : "保存设置"}
|
||||
{savingConfig ? '正在保存...' : '保存设置'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center py-10 text-muted-foreground">
|
||||
<HardDrive className="size-8 opacity-45 mb-2" />
|
||||
<span className="text-xs">未加载到缓存状态信息</span>
|
||||
<div className='flex flex-col items-center justify-center py-10 text-muted-foreground'>
|
||||
<HardDrive className='size-8 opacity-45 mb-2' />
|
||||
<span className='text-xs'>未加载到缓存状态信息</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
{/* 清除缓存确认对话框 */}
|
||||
<Dialog open={showClearConfirm} onOpenChange={setShowClearConfirm}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogContent className='sm:max-w-md'>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-sm font-semibold flex items-center gap-2 text-destructive">
|
||||
<Trash2 className="size-4" />
|
||||
<DialogTitle className='text-sm font-semibold flex items-center gap-2 text-destructive'>
|
||||
<Trash2 className='size-4' />
|
||||
确认清空所有缓存?
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-muted-foreground pt-1">
|
||||
该操作将彻底清空磁盘目录下的全部缓存文件(包含临时解压、处理后的图片及各种块文件),重置键数量统计为 0。此操作不可撤销,且可能导致用户拉取资源时出现一过性的响应变慢。
|
||||
<DialogDescription className='text-xs text-muted-foreground pt-1'>
|
||||
该操作将彻底清空磁盘目录下的全部缓存文件(包含临时解压、处理后的图片及各种块文件),重置键数量统计为
|
||||
0。此操作不可撤销,且可能导致用户拉取资源时出现一过性的响应变慢。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="flex gap-2 justify-end mt-4">
|
||||
<DialogFooter className='flex gap-2 justify-end mt-4'>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 text-xs"
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8 text-xs'
|
||||
onClick={() => setShowClearConfirm(false)}
|
||||
disabled={clearingCache}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="h-8 text-xs"
|
||||
variant='destructive'
|
||||
size='sm'
|
||||
className='h-8 text-xs'
|
||||
onClick={handleClearCache}
|
||||
disabled={clearingCache}
|
||||
>
|
||||
{clearingCache ? "清理中..." : "确认清空"}
|
||||
{clearingCache ? '清理中...' : '确认清空'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Card>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,182 +1,210 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useRef, useState} from "react"
|
||||
import {useTheme} from "next-themes"
|
||||
import CodeMirror from "@uiw/react-codemirror"
|
||||
import {sql} from "@codemirror/lang-sql"
|
||||
import {toast} from "sonner"
|
||||
import {ArrowLeft, Play, RefreshCw, Terminal, Trash2,} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { useTheme } from 'next-themes';
|
||||
import CodeMirror from '@uiw/react-codemirror';
|
||||
import { sql } from '@codemirror/lang-sql';
|
||||
import { toast } from 'sonner';
|
||||
import { ArrowLeft, Play, RefreshCw, Terminal, Trash2 } from 'lucide-react';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table"
|
||||
import type {ExecuteSQLResponse} from "@/lib/services/db-manage"
|
||||
import {DbManageService} from "@/lib/services/db-manage"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import type { ExecuteSQLResponse } from '@/lib/services/db-manage';
|
||||
import { DbManageService } from '@/lib/services/db-manage';
|
||||
|
||||
/**
|
||||
* 格式化表格单元格内容
|
||||
*/
|
||||
const formatCellValue = (val: unknown): string => {
|
||||
if (val === null || val === undefined) return "-"
|
||||
if (typeof val === "boolean") return val ? "true" : "false"
|
||||
if (typeof val === "object") {
|
||||
if (val === null || val === undefined) return '-';
|
||||
if (typeof val === 'boolean') return val ? 'true' : 'false';
|
||||
if (typeof val === 'object') {
|
||||
try {
|
||||
return JSON.stringify(val)
|
||||
return JSON.stringify(val);
|
||||
} catch {
|
||||
return "[Object]"
|
||||
return '[Object]';
|
||||
}
|
||||
}
|
||||
return String(val)
|
||||
}
|
||||
return String(val);
|
||||
};
|
||||
|
||||
interface SQLConsoleProps {
|
||||
dbType?: string // "postgres" | "sqlite"
|
||||
onClose: () => void
|
||||
dbType?: string; // "postgres" | "sqlite"
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function SQLConsole({ dbType, onClose }: SQLConsoleProps) {
|
||||
// SQL 控制台状态
|
||||
const [sqlQuery, setSqlQuery] = useState<string>("")
|
||||
const [executingSQL, setExecutingSQL] = useState<boolean>(false)
|
||||
const [sqlResult, setSqlResult] = useState<ExecuteSQLResponse | null>(null)
|
||||
const [sqlError, setSqlError] = useState<string | null>(null)
|
||||
const [sqlQuery, setSqlQuery] = useState<string>('');
|
||||
const [executingSQL, setExecutingSQL] = useState<boolean>(false);
|
||||
const [sqlResult, setSqlResult] = useState<ExecuteSQLResponse | null>(null);
|
||||
const [sqlError, setSqlError] = useState<string | null>(null);
|
||||
|
||||
// 拖拽与主题状态
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [editorHeight, setEditorHeight] = useState<number>(240)
|
||||
const { resolvedTheme } = useTheme()
|
||||
const cmTheme = resolvedTheme === "dark" ? "dark" : "light"
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [editorHeight, setEditorHeight] = useState<number>(240);
|
||||
const { resolvedTheme } = useTheme();
|
||||
const cmTheme = resolvedTheme === 'dark' ? 'dark' : 'light';
|
||||
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
const startY = e.clientY
|
||||
const startHeight = editorHeight
|
||||
e.preventDefault();
|
||||
const startY = e.clientY;
|
||||
const startHeight = editorHeight;
|
||||
|
||||
const handleMouseMove = (moveEvent: MouseEvent) => {
|
||||
if (!containerRef.current) return
|
||||
const deltaY = moveEvent.clientY - startY
|
||||
const containerHeight = containerRef.current.getBoundingClientRect().height
|
||||
const newHeight = startHeight + deltaY
|
||||
if (!containerRef.current) return;
|
||||
const deltaY = moveEvent.clientY - startY;
|
||||
const containerHeight =
|
||||
containerRef.current.getBoundingClientRect().height;
|
||||
const newHeight = startHeight + deltaY;
|
||||
|
||||
// Limit editor height between 80px and containerHeight - 80px
|
||||
if (newHeight > 80 && newHeight < containerHeight - 80) {
|
||||
setEditorHeight(newHeight)
|
||||
setEditorHeight(newHeight);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
document.removeEventListener("mousemove", handleMouseMove)
|
||||
document.removeEventListener("mouseup", handleMouseUp)
|
||||
}
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
};
|
||||
|
||||
document.addEventListener("mousemove", handleMouseMove)
|
||||
document.addEventListener("mouseup", handleMouseUp)
|
||||
}
|
||||
document.addEventListener('mousemove', handleMouseMove);
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
};
|
||||
|
||||
// 执行 SQL 查询
|
||||
const handleExecuteSQL = async () => {
|
||||
if (!sqlQuery.trim()) return
|
||||
setExecutingSQL(true)
|
||||
setSqlResult(null)
|
||||
setSqlError(null)
|
||||
if (!sqlQuery.trim()) return;
|
||||
setExecutingSQL(true);
|
||||
setSqlResult(null);
|
||||
setSqlError(null);
|
||||
try {
|
||||
const result = await DbManageService.executeSQL(sqlQuery)
|
||||
setSqlResult(result)
|
||||
toast.success("SQL 执行成功")
|
||||
const result = await DbManageService.executeSQL(sqlQuery);
|
||||
setSqlResult(result);
|
||||
toast.success('SQL 执行成功');
|
||||
} catch (err) {
|
||||
setSqlError(err instanceof Error ? err.message : "未知执行错误")
|
||||
toast.error("SQL 执行失败")
|
||||
setSqlError(err instanceof Error ? err.message : '未知执行错误');
|
||||
toast.error('SQL 执行失败');
|
||||
} finally {
|
||||
setExecutingSQL(false)
|
||||
setExecutingSQL(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Preset SQL 选择器
|
||||
const handlePresetSQLChange = (query: string) => {
|
||||
setSqlQuery(query)
|
||||
}
|
||||
setSqlQuery(query);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setSqlResult(null)
|
||||
setSqlError(null)
|
||||
onClose()
|
||||
}
|
||||
setSqlResult(null);
|
||||
setSqlError(null);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6 w-full">
|
||||
<div className='py-6 px-1 space-y-6 w-full'>
|
||||
{/* 顶部控制与标题 */}
|
||||
<div className="flex items-center justify-between pb-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className='flex items-center justify-between pb-2'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
variant='outline'
|
||||
size='icon'
|
||||
className='h-8 w-8'
|
||||
onClick={handleClose}
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
<ArrowLeft className='size-4' />
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="size-5 text-primary" />
|
||||
<div className='flex items-center gap-2'>
|
||||
<Terminal className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">SQL 查询终端</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>
|
||||
SQL 查询终端
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground font-mono">
|
||||
{dbType === "postgres" ? "PostgreSQL Connected" : "SQLite Connected"}
|
||||
<div className='text-xs text-muted-foreground font-mono'>
|
||||
{dbType === 'postgres' ? 'PostgreSQL Connected' : 'SQLite Connected'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 类似于 VS Code 的单个整体编辑器+结果区域,固定高度,有分水岭拖拽调整大小 */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="w-full border border-border/40 bg-card/60 backdrop-blur-md rounded-lg overflow-hidden flex flex-col shadow-sm h-[calc(100vh-140px)] min-h-[500px]"
|
||||
className='w-full border border-border/40 bg-card/60 backdrop-blur-md rounded-lg overflow-hidden flex flex-col shadow-sm h-[calc(100vh-140px)] min-h-[500px]'
|
||||
>
|
||||
{/* 顶部编辑工具栏 */}
|
||||
<div className="flex items-center justify-between px-4 py-2 border-b bg-muted/40 shrink-0 gap-4 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="size-4 text-primary" />
|
||||
<span className="text-xs font-semibold">SQL 编辑器</span>
|
||||
<div className='flex items-center justify-between px-4 py-2 border-b bg-muted/40 shrink-0 gap-4 flex-wrap'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Terminal className='size-4 text-primary' />
|
||||
<span className='text-xs font-semibold'>SQL 编辑器</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<div className='flex items-center gap-3 flex-wrap'>
|
||||
{/* 快速模板 */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-[11px] text-muted-foreground">快速模板:</span>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<span className='text-[11px] text-muted-foreground'>
|
||||
快速模板:
|
||||
</span>
|
||||
<Select onValueChange={handlePresetSQLChange}>
|
||||
<SelectTrigger className="h-7 w-[180px] text-[11px] bg-background">
|
||||
<SelectValue placeholder="选择预设 SQL" />
|
||||
<SelectTrigger className='h-7 w-[180px] text-[11px] bg-background'>
|
||||
<SelectValue placeholder='选择预设 SQL' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="SELECT * FROM users LIMIT 10;">查询用户 (SELECT users)</SelectItem>
|
||||
<SelectItem value="SELECT * FROM uploads LIMIT 10;">查询文件 (SELECT uploads)</SelectItem>
|
||||
<SelectItem value="SELECT * FROM task_executions ORDER BY created_at DESC LIMIT 10;">查询任务流水 (SELECT task_executions)</SelectItem>
|
||||
<SelectItem value="SELECT sqlite_version();">SQLite 版本 (SQLite only)</SelectItem>
|
||||
<SelectItem value="SELECT version();">PostgreSQL 版本 (Postgres only)</SelectItem>
|
||||
<SelectItem value='SELECT * FROM users LIMIT 10;'>
|
||||
查询用户 (SELECT users)
|
||||
</SelectItem>
|
||||
<SelectItem value='SELECT * FROM uploads LIMIT 10;'>
|
||||
查询文件 (SELECT uploads)
|
||||
</SelectItem>
|
||||
<SelectItem value='SELECT * FROM task_executions ORDER BY created_at DESC LIMIT 10;'>
|
||||
查询任务流水 (SELECT task_executions)
|
||||
</SelectItem>
|
||||
<SelectItem value='SELECT sqlite_version();'>
|
||||
SQLite 版本 (SQLite only)
|
||||
</SelectItem>
|
||||
<SelectItem value='SELECT version();'>
|
||||
PostgreSQL 版本 (Postgres only)
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 控制按钮 */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setSqlQuery("")}
|
||||
title="清空编辑器"
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='h-7 w-7 text-muted-foreground hover:text-foreground'
|
||||
onClick={() => setSqlQuery('')}
|
||||
title='清空编辑器'
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
<Trash2 className='size-3.5' />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-7 px-3 gap-1 text-[11px]"
|
||||
size='sm'
|
||||
className='h-7 px-3 gap-1 text-[11px]'
|
||||
onClick={handleExecuteSQL}
|
||||
disabled={executingSQL || !sqlQuery.trim()}
|
||||
>
|
||||
<Play className="size-3" />
|
||||
{executingSQL ? "运行中..." : "运行"}
|
||||
<Play className='size-3' />
|
||||
{executingSQL ? '运行中...' : '运行'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -185,15 +213,15 @@ export function SQLConsole({ dbType, onClose }: SQLConsoleProps) {
|
||||
{/* 上半区:编辑器输入框 */}
|
||||
<div
|
||||
style={{ height: editorHeight }}
|
||||
className="w-full overflow-hidden relative min-h-[100px] bg-background"
|
||||
className='w-full overflow-hidden relative min-h-[100px] bg-background'
|
||||
>
|
||||
<CodeMirror
|
||||
value={sqlQuery}
|
||||
height="100%"
|
||||
height='100%'
|
||||
extensions={[sql()]}
|
||||
theme={cmTheme}
|
||||
onChange={(value) => setSqlQuery(value)}
|
||||
className="h-full text-xs font-mono"
|
||||
className='h-full text-xs font-mono'
|
||||
basicSetup={{
|
||||
lineNumbers: true,
|
||||
foldGutter: true,
|
||||
@@ -207,82 +235,107 @@ export function SQLConsole({ dbType, onClose }: SQLConsoleProps) {
|
||||
{/* 拖动分割线 */}
|
||||
<div
|
||||
onMouseDown={handleMouseDown}
|
||||
className="h-1.5 bg-border/60 hover:bg-primary/50 cursor-row-resize transition-colors flex items-center justify-center shrink-0 select-none z-10"
|
||||
title="拖动调整大小"
|
||||
className='h-1.5 bg-border/60 hover:bg-primary/50 cursor-row-resize transition-colors flex items-center justify-center shrink-0 select-none z-10'
|
||||
title='拖动调整大小'
|
||||
>
|
||||
<div className="w-8 h-1 rounded bg-muted-foreground/30" />
|
||||
<div className='w-8 h-1 rounded bg-muted-foreground/30' />
|
||||
</div>
|
||||
|
||||
{/* 下半区:查看结果 (可滑动查看) */}
|
||||
<div className="flex-1 min-h-[100px] flex flex-col overflow-hidden bg-muted/10">
|
||||
<div className='flex-1 min-h-[100px] flex flex-col overflow-hidden bg-muted/10'>
|
||||
{/* 结果栏工具提示 */}
|
||||
<div className="flex items-center justify-between px-4 py-1.5 border-b bg-muted/20 shrink-0 text-[11px] text-muted-foreground font-mono">
|
||||
<span className="font-semibold">执行输出</span>
|
||||
<div className='flex items-center justify-between px-4 py-1.5 border-b bg-muted/20 shrink-0 text-[11px] text-muted-foreground font-mono'>
|
||||
<span className='font-semibold'>执行输出</span>
|
||||
{sqlResult && (
|
||||
<span>
|
||||
类型: {sqlResult.type.toUpperCase()} | 耗时: {sqlResult.execution_time_ms} ms
|
||||
类型: {sqlResult.type.toUpperCase()} | 耗时:{' '}
|
||||
{sqlResult.execution_time_ms} ms
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 滚动结果内容 */}
|
||||
<div className="flex-1 overflow-auto p-4 min-h-0">
|
||||
<div className='flex-1 overflow-auto p-4 min-h-0'>
|
||||
{executingSQL && (
|
||||
<div className="flex flex-col items-center justify-center h-full py-10 space-y-2">
|
||||
<RefreshCw className="size-5 text-primary animate-spin" />
|
||||
<span className="text-xs text-muted-foreground">正在在数据库执行查询,请稍候...</span>
|
||||
<div className='flex flex-col items-center justify-center h-full py-10 space-y-2'>
|
||||
<RefreshCw className='size-5 text-primary animate-spin' />
|
||||
<span className='text-xs text-muted-foreground'>
|
||||
正在在数据库执行查询,请稍候...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sqlError && (
|
||||
<div className="bg-destructive/10 border border-destructive/20 text-destructive font-mono text-xs p-4 rounded-lg overflow-auto h-full max-h-[300px]">
|
||||
<p className="font-semibold mb-1">SQL 执行报错 (Error):</p>
|
||||
<pre className="whitespace-pre-wrap">{sqlError}</pre>
|
||||
<div className='bg-destructive/10 border border-destructive/20 text-destructive font-mono text-xs p-4 rounded-lg overflow-auto h-full max-h-[300px]'>
|
||||
<p className='font-semibold mb-1'>SQL 执行报错 (Error):</p>
|
||||
<pre className='whitespace-pre-wrap'>{sqlError}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sqlResult && (
|
||||
<div className="h-full flex flex-col">
|
||||
{sqlResult.type === "select" && sqlResult.columns && sqlResult.columns.length > 0 && (
|
||||
<div className="border rounded-md overflow-auto max-w-full max-h-full bg-background relative flex-1 min-h-0">
|
||||
<Table className="text-xs">
|
||||
<TableHeader className="bg-muted/40 font-semibold sticky top-0 z-10">
|
||||
<TableRow>
|
||||
{sqlResult.columns.map((col) => (
|
||||
<TableHead key={col} className="font-semibold text-foreground py-2">{col}</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sqlResult.results && sqlResult.results.length > 0 ? (
|
||||
sqlResult.results.map((row, rIndex) => (
|
||||
<TableRow key={rIndex} className="hover:bg-muted/10">
|
||||
{sqlResult.columns!.map((col) => (
|
||||
<TableCell key={col} className="font-mono py-1.5">
|
||||
<span className="truncate max-w-[240px] block" title={formatCellValue(row[col])}>
|
||||
{formatCellValue(row[col])}
|
||||
</span>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<div className='h-full flex flex-col'>
|
||||
{sqlResult.type === 'select' &&
|
||||
sqlResult.columns &&
|
||||
sqlResult.columns.length > 0 && (
|
||||
<div className='border rounded-md overflow-auto max-w-full max-h-full bg-background relative flex-1 min-h-0'>
|
||||
<Table className='text-xs'>
|
||||
<TableHeader className='bg-muted/40 font-semibold sticky top-0 z-10'>
|
||||
<TableRow>
|
||||
<TableCell colSpan={sqlResult.columns.length} className="text-center py-10 text-muted-foreground">
|
||||
查询结果为空
|
||||
</TableCell>
|
||||
{sqlResult.columns.map((col) => (
|
||||
<TableHead
|
||||
key={col}
|
||||
className='font-semibold text-foreground py-2'
|
||||
>
|
||||
{col}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sqlResult.results && sqlResult.results.length > 0 ? (
|
||||
sqlResult.results.map((row, rIndex) => (
|
||||
<TableRow
|
||||
key={rIndex}
|
||||
className='hover:bg-muted/10'
|
||||
>
|
||||
{sqlResult.columns!.map((col) => (
|
||||
<TableCell
|
||||
key={col}
|
||||
className='font-mono py-1.5'
|
||||
>
|
||||
<span
|
||||
className='truncate max-w-[240px] block'
|
||||
title={formatCellValue(row[col])}
|
||||
>
|
||||
{formatCellValue(row[col])}
|
||||
</span>
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={sqlResult.columns.length}
|
||||
className='text-center py-10 text-muted-foreground'
|
||||
>
|
||||
查询结果为空
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sqlResult.type === "exec" && (
|
||||
<div className="bg-primary/5 border border-primary/10 text-primary-foreground font-mono text-xs p-6 rounded-lg text-center my-auto">
|
||||
<p className="text-foreground text-sm font-semibold">SQL 执行成功</p>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
受影响行数: {sqlResult.affected_rows} 行,耗时 {sqlResult.execution_time_ms} 毫秒。
|
||||
{sqlResult.type === 'exec' && (
|
||||
<div className='bg-primary/5 border border-primary/10 text-primary-foreground font-mono text-xs p-6 rounded-lg text-center my-auto'>
|
||||
<p className='text-foreground text-sm font-semibold'>
|
||||
SQL 执行成功
|
||||
</p>
|
||||
<p className='text-muted-foreground mt-2'>
|
||||
受影响行数: {sqlResult.affected_rows} 行,耗时{' '}
|
||||
{sqlResult.execution_time_ms} 毫秒。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -290,14 +343,16 @@ export function SQLConsole({ dbType, onClose }: SQLConsoleProps) {
|
||||
)}
|
||||
|
||||
{!executingSQL && !sqlResult && !sqlError && (
|
||||
<div className="flex flex-col items-center justify-center h-full py-10 text-muted-foreground opacity-60">
|
||||
<Terminal className="size-8 mb-2" />
|
||||
<span className="text-xs">编辑器就绪,请在上方编写 SQL 并运行查看结果</span>
|
||||
<div className='flex flex-col items-center justify-center h-full py-10 text-muted-foreground opacity-60'>
|
||||
<Terminal className='size-8 mb-2' />
|
||||
<span className='text-xs'>
|
||||
编辑器就绪,请在上方编写 SQL 并运行查看结果
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,157 +1,195 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useCallback, useEffect, useState} from "react"
|
||||
import {toast} from "sonner"
|
||||
import {Layers, RefreshCw} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { Layers, RefreshCw } from 'lucide-react';
|
||||
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Skeleton} from "@/components/ui/skeleton"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import type {TableDataResponse} from "@/lib/services/db-manage"
|
||||
import {DbManageService} from "@/lib/services/db-manage"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { TableDataResponse } from '@/lib/services/db-manage';
|
||||
import { DbManageService } from '@/lib/services/db-manage';
|
||||
|
||||
/**
|
||||
* 格式化数字,每3位加逗号
|
||||
*/
|
||||
const formatNumber = (num: number | string) => {
|
||||
if (num === undefined || num === null) return "0"
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ",")
|
||||
}
|
||||
if (num === undefined || num === null) return '0';
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ',');
|
||||
};
|
||||
|
||||
/**
|
||||
* 格式化表格单元格内容
|
||||
*/
|
||||
const formatCellValue = (val: unknown): string => {
|
||||
if (val === null || val === undefined) return "-"
|
||||
if (typeof val === "boolean") return val ? "true" : "false"
|
||||
if (typeof val === "object") {
|
||||
if (val === null || val === undefined) return '-';
|
||||
if (typeof val === 'boolean') return val ? 'true' : 'false';
|
||||
if (typeof val === 'object') {
|
||||
try {
|
||||
return JSON.stringify(val)
|
||||
return JSON.stringify(val);
|
||||
} catch {
|
||||
return "[Object]"
|
||||
return '[Object]';
|
||||
}
|
||||
}
|
||||
return String(val)
|
||||
}
|
||||
return String(val);
|
||||
};
|
||||
|
||||
interface TableBrowserProps {
|
||||
tables: string[]
|
||||
loadingTables: boolean
|
||||
refreshTrigger: number
|
||||
tables: string[];
|
||||
loadingTables: boolean;
|
||||
refreshTrigger: number;
|
||||
}
|
||||
|
||||
export function TableBrowser({ tables, loadingTables, refreshTrigger }: TableBrowserProps) {
|
||||
const [selectedTable, setSelectedTable] = useState<string>("")
|
||||
const [tableData, setTableData] = useState<TableDataResponse | null>(null)
|
||||
const [page, setPage] = useState<number>(1)
|
||||
const [loadingData, setLoadingData] = useState<boolean>(false)
|
||||
const pageSize = 10
|
||||
export function TableBrowser({
|
||||
tables,
|
||||
loadingTables,
|
||||
refreshTrigger,
|
||||
}: TableBrowserProps) {
|
||||
const [selectedTable, setSelectedTable] = useState<string>('');
|
||||
const [tableData, setTableData] = useState<TableDataResponse | null>(null);
|
||||
const [page, setPage] = useState<number>(1);
|
||||
const [loadingData, setLoadingData] = useState<boolean>(false);
|
||||
const pageSize = 10;
|
||||
|
||||
// 获取具体表数据
|
||||
const fetchTableData = useCallback(async (tableName: string, targetPage: number, size: number) => {
|
||||
if (!tableName) return
|
||||
setLoadingData(true)
|
||||
try {
|
||||
const data = await DbManageService.getTableData({
|
||||
table: tableName,
|
||||
page: targetPage,
|
||||
pageSize: size,
|
||||
})
|
||||
setTableData(data)
|
||||
} catch (err) {
|
||||
toast.error(`获取数据表 ${tableName} 数据失败`, {
|
||||
description: err instanceof Error ? err.message : "未知错误",
|
||||
})
|
||||
} finally {
|
||||
setLoadingData(false)
|
||||
}
|
||||
}, [])
|
||||
const fetchTableData = useCallback(
|
||||
async (tableName: string, targetPage: number, size: number) => {
|
||||
if (!tableName) return;
|
||||
setLoadingData(true);
|
||||
try {
|
||||
const data = await DbManageService.getTableData({
|
||||
table: tableName,
|
||||
page: targetPage,
|
||||
pageSize: size,
|
||||
});
|
||||
setTableData(data);
|
||||
} catch (err) {
|
||||
toast.error(`获取数据表 ${tableName} 数据失败`, {
|
||||
description: err instanceof Error ? err.message : '未知错误',
|
||||
});
|
||||
} finally {
|
||||
setLoadingData(false);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// 默认选择第一张表
|
||||
useEffect(() => {
|
||||
if (tables.length > 0 && !selectedTable) {
|
||||
setSelectedTable(tables[0])
|
||||
setSelectedTable(tables[0]);
|
||||
}
|
||||
}, [tables, selectedTable])
|
||||
}, [tables, selectedTable]);
|
||||
|
||||
// 当选中的表、页码或外部刷新触发器改变时获取数据
|
||||
useEffect(() => {
|
||||
if (selectedTable) {
|
||||
fetchTableData(selectedTable, page, pageSize)
|
||||
fetchTableData(selectedTable, page, pageSize);
|
||||
}
|
||||
}, [selectedTable, page, pageSize, refreshTrigger, fetchTableData])
|
||||
}, [selectedTable, page, pageSize, refreshTrigger, fetchTableData]);
|
||||
|
||||
// 处理页码改变
|
||||
const handlePageChange = (newPage: number) => {
|
||||
setPage(newPage)
|
||||
}
|
||||
setPage(newPage);
|
||||
};
|
||||
|
||||
// 处理表切换
|
||||
const handleTableChange = (value: string) => {
|
||||
setSelectedTable(value)
|
||||
setPage(1) // 切换表重置为第一页
|
||||
}
|
||||
setSelectedTable(value);
|
||||
setPage(1); // 切换表重置为第一页
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="border-border/40 bg-card/50 backdrop-blur-sm shadow-sm">
|
||||
<CardHeader className="pb-3 border-b border-dashed flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-sm font-semibold">数据表浏览器</CardTitle>
|
||||
<CardDescription className="text-[11px]">浏览数据库中的物理数据表详情及内容</CardDescription>
|
||||
<Card className='border-border/40 bg-card/50 backdrop-blur-sm shadow-sm'>
|
||||
<CardHeader className='pb-3 border-b border-dashed flex flex-col md:flex-row md:items-center md:justify-between gap-4'>
|
||||
<div className='space-y-0.5'>
|
||||
<CardTitle className='text-sm font-semibold'>数据表浏览器</CardTitle>
|
||||
<CardDescription className='text-[11px]'>
|
||||
浏览数据库中的物理数据表详情及内容
|
||||
</CardDescription>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className='flex items-center gap-2'>
|
||||
{loadingTables ? (
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className='h-8 w-48' />
|
||||
) : (
|
||||
<Select value={selectedTable} onValueChange={handleTableChange}>
|
||||
<SelectTrigger className="h-8 w-[200px] text-xs bg-background border-border/40">
|
||||
<SelectValue placeholder="选择数据表" />
|
||||
<SelectTrigger className='h-8 w-[200px] text-xs bg-background border-border/40'>
|
||||
<SelectValue placeholder='选择数据表' />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="max-h-[300px]">
|
||||
<SelectContent className='max-h-[300px]'>
|
||||
{tables.map((t) => (
|
||||
<SelectItem key={t} value={t} className="text-xs font-mono">{t}</SelectItem>
|
||||
<SelectItem key={t} value={t} className='text-xs font-mono'>
|
||||
{t}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-4">
|
||||
<CardContent className='pt-4'>
|
||||
{loadingData && !tableData ? (
|
||||
<div className="space-y-3 py-6">
|
||||
<Skeleton className="h-6 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className='space-y-3 py-6'>
|
||||
<Skeleton className='h-6 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
<Skeleton className='h-10 w-full' />
|
||||
</div>
|
||||
) : tableData && tableData.columns.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
<div className='space-y-4'>
|
||||
{/* 数据表格区域 */}
|
||||
<div className="border rounded-md overflow-x-auto max-w-full bg-background/50 relative">
|
||||
<div className='border rounded-md overflow-x-auto max-w-full bg-background/50 relative'>
|
||||
{loadingData && (
|
||||
<div className="absolute inset-0 bg-background/40 backdrop-blur-[1px] flex items-center justify-center z-10">
|
||||
<RefreshCw className="size-5 text-primary animate-spin" />
|
||||
<div className='absolute inset-0 bg-background/40 backdrop-blur-[1px] flex items-center justify-center z-10'>
|
||||
<RefreshCw className='size-5 text-primary animate-spin' />
|
||||
</div>
|
||||
)}
|
||||
<Table className="text-xs">
|
||||
<TableHeader className="bg-muted/40 font-semibold sticky top-0">
|
||||
<Table className='text-xs'>
|
||||
<TableHeader className='bg-muted/40 font-semibold sticky top-0'>
|
||||
<TableRow>
|
||||
{tableData.columns.map((col) => (
|
||||
<TableHead key={col} className="font-semibold text-foreground py-2.5">{col}</TableHead>
|
||||
<TableHead
|
||||
key={col}
|
||||
className='font-semibold text-foreground py-2.5'
|
||||
>
|
||||
{col}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{tableData.results && tableData.results.length > 0 ? (
|
||||
tableData.results.map((row, rIndex) => (
|
||||
<TableRow key={rIndex} className="hover:bg-muted/10">
|
||||
<TableRow key={rIndex} className='hover:bg-muted/10'>
|
||||
{tableData.columns.map((col) => (
|
||||
<TableCell key={col} className="font-mono py-2">
|
||||
<span className="truncate max-w-[200px] block" title={formatCellValue(row[col])}>
|
||||
<TableCell key={col} className='font-mono py-2'>
|
||||
<span
|
||||
className='truncate max-w-[200px] block'
|
||||
title={formatCellValue(row[col])}
|
||||
>
|
||||
{formatCellValue(row[col])}
|
||||
</span>
|
||||
</TableCell>
|
||||
@@ -160,7 +198,10 @@ export function TableBrowser({ tables, loadingTables, refreshTrigger }: TableBro
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={tableData.columns.length} className="text-center py-10 text-muted-foreground">
|
||||
<TableCell
|
||||
colSpan={tableData.columns.length}
|
||||
className='text-center py-10 text-muted-foreground'
|
||||
>
|
||||
表中无记录数据
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -170,29 +211,36 @@ export function TableBrowser({ tables, loadingTables, refreshTrigger }: TableBro
|
||||
</div>
|
||||
|
||||
{/* 分页控制 */}
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground flex-wrap gap-2 pt-2 border-t border-dashed">
|
||||
<div className='flex items-center justify-between text-xs text-muted-foreground flex-wrap gap-2 pt-2 border-t border-dashed'>
|
||||
<div>
|
||||
总行数: <span className="font-mono text-foreground font-semibold">{formatNumber(tableData.total)}</span> 条记录
|
||||
总行数:{' '}
|
||||
<span className='font-mono text-foreground font-semibold'>
|
||||
{formatNumber(tableData.total)}
|
||||
</span>{' '}
|
||||
条记录
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className='flex items-center gap-2'>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-[11px]"
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 px-2 text-[11px]'
|
||||
onClick={() => handlePageChange(page - 1)}
|
||||
disabled={page <= 1 || loadingData}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<span className="text-xs px-2 font-mono">
|
||||
第 {page} / {Math.max(1, Math.ceil(tableData.total / pageSize))} 页
|
||||
<span className='text-xs px-2 font-mono'>
|
||||
第 {page} /{' '}
|
||||
{Math.max(1, Math.ceil(tableData.total / pageSize))} 页
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-[11px]"
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 px-2 text-[11px]'
|
||||
onClick={() => handlePageChange(page + 1)}
|
||||
disabled={page >= Math.ceil(tableData.total / pageSize) || loadingData}
|
||||
disabled={
|
||||
page >= Math.ceil(tableData.total / pageSize) || loadingData
|
||||
}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
@@ -200,12 +248,12 @@ export function TableBrowser({ tables, loadingTables, refreshTrigger }: TableBro
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center py-10 text-muted-foreground">
|
||||
<Layers className="size-8 opacity-45 mb-2" />
|
||||
<span className="text-xs">未选择数据表或表结构无法加载</span>
|
||||
<div className='flex flex-col items-center justify-center py-10 text-muted-foreground'>
|
||||
<Layers className='size-8 opacity-45 mb-2' />
|
||||
<span className='text-xs'>未选择数据表或表结构无法加载</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import dynamic from "next/dynamic"
|
||||
import * as React from "react"
|
||||
import {useCallback, useEffect, useState} from "react"
|
||||
import {toast} from "sonner"
|
||||
import dynamic from 'next/dynamic';
|
||||
import * as React from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
Activity,
|
||||
Cpu,
|
||||
@@ -15,134 +15,142 @@ import {
|
||||
RefreshCw,
|
||||
Server,
|
||||
Terminal,
|
||||
} from "lucide-react"
|
||||
} from 'lucide-react';
|
||||
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Skeleton} from "@/components/ui/skeleton"
|
||||
import services from "@/lib/services"
|
||||
import type {DBOverview} from "@/lib/services/db-manage"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import services from '@/lib/services';
|
||||
import type { DBOverview } from '@/lib/services/db-manage';
|
||||
|
||||
const sectionFallback = (
|
||||
<div className="h-48 animate-pulse rounded-lg border border-border/40 bg-muted/20" />
|
||||
)
|
||||
<div className='h-48 animate-pulse rounded-lg border border-border/40 bg-muted/20' />
|
||||
);
|
||||
|
||||
const TableBrowser = dynamic(
|
||||
() => import("./components/table-browser").then((mod) => mod.TableBrowser),
|
||||
() => import('./components/table-browser').then((mod) => mod.TableBrowser),
|
||||
{ loading: () => sectionFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const CacheManager = dynamic(
|
||||
() => import("./components/cache-manager").then((mod) => mod.CacheManager),
|
||||
() => import('./components/cache-manager').then((mod) => mod.CacheManager),
|
||||
{ loading: () => sectionFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const SQLConsole = dynamic(
|
||||
() => import("./components/sql-console").then((mod) => mod.SQLConsole),
|
||||
() => import('./components/sql-console').then((mod) => mod.SQLConsole),
|
||||
{ ssr: false },
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* 格式化数字,每3位加逗号
|
||||
*/
|
||||
const formatNumber = (num: number | string) => {
|
||||
if (num === undefined || num === null) return "0"
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
|
||||
}
|
||||
if (num === undefined || num === null) return '0';
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
};
|
||||
|
||||
export function DatabasePageClient() {
|
||||
// 核心状态
|
||||
const [overview, setOverview] = useState<DBOverview | null>(null)
|
||||
const [tables, setTables] = useState<string[]>([])
|
||||
const [loadingOverview, setLoadingOverview] = useState<boolean>(true)
|
||||
const [loadingTables, setLoadingTables] = useState<boolean>(true)
|
||||
const [exporting, setExporting] = useState<boolean>(false)
|
||||
const [overview, setOverview] = useState<DBOverview | null>(null);
|
||||
const [tables, setTables] = useState<string[]>([]);
|
||||
const [loadingOverview, setLoadingOverview] = useState<boolean>(true);
|
||||
const [loadingTables, setLoadingTables] = useState<boolean>(true);
|
||||
const [exporting, setExporting] = useState<boolean>(false);
|
||||
|
||||
// 协调子组件刷新与视图切换状态
|
||||
const [showConsole, setShowConsole] = useState<boolean>(false)
|
||||
const [refreshTrigger, setRefreshTrigger] = useState<number>(0)
|
||||
const [showConsole, setShowConsole] = useState<boolean>(false);
|
||||
const [refreshTrigger, setRefreshTrigger] = useState<number>(0);
|
||||
|
||||
// 1. 获取运行概览
|
||||
const fetchOverview = useCallback(async (isSilent = false) => {
|
||||
if (!isSilent) setLoadingOverview(true)
|
||||
if (!isSilent) setLoadingOverview(true);
|
||||
try {
|
||||
const data = await services.dbManage.getOverview()
|
||||
setOverview(data)
|
||||
const data = await services.dbManage.getOverview();
|
||||
setOverview(data);
|
||||
} catch (err) {
|
||||
toast.error("获取数据库概览失败", {
|
||||
description: err instanceof Error ? err.message : "未知错误",
|
||||
})
|
||||
toast.error('获取数据库概览失败', {
|
||||
description: err instanceof Error ? err.message : '未知错误',
|
||||
});
|
||||
} finally {
|
||||
setLoadingOverview(false)
|
||||
setLoadingOverview(false);
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
// 2. 获取表列表
|
||||
const fetchTables = useCallback(async () => {
|
||||
setLoadingTables(true)
|
||||
setLoadingTables(true);
|
||||
try {
|
||||
const data = await services.dbManage.listTables()
|
||||
setTables(data)
|
||||
const data = await services.dbManage.listTables();
|
||||
setTables(data);
|
||||
} catch (err) {
|
||||
toast.error("获取数据库数据表列表失败", {
|
||||
description: err instanceof Error ? err.message : "未知错误",
|
||||
})
|
||||
toast.error('获取数据库数据表列表失败', {
|
||||
description: err instanceof Error ? err.message : '未知错误',
|
||||
});
|
||||
} finally {
|
||||
setLoadingTables(false)
|
||||
setLoadingTables(false);
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
// 3. 协调刷新
|
||||
const handleRefreshAll = () => {
|
||||
fetchOverview()
|
||||
fetchTables()
|
||||
setRefreshTrigger((prev) => prev + 1)
|
||||
}
|
||||
fetchOverview();
|
||||
fetchTables();
|
||||
setRefreshTrigger((prev) => prev + 1);
|
||||
};
|
||||
|
||||
// 4. 导出数据库备份
|
||||
const handleExport = async () => {
|
||||
setExporting(true)
|
||||
setExporting(true);
|
||||
try {
|
||||
const { blob, filename } = await services.dbManage.exportDatabase()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = filename
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
toast.success("数据库导出成功", { description: `已下载归档文件: ${filename}` })
|
||||
const { blob, filename } = await services.dbManage.exportDatabase();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
toast.success('数据库导出成功', {
|
||||
description: `已下载归档文件: ${filename}`,
|
||||
});
|
||||
} catch (err) {
|
||||
toast.error("数据库导出失败", {
|
||||
description: err instanceof Error ? err.message : "导出异常",
|
||||
})
|
||||
toast.error('数据库导出失败', {
|
||||
description: err instanceof Error ? err.message : '导出异常',
|
||||
});
|
||||
} finally {
|
||||
setExporting(false)
|
||||
setExporting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 初始化加载
|
||||
useEffect(() => {
|
||||
fetchOverview()
|
||||
fetchTables()
|
||||
}, [fetchOverview, fetchTables])
|
||||
fetchOverview();
|
||||
fetchTables();
|
||||
}, [fetchOverview, fetchTables]);
|
||||
|
||||
// 渲染概览卡片骨架
|
||||
const renderOverviewSkeleton = () => (
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
|
||||
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'>
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Card key={i} className="border-border/40 bg-card/50">
|
||||
<CardHeader className="pb-2">
|
||||
<Skeleton className="h-4 w-16" />
|
||||
<Card key={i} className='border-border/40 bg-card/50'>
|
||||
<CardHeader className='pb-2'>
|
||||
<Skeleton className='h-4 w-16' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Skeleton className="h-6 w-24" />
|
||||
<Skeleton className='h-6 w-24' />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
// 渲染 SQL 查询控台全屏视图
|
||||
if (showConsole) {
|
||||
@@ -151,110 +159,136 @@ export function DatabasePageClient() {
|
||||
dbType={overview?.type}
|
||||
onClose={() => setShowConsole(false)}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 正常页面排版布局
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6 w-full">
|
||||
<div className='py-6 px-1 space-y-6 w-full'>
|
||||
{/* 顶部控制与标题 */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between pb-4 gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="size-5 text-primary" />
|
||||
<div className='flex flex-col sm:flex-row sm:items-center sm:justify-between pb-4 gap-4'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Database className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">数据管理</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>数据管理</h1>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 gap-1.5 text-xs self-start sm:self-auto"
|
||||
size='sm'
|
||||
variant='secondary'
|
||||
className='h-8 gap-1.5 text-xs self-start sm:self-auto'
|
||||
onClick={handleRefreshAll}
|
||||
disabled={loadingOverview}
|
||||
>
|
||||
<RefreshCw className={`size-3 ${loadingOverview ? "animate-spin" : ""}`} />
|
||||
<RefreshCw
|
||||
className={`size-3 ${loadingOverview ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
刷新数据
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 1. 概览指标卡片组 */}
|
||||
{loadingOverview ? (
|
||||
renderOverviewSkeleton()
|
||||
) : (
|
||||
overview && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
|
||||
{/* 卡片1: 数据库类型 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardDescription className="text-[10px] font-medium">数据库类型</CardDescription>
|
||||
<Server className="size-3.5 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-sm font-bold uppercase">{overview.type}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{loadingOverview
|
||||
? renderOverviewSkeleton()
|
||||
: overview && (
|
||||
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4'>
|
||||
{/* 卡片1: 数据库类型 */}
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardDescription className='text-[10px] font-medium'>
|
||||
数据库类型
|
||||
</CardDescription>
|
||||
<Server className='size-3.5 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='text-sm font-bold uppercase'>
|
||||
{overview.type}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 卡片2: 数据库版本 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300 col-span-1 md:col-span-2 lg:col-span-1">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardDescription className="text-[10px] font-medium">版本信息</CardDescription>
|
||||
<Cpu className="size-3.5 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-xs font-semibold truncate" title={overview.version}>
|
||||
{overview.version.split(" ").slice(0, 2).join(" ")}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 卡片2: 数据库版本 */}
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300 col-span-1 md:col-span-2 lg:col-span-1'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardDescription className='text-[10px] font-medium'>
|
||||
版本信息
|
||||
</CardDescription>
|
||||
<Cpu className='size-3.5 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className='text-xs font-semibold truncate'
|
||||
title={overview.version}
|
||||
>
|
||||
{overview.version.split(' ').slice(0, 2).join(' ')}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 卡片3: 数据库名称 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardDescription className="text-[10px] font-medium">名称/路径</CardDescription>
|
||||
<Database className="size-3.5 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-xs font-semibold truncate" title={overview.name}>
|
||||
{overview.name.substring(overview.name.lastIndexOf("/") + 1)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 卡片3: 数据库名称 */}
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardDescription className='text-[10px] font-medium'>
|
||||
名称/路径
|
||||
</CardDescription>
|
||||
<Database className='size-3.5 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className='text-xs font-semibold truncate'
|
||||
title={overview.name}
|
||||
>
|
||||
{overview.name.substring(
|
||||
overview.name.lastIndexOf('/') + 1,
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 卡片4: 数据库大小 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardDescription className="text-[10px] font-medium">数据库大小</CardDescription>
|
||||
<HardDrive className="size-3.5 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-sm font-bold">{overview.size}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 卡片4: 数据库大小 */}
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardDescription className='text-[10px] font-medium'>
|
||||
数据库大小
|
||||
</CardDescription>
|
||||
<HardDrive className='size-3.5 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='text-sm font-bold'>{overview.size}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 卡片5: 表数量 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardDescription className="text-[10px] font-medium">物理数据表</CardDescription>
|
||||
<Layers className="size-3.5 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-sm font-bold">{formatNumber(overview.table_count)}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* 卡片5: 表数量 */}
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardDescription className='text-[10px] font-medium'>
|
||||
物理数据表
|
||||
</CardDescription>
|
||||
<Layers className='size-3.5 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='text-sm font-bold'>
|
||||
{formatNumber(overview.table_count)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 卡片6: 连接数 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardDescription className="text-[10px] font-medium">活跃连接数</CardDescription>
|
||||
<Activity className="size-3.5 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-sm font-bold">{formatNumber(overview.connections)}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
{/* 卡片6: 连接数 */}
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-sm hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardDescription className='text-[10px] font-medium'>
|
||||
活跃连接数
|
||||
</CardDescription>
|
||||
<Activity className='size-3.5 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='text-sm font-bold'>
|
||||
{formatNumber(overview.connections)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 2. 数据表浏览器区块 */}
|
||||
<TableBrowser
|
||||
@@ -264,60 +298,64 @@ export function DatabasePageClient() {
|
||||
/>
|
||||
|
||||
{/* 3. 缓存管理区块 */}
|
||||
<CacheManager
|
||||
refreshTrigger={refreshTrigger}
|
||||
/>
|
||||
<CacheManager refreshTrigger={refreshTrigger} />
|
||||
|
||||
{/* 4. 底部功能卡片区 */}
|
||||
<Card className="border-border/40 bg-card/50 backdrop-blur-sm shadow-sm">
|
||||
<CardHeader className="pb-3 border-b border-dashed">
|
||||
<CardTitle className="text-sm font-semibold">功能区</CardTitle>
|
||||
<CardDescription className="text-[11px]">数据库导出及自定义高级 SQL 执行终端</CardDescription>
|
||||
<Card className='border-border/40 bg-card/50 backdrop-blur-sm shadow-sm'>
|
||||
<CardHeader className='pb-3 border-b border-dashed'>
|
||||
<CardTitle className='text-sm font-semibold'>功能区</CardTitle>
|
||||
<CardDescription className='text-[11px]'>
|
||||
数据库导出及自定义高级 SQL 执行终端
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<CardContent className='pt-4'>
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
|
||||
{/* 功能一: 数据库导出 */}
|
||||
<div className="flex items-center justify-between p-4 border border-dashed rounded-lg hover:bg-muted/20 transition-colors duration-150">
|
||||
<div className="space-y-1 pr-4">
|
||||
<p className="text-xs font-semibold flex items-center gap-1.5">
|
||||
<Download className="size-4 text-primary" />
|
||||
<div className='flex items-center justify-between p-4 border border-dashed rounded-lg hover:bg-muted/20 transition-colors duration-150'>
|
||||
<div className='space-y-1 pr-4'>
|
||||
<p className='text-xs font-semibold flex items-center gap-1.5'>
|
||||
<Download className='size-4 text-primary' />
|
||||
数据库备份导出
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
直接导出并下载物理数据库镜像文件(SQLite 导出 .db,PostgreSQL 导出为打包的 .sql 文本文件)
|
||||
<p className='text-[10px] text-muted-foreground'>
|
||||
直接导出并下载物理数据库镜像文件(SQLite 导出 .db,PostgreSQL
|
||||
导出为打包的 .sql 文本文件)
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 text-xs gap-1"
|
||||
size='sm'
|
||||
variant='outline'
|
||||
className='h-8 text-xs gap-1'
|
||||
onClick={handleExport}
|
||||
disabled={exporting}
|
||||
>
|
||||
<RefreshCw className={`size-3 ${exporting ? "animate-spin" : ""}`} />
|
||||
{exporting ? "正在准备..." : "开始导出"}
|
||||
<RefreshCw
|
||||
className={`size-3 ${exporting ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
{exporting ? '正在准备...' : '开始导出'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 功能二: SQL 查询终端 */}
|
||||
<div className="flex items-center justify-between p-4 border border-dashed rounded-lg hover:bg-muted/20 transition-colors duration-150">
|
||||
<div className="space-y-1 pr-4">
|
||||
<p className="text-xs font-semibold flex items-center gap-1.5">
|
||||
<Terminal className="size-4 text-primary" />
|
||||
<div className='flex items-center justify-between p-4 border border-dashed rounded-lg hover:bg-muted/20 transition-colors duration-150'>
|
||||
<div className='space-y-1 pr-4'>
|
||||
<p className='text-xs font-semibold flex items-center gap-1.5'>
|
||||
<Terminal className='size-4 text-primary' />
|
||||
SQL 查询控台
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
打开在线 SQL 控制终端,执行原生的 SQL 进行数据筛选、更新、调试或性能优化
|
||||
<p className='text-[10px] text-muted-foreground'>
|
||||
打开在线 SQL 控制终端,执行原生的 SQL
|
||||
进行数据筛选、更新、调试或性能优化
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 text-xs gap-1 bg-primary text-primary-foreground hover:bg-primary/95"
|
||||
size='sm'
|
||||
className='h-8 text-xs gap-1 bg-primary text-primary-foreground hover:bg-primary/95'
|
||||
onClick={() => {
|
||||
setShowConsole(true)
|
||||
setShowConsole(true);
|
||||
}}
|
||||
>
|
||||
<FileText className="size-3.5" />
|
||||
<FileText className='size-3.5' />
|
||||
进入控台
|
||||
</Button>
|
||||
</div>
|
||||
@@ -325,5 +363,5 @@ export function DatabasePageClient() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {DatabasePageClient} from "./page-client"
|
||||
import { DatabasePageClient } from './page-client';
|
||||
|
||||
export default function DatabasePage() {
|
||||
return <DatabasePageClient />
|
||||
}
|
||||
return <DatabasePageClient />;
|
||||
}
|
||||
|
||||
@@ -1,82 +1,176 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {Code} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { Code } from 'lucide-react';
|
||||
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
|
||||
// 引入模块化拆分后的 Tab 子组件
|
||||
import {DashboardTab} from "./tabs/dashboard-tab"
|
||||
import {TableTab} from "./tabs/table-tab"
|
||||
import {ControlsTab} from "./tabs/controls-tab"
|
||||
import { DashboardTab } from './tabs/dashboard-tab';
|
||||
import { TableTab } from './tabs/table-tab';
|
||||
import { ControlsTab } from './tabs/controls-tab';
|
||||
|
||||
export default function HeaderDemoPage() {
|
||||
const [activeTab, setActiveTab] = React.useState("dashboard")
|
||||
const [activeTab, setActiveTab] = React.useState('dashboard');
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6">
|
||||
<div className='py-6 px-1 space-y-6'>
|
||||
{/* 1. 标准页面标题 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Code className="size-5 text-primary" />
|
||||
<div className='flex items-center gap-2'>
|
||||
<Code className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">开发规范示例</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>
|
||||
开发规范示例
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 说明区域 */}
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Code className="size-4 text-primary" />
|
||||
<CardTitle className="text-base font-semibold">规范说明</CardTitle>
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader className='pb-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Code className='size-4 text-primary' />
|
||||
<CardTitle className='text-base font-semibold'>规范说明</CardTitle>
|
||||
</div>
|
||||
<CardDescription>
|
||||
此页面展示了后台 Sidebar 关联页面的标准标题栏布局,供开发参考。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">核心规范细节与编写原则:</h3>
|
||||
<ul className="list-disc pl-4 text-xs text-muted-foreground space-y-1.5">
|
||||
<li><strong>结构专注</strong>:页面标题区必须保持绝对干净。请不要在标题下方放置任何描述段落或小字副标题,让页面在视线进入时保持极简与信息纯粹。</li>
|
||||
<li><strong>容器与上边距对齐</strong>:使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">flex items-center gap-2</code> 作为标题行基础容器(不含下边框),外层统一使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">py-6 px-1</code> (或 <code className="bg-muted px-1 py-0.5 rounded font-mono">py-6</code>) 进行上边距的视觉对齐,确保切换菜单时顶部高度感一致。</li>
|
||||
<li><strong>图标呈现</strong>:直接将 Lucide 图标组件嵌套于标题容器中,应用 <code className="bg-muted px-1 py-0.5 rounded font-mono">size-5 text-primary</code> 样式。禁止为图标包裹任何背景色小卡片、圆角或装饰性边框。</li>
|
||||
<li><strong>文本样式标准</strong>:文本使用且仅使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">{'h1 className="text-2xl font-semibold tracking-tight"'}</code>,禁用字重加粗(如 <code className="bg-muted px-1 py-0.5 rounded font-mono">font-bold</code>)或任何渐变色,保证全站字体一致性。</li>
|
||||
<li><strong>Tabs 模块化拆分</strong>:凡是带有多个 Tab 页切换的页面,**禁止**将所有 Tab 的渲染代码堆积在同一个物理页面主文件内。每个 Tab 页对应的 Content 必须单独拆分为独立组件文件(如 <code className="bg-muted px-1 py-0.5 rounded font-mono">tabs/events-tab.tsx</code> 或就近放在 <code className="bg-muted px-1 py-0.5 rounded font-mono">components/</code> 下),主页面文件只负责维护当前 Tab 的激活状态及外层骨架布局。</li>
|
||||
<li><strong>复杂度驱动的区块拆分</strong>:不仅是 Tabs 切换,当一个页面代码行数超过 600 行时,必须将高密度区块拆分为子组件。路由专属、不复用的子组件应放在对应路由的特征目录中(如 <code className="bg-muted px-1 py-0.5 rounded font-mono">app/(main)/admin/database/components/</code>),只有真正跨页面复用的组件才进入全局 <code className="bg-muted px-1 py-0.5 rounded font-mono">components/common/</code>。典型标杆案例参考“数据管理” (<code className="bg-muted px-1 py-0.5 rounded font-mono">/admin/database</code>) 的 <code className="bg-muted px-1 py-0.5 rounded font-mono">table-browser.tsx</code>、<code className="bg-muted px-1 py-0.5 rounded font-mono">cache-manager.tsx</code> 与 <code className="bg-muted px-1 py-0.5 rounded font-mono">sql-console.tsx</code>。</li>
|
||||
<CardContent className='space-y-4'>
|
||||
<div className='space-y-2'>
|
||||
<h3 className='text-xs font-semibold uppercase tracking-wider text-muted-foreground'>
|
||||
核心规范细节与编写原则:
|
||||
</h3>
|
||||
<ul className='list-disc pl-4 text-xs text-muted-foreground space-y-1.5'>
|
||||
<li>
|
||||
<strong>结构专注</strong>
|
||||
:页面标题区必须保持绝对干净。请不要在标题下方放置任何描述段落或小字副标题,让页面在视线进入时保持极简与信息纯粹。
|
||||
</li>
|
||||
<li>
|
||||
<strong>容器与上边距对齐</strong>:使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
flex items-center gap-2
|
||||
</code>{' '}
|
||||
作为标题行基础容器(不含下边框),外层统一使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
py-6 px-1
|
||||
</code>{' '}
|
||||
(或{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
py-6
|
||||
</code>
|
||||
) 进行上边距的视觉对齐,确保切换菜单时顶部高度感一致。
|
||||
</li>
|
||||
<li>
|
||||
<strong>图标呈现</strong>:直接将 Lucide
|
||||
图标组件嵌套于标题容器中,应用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
size-5 text-primary
|
||||
</code>{' '}
|
||||
样式。禁止为图标包裹任何背景色小卡片、圆角或装饰性边框。
|
||||
</li>
|
||||
<li>
|
||||
<strong>文本样式标准</strong>:文本使用且仅使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
{'h1 className="text-2xl font-semibold tracking-tight"'}
|
||||
</code>
|
||||
,禁用字重加粗(如{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
font-bold
|
||||
</code>
|
||||
)或任何渐变色,保证全站字体一致性。
|
||||
</li>
|
||||
<li>
|
||||
<strong>Tabs 模块化拆分</strong>:凡是带有多个 Tab
|
||||
页切换的页面,**禁止**将所有 Tab
|
||||
的渲染代码堆积在同一个物理页面主文件内。每个 Tab 页对应的
|
||||
Content 必须单独拆分为独立组件文件(如{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
tabs/events-tab.tsx
|
||||
</code>{' '}
|
||||
或就近放在{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
components/
|
||||
</code>{' '}
|
||||
下),主页面文件只负责维护当前 Tab 的激活状态及外层骨架布局。
|
||||
</li>
|
||||
<li>
|
||||
<strong>复杂度驱动的区块拆分</strong>:不仅是 Tabs
|
||||
切换,当一个页面代码行数超过 600
|
||||
行时,必须将高密度区块拆分为子组件。路由专属、不复用的子组件应放在对应路由的特征目录中(如{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
app/(main)/admin/database/components/
|
||||
</code>
|
||||
),只有真正跨页面复用的组件才进入全局{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
components/common/
|
||||
</code>
|
||||
。典型标杆案例参考“数据管理” (
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
/admin/database
|
||||
</code>
|
||||
) 的{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
table-browser.tsx
|
||||
</code>
|
||||
、
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
cache-manager.tsx
|
||||
</code>{' '}
|
||||
与{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
sql-console.tsx
|
||||
</code>
|
||||
。
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Tabs 切换 */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
|
||||
<TabsList variant="line" className="w-fit inline-flex gap-8 mb-6">
|
||||
<TabsTrigger value="dashboard" className="px-0 pb-2 text-xs font-semibold">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className='w-full'>
|
||||
<TabsList variant='line' className='w-fit inline-flex gap-8 mb-6'>
|
||||
<TabsTrigger
|
||||
value='dashboard'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
仪表盘与指标卡片
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="table" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='table'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
数据表格规范
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="controls" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='controls'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
输入控件与表单
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="dashboard" className="focus-visible:outline-none">
|
||||
<TabsContent value='dashboard' className='focus-visible:outline-none'>
|
||||
<DashboardTab />
|
||||
</TabsContent>
|
||||
<TabsContent value="table" className="focus-visible:outline-none">
|
||||
<TabsContent value='table' className='focus-visible:outline-none'>
|
||||
<TableTab />
|
||||
</TabsContent>
|
||||
<TabsContent value="controls" className="focus-visible:outline-none">
|
||||
<TabsContent value='controls' className='focus-visible:outline-none'>
|
||||
<ControlsTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,100 +1,148 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {Code} from "lucide-react"
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Label} from "@/components/ui/label"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
|
||||
import {Checkbox} from "@/components/ui/checkbox"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import * as React from 'react';
|
||||
import { Code } from 'lucide-react';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export function ControlsTab() {
|
||||
const [formData, setFormData] = React.useState({
|
||||
name: "",
|
||||
category: "database",
|
||||
name: '',
|
||||
category: 'database',
|
||||
allowNotify: true,
|
||||
channel: "all",
|
||||
})
|
||||
channel: 'all',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6'>
|
||||
{/* 控件展示 */}
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-semibold">表单与输入框交互演示</CardTitle>
|
||||
<CardDescription>包含按钮变体、下拉选择、多选框及基础输入框的标准样式</CardDescription>
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader className='pb-3'>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
表单与输入框交互演示
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
包含按钮变体、下拉选择、多选框及基础输入框的标准样式
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<CardContent className='space-y-4'>
|
||||
{/* 输入框 */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-name" className="text-xs font-medium text-foreground">任务名称</Label>
|
||||
<div className='space-y-1.5'>
|
||||
<Label
|
||||
htmlFor='task-name'
|
||||
className='text-xs font-medium text-foreground'
|
||||
>
|
||||
任务名称
|
||||
</Label>
|
||||
<Input
|
||||
id="task-name"
|
||||
id='task-name'
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
|
||||
placeholder="输入要创建的任务描述..."
|
||||
className="h-8 text-xs shadow-none bg-background focus-visible:ring-1"
|
||||
onChange={(e) =>
|
||||
setFormData((prev) => ({ ...prev, name: e.target.value }))
|
||||
}
|
||||
placeholder='输入要创建的任务描述...'
|
||||
className='h-8 text-xs shadow-none bg-background focus-visible:ring-1'
|
||||
/>
|
||||
<p className="text-[10px] text-muted-foreground">任务名称将用于后台执行记录的可读性显示</p>
|
||||
<p className='text-[10px] text-muted-foreground'>
|
||||
任务名称将用于后台执行记录的可读性显示
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 下拉框 */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-medium text-foreground">任务分类</Label>
|
||||
<div className='space-y-1.5'>
|
||||
<Label className='text-xs font-medium text-foreground'>
|
||||
任务分类
|
||||
</Label>
|
||||
<Select
|
||||
value={formData.category}
|
||||
onValueChange={(val) => setFormData(prev => ({ ...prev, category: val }))}
|
||||
onValueChange={(val) =>
|
||||
setFormData((prev) => ({ ...prev, category: val }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 text-xs shadow-none bg-background focus:ring-1">
|
||||
<SelectTrigger className='h-8 text-xs shadow-none bg-background focus:ring-1'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="database">数据库运维</SelectItem>
|
||||
<SelectItem value="sync">数据批量同步</SelectItem>
|
||||
<SelectItem value="cleanup">过期磁盘清理</SelectItem>
|
||||
<SelectItem value='database'>数据库运维</SelectItem>
|
||||
<SelectItem value='sync'>数据批量同步</SelectItem>
|
||||
<SelectItem value='cleanup'>过期磁盘清理</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 多选框 Checkbox */}
|
||||
<div className="flex items-start gap-2.5 p-3 bg-muted/30 border border-dashed rounded-lg">
|
||||
<div className='flex items-start gap-2.5 p-3 bg-muted/30 border border-dashed rounded-lg'>
|
||||
<Checkbox
|
||||
id="allow-notify"
|
||||
id='allow-notify'
|
||||
checked={formData.allowNotify}
|
||||
onCheckedChange={(checked) => setFormData(prev => ({ ...prev, allowNotify: checked === true }))}
|
||||
className="mt-0.5"
|
||||
onCheckedChange={(checked) =>
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
allowNotify: checked === true,
|
||||
}))
|
||||
}
|
||||
className='mt-0.5'
|
||||
/>
|
||||
<div className="grid gap-1">
|
||||
<div className='grid gap-1'>
|
||||
<label
|
||||
htmlFor="allow-notify"
|
||||
className="text-xs font-medium text-foreground cursor-pointer select-none leading-none"
|
||||
htmlFor='allow-notify'
|
||||
className='text-xs font-medium text-foreground cursor-pointer select-none leading-none'
|
||||
>
|
||||
允许触发异步通知推送
|
||||
</label>
|
||||
<p className="text-[10px] text-muted-foreground leading-normal">
|
||||
<p className='text-[10px] text-muted-foreground leading-normal'>
|
||||
勾选后,在当前后台任务顺利执行结束时,会关联派发多渠道通知推送。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 按钮变体 */}
|
||||
<div className="pt-2">
|
||||
<div className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">按钮样式对齐:</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button size="sm" className="h-8 text-xs shadow-none">
|
||||
<div className='pt-2'>
|
||||
<div className='text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2'>
|
||||
按钮样式对齐:
|
||||
</div>
|
||||
<div className='flex flex-wrap items-center gap-2'>
|
||||
<Button size='sm' className='h-8 text-xs shadow-none'>
|
||||
主要操作 (Primary)
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" className="h-8 text-xs shadow-none">
|
||||
<Button
|
||||
variant='secondary'
|
||||
size='sm'
|
||||
className='h-8 text-xs shadow-none'
|
||||
>
|
||||
次要操作 (Secondary)
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="h-8 border-dashed text-xs shadow-none">
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8 border-dashed text-xs shadow-none'
|
||||
>
|
||||
辅助线框 (Outline)
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" className="h-8 text-xs hover:bg-muted">
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
className='h-8 text-xs hover:bg-muted'
|
||||
>
|
||||
幽灵按钮 (Ghost)
|
||||
</Button>
|
||||
</div>
|
||||
@@ -103,38 +151,84 @@ export function ControlsTab() {
|
||||
</Card>
|
||||
|
||||
{/* 控件设计规范说明 */}
|
||||
<Card className="border-dashed shadow-none bg-muted/20">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-semibold flex items-center gap-1.5">
|
||||
<Code className="size-4 text-primary" />
|
||||
<Card className='border-dashed shadow-none bg-muted/20'>
|
||||
<CardHeader className='pb-3'>
|
||||
<CardTitle className='text-sm font-semibold flex items-center gap-1.5'>
|
||||
<Code className='size-4 text-primary' />
|
||||
表单设计规范
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 text-xs text-muted-foreground">
|
||||
<div className="space-y-2 leading-relaxed">
|
||||
<p className="font-semibold text-foreground text-[11px]">1. 统一控件高度与投影:</p>
|
||||
<CardContent className='space-y-4 text-xs text-muted-foreground'>
|
||||
<div className='space-y-2 leading-relaxed'>
|
||||
<p className='font-semibold text-foreground text-[11px]'>
|
||||
1. 统一控件高度与投影:
|
||||
</p>
|
||||
<p>
|
||||
输入框 (<code className="bg-muted px-1 py-0.5 rounded font-mono">Input</code>) 与下拉选择器 (<code className="bg-muted px-1 py-0.5 rounded font-mono">SelectTrigger</code>) 的高度应统一限制为小号高度 <code className="bg-muted px-1 py-0.5 rounded font-mono">h-8</code>,字体大小使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">text-xs</code>,并使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">shadow-none</code> 去除原生的重叠阴影。
|
||||
输入框 (
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
Input
|
||||
</code>
|
||||
) 与下拉选择器 (
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
SelectTrigger
|
||||
</code>
|
||||
) 的高度应统一限制为小号高度{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
h-8
|
||||
</code>
|
||||
,字体大小使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
text-xs
|
||||
</code>
|
||||
,并使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
shadow-none
|
||||
</code>{' '}
|
||||
去除原生的重叠阴影。
|
||||
</p>
|
||||
|
||||
<p className="font-semibold text-foreground text-[11px] pt-1">2. Checkbox 与文本的对齐:</p>
|
||||
<p className='font-semibold text-foreground text-[11px] pt-1'>
|
||||
2. Checkbox 与文本的对齐:
|
||||
</p>
|
||||
<p>
|
||||
Checkbox 应在左侧垂直偏上对齐,使用容器 <code className="bg-muted px-1 py-0.5 rounded font-mono">flex items-start gap-2.5</code> 排列。Checkbox 组件本身添加 <code className="bg-muted px-1 py-0.5 rounded font-mono">mt-0.5</code>,从而在多行描述文本的情况下依然保持良好的顶对齐,避免出现居中对齐导致的凌乱感。
|
||||
Checkbox 应在左侧垂直偏上对齐,使用容器{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
flex items-start gap-2.5
|
||||
</code>{' '}
|
||||
排列。Checkbox 组件本身添加{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
mt-0.5
|
||||
</code>
|
||||
,从而在多行描述文本的情况下依然保持良好的顶对齐,避免出现居中对齐导致的凌乱感。
|
||||
</p>
|
||||
|
||||
<p className="font-semibold text-foreground text-[11px] pt-1">3. 按钮使用策略:</p>
|
||||
<p className='font-semibold text-foreground text-[11px] pt-1'>
|
||||
3. 按钮使用策略:
|
||||
</p>
|
||||
<p>
|
||||
普通主表单及新增/保存按钮,一律使用默认 Primary 按钮或次要 <code className="bg-muted px-1 py-0.5 rounded font-mono">{'variant="secondary"'}</code> 按钮,小号高度统一采用 <code className="bg-muted px-1 py-0.5 rounded font-mono">h-8 text-xs</code>。线框按钮必须带有 <code className="bg-muted px-1 py-0.5 rounded font-mono">border-dashed shadow-none</code> 类。
|
||||
普通主表单及新增/保存按钮,一律使用默认 Primary 按钮或次要{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
{'variant="secondary"'}
|
||||
</code>{' '}
|
||||
按钮,小号高度统一采用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
h-8 text-xs
|
||||
</code>
|
||||
。线框按钮必须带有{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
border-dashed shadow-none
|
||||
</code>{' '}
|
||||
类。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-background/80 p-3 rounded border border-border/40 font-mono text-[10px] space-y-2 overflow-x-auto">
|
||||
<div className='bg-background/80 p-3 rounded border border-border/40 font-mono text-[10px] space-y-2 overflow-x-auto'>
|
||||
<div>{`// 1. Label 与 Input 对齐`}</div>
|
||||
<div>{`<div className="space-y-1.5">
|
||||
<Label htmlFor="id" className="text-xs font-medium text-foreground">标题</Label>
|
||||
<Input id="id" className="h-8 text-xs shadow-none" />
|
||||
</div>`}</div>
|
||||
<div className="pt-2">{`// 2. Checkbox 顶对齐`}</div>
|
||||
<div className='pt-2'>{`// 2. Checkbox 顶对齐`}</div>
|
||||
<div>{`<div className="flex items-start gap-2.5">
|
||||
<Checkbox id="c" className="mt-0.5" />
|
||||
<div className="grid gap-1">
|
||||
@@ -146,5 +240,5 @@ export function ControlsTab() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,61 +1,81 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {Code, Cpu, Database, HardDrive} from "lucide-react"
|
||||
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Progress} from "@/components/ui/progress"
|
||||
import * as React from 'react';
|
||||
import { Code, Cpu, Database, HardDrive } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
|
||||
export function DashboardTab() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className='space-y-6'>
|
||||
<div className='grid grid-cols-1 md:grid-cols-3 gap-4'>
|
||||
{/* CPU */}
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">容器 CPU 使用率</span>
|
||||
<Cpu className="size-4 text-primary" />
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2'>
|
||||
<span className='text-xs font-medium text-muted-foreground'>
|
||||
容器 CPU 使用率
|
||||
</span>
|
||||
<Cpu className='size-4 text-primary' />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<div className="text-2xl font-semibold tracking-tight">42.8 %</div>
|
||||
<Progress value={42.8} className="h-1.5" />
|
||||
<p className="text-[10px] text-muted-foreground flex items-center gap-1">
|
||||
<span className="size-1.5 rounded-full bg-emerald-500 inline-block animate-pulse" />
|
||||
<CardContent className='space-y-2'>
|
||||
<div className='text-2xl font-semibold tracking-tight'>42.8 %</div>
|
||||
<Progress value={42.8} className='h-1.5' />
|
||||
<p className='text-[10px] text-muted-foreground flex items-center gap-1'>
|
||||
<span className='size-1.5 rounded-full bg-emerald-500 inline-block animate-pulse' />
|
||||
容器运行正常,负载平稳
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Storage */}
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">存储已用容量</span>
|
||||
<HardDrive className="size-4 text-primary" />
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2'>
|
||||
<span className='text-xs font-medium text-muted-foreground'>
|
||||
存储已用容量
|
||||
</span>
|
||||
<HardDrive className='size-4 text-primary' />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<div className="text-2xl font-semibold tracking-tight">72.4 GB <span className="text-xs text-muted-foreground">/ 100 GB</span></div>
|
||||
<Progress value={72.4} className="h-1.5" />
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
<CardContent className='space-y-2'>
|
||||
<div className='text-2xl font-semibold tracking-tight'>
|
||||
72.4 GB{' '}
|
||||
<span className='text-xs text-muted-foreground'>/ 100 GB</span>
|
||||
</div>
|
||||
<Progress value={72.4} className='h-1.5' />
|
||||
<p className='text-[10px] text-muted-foreground'>
|
||||
数据已同步远端 S3 存储桶,支持自动过期
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* DB Overview */}
|
||||
<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">物理数据库</span>
|
||||
<Database className="size-4 text-primary" />
|
||||
<Card className='border-dashed shadow-none'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2'>
|
||||
<span className='text-xs font-medium text-muted-foreground'>
|
||||
物理数据库
|
||||
</span>
|
||||
<Database className='size-4 text-primary' />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<div className="text-2xl font-semibold tracking-tight">PostgreSQL <span className="text-xs font-normal text-muted-foreground">(v16.2)</span></div>
|
||||
<div className="flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<div>活跃连接: <span className="font-semibold text-foreground">12</span></div>
|
||||
<div>总表数量: <span className="font-semibold text-foreground">34</span></div>
|
||||
<CardContent className='space-y-2'>
|
||||
<div className='text-2xl font-semibold tracking-tight'>
|
||||
PostgreSQL{' '}
|
||||
<span className='text-xs font-normal text-muted-foreground'>
|
||||
(v16.2)
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
<div className='flex items-center gap-3 text-xs text-muted-foreground'>
|
||||
<div>
|
||||
活跃连接:{' '}
|
||||
<span className='font-semibold text-foreground'>12</span>
|
||||
</div>
|
||||
<div>
|
||||
总表数量:{' '}
|
||||
<span className='font-semibold text-foreground'>34</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className='text-[10px] text-muted-foreground'>
|
||||
链接池自动维护中,最大连接限制为 100
|
||||
</p>
|
||||
</CardContent>
|
||||
@@ -63,23 +83,53 @@ export function DashboardTab() {
|
||||
</div>
|
||||
|
||||
{/* 指标卡片规范与代码 */}
|
||||
<Card className="border-dashed shadow-none bg-muted/20">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-semibold flex items-center gap-1.5">
|
||||
<Code className="size-4 text-primary" />
|
||||
<Card className='border-dashed shadow-none bg-muted/20'>
|
||||
<CardHeader className='pb-3'>
|
||||
<CardTitle className='text-sm font-semibold flex items-center gap-1.5'>
|
||||
<Code className='size-4 text-primary' />
|
||||
指标卡片 & 仪表盘设计规范
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<ul className="list-disc pl-4 text-xs text-muted-foreground space-y-1.5">
|
||||
<li>指标卡片统一采用 <code className="bg-muted px-1 py-0.5 rounded font-mono">border-dashed shadow-none</code> 作为边框和投影。</li>
|
||||
<li>头部使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">flex flex-row items-center justify-between pb-2</code> 布局,左侧为标题小字,右侧为直接呈现的 Lucide 图标。</li>
|
||||
<li>数值强调使用且仅使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">text-2xl font-semibold tracking-tight</code> 展示。</li>
|
||||
<li>进度条使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">h-1.5</code> 细条高度,不喧宾夺主。</li>
|
||||
<li>底部的次要说明信息必须统一使用 <code className="bg-muted px-1 py-0.5 rounded font-mono">text-[10px] text-muted-foreground</code> 等辅助类。</li>
|
||||
<CardContent className='space-y-4'>
|
||||
<ul className='list-disc pl-4 text-xs text-muted-foreground space-y-1.5'>
|
||||
<li>
|
||||
指标卡片统一采用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
border-dashed shadow-none
|
||||
</code>{' '}
|
||||
作为边框和投影。
|
||||
</li>
|
||||
<li>
|
||||
头部使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
flex flex-row items-center justify-between pb-2
|
||||
</code>{' '}
|
||||
布局,左侧为标题小字,右侧为直接呈现的 Lucide 图标。
|
||||
</li>
|
||||
<li>
|
||||
数值强调使用且仅使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
text-2xl font-semibold tracking-tight
|
||||
</code>{' '}
|
||||
展示。
|
||||
</li>
|
||||
<li>
|
||||
进度条使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
h-1.5
|
||||
</code>{' '}
|
||||
细条高度,不喧宾夺主。
|
||||
</li>
|
||||
<li>
|
||||
底部的次要说明信息必须统一使用{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
text-[10px] text-muted-foreground
|
||||
</code>{' '}
|
||||
等辅助类。
|
||||
</li>
|
||||
</ul>
|
||||
<pre className="text-[11px] font-mono text-muted-foreground overflow-x-auto p-3 bg-background rounded border border-border/40 leading-relaxed">
|
||||
{`<Card className="border-dashed shadow-none">
|
||||
<pre className='text-[11px] font-mono text-muted-foreground overflow-x-auto p-3 bg-background rounded border border-border/40 leading-relaxed'>
|
||||
{`<Card className="border-dashed shadow-none">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">指标标题</span>
|
||||
<Cpu className="size-4 text-primary" />
|
||||
@@ -94,5 +144,5 @@ export function DashboardTab() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,92 +1,171 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {Code, Edit, ListFilter, Plus, Search, Trash2} from "lucide-react"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import * as React from 'react';
|
||||
import { Code, Edit, ListFilter, Plus, Search, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
|
||||
export function TableTab() {
|
||||
const mockTableData = [
|
||||
{ id: "TX-1002", name: "用户信息批量同步导出", type: "数据同步", status: "success", duration: "1.2s", time: "2026-06-15 14:22" },
|
||||
{ id: "TX-1003", name: "系统数据库每周自动备份归档", type: "数据库运维", status: "running", duration: "在执行中", time: "2026-06-15 15:00" },
|
||||
{ id: "TX-1004", name: "远端S3过期缓存对象自动清理任务", type: "磁盘清理", status: "failed", duration: "0.4s", time: "2026-06-15 10:05" },
|
||||
]
|
||||
{
|
||||
id: 'TX-1002',
|
||||
name: '用户信息批量同步导出',
|
||||
type: '数据同步',
|
||||
status: 'success',
|
||||
duration: '1.2s',
|
||||
time: '2026-06-15 14:22',
|
||||
},
|
||||
{
|
||||
id: 'TX-1003',
|
||||
name: '系统数据库每周自动备份归档',
|
||||
type: '数据库运维',
|
||||
status: 'running',
|
||||
duration: '在执行中',
|
||||
time: '2026-06-15 15:00',
|
||||
},
|
||||
{
|
||||
id: 'TX-1004',
|
||||
name: '远端S3过期缓存对象自动清理任务',
|
||||
type: '磁盘清理',
|
||||
status: 'failed',
|
||||
duration: '0.4s',
|
||||
time: '2026-06-15 10:05',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className='space-y-6'>
|
||||
{/* 表格控制工具栏 */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative w-64">
|
||||
<Search className="absolute left-2.5 top-2.5 size-3 text-muted-foreground" />
|
||||
<Input placeholder="输入任务名称搜索..." className="h-8 pl-8 text-xs w-full shadow-none border-dashed bg-background" />
|
||||
<div className='flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='relative w-64'>
|
||||
<Search className='absolute left-2.5 top-2.5 size-3 text-muted-foreground' />
|
||||
<Input
|
||||
placeholder='输入任务名称搜索...'
|
||||
className='h-8 pl-8 text-xs w-full shadow-none border-dashed bg-background'
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" className="h-8 border-dashed text-xs shadow-none">
|
||||
<ListFilter className="size-3 mr-1" />
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-8 border-dashed text-xs shadow-none'
|
||||
>
|
||||
<ListFilter className='size-3 mr-1' />
|
||||
过滤
|
||||
</Button>
|
||||
</div>
|
||||
<Button size="sm" className="h-8 text-xs shadow-none">
|
||||
<Plus className="size-3.5 mr-1" />
|
||||
<Button size='sm' className='h-8 text-xs shadow-none'>
|
||||
<Plus className='size-3.5 mr-1' />
|
||||
新建任务
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 数据表格本身 */}
|
||||
<div className="border border-dashed shadow-none rounded-lg overflow-hidden bg-background">
|
||||
<Table className="w-full caption-bottom text-sm min-w-full">
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow className="border-dashed hover:bg-transparent">
|
||||
<TableHead className="w-[100px] text-xs font-semibold">任务编号</TableHead>
|
||||
<TableHead className="text-xs font-semibold">执行任务名称</TableHead>
|
||||
<TableHead className="w-[120px] text-xs font-semibold">任务类型</TableHead>
|
||||
<TableHead className="w-[100px] text-xs font-semibold">状态</TableHead>
|
||||
<TableHead className="w-[100px] text-xs font-semibold">执行耗时</TableHead>
|
||||
<TableHead className="w-[150px] text-xs font-semibold">触发时间</TableHead>
|
||||
<TableHead className="w-[80px] text-xs font-semibold text-right">操作</TableHead>
|
||||
<div className='border border-dashed shadow-none rounded-lg overflow-hidden bg-background'>
|
||||
<Table className='w-full caption-bottom text-sm min-w-full'>
|
||||
<TableHeader className='bg-muted/40'>
|
||||
<TableRow className='border-dashed hover:bg-transparent'>
|
||||
<TableHead className='w-[100px] text-xs font-semibold'>
|
||||
任务编号
|
||||
</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>
|
||||
执行任务名称
|
||||
</TableHead>
|
||||
<TableHead className='w-[120px] text-xs font-semibold'>
|
||||
任务类型
|
||||
</TableHead>
|
||||
<TableHead className='w-[100px] text-xs font-semibold'>
|
||||
状态
|
||||
</TableHead>
|
||||
<TableHead className='w-[100px] text-xs font-semibold'>
|
||||
执行耗时
|
||||
</TableHead>
|
||||
<TableHead className='w-[150px] text-xs font-semibold'>
|
||||
触发时间
|
||||
</TableHead>
|
||||
<TableHead className='w-[80px] text-xs font-semibold text-right'>
|
||||
操作
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{mockTableData.map((row) => (
|
||||
<TableRow key={row.id} className="border-dashed hover:bg-muted/10 transition-colors">
|
||||
<TableCell className="font-mono text-xs font-semibold">{row.id}</TableCell>
|
||||
<TableCell className="text-xs font-medium text-foreground">{row.name}</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">{row.type}</TableCell>
|
||||
<TableRow
|
||||
key={row.id}
|
||||
className='border-dashed hover:bg-muted/10 transition-colors'
|
||||
>
|
||||
<TableCell className='font-mono text-xs font-semibold'>
|
||||
{row.id}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs font-medium text-foreground'>
|
||||
{row.name}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-muted-foreground'>
|
||||
{row.type}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{row.status === "success" && (
|
||||
<Badge variant="outline" className="text-[10px] bg-emerald-500/10 border-emerald-500/20 text-emerald-600 rounded-full py-0 px-2 font-medium">
|
||||
<span className="size-1 bg-emerald-500 rounded-full mr-1.5 shrink-0" />
|
||||
{row.status === 'success' && (
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='text-[10px] bg-emerald-500/10 border-emerald-500/20 text-emerald-600 rounded-full py-0 px-2 font-medium'
|
||||
>
|
||||
<span className='size-1 bg-emerald-500 rounded-full mr-1.5 shrink-0' />
|
||||
成功
|
||||
</Badge>
|
||||
)}
|
||||
{row.status === "running" && (
|
||||
<Badge variant="outline" className="text-[10px] bg-blue-500/10 border-blue-500/20 text-blue-600 rounded-full py-0 px-2 font-medium">
|
||||
<span className="size-1 bg-blue-500 rounded-full mr-1.5 shrink-0 animate-pulse" />
|
||||
{row.status === 'running' && (
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='text-[10px] bg-blue-500/10 border-blue-500/20 text-blue-600 rounded-full py-0 px-2 font-medium'
|
||||
>
|
||||
<span className='size-1 bg-blue-500 rounded-full mr-1.5 shrink-0 animate-pulse' />
|
||||
运行中
|
||||
</Badge>
|
||||
)}
|
||||
{row.status === "failed" && (
|
||||
<Badge variant="outline" className="text-[10px] bg-destructive/10 border-destructive/20 text-destructive rounded-full py-0 px-2 font-medium">
|
||||
<span className="size-1 bg-destructive rounded-full mr-1.5 shrink-0" />
|
||||
{row.status === 'failed' && (
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='text-[10px] bg-destructive/10 border-destructive/20 text-destructive rounded-full py-0 px-2 font-medium'
|
||||
>
|
||||
<span className='size-1 bg-destructive rounded-full mr-1.5 shrink-0' />
|
||||
失败
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground font-mono">{row.duration}</TableCell>
|
||||
<TableCell className="text-xs text-muted-foreground">{row.time}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex items-center justify-end gap-1.5">
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6 rounded hover:bg-muted text-muted-foreground">
|
||||
<Edit className="size-3" />
|
||||
<TableCell className='text-xs text-muted-foreground font-mono'>
|
||||
{row.duration}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs text-muted-foreground'>
|
||||
{row.time}
|
||||
</TableCell>
|
||||
<TableCell className='text-right'>
|
||||
<div className='flex items-center justify-end gap-1.5'>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='h-6 w-6 rounded hover:bg-muted text-muted-foreground'
|
||||
>
|
||||
<Edit className='size-3' />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" className="h-6 w-6 rounded hover:bg-destructive/10 text-destructive">
|
||||
<Trash2 className="size-3" />
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='h-6 w-6 rounded hover:bg-destructive/10 text-destructive'
|
||||
>
|
||||
<Trash2 className='size-3' />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
@@ -97,23 +176,62 @@ export function TableTab() {
|
||||
</div>
|
||||
|
||||
{/* 表格规范指引 */}
|
||||
<Card className="border-dashed shadow-none bg-muted/20">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm font-semibold flex items-center gap-1.5">
|
||||
<Code className="size-4 text-primary" />
|
||||
<Card className='border-dashed shadow-none bg-muted/20'>
|
||||
<CardHeader className='pb-3'>
|
||||
<CardTitle className='text-sm font-semibold flex items-center gap-1.5'>
|
||||
<Code className='size-4 text-primary' />
|
||||
表格设计规范与代码模板
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<ul className="list-disc pl-4 text-xs text-muted-foreground space-y-1.5">
|
||||
<li>表格容器必须统一使用带有虚线边框的容器,即类名:<code className="bg-muted px-1 py-0.5 rounded font-mono">border border-dashed shadow-none rounded-lg overflow-hidden bg-background</code>。</li>
|
||||
<li>表头背景设为 <code className="bg-muted px-1 py-0.5 rounded font-mono">bg-muted/40</code>。表头表项字号统一为小字粗体 <code className="bg-muted px-1 py-0.5 rounded font-mono">text-xs font-semibold</code>。</li>
|
||||
<li>单元格行与列之间使用虚线分割(<code className="bg-muted px-1 py-0.5 rounded font-mono">border-dashed</code>)。表格行悬浮交互采用温和过渡色 <code className="bg-muted px-1 py-0.5 rounded font-mono">hover:bg-muted/10 transition-colors</code>。</li>
|
||||
<li>编码、主键或唯一 ID 类字段一律采用等宽字体呈现:<code className="bg-muted px-1 py-0.5 rounded font-mono">font-mono text-xs</code>。</li>
|
||||
<li>状态标签(Badge)尽量圆角化(<code className="bg-muted px-1 py-0.5 rounded font-mono">rounded-full py-0 px-2</code>),并以浅背景配以各自对应的图标圆点,以实现现代、高对比度的视觉质感。</li>
|
||||
<CardContent className='space-y-4'>
|
||||
<ul className='list-disc pl-4 text-xs text-muted-foreground space-y-1.5'>
|
||||
<li>
|
||||
表格容器必须统一使用带有虚线边框的容器,即类名:
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
border border-dashed shadow-none rounded-lg overflow-hidden
|
||||
bg-background
|
||||
</code>
|
||||
。
|
||||
</li>
|
||||
<li>
|
||||
表头背景设为{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
bg-muted/40
|
||||
</code>
|
||||
。表头表项字号统一为小字粗体{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
text-xs font-semibold
|
||||
</code>
|
||||
。
|
||||
</li>
|
||||
<li>
|
||||
单元格行与列之间使用虚线分割(
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
border-dashed
|
||||
</code>
|
||||
)。表格行悬浮交互采用温和过渡色{' '}
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
hover:bg-muted/10 transition-colors
|
||||
</code>
|
||||
。
|
||||
</li>
|
||||
<li>
|
||||
编码、主键或唯一 ID 类字段一律采用等宽字体呈现:
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
font-mono text-xs
|
||||
</code>
|
||||
。
|
||||
</li>
|
||||
<li>
|
||||
状态标签(Badge)尽量圆角化(
|
||||
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
|
||||
rounded-full py-0 px-2
|
||||
</code>
|
||||
),并以浅背景配以各自对应的图标圆点,以实现现代、高对比度的视觉质感。
|
||||
</li>
|
||||
</ul>
|
||||
<pre className="text-[11px] font-mono text-muted-foreground overflow-x-auto p-3 bg-background rounded border border-border/40 leading-relaxed">
|
||||
{`<div className="border border-dashed shadow-none rounded-lg overflow-hidden bg-background">
|
||||
<pre className='text-[11px] font-mono text-muted-foreground overflow-x-auto p-3 bg-background rounded border border-border/40 leading-relaxed'>
|
||||
{`<div className="border border-dashed shadow-none rounded-lg overflow-hidden bg-background">
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow className="border-dashed hover:bg-transparent">
|
||||
@@ -138,5 +256,5 @@ export function TableTab() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query"
|
||||
import {AnimatePresence, motion} from "motion/react"
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import {
|
||||
Download,
|
||||
Eye,
|
||||
@@ -16,14 +16,21 @@ import {
|
||||
Trash2,
|
||||
Upload,
|
||||
X,
|
||||
} from "lucide-react"
|
||||
import {toast} from "sonner"
|
||||
} from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Checkbox} from "@/components/ui/checkbox"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -33,207 +40,236 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import {Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle} from "@/components/ui/sheet"
|
||||
import {FileImagePreview} from "@/components/common/file-image-preview"
|
||||
import services, {formatFileSize} from "@/lib/services"
|
||||
import type {Upload as UploadRecord} from "@/lib/services/upload/types"
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet';
|
||||
import { FileImagePreview } from '@/components/common/file-image-preview';
|
||||
import services, { formatFileSize } from '@/lib/services';
|
||||
import type { Upload as UploadRecord } from '@/lib/services/upload/types';
|
||||
|
||||
/* ─── 工具函数 ─────────────────────────────────────────── */
|
||||
|
||||
function getFileIcon(mimeType: string, className = "size-8") {
|
||||
if (mimeType.startsWith("image/")) return <FileImage className={`${className} text-blue-400`} />
|
||||
if (mimeType.startsWith("video/")) return <FileVideo className={`${className} text-purple-400`} />
|
||||
if (mimeType.startsWith("audio/")) return <FileAudio className={`${className} text-green-400`} />
|
||||
if (mimeType.includes("zip") || mimeType.includes("tar") || mimeType.includes("gzip"))
|
||||
return <FileArchive className={`${className} text-amber-400`} />
|
||||
return <FileText className={`${className} text-slate-400`} />
|
||||
function getFileIcon(mimeType: string, className = 'size-8') {
|
||||
if (mimeType.startsWith('image/'))
|
||||
return <FileImage className={`${className} text-blue-400`} />;
|
||||
if (mimeType.startsWith('video/'))
|
||||
return <FileVideo className={`${className} text-purple-400`} />;
|
||||
if (mimeType.startsWith('audio/'))
|
||||
return <FileAudio className={`${className} text-green-400`} />;
|
||||
if (
|
||||
mimeType.includes('zip') ||
|
||||
mimeType.includes('tar') ||
|
||||
mimeType.includes('gzip')
|
||||
)
|
||||
return <FileArchive className={`${className} text-amber-400`} />;
|
||||
return <FileText className={`${className} text-slate-400`} />;
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string) {
|
||||
return new Date(dateStr).toLocaleString("zh-CN", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
return new Date(dateStr).toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
export function FileList() {
|
||||
const queryClient = useQueryClient()
|
||||
const [keyword, setKeyword] = React.useState("")
|
||||
const [debouncedKeyword, setDebouncedKeyword] = React.useState("")
|
||||
const [selectedIds, setSelectedIds] = React.useState<Set<string>>(new Set())
|
||||
const [deleteTarget, setDeleteTarget] = React.useState<UploadRecord | null>(null)
|
||||
const [detailTarget, setDetailTarget] = React.useState<UploadRecord | null>(null)
|
||||
const [page, setPage] = React.useState(1)
|
||||
const pageSize = 15 // 表格视图下 15 条更紧凑
|
||||
const queryClient = useQueryClient();
|
||||
const [keyword, setKeyword] = React.useState('');
|
||||
const [debouncedKeyword, setDebouncedKeyword] = React.useState('');
|
||||
const [selectedIds, setSelectedIds] = React.useState<Set<string>>(new Set());
|
||||
const [deleteTarget, setDeleteTarget] = React.useState<UploadRecord | null>(
|
||||
null,
|
||||
);
|
||||
const [detailTarget, setDetailTarget] = React.useState<UploadRecord | null>(
|
||||
null,
|
||||
);
|
||||
const [page, setPage] = React.useState(1);
|
||||
const pageSize = 15; // 表格视图下 15 条更紧凑
|
||||
|
||||
// 搜索防抖
|
||||
React.useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedKeyword(keyword)
|
||||
setPage(1)
|
||||
}, 400)
|
||||
return () => clearTimeout(timer)
|
||||
}, [keyword])
|
||||
setDebouncedKeyword(keyword);
|
||||
setPage(1);
|
||||
}, 400);
|
||||
return () => clearTimeout(timer);
|
||||
}, [keyword]);
|
||||
|
||||
// 文件列表查询
|
||||
const listQuery = useQuery({
|
||||
queryKey: ["files", "all", page, pageSize, debouncedKeyword],
|
||||
queryFn: () => services.adminUpload.listUploads(page, pageSize, debouncedKeyword || undefined),
|
||||
})
|
||||
queryKey: ['files', 'all', page, pageSize, debouncedKeyword],
|
||||
queryFn: () =>
|
||||
services.adminUpload.listUploads(
|
||||
page,
|
||||
pageSize,
|
||||
debouncedKeyword || undefined,
|
||||
),
|
||||
});
|
||||
|
||||
const storageDriverQuery = useQuery({
|
||||
queryKey: ["admin", "storage-config", "driver"],
|
||||
queryKey: ['admin', 'storage-config', 'driver'],
|
||||
queryFn: async () => {
|
||||
const record = await services.adminSystemConfig.getSystemConfig("storage_config")
|
||||
const cfg = JSON.parse(record.value) as {driver?: string}
|
||||
return cfg.driver ?? "local"
|
||||
const record =
|
||||
await services.adminSystemConfig.getSystemConfig('storage_config');
|
||||
const cfg = JSON.parse(record.value) as { driver?: string };
|
||||
return cfg.driver ?? 'local';
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
const files = listQuery.data?.items ?? []
|
||||
const total = listQuery.data?.total ?? 0
|
||||
const totalPages = Math.ceil(total / pageSize)
|
||||
const files = listQuery.data?.items ?? [];
|
||||
const total = listQuery.data?.total ?? 0;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
const isAllSelected = files.length > 0 && files.every((f) => selectedIds.has(f.id))
|
||||
const isSomeSelected = files.length > 0 && files.some((f) => selectedIds.has(f.id)) && !isAllSelected
|
||||
const isAllSelected =
|
||||
files.length > 0 && files.every((f) => selectedIds.has(f.id));
|
||||
const isSomeSelected =
|
||||
files.length > 0 &&
|
||||
files.some((f) => selectedIds.has(f.id)) &&
|
||||
!isAllSelected;
|
||||
|
||||
const handleSelectAll = () => {
|
||||
if (isAllSelected) {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
files.forEach((f) => next.delete(f.id))
|
||||
return next
|
||||
})
|
||||
const next = new Set(prev);
|
||||
files.forEach((f) => next.delete(f.id));
|
||||
return next;
|
||||
});
|
||||
} else {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
files.forEach((f) => next.add(f.id))
|
||||
return next
|
||||
})
|
||||
const next = new Set(prev);
|
||||
files.forEach((f) => next.add(f.id));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 删除单文件
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: (id: string) => services.adminUpload.deleteFile(id),
|
||||
onSuccess: () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["files", "my"] })
|
||||
void queryClient.invalidateQueries({ queryKey: ["files", "stats"] })
|
||||
toast.success("文件已删除")
|
||||
setDeleteTarget(null)
|
||||
void queryClient.invalidateQueries({ queryKey: ['files', 'my'] });
|
||||
void queryClient.invalidateQueries({ queryKey: ['files', 'stats'] });
|
||||
toast.success('文件已删除');
|
||||
setDeleteTarget(null);
|
||||
},
|
||||
onError: (err: Error) => toast.error(err.message || "删除失败"),
|
||||
})
|
||||
onError: (err: Error) => toast.error(err.message || '删除失败'),
|
||||
});
|
||||
|
||||
// 批量 ZIP 下载
|
||||
const batchDownloadMutation = useMutation({
|
||||
mutationFn: (ids: string[]) => services.adminUpload.batchDownload(ids),
|
||||
onSuccess: (blob) => {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = "batch_download.zip"
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
toast.success("批量下载已开始")
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'batch_download.zip';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
toast.success('批量下载已开始');
|
||||
},
|
||||
onError: () => toast.error("批量下载失败"),
|
||||
})
|
||||
onError: () => toast.error('批量下载失败'),
|
||||
});
|
||||
|
||||
const toggleSelect = (id: string) => {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev)
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) {
|
||||
next.delete(id)
|
||||
next.delete(id);
|
||||
} else {
|
||||
next.add(id)
|
||||
next.add(id);
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const clearSelection = () => setSelectedIds(new Set())
|
||||
const clearSelection = () => setSelectedIds(new Set());
|
||||
|
||||
const selectAll = () => setSelectedIds(new Set(files.map((f) => f.id)))
|
||||
const selectAll = () => setSelectedIds(new Set(files.map((f) => f.id)));
|
||||
|
||||
const handleDownload = (file: UploadRecord) => {
|
||||
const url = services.adminUpload.getDownloadUrl(file.id)
|
||||
const a = document.createElement("a")
|
||||
a.href = url
|
||||
a.download = file.file_name
|
||||
a.click()
|
||||
}
|
||||
const url = services.adminUpload.getDownloadUrl(file.id);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = file.file_name;
|
||||
a.click();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className='space-y-6'>
|
||||
{/* 搜索栏 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='relative flex-1 max-w-sm'>
|
||||
<Search className='absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground' />
|
||||
<Input
|
||||
placeholder="搜索文件名..."
|
||||
className="pl-8 h-8 text-xs border-dashed rounded-lg focus-visible:ring-0"
|
||||
placeholder='搜索文件名...'
|
||||
className='pl-8 h-8 text-xs border-dashed rounded-lg focus-visible:ring-0'
|
||||
value={keyword}
|
||||
onChange={(e) => setKeyword(e.target.value)}
|
||||
/>
|
||||
{keyword && (
|
||||
<button
|
||||
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setKeyword("")}
|
||||
className='absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground'
|
||||
onClick={() => setKeyword('')}
|
||||
>
|
||||
<X className="size-3" />
|
||||
<X className='size-3' />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{files.length > 0 && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-xs h-8 border border-dashed text-muted-foreground"
|
||||
onClick={selectedIds.size === files.length ? clearSelection : selectAll}
|
||||
size='sm'
|
||||
variant='ghost'
|
||||
className='text-xs h-8 border border-dashed text-muted-foreground'
|
||||
onClick={
|
||||
selectedIds.size === files.length ? clearSelection : selectAll
|
||||
}
|
||||
>
|
||||
{selectedIds.size === files.length ? "取消全选" : "全选本页"}
|
||||
{selectedIds.size === files.length ? '取消全选' : '全选本页'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 打包下载等批量操作 */}
|
||||
<div className="flex items-center gap-2 ml-auto shrink-0">
|
||||
<div className='flex items-center gap-2 ml-auto shrink-0'>
|
||||
<AnimatePresence>
|
||||
{selectedIds.size > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.9 }}
|
||||
className="flex items-center gap-2"
|
||||
className='flex items-center gap-2'
|
||||
>
|
||||
<Badge variant="secondary" className="text-xs px-2.5">
|
||||
<Badge variant='secondary' className='text-xs px-2.5'>
|
||||
已选 {selectedIds.size} 个
|
||||
</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="border-dashed text-xs h-8"
|
||||
size='sm'
|
||||
variant='outline'
|
||||
className='border-dashed text-xs h-8'
|
||||
onClick={() => batchDownloadMutation.mutate([...selectedIds])}
|
||||
disabled={batchDownloadMutation.isPending}
|
||||
>
|
||||
{batchDownloadMutation.isPending ? (
|
||||
<Loader2 className="size-3.5 mr-1 animate-spin" />
|
||||
<Loader2 className='size-3.5 mr-1 animate-spin' />
|
||||
) : (
|
||||
<FileArchive className="size-3.5 mr-1" />
|
||||
<FileArchive className='size-3.5 mr-1' />
|
||||
)}
|
||||
打包下载
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-xs h-8 px-2"
|
||||
size='sm'
|
||||
variant='ghost'
|
||||
className='text-xs h-8 px-2'
|
||||
onClick={clearSelection}
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
<X className='size-3.5' />
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
@@ -241,131 +277,152 @@ export function FileList() {
|
||||
</div>
|
||||
|
||||
{total > 0 && (
|
||||
<span className="text-xs text-muted-foreground shrink-0">共 {total} 个文件</span>
|
||||
<span className='text-xs text-muted-foreground shrink-0'>
|
||||
共 {total} 个文件
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 文件列表 Table */}
|
||||
{listQuery.isPending ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="size-6 animate-spin text-sky-500" />
|
||||
<div className='flex items-center justify-center py-20'>
|
||||
<Loader2 className='size-6 animate-spin text-sky-500' />
|
||||
</div>
|
||||
) : files.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-20 gap-4 text-muted-foreground">
|
||||
<Upload className="size-12 text-muted-foreground/30" />
|
||||
<p className="text-sm">
|
||||
{debouncedKeyword ? "没有匹配的文件" : "您还没有上传任何文件"}
|
||||
<div className='flex flex-col items-center justify-center py-20 gap-4 text-muted-foreground'>
|
||||
<Upload className='size-12 text-muted-foreground/30' />
|
||||
<p className='text-sm'>
|
||||
{debouncedKeyword ? '没有匹配的文件' : '您还没有上传任何文件'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-dashed rounded-xl bg-card overflow-hidden">
|
||||
<div className='border border-dashed rounded-xl bg-card overflow-hidden'>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent border-dashed">
|
||||
<TableHead className="w-[50px] pl-4 py-3">
|
||||
<TableRow className='hover:bg-transparent border-dashed'>
|
||||
<TableHead className='w-[50px] pl-4 py-3'>
|
||||
<Checkbox
|
||||
checked={isAllSelected || (isSomeSelected ? "indeterminate" : false)}
|
||||
checked={
|
||||
isAllSelected ||
|
||||
(isSomeSelected ? 'indeterminate' : false)
|
||||
}
|
||||
onCheckedChange={handleSelectAll}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="w-[80px] py-3">预览</TableHead>
|
||||
<TableHead className="w-[180px] py-3">ID</TableHead>
|
||||
<TableHead className="py-3">文件名</TableHead>
|
||||
<TableHead className="max-w-[200px] truncate py-3">路径</TableHead>
|
||||
<TableHead className="w-[100px] py-3">业务类别</TableHead>
|
||||
<TableHead className="w-[125px] py-3">MIME类型</TableHead>
|
||||
<TableHead className="w-[100px] py-3">大小</TableHead>
|
||||
<TableHead className="w-[150px] py-3">上传时间</TableHead>
|
||||
<TableHead className="w-[120px] text-right pr-4 py-3">操作</TableHead>
|
||||
<TableHead className='w-[80px] py-3'>预览</TableHead>
|
||||
<TableHead className='w-[180px] py-3'>ID</TableHead>
|
||||
<TableHead className='py-3'>文件名</TableHead>
|
||||
<TableHead className='max-w-[200px] truncate py-3'>
|
||||
路径
|
||||
</TableHead>
|
||||
<TableHead className='w-[100px] py-3'>业务类别</TableHead>
|
||||
<TableHead className='w-[125px] py-3'>MIME类型</TableHead>
|
||||
<TableHead className='w-[100px] py-3'>大小</TableHead>
|
||||
<TableHead className='w-[150px] py-3'>上传时间</TableHead>
|
||||
<TableHead className='w-[120px] text-right pr-4 py-3'>
|
||||
操作
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{files.map((file) => {
|
||||
const isSelected = selectedIds.has(file.id)
|
||||
const isSelected = selectedIds.has(file.id);
|
||||
return (
|
||||
<TableRow
|
||||
key={file.id}
|
||||
className={`border-dashed hover:bg-muted/30 transition-colors ${
|
||||
isSelected ? "bg-sky-500/5 hover:bg-sky-500/10" : ""
|
||||
isSelected ? 'bg-sky-500/5 hover:bg-sky-500/10' : ''
|
||||
}`}
|
||||
>
|
||||
<TableCell className="pl-4 py-3">
|
||||
<TableCell className='pl-4 py-3'>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => toggleSelect(file.id)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="py-3">
|
||||
<div className="flex items-center justify-center size-9 rounded-lg bg-muted/40 overflow-hidden border">
|
||||
{file.mime_type.startsWith("image/") ? (
|
||||
<TableCell className='py-3'>
|
||||
<div className='flex items-center justify-center size-9 rounded-lg bg-muted/40 overflow-hidden border'>
|
||||
{file.mime_type.startsWith('image/') ? (
|
||||
<FileImagePreview
|
||||
fileId={file.id}
|
||||
alt={file.file_name}
|
||||
quality="low"
|
||||
variant="compact"
|
||||
className="size-full object-cover"
|
||||
quality='low'
|
||||
variant='compact'
|
||||
className='size-full object-cover'
|
||||
/>
|
||||
) : (
|
||||
getFileIcon(file.mime_type, "size-4.5")
|
||||
getFileIcon(file.mime_type, 'size-4.5')
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="py-3 font-mono text-[11px] text-muted-foreground select-all">
|
||||
<TableCell className='py-3 font-mono text-[11px] text-muted-foreground select-all'>
|
||||
{file.id}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 font-medium max-w-[180px] truncate text-xs" title={file.file_name}>
|
||||
<TableCell
|
||||
className='py-3 font-medium max-w-[180px] truncate text-xs'
|
||||
title={file.file_name}
|
||||
>
|
||||
{file.file_name}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 font-mono text-[11px] max-w-[200px] truncate text-muted-foreground select-all" title={file.file_path}>
|
||||
<TableCell
|
||||
className='py-3 font-mono text-[11px] max-w-[200px] truncate text-muted-foreground select-all'
|
||||
title={file.file_path}
|
||||
>
|
||||
{file.file_path}
|
||||
</TableCell>
|
||||
<TableCell className="py-3">
|
||||
<Badge variant="secondary" className="text-[10px] py-0 px-1.5 font-normal rounded-md">
|
||||
<TableCell className='py-3'>
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='text-[10px] py-0 px-1.5 font-normal rounded-md'
|
||||
>
|
||||
{file.type}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-[11px] text-muted-foreground truncate max-w-[125px]" title={file.mime_type}>
|
||||
<TableCell
|
||||
className='py-3 text-[11px] text-muted-foreground truncate max-w-[125px]'
|
||||
title={file.mime_type}
|
||||
>
|
||||
{file.mime_type}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-xs">
|
||||
<TableCell className='py-3 text-xs'>
|
||||
{formatFileSize(file.file_size)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-xs text-muted-foreground">
|
||||
<TableCell className='py-3 text-xs text-muted-foreground'>
|
||||
{formatDate(file.created_at)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-right pr-4">
|
||||
<div className="flex items-center justify-end gap-0.5">
|
||||
<TableCell className='py-3 text-right pr-4'>
|
||||
<div className='flex items-center justify-end gap-0.5'>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground"
|
||||
title="查看详情"
|
||||
size='icon'
|
||||
variant='ghost'
|
||||
className='h-7 w-7 rounded-md hover:bg-muted text-muted-foreground hover:text-foreground'
|
||||
title='查看详情'
|
||||
onClick={() => setDetailTarget(file)}
|
||||
>
|
||||
<Eye className="size-3.5" />
|
||||
<Eye className='size-3.5' />
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 rounded-md hover:bg-muted"
|
||||
title="下载"
|
||||
size='icon'
|
||||
variant='ghost'
|
||||
className='h-7 w-7 rounded-md hover:bg-muted'
|
||||
title='下载'
|
||||
onClick={() => handleDownload(file)}
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
<Download className='size-3.5' />
|
||||
</Button>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive"
|
||||
title="删除"
|
||||
size='icon'
|
||||
variant='ghost'
|
||||
className='h-7 w-7 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive'
|
||||
title='删除'
|
||||
onClick={() => setDeleteTarget(file)}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
<Trash2 className='size-3.5' />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
@@ -374,23 +431,23 @@ export function FileList() {
|
||||
|
||||
{/* 分页 */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2">
|
||||
<div className='flex items-center justify-center gap-2 pt-2'>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="border-dashed text-xs h-7 px-3"
|
||||
size='sm'
|
||||
variant='outline'
|
||||
className='border-dashed text-xs h-7 px-3'
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
<span className='text-xs text-muted-foreground'>
|
||||
{page} / {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="border-dashed text-xs h-7 px-3"
|
||||
size='sm'
|
||||
variant='outline'
|
||||
className='border-dashed text-xs h-7 px-3'
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
@@ -400,29 +457,34 @@ export function FileList() {
|
||||
)}
|
||||
|
||||
{/* 详情查看 Sheet */}
|
||||
<Sheet open={!!detailTarget} onOpenChange={(open) => !open && setDetailTarget(null)}>
|
||||
<SheetContent className="w-full sm:max-w-md overflow-y-auto p-6">
|
||||
<SheetHeader className="border-b pb-4 px-0">
|
||||
<Sheet
|
||||
open={!!detailTarget}
|
||||
onOpenChange={(open) => !open && setDetailTarget(null)}
|
||||
>
|
||||
<SheetContent className='w-full sm:max-w-md overflow-y-auto p-6'>
|
||||
<SheetHeader className='border-b pb-4 px-0'>
|
||||
<SheetTitle>文件详情</SheetTitle>
|
||||
<SheetDescription>查看文件的完整元数据与配置属性。</SheetDescription>
|
||||
<SheetDescription>
|
||||
查看文件的完整元数据与配置属性。
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
{detailTarget && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className='space-y-6 py-4'>
|
||||
{/* 大图/格式预览 */}
|
||||
<div className="flex items-center justify-center h-48 rounded-xl bg-muted/30 border border-dashed overflow-hidden p-2">
|
||||
{detailTarget.mime_type.startsWith("image/") ? (
|
||||
<div className='flex items-center justify-center h-48 rounded-xl bg-muted/30 border border-dashed overflow-hidden p-2'>
|
||||
{detailTarget.mime_type.startsWith('image/') ? (
|
||||
<FileImagePreview
|
||||
fileId={detailTarget.id}
|
||||
alt={detailTarget.file_name}
|
||||
quality="low"
|
||||
className="max-h-full max-w-full object-contain rounded-lg shadow-sm"
|
||||
fallbackClassName="min-h-32 w-full rounded-lg"
|
||||
quality='low'
|
||||
className='max-h-full max-w-full object-contain rounded-lg shadow-sm'
|
||||
fallbackClassName='min-h-32 w-full rounded-lg'
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
{getFileIcon(detailTarget.mime_type, "size-14")}
|
||||
<span className="text-xs font-medium text-muted-foreground uppercase">
|
||||
<div className='flex flex-col items-center gap-3'>
|
||||
{getFileIcon(detailTarget.mime_type, 'size-14')}
|
||||
<span className='text-xs font-medium text-muted-foreground uppercase'>
|
||||
{detailTarget.extension} 文件
|
||||
</span>
|
||||
</div>
|
||||
@@ -430,76 +492,123 @@ export function FileList() {
|
||||
</div>
|
||||
|
||||
{/* 元数据列表 */}
|
||||
<div className="space-y-4 text-xs">
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">文件 ID</span>
|
||||
<span className="col-span-2 font-mono break-all select-all text-foreground/90">{detailTarget.id}</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">文件名</span>
|
||||
<span className="col-span-2 break-all font-medium text-foreground/90">{detailTarget.file_name}</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">存储路径</span>
|
||||
<span className="col-span-2 font-mono break-all select-all text-foreground/90">{detailTarget.file_path}</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">大小</span>
|
||||
<span className="col-span-2 text-foreground/90">
|
||||
{formatFileSize(detailTarget.file_size)} ({detailTarget.file_size.toLocaleString()} 字节)
|
||||
<div className='space-y-4 text-xs'>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
文件 ID
|
||||
</span>
|
||||
<span className='col-span-2 font-mono break-all select-all text-foreground/90'>
|
||||
{detailTarget.id}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">MIME 类型</span>
|
||||
<span className="col-span-2 font-mono text-foreground/90">{detailTarget.mime_type}</span>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
文件名
|
||||
</span>
|
||||
<span className='col-span-2 break-all font-medium text-foreground/90'>
|
||||
{detailTarget.file_name}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">文件后缀</span>
|
||||
<span className="col-span-2 font-mono text-foreground/90">{detailTarget.extension}</span>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
存储路径
|
||||
</span>
|
||||
<span className='col-span-2 font-mono break-all select-all text-foreground/90'>
|
||||
{detailTarget.file_path}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">Hash (SHA-256)</span>
|
||||
<span className="col-span-2 font-mono break-all select-all text-foreground/90">{detailTarget.hash}</span>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
大小
|
||||
</span>
|
||||
<span className='col-span-2 text-foreground/90'>
|
||||
{formatFileSize(detailTarget.file_size)} (
|
||||
{detailTarget.file_size.toLocaleString()} 字节)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">业务类型</span>
|
||||
<span className="col-span-2">
|
||||
<Badge variant="secondary" className="text-[10px] py-0 px-2 rounded-md font-normal">
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
MIME 类型
|
||||
</span>
|
||||
<span className='col-span-2 font-mono text-foreground/90'>
|
||||
{detailTarget.mime_type}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
文件后缀
|
||||
</span>
|
||||
<span className='col-span-2 font-mono text-foreground/90'>
|
||||
{detailTarget.extension}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
Hash (SHA-256)
|
||||
</span>
|
||||
<span className='col-span-2 font-mono break-all select-all text-foreground/90'>
|
||||
{detailTarget.hash}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
业务类型
|
||||
</span>
|
||||
<span className='col-span-2'>
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='text-[10px] py-0 px-2 rounded-md font-normal'
|
||||
>
|
||||
{detailTarget.type}
|
||||
</Badge>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">存储驱动</span>
|
||||
<span className="col-span-2 font-mono text-foreground/90">{storageDriverQuery.data ?? "local"}</span>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
存储驱动
|
||||
</span>
|
||||
<span className='col-span-2 font-mono text-foreground/90'>
|
||||
{storageDriverQuery.data ?? 'local'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">上传者 ID</span>
|
||||
<span className="col-span-2 font-mono text-foreground/90">{detailTarget.user_id}</span>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
上传者 ID
|
||||
</span>
|
||||
<span className='col-span-2 font-mono text-foreground/90'>
|
||||
{detailTarget.user_id}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-dashed pb-2">
|
||||
<span className="text-muted-foreground font-medium">上传时间</span>
|
||||
<span className="col-span-2 text-foreground/90">{formatDate(detailTarget.created_at)}</span>
|
||||
<div className='grid grid-cols-3 gap-2 border-b border-dashed pb-2'>
|
||||
<span className='text-muted-foreground font-medium'>
|
||||
上传时间
|
||||
</span>
|
||||
<span className='col-span-2 text-foreground/90'>
|
||||
{formatDate(detailTarget.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{detailTarget.metadata && Object.keys(detailTarget.metadata).length > 0 && (
|
||||
<div className="space-y-1.5 pt-2">
|
||||
<span className="text-muted-foreground font-medium block">额外元数据</span>
|
||||
<pre className="p-3 bg-muted/40 border rounded-lg text-[10px] font-mono overflow-x-auto text-foreground/90 max-h-40 overflow-y-auto">
|
||||
{JSON.stringify(detailTarget.metadata, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
{detailTarget.metadata &&
|
||||
Object.keys(detailTarget.metadata).length > 0 && (
|
||||
<div className='space-y-1.5 pt-2'>
|
||||
<span className='text-muted-foreground font-medium block'>
|
||||
额外元数据
|
||||
</span>
|
||||
<pre className='p-3 bg-muted/40 border rounded-lg text-[10px] font-mono overflow-x-auto text-foreground/90 max-h-40 overflow-y-auto'>
|
||||
{JSON.stringify(detailTarget.metadata, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -507,29 +616,40 @@ export function FileList() {
|
||||
</Sheet>
|
||||
|
||||
{/* 删除确认 Dialog */}
|
||||
<AlertDialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
|
||||
<AlertDialog
|
||||
open={!!deleteTarget}
|
||||
onOpenChange={(open) => !open && setDeleteTarget(null)}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确认删除文件</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
确定要删除文件{" "}
|
||||
<span className="font-semibold text-foreground">「{deleteTarget?.file_name}」</span>{" "}
|
||||
确定要删除文件{' '}
|
||||
<span className='font-semibold text-foreground'>
|
||||
「{deleteTarget?.file_name}」
|
||||
</span>{' '}
|
||||
吗?此操作不可撤销。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>取消</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>
|
||||
取消
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)}
|
||||
onClick={() =>
|
||||
deleteTarget && deleteMutation.mutate(deleteTarget.id)
|
||||
}
|
||||
disabled={deleteMutation.isPending}
|
||||
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
|
||||
className='bg-destructive hover:bg-destructive/90 text-destructive-foreground'
|
||||
>
|
||||
{deleteMutation.isPending && <Loader2 className="mr-1.5 size-3.5 animate-spin" />}
|
||||
{deleteMutation.isPending && (
|
||||
<Loader2 className='mr-1.5 size-3.5 animate-spin' />
|
||||
)}
|
||||
确认删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,35 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useQuery} from "@tanstack/react-query"
|
||||
import {Database, Files, HardDrive, Info, Loader2, TrendingUp, Upload,} from "lucide-react"
|
||||
import {Area, AreaChart, CartesianGrid, Cell, Pie, PieChart, XAxis, YAxis,} from "recharts"
|
||||
import * as React from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
Database,
|
||||
Files,
|
||||
HardDrive,
|
||||
Info,
|
||||
Loader2,
|
||||
TrendingUp,
|
||||
Upload,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
Area,
|
||||
AreaChart,
|
||||
CartesianGrid,
|
||||
Cell,
|
||||
Pie,
|
||||
PieChart,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import {
|
||||
ChartConfig,
|
||||
ChartContainer,
|
||||
@@ -14,265 +37,322 @@ import {
|
||||
ChartLegendContent,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
} from "@/components/ui/chart"
|
||||
import services, {formatFileSize} from "@/lib/services"
|
||||
} from '@/components/ui/chart';
|
||||
import services, { formatFileSize } from '@/lib/services';
|
||||
|
||||
const categoryMap: Record<string, string> = {
|
||||
"图片": "images",
|
||||
"视频": "videos",
|
||||
"音频": "audio",
|
||||
"文档": "documents",
|
||||
"压缩包": "archives",
|
||||
"其他": "others",
|
||||
}
|
||||
图片: 'images',
|
||||
视频: 'videos',
|
||||
音频: 'audio',
|
||||
文档: 'documents',
|
||||
压缩包: 'archives',
|
||||
其他: 'others',
|
||||
};
|
||||
|
||||
const statsChartConfig = {
|
||||
images: {
|
||||
label: "图片",
|
||||
color: "hsl(var(--chart-1))",
|
||||
label: '图片',
|
||||
color: 'hsl(var(--chart-1))',
|
||||
},
|
||||
videos: {
|
||||
label: "视频",
|
||||
color: "hsl(var(--chart-2))",
|
||||
label: '视频',
|
||||
color: 'hsl(var(--chart-2))',
|
||||
},
|
||||
audio: {
|
||||
label: "音频",
|
||||
color: "hsl(var(--chart-3))",
|
||||
label: '音频',
|
||||
color: 'hsl(var(--chart-3))',
|
||||
},
|
||||
documents: {
|
||||
label: "文档",
|
||||
color: "hsl(var(--chart-4))",
|
||||
label: '文档',
|
||||
color: 'hsl(var(--chart-4))',
|
||||
},
|
||||
archives: {
|
||||
label: "压缩包",
|
||||
color: "hsl(var(--chart-5))",
|
||||
label: '压缩包',
|
||||
color: 'hsl(var(--chart-5))',
|
||||
},
|
||||
others: {
|
||||
label: "其他",
|
||||
color: "hsl(var(--chart-6))",
|
||||
label: '其他',
|
||||
color: 'hsl(var(--chart-6))',
|
||||
},
|
||||
count: {
|
||||
label: "新增文件数",
|
||||
color: "hsl(var(--primary))",
|
||||
label: '新增文件数',
|
||||
color: 'hsl(var(--primary))',
|
||||
},
|
||||
size: {
|
||||
label: "新增大小",
|
||||
color: "hsl(var(--chart-2))",
|
||||
label: '新增大小',
|
||||
color: 'hsl(var(--chart-2))',
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
} satisfies ChartConfig;
|
||||
|
||||
export function FileStats() {
|
||||
const [trendMetric, setTrendMetric] = React.useState<"count" | "size">("count")
|
||||
const [trendMetric, setTrendMetric] = React.useState<'count' | 'size'>(
|
||||
'count',
|
||||
);
|
||||
|
||||
const statsQuery = useQuery({
|
||||
queryKey: ["files", "stats"],
|
||||
queryKey: ['files', 'stats'],
|
||||
queryFn: () => services.adminUpload.getFileStats(),
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
})
|
||||
refetchOnMount: 'always',
|
||||
});
|
||||
|
||||
const stats = statsQuery.data
|
||||
const stats = statsQuery.data;
|
||||
|
||||
const trendData = React.useMemo(() => {
|
||||
if (!stats?.trend) return []
|
||||
if (!stats?.trend) return [];
|
||||
return stats.trend.map((item) => ({
|
||||
...item,
|
||||
formattedDate: item.date.substring(5), // YYYY-MM-DD -> MM-DD
|
||||
value: trendMetric === "count" ? item.count : item.size,
|
||||
}))
|
||||
}, [stats?.trend, trendMetric])
|
||||
value: trendMetric === 'count' ? item.count : item.size,
|
||||
}));
|
||||
}, [stats?.trend, trendMetric]);
|
||||
|
||||
const categoryCountData = React.useMemo(() => {
|
||||
if (!stats?.categories) return []
|
||||
if (!stats?.categories) return [];
|
||||
return stats.categories
|
||||
.filter((c) => c.count > 0)
|
||||
.map((c) => {
|
||||
const key = categoryMap[c.name] || "others"
|
||||
const key = categoryMap[c.name] || 'others';
|
||||
return {
|
||||
name: key,
|
||||
value: c.count,
|
||||
fill: `var(--color-${key})`,
|
||||
}
|
||||
})
|
||||
}, [stats?.categories])
|
||||
};
|
||||
});
|
||||
}, [stats?.categories]);
|
||||
|
||||
const categorySizeData = React.useMemo(() => {
|
||||
if (!stats?.categories) return []
|
||||
if (!stats?.categories) return [];
|
||||
return stats.categories
|
||||
.filter((c) => c.size > 0)
|
||||
.map((c) => {
|
||||
const key = categoryMap[c.name] || "others"
|
||||
const key = categoryMap[c.name] || 'others';
|
||||
return {
|
||||
name: key,
|
||||
value: c.size,
|
||||
fill: `var(--color-${key})`,
|
||||
}
|
||||
})
|
||||
}, [stats?.categories])
|
||||
};
|
||||
});
|
||||
}, [stats?.categories]);
|
||||
|
||||
const maxStats = React.useMemo(() => {
|
||||
if (!stats?.categories || stats.categories.length === 0) {
|
||||
return { maxCountName: "无", maxCount: 0, maxSizeName: "无", maxSize: 0 }
|
||||
return { maxCountName: '无', maxCount: 0, maxSizeName: '无', maxSize: 0 };
|
||||
}
|
||||
let maxCountName = "无"
|
||||
let maxCount = 0
|
||||
let maxSizeName = "无"
|
||||
let maxSize = 0
|
||||
let maxCountName = '无';
|
||||
let maxCount = 0;
|
||||
let maxSizeName = '无';
|
||||
let maxSize = 0;
|
||||
|
||||
stats.categories.forEach((cat) => {
|
||||
if (cat.count > maxCount) {
|
||||
maxCount = cat.count
|
||||
maxCountName = cat.name
|
||||
maxCount = cat.count;
|
||||
maxCountName = cat.name;
|
||||
}
|
||||
if (cat.size > maxSize) {
|
||||
maxSize = cat.size
|
||||
maxSizeName = cat.name
|
||||
maxSize = cat.size;
|
||||
maxSizeName = cat.name;
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
return { maxCountName, maxCount, maxSizeName, maxSize }
|
||||
}, [stats?.categories])
|
||||
return { maxCountName, maxCount, maxSizeName, maxSize };
|
||||
}, [stats?.categories]);
|
||||
|
||||
const trendSummary = React.useMemo(() => {
|
||||
if (!stats?.trend) return { count: 0, size: 0 }
|
||||
if (!stats?.trend) return { count: 0, size: 0 };
|
||||
return stats.trend.reduce(
|
||||
(acc, curr) => ({
|
||||
count: acc.count + curr.count,
|
||||
size: acc.size + curr.size,
|
||||
}),
|
||||
{ count: 0, size: 0 }
|
||||
)
|
||||
}, [stats?.trend])
|
||||
{ count: 0, size: 0 },
|
||||
);
|
||||
}, [stats?.trend]);
|
||||
|
||||
if (statsQuery.isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-32">
|
||||
<Loader2 className="size-8 animate-spin text-sky-500" />
|
||||
<div className='flex items-center justify-center py-32'>
|
||||
<Loader2 className='size-8 animate-spin text-sky-500' />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!stats || stats.total_count === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-24 border border-dashed rounded-xl bg-card text-muted-foreground gap-4">
|
||||
<Upload className="size-14 text-muted-foreground/25" />
|
||||
<div className="text-center space-y-1">
|
||||
<p className="font-medium">暂无上传数据</p>
|
||||
<p className="text-xs text-muted-foreground">上传文件后即可在此查看容量与文件分布分析。</p>
|
||||
<div className='flex flex-col items-center justify-center py-24 border border-dashed rounded-xl bg-card text-muted-foreground gap-4'>
|
||||
<Upload className='size-14 text-muted-foreground/25' />
|
||||
<div className='text-center space-y-1'>
|
||||
<p className='font-medium'>暂无上传数据</p>
|
||||
<p className='text-xs text-muted-foreground'>
|
||||
上传文件后即可在此查看容量与文件分布分析。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className='space-y-6'>
|
||||
{/* 四个指标卡片 */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Card className="bg-card/25 border-border/40 hover:shadow-md transition-shadow">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-xs font-semibold tracking-tight text-muted-foreground">总文件数</CardTitle>
|
||||
<Files className="size-4 text-sky-500" />
|
||||
<div className='grid gap-4 sm:grid-cols-2 lg:grid-cols-4'>
|
||||
<Card className='bg-card/25 border-border/40 hover:shadow-md transition-shadow'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-xs font-semibold tracking-tight text-muted-foreground'>
|
||||
总文件数
|
||||
</CardTitle>
|
||||
<Files className='size-4 text-sky-500' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono text-sky-500">
|
||||
{stats.total_count.toLocaleString()}{" "}
|
||||
<span className="text-xs font-normal text-muted-foreground">个</span>
|
||||
<div className='text-2xl font-bold font-mono text-sky-500'>
|
||||
{stats.total_count.toLocaleString()}{' '}
|
||||
<span className='text-xs font-normal text-muted-foreground'>
|
||||
个
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">您上传的可用文件数量汇总</p>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
您上传的可用文件数量汇总
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="bg-card/25 border-border/40 hover:shadow-md transition-shadow">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-xs font-semibold tracking-tight text-muted-foreground">占用存储容量</CardTitle>
|
||||
<Database className="size-4 text-emerald-500" />
|
||||
<Card className='bg-card/25 border-border/40 hover:shadow-md transition-shadow'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-xs font-semibold tracking-tight text-muted-foreground'>
|
||||
占用存储容量
|
||||
</CardTitle>
|
||||
<Database className='size-4 text-emerald-500' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono text-emerald-500">{formatFileSize(stats.total_size)}</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">文件实际在磁盘/S3中占用的总空间</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="bg-card/25 border-border/40 hover:shadow-md transition-shadow">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-xs font-semibold tracking-tight text-muted-foreground">近 7 天新增文件</CardTitle>
|
||||
<TrendingUp className="size-4 text-indigo-500" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono text-indigo-500">
|
||||
+{trendSummary.count.toLocaleString()}{" "}
|
||||
<span className="text-xs font-normal text-muted-foreground">个</span>
|
||||
<div className='text-2xl font-bold font-mono text-emerald-500'>
|
||||
{formatFileSize(stats.total_size)}
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">最近 7 天上传成功的文件总数</p>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
文件实际在磁盘/S3中占用的总空间
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="bg-card/25 border-border/40 hover:shadow-md transition-shadow">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-xs font-semibold tracking-tight text-muted-foreground">近 7 天新增大小</CardTitle>
|
||||
<HardDrive className="size-4 text-amber-500" />
|
||||
<Card className='bg-card/25 border-border/40 hover:shadow-md transition-shadow'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-xs font-semibold tracking-tight text-muted-foreground'>
|
||||
近 7 天新增文件
|
||||
</CardTitle>
|
||||
<TrendingUp className='size-4 text-indigo-500' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono text-amber-500">+{formatFileSize(trendSummary.size)}</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">最近 7 天上传所消耗的存储带宽</p>
|
||||
<div className='text-2xl font-bold font-mono text-indigo-500'>
|
||||
+{trendSummary.count.toLocaleString()}{' '}
|
||||
<span className='text-xs font-normal text-muted-foreground'>
|
||||
个
|
||||
</span>
|
||||
</div>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
最近 7 天上传成功的文件总数
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className='bg-card/25 border-border/40 hover:shadow-md transition-shadow'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-xs font-semibold tracking-tight text-muted-foreground'>
|
||||
近 7 天新增大小
|
||||
</CardTitle>
|
||||
<HardDrive className='size-4 text-amber-500' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className='text-2xl font-bold font-mono text-amber-500'>
|
||||
+{formatFileSize(trendSummary.size)}
|
||||
</div>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
最近 7 天上传所消耗的存储带宽
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 7 天新增趋势折线图 */}
|
||||
<Card className="bg-card/20 border-border/40">
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<Card className='bg-card/20 border-border/40'>
|
||||
<CardHeader className='flex flex-row items-center justify-between'>
|
||||
<div>
|
||||
<CardTitle className="text-sm font-bold">最近 7 天新增趋势</CardTitle>
|
||||
<CardDescription className="text-xs">按日统计近一周期内的上传波动</CardDescription>
|
||||
<CardTitle className='text-sm font-bold'>
|
||||
最近 7 天新增趋势
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs'>
|
||||
按日统计近一周期内的上传波动
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 border rounded-lg p-0.5 bg-muted/30">
|
||||
<div className='flex items-center gap-1 border rounded-lg p-0.5 bg-muted/30'>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={trendMetric === "count" ? "secondary" : "ghost"}
|
||||
className="h-7 text-xs px-2.5 rounded-md"
|
||||
onClick={() => setTrendMetric("count")}
|
||||
size='sm'
|
||||
variant={trendMetric === 'count' ? 'secondary' : 'ghost'}
|
||||
className='h-7 text-xs px-2.5 rounded-md'
|
||||
onClick={() => setTrendMetric('count')}
|
||||
>
|
||||
新增数量 (个)
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={trendMetric === "size" ? "secondary" : "ghost"}
|
||||
className="h-7 text-xs px-2.5 rounded-md"
|
||||
onClick={() => setTrendMetric("size")}
|
||||
size='sm'
|
||||
variant={trendMetric === 'size' ? 'secondary' : 'ghost'}
|
||||
className='h-7 text-xs px-2.5 rounded-md'
|
||||
onClick={() => setTrendMetric('size')}
|
||||
>
|
||||
新增大小 (MB)
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pl-2 pr-4 pt-2">
|
||||
<div className="h-[280px] w-full">
|
||||
<ChartContainer config={statsChartConfig} className="w-full h-full">
|
||||
<AreaChart data={trendData} margin={{ top: 10, right: 10, left: 10, bottom: 0 }}>
|
||||
<CardContent className='pl-2 pr-4 pt-2'>
|
||||
<div className='h-[280px] w-full'>
|
||||
<ChartContainer config={statsChartConfig} className='w-full h-full'>
|
||||
<AreaChart
|
||||
data={trendData}
|
||||
margin={{ top: 10, right: 10, left: 10, bottom: 0 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="colorCount" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="var(--color-count)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="var(--color-count)" stopOpacity={0.01} />
|
||||
<linearGradient id='colorCount' x1='0' y1='0' x2='0' y2='1'>
|
||||
<stop
|
||||
offset='5%'
|
||||
stopColor='var(--color-count)'
|
||||
stopOpacity={0.3}
|
||||
/>
|
||||
<stop
|
||||
offset='95%'
|
||||
stopColor='var(--color-count)'
|
||||
stopOpacity={0.01}
|
||||
/>
|
||||
</linearGradient>
|
||||
<linearGradient id="colorSize" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="var(--color-size)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="var(--color-size)" stopOpacity={0.01} />
|
||||
<linearGradient id='colorSize' x1='0' y1='0' x2='0' y2='1'>
|
||||
<stop
|
||||
offset='5%'
|
||||
stopColor='var(--color-size)'
|
||||
stopOpacity={0.3}
|
||||
/>
|
||||
<stop
|
||||
offset='95%'
|
||||
stopColor='var(--color-size)'
|
||||
stopOpacity={0.01}
|
||||
/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border)/40)" />
|
||||
<CartesianGrid
|
||||
strokeDasharray='3 3'
|
||||
vertical={false}
|
||||
stroke='hsl(var(--border)/40)'
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="formattedDate"
|
||||
dataKey='formattedDate'
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
style={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
|
||||
style={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
|
||||
/>
|
||||
<YAxis
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
tickMargin={8}
|
||||
style={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
|
||||
tickFormatter={(v) => (trendMetric === "size" ? formatFileSize(v) : v.toString())}
|
||||
style={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
|
||||
tickFormatter={(v) =>
|
||||
trendMetric === 'size' ? formatFileSize(v) : v.toString()
|
||||
}
|
||||
/>
|
||||
<ChartTooltip
|
||||
cursor={false}
|
||||
@@ -280,37 +360,52 @@ export function FileStats() {
|
||||
<ChartTooltipContent
|
||||
hideLabel
|
||||
formatter={(value) => {
|
||||
const label = trendMetric === "count" ? "新增文件数" : "新增大小"
|
||||
const label =
|
||||
trendMetric === 'count' ? '新增文件数' : '新增大小';
|
||||
const formattedValue =
|
||||
trendMetric === "size" ? formatFileSize(Number(value)) : `${value} 个`
|
||||
trendMetric === 'size'
|
||||
? formatFileSize(Number(value))
|
||||
: `${value} 个`;
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<span
|
||||
className="size-2 rounded-full animate-pulse"
|
||||
className='size-2 rounded-full animate-pulse'
|
||||
style={{
|
||||
backgroundColor:
|
||||
trendMetric === "count" ? "var(--color-count)" : "var(--color-size)",
|
||||
trendMetric === 'count'
|
||||
? 'var(--color-count)'
|
||||
: 'var(--color-size)',
|
||||
}}
|
||||
/>
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className='text-muted-foreground'>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-foreground font-mono font-medium tabular-nums ml-auto">
|
||||
<span className='text-foreground font-mono font-medium tabular-nums ml-auto'>
|
||||
{formattedValue}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke={trendMetric === "count" ? "var(--color-count)" : "var(--color-size)"}
|
||||
type='monotone'
|
||||
dataKey='value'
|
||||
stroke={
|
||||
trendMetric === 'count'
|
||||
? 'var(--color-count)'
|
||||
: 'var(--color-size)'
|
||||
}
|
||||
strokeWidth={2.5}
|
||||
fillOpacity={1}
|
||||
fill={trendMetric === "count" ? "url(#colorCount)" : "url(#colorSize)"}
|
||||
fill={
|
||||
trendMetric === 'count'
|
||||
? 'url(#colorCount)'
|
||||
: 'url(#colorSize)'
|
||||
}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
@@ -319,30 +414,37 @@ export function FileStats() {
|
||||
</Card>
|
||||
|
||||
{/* 两个饼图分布 */}
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<div className='grid gap-6 md:grid-cols-2'>
|
||||
{/* 饼图 1: 格式数量分布 */}
|
||||
<Card className="bg-card/20 border-border/40 flex flex-col">
|
||||
<Card className='bg-card/20 border-border/40 flex flex-col'>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm font-bold">文件格式数量分布</CardTitle>
|
||||
<CardDescription className="text-xs">各种格式类型的文件个数占比</CardDescription>
|
||||
<CardTitle className='text-sm font-bold'>
|
||||
文件格式数量分布
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs'>
|
||||
各种格式类型的文件个数占比
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex-1 flex flex-col justify-between gap-4">
|
||||
<CardContent className='flex-1 flex flex-col justify-between gap-4'>
|
||||
{categoryCountData.length === 0 ? (
|
||||
<div className="h-[240px] flex items-center justify-center text-xs text-muted-foreground">
|
||||
<div className='h-[240px] flex items-center justify-center text-xs text-muted-foreground'>
|
||||
暂无分类数据
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-[240px] w-full">
|
||||
<ChartContainer config={statsChartConfig} className="w-full h-full">
|
||||
<div className='h-[240px] w-full'>
|
||||
<ChartContainer
|
||||
config={statsChartConfig}
|
||||
className='w-full h-full'
|
||||
>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={categoryCountData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
cx='50%'
|
||||
cy='50%'
|
||||
innerRadius={60}
|
||||
outerRadius={80}
|
||||
paddingAngle={3}
|
||||
dataKey="value"
|
||||
dataKey='value'
|
||||
>
|
||||
{categoryCountData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.fill} />
|
||||
@@ -354,66 +456,88 @@ export function FileStats() {
|
||||
<ChartTooltipContent
|
||||
hideLabel
|
||||
formatter={(value, name) => {
|
||||
const configObj = statsChartConfig[name as keyof typeof statsChartConfig]
|
||||
const label = configObj?.label || name
|
||||
const color = configObj?.color || "hsl(var(--muted))"
|
||||
const configObj =
|
||||
statsChartConfig[
|
||||
name as keyof typeof statsChartConfig
|
||||
];
|
||||
const label = configObj?.label || name;
|
||||
const color =
|
||||
configObj?.color || 'hsl(var(--muted))';
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="size-2 rounded-full" style={{ backgroundColor: color }} />
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<span
|
||||
className='size-2 rounded-full'
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<span className='text-muted-foreground'>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-foreground font-mono font-medium tabular-nums ml-auto">
|
||||
<span className='text-foreground font-mono font-medium tabular-nums ml-auto'>
|
||||
{value} 个
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<ChartLegend
|
||||
content={<ChartLegendContent nameKey="name" />}
|
||||
className="flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] pt-4"
|
||||
content={<ChartLegendContent nameKey='name' />}
|
||||
className='flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] pt-4'
|
||||
/>
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-sky-500/5 border border-sky-500/10 rounded-lg p-3 flex items-start gap-2.5 text-xs text-sky-600 dark:text-sky-400">
|
||||
<Info className="size-4 shrink-0 mt-0.5" />
|
||||
<p className="leading-normal">
|
||||
文件类型中数量最多的是{" "}
|
||||
<strong className="font-bold">「{maxStats.maxCountName}」</strong>,累计上传了{" "}
|
||||
<strong className="font-mono font-bold">{maxStats.maxCount}</strong> 个文件。
|
||||
<div className='bg-sky-500/5 border border-sky-500/10 rounded-lg p-3 flex items-start gap-2.5 text-xs text-sky-600 dark:text-sky-400'>
|
||||
<Info className='size-4 shrink-0 mt-0.5' />
|
||||
<p className='leading-normal'>
|
||||
文件类型中数量最多的是{' '}
|
||||
<strong className='font-bold'>
|
||||
「{maxStats.maxCountName}」
|
||||
</strong>
|
||||
,累计上传了{' '}
|
||||
<strong className='font-mono font-bold'>
|
||||
{maxStats.maxCount}
|
||||
</strong>{' '}
|
||||
个文件。
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 饼图 2: 格式容量分布 */}
|
||||
<Card className="bg-card/20 border-border/40 flex flex-col">
|
||||
<Card className='bg-card/20 border-border/40 flex flex-col'>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm font-bold">文件占用容量分布</CardTitle>
|
||||
<CardDescription className="text-xs">各种格式类型的文件大小占比</CardDescription>
|
||||
<CardTitle className='text-sm font-bold'>
|
||||
文件占用容量分布
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs'>
|
||||
各种格式类型的文件大小占比
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex-1 flex flex-col justify-between gap-4">
|
||||
<CardContent className='flex-1 flex flex-col justify-between gap-4'>
|
||||
{categorySizeData.length === 0 ? (
|
||||
<div className="h-[240px] flex items-center justify-center text-xs text-muted-foreground">
|
||||
<div className='h-[240px] flex items-center justify-center text-xs text-muted-foreground'>
|
||||
暂无容量数据
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-[240px] w-full">
|
||||
<ChartContainer config={statsChartConfig} className="w-full h-full">
|
||||
<div className='h-[240px] w-full'>
|
||||
<ChartContainer
|
||||
config={statsChartConfig}
|
||||
className='w-full h-full'
|
||||
>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={categorySizeData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
cx='50%'
|
||||
cy='50%'
|
||||
innerRadius={60}
|
||||
outerRadius={80}
|
||||
paddingAngle={3}
|
||||
dataKey="value"
|
||||
dataKey='value'
|
||||
>
|
||||
{categorySizeData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.fill} />
|
||||
@@ -425,38 +549,52 @@ export function FileStats() {
|
||||
<ChartTooltipContent
|
||||
hideLabel
|
||||
formatter={(value, name) => {
|
||||
const configObj = statsChartConfig[name as keyof typeof statsChartConfig]
|
||||
const label = configObj?.label || name
|
||||
const color = configObj?.color || "hsl(var(--muted))"
|
||||
const configObj =
|
||||
statsChartConfig[
|
||||
name as keyof typeof statsChartConfig
|
||||
];
|
||||
const label = configObj?.label || name;
|
||||
const color =
|
||||
configObj?.color || 'hsl(var(--muted))';
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="size-2 rounded-full" style={{ backgroundColor: color }} />
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<span
|
||||
className='size-2 rounded-full'
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
<span className='text-muted-foreground'>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-foreground font-mono font-medium tabular-nums ml-auto">
|
||||
<span className='text-foreground font-mono font-medium tabular-nums ml-auto'>
|
||||
{formatFileSize(Number(value))}
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<ChartLegend
|
||||
content={<ChartLegendContent nameKey="name" />}
|
||||
className="flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] pt-4"
|
||||
content={<ChartLegendContent nameKey='name' />}
|
||||
className='flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] pt-4'
|
||||
/>
|
||||
</PieChart>
|
||||
</ChartContainer>
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3 flex items-start gap-2.5 text-xs text-emerald-600 dark:text-emerald-400">
|
||||
<Info className="size-4 shrink-0 mt-0.5" />
|
||||
<p className="leading-normal">
|
||||
文件类型中占用存储最大的是{" "}
|
||||
<strong className="font-bold">「{maxStats.maxSizeName}」</strong>,共消耗了{" "}
|
||||
<strong className="font-mono font-bold">{formatFileSize(maxStats.maxSize)}</strong>{" "}
|
||||
<div className='bg-emerald-500/5 border border-emerald-500/10 rounded-lg p-3 flex items-start gap-2.5 text-xs text-emerald-600 dark:text-emerald-400'>
|
||||
<Info className='size-4 shrink-0 mt-0.5' />
|
||||
<p className='leading-normal'>
|
||||
文件类型中占用存储最大的是{' '}
|
||||
<strong className='font-bold'>
|
||||
「{maxStats.maxSizeName}」
|
||||
</strong>
|
||||
,共消耗了{' '}
|
||||
<strong className='font-mono font-bold'>
|
||||
{formatFileSize(maxStats.maxSize)}
|
||||
</strong>{' '}
|
||||
存储容量。
|
||||
</p>
|
||||
</div>
|
||||
@@ -464,5 +602,5 @@ export function FileStats() {
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,104 +1,130 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query"
|
||||
import {Database, Loader2, Play, Save} from "lucide-react"
|
||||
import {toast} from "sonner"
|
||||
import * as React from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Database, Loader2, Play, Save } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Field, FieldDescription, FieldGroup, FieldLabel} from "@/components/ui/field"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Progress} from "@/components/ui/progress"
|
||||
import {Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select"
|
||||
import {Switch} from "@/components/ui/switch"
|
||||
import services from "@/lib/services"
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import services from '@/lib/services';
|
||||
import type {
|
||||
ObjectStorageConfig,
|
||||
StorageConfig,
|
||||
StorageDriver,
|
||||
TaskExecution,
|
||||
TaskExecutionStatus
|
||||
} from "@/lib/services/admin/types"
|
||||
TaskExecutionStatus,
|
||||
} from '@/lib/services/admin/types';
|
||||
|
||||
const storageConfigKey = "storage_config"
|
||||
const storageMigrationTaskType = "storage_migration"
|
||||
const storageConfigKey = 'storage_config';
|
||||
const storageMigrationTaskType = 'storage_migration';
|
||||
|
||||
const driverLabels: Record<StorageDriver, string> = {
|
||||
local: "本地文件系统",
|
||||
s3: "AWS S3",
|
||||
r2: "Cloudflare R2",
|
||||
minio: "MinIO",
|
||||
oss: "阿里云 OSS",
|
||||
webdav: "WebDAV",
|
||||
}
|
||||
local: '本地文件系统',
|
||||
s3: 'AWS S3',
|
||||
r2: 'Cloudflare R2',
|
||||
minio: 'MinIO',
|
||||
oss: '阿里云 OSS',
|
||||
webdav: 'WebDAV',
|
||||
};
|
||||
|
||||
const emptyObjectConfig: ObjectStorageConfig = {
|
||||
endpoint: "",
|
||||
region: "",
|
||||
bucket: "",
|
||||
access_key_id: "",
|
||||
secret_access_key: "",
|
||||
endpoint: '',
|
||||
region: '',
|
||||
bucket: '',
|
||||
access_key_id: '',
|
||||
secret_access_key: '',
|
||||
path_style: false,
|
||||
key_prefix: "",
|
||||
cdn_url: "",
|
||||
}
|
||||
key_prefix: '',
|
||||
cdn_url: '',
|
||||
};
|
||||
|
||||
function normalizeConfig(config: StorageConfig): StorageConfig {
|
||||
const s3 = {...emptyObjectConfig, ...config.s3}
|
||||
const r2 = {...emptyObjectConfig, ...config.r2}
|
||||
const minio = {...emptyObjectConfig, ...config.minio}
|
||||
const oss = {...emptyObjectConfig, ...config.oss}
|
||||
const webdav = {...config.webdav}
|
||||
const s3 = { ...emptyObjectConfig, ...config.s3 };
|
||||
const r2 = { ...emptyObjectConfig, ...config.r2 };
|
||||
const minio = { ...emptyObjectConfig, ...config.minio };
|
||||
const oss = { ...emptyObjectConfig, ...config.oss };
|
||||
const webdav = { ...config.webdav };
|
||||
return {
|
||||
...config,
|
||||
local: {root: config.local?.root || "."},
|
||||
s3: {...s3, region: s3.region || "us-east-1"},
|
||||
r2: {...r2, region: r2.region || "auto"},
|
||||
minio: {...minio, region: minio.region || "us-east-1", path_style: config.minio?.path_style ?? true},
|
||||
local: { root: config.local?.root || '.' },
|
||||
s3: { ...s3, region: s3.region || 'us-east-1' },
|
||||
r2: { ...r2, region: r2.region || 'auto' },
|
||||
minio: {
|
||||
...minio,
|
||||
region: minio.region || 'us-east-1',
|
||||
path_style: config.minio?.path_style ?? true,
|
||||
},
|
||||
oss,
|
||||
webdav: {
|
||||
endpoint: webdav.endpoint || "",
|
||||
username: webdav.username || "",
|
||||
password: webdav.password || "",
|
||||
base_path: webdav.base_path || "",
|
||||
endpoint: webdav.endpoint || '',
|
||||
username: webdav.username || '',
|
||||
password: webdav.password || '',
|
||||
base_path: webdav.base_path || '',
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
type StorageMigrationView = {
|
||||
state: "idle" | TaskExecutionStatus
|
||||
id?: string
|
||||
task_id?: string
|
||||
source_driver?: StorageDriver
|
||||
target_driver?: StorageDriver
|
||||
error?: string
|
||||
}
|
||||
state: 'idle' | TaskExecutionStatus;
|
||||
id?: string;
|
||||
task_id?: string;
|
||||
source_driver?: StorageDriver;
|
||||
target_driver?: StorageDriver;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type StorageMigrationPayload = {
|
||||
target: StorageConfig
|
||||
}
|
||||
target: StorageConfig;
|
||||
};
|
||||
|
||||
function parseMigrationPayload(payload: string): StorageConfig | undefined {
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as Partial<StorageMigrationPayload>
|
||||
return parsed.target ? normalizeConfig(parsed.target) : undefined
|
||||
const parsed = JSON.parse(payload) as Partial<StorageMigrationPayload>;
|
||||
return parsed.target ? normalizeConfig(parsed.target) : undefined;
|
||||
} catch {
|
||||
return undefined
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function driverLabel(driver?: StorageDriver): string {
|
||||
return driver ? driverLabels[driver] : "未知"
|
||||
return driver ? driverLabels[driver] : '未知';
|
||||
}
|
||||
|
||||
function latestMigration(executions: TaskExecution[], current?: StorageConfig): StorageMigrationView {
|
||||
const execution = executions[0]
|
||||
if (!execution || execution.status === "succeeded") {
|
||||
return {state: "idle"}
|
||||
function latestMigration(
|
||||
executions: TaskExecution[],
|
||||
current?: StorageConfig,
|
||||
): StorageMigrationView {
|
||||
const execution = executions[0];
|
||||
if (!execution || execution.status === 'succeeded') {
|
||||
return { state: 'idle' };
|
||||
}
|
||||
const target = parseMigrationPayload(execution.payload)
|
||||
const target = parseMigrationPayload(execution.payload);
|
||||
return {
|
||||
state: execution.status,
|
||||
id: execution.id,
|
||||
@@ -106,227 +132,339 @@ function latestMigration(executions: TaskExecution[], current?: StorageConfig):
|
||||
source_driver: current?.driver,
|
||||
target_driver: target?.driver,
|
||||
error: execution.error_message,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function StorageConfigTab() {
|
||||
const queryClient = useQueryClient()
|
||||
const [config, setConfig] = React.useState<StorageConfig | null>(null)
|
||||
const queryClient = useQueryClient();
|
||||
const [config, setConfig] = React.useState<StorageConfig | null>(null);
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "storage-config"],
|
||||
queryKey: ['admin', 'storage-config'],
|
||||
queryFn: async () => {
|
||||
const [configRecord, executions] = await Promise.all([
|
||||
services.adminSystemConfig.getSystemConfig(storageConfigKey),
|
||||
services.adminTask.listTaskExecutions({task_type: storageMigrationTaskType, page: 1, page_size: 1}),
|
||||
])
|
||||
const current = normalizeConfig(JSON.parse(configRecord.value) as StorageConfig)
|
||||
const migration = latestMigration(executions.items, current)
|
||||
services.adminTask.listTaskExecutions({
|
||||
task_type: storageMigrationTaskType,
|
||||
page: 1,
|
||||
page_size: 1,
|
||||
}),
|
||||
]);
|
||||
const current = normalizeConfig(
|
||||
JSON.parse(configRecord.value) as StorageConfig,
|
||||
);
|
||||
const migration = latestMigration(executions.items, current);
|
||||
return {
|
||||
config: current,
|
||||
migration,
|
||||
}
|
||||
};
|
||||
},
|
||||
refetchInterval: (result) => {
|
||||
const state = result.state.data?.migration.state
|
||||
return state === "pending" || state === "running" ? 2000 : false
|
||||
const state = result.state.data?.migration.state;
|
||||
return state === 'pending' || state === 'running' ? 2000 : false;
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (query.data?.config) {
|
||||
setConfig((current) => {
|
||||
const normalized = normalizeConfig(query.data.config)
|
||||
const normalized = normalizeConfig(query.data.config);
|
||||
if (current) {
|
||||
return {
|
||||
...normalized,
|
||||
driver: current.driver,
|
||||
}
|
||||
};
|
||||
}
|
||||
return normalized
|
||||
})
|
||||
return normalized;
|
||||
});
|
||||
}
|
||||
}, [query.data?.config])
|
||||
}, [query.data?.config]);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async (value: StorageConfig) => {
|
||||
await services.adminSystemConfig.updateSystemConfig(storageConfigKey, {
|
||||
value: JSON.stringify(value),
|
||||
})
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("存储配置已保存")
|
||||
void queryClient.invalidateQueries({queryKey: ["admin", "storage-config"]})
|
||||
toast.success('存储配置已保存');
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ['admin', 'storage-config'],
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message || "保存存储配置失败")
|
||||
void queryClient.invalidateQueries({queryKey: ["admin", "storage-config"]})
|
||||
toast.error(error.message || '保存存储配置失败');
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ['admin', 'storage-config'],
|
||||
});
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
const migrateMutation = useMutation({
|
||||
mutationFn: async (value: StorageConfig) => {
|
||||
const payload: StorageMigrationPayload = {target: value}
|
||||
const payload: StorageMigrationPayload = { target: value };
|
||||
return services.adminTask.dispatchTask({
|
||||
task_type: storageMigrationTaskType,
|
||||
payload: JSON.stringify(payload),
|
||||
})
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("存储迁移任务已下发")
|
||||
void queryClient.invalidateQueries({queryKey: ["admin", "storage-config"]})
|
||||
toast.success('存储迁移任务已下发');
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ['admin', 'storage-config'],
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message || "下发存储迁移任务失败")
|
||||
void queryClient.invalidateQueries({queryKey: ["admin", "storage-config"]})
|
||||
toast.error(error.message || '下发存储迁移任务失败');
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ['admin', 'storage-config'],
|
||||
});
|
||||
},
|
||||
})
|
||||
});
|
||||
const runMutation = useMutation({
|
||||
mutationFn: (executionID: string) => services.adminTask.retryTaskExecution(executionID),
|
||||
mutationFn: (executionID: string) =>
|
||||
services.adminTask.retryTaskExecution(executionID),
|
||||
onSuccess: () => {
|
||||
toast.success("存储迁移任务已重新下发")
|
||||
void queryClient.invalidateQueries({queryKey: ["admin", "storage-config"]})
|
||||
toast.success('存储迁移任务已重新下发');
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: ['admin', 'storage-config'],
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => toast.error(error.message || "运行存储迁移失败"),
|
||||
})
|
||||
onError: (error: Error) => toast.error(error.message || '运行存储迁移失败'),
|
||||
});
|
||||
|
||||
if (query.isPending || !config) {
|
||||
return <div className="flex justify-center py-20"><Loader2 className="animate-spin" /></div>
|
||||
return (
|
||||
<div className='flex justify-center py-20'>
|
||||
<Loader2 className='animate-spin' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const migration = query.data?.migration
|
||||
const isReadOnly = migration ? migration.state !== "idle" : false
|
||||
const migration = query.data?.migration;
|
||||
const isReadOnly = migration ? migration.state !== 'idle' : false;
|
||||
const isFormDisabled =
|
||||
(migration ? (migration.state === "pending" || migration.state === "running") : false) ||
|
||||
(migration
|
||||
? migration.state === 'pending' || migration.state === 'running'
|
||||
: false) ||
|
||||
saveMutation.isPending ||
|
||||
migrateMutation.isPending
|
||||
migrateMutation.isPending;
|
||||
|
||||
const updateObject = (driver: "s3" | "r2" | "minio" | "oss", patch: Partial<ObjectStorageConfig>) => {
|
||||
setConfig((current) => current ? {
|
||||
...current,
|
||||
[driver]: {...current[driver], ...patch},
|
||||
} : current)
|
||||
}
|
||||
const updateObject = (
|
||||
driver: 's3' | 'r2' | 'minio' | 'oss',
|
||||
patch: Partial<ObjectStorageConfig>,
|
||||
) => {
|
||||
setConfig((current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
[driver]: { ...current[driver], ...patch },
|
||||
}
|
||||
: current,
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className='flex w-full flex-col gap-6'>
|
||||
{isReadOnly && migration && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<CardTitle className='flex items-center gap-2'>
|
||||
存储维护模式
|
||||
<Badge variant={migration.state === "failed" ? "destructive" : "secondary"}>
|
||||
<Badge
|
||||
variant={
|
||||
migration.state === 'failed' ? 'destructive' : 'secondary'
|
||||
}
|
||||
>
|
||||
{migration.state}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{driverLabel(migration.source_driver)} → {driverLabel(migration.target_driver)}。迁移期间文件只允许读取,禁止上传、删除和清理。
|
||||
{driverLabel(migration.source_driver)} →{' '}
|
||||
{driverLabel(migration.target_driver)}
|
||||
。迁移期间文件只允许读取,禁止上传、删除和清理。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<Progress value={migration.state === "succeeded" ? 100 : undefined} />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
迁移进度请查看任务执行日志:{migration.task_id || "尚未下发"}
|
||||
<CardContent className='flex flex-col gap-3'>
|
||||
<Progress
|
||||
value={migration.state === 'succeeded' ? 100 : undefined}
|
||||
/>
|
||||
<p className='text-sm text-muted-foreground'>
|
||||
迁移进度请查看任务执行日志:{migration.task_id || '尚未下发'}
|
||||
</p>
|
||||
{migration.error && <p className="text-sm text-destructive">{migration.error}</p>}
|
||||
{migration.error && (
|
||||
<p className='text-sm text-destructive'>{migration.error}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={migration.state !== "failed" || !migration.id || runMutation.isPending}
|
||||
variant='outline'
|
||||
disabled={
|
||||
migration.state !== 'failed' ||
|
||||
!migration.id ||
|
||||
runMutation.isPending
|
||||
}
|
||||
onClick={() => migration.id && runMutation.mutate(migration.id)}
|
||||
>
|
||||
{runMutation.isPending ? <Loader2 data-icon="inline-start" className="animate-spin" /> : <Play data-icon="inline-start" />}
|
||||
{runMutation.isPending ? (
|
||||
<Loader2 data-icon='inline-start' className='animate-spin' />
|
||||
) : (
|
||||
<Play data-icon='inline-start' />
|
||||
)}
|
||||
重试迁移
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card className="border border-dashed shadow-sm">
|
||||
<CardHeader className="border-b border-dashed pb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="rounded-lg bg-indigo-500/10 p-1.5 text-indigo-500">
|
||||
<Database className="size-4" />
|
||||
<Card className='border border-dashed shadow-sm'>
|
||||
<CardHeader className='border-b border-dashed pb-4'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='rounded-lg bg-indigo-500/10 p-1.5 text-indigo-500'>
|
||||
<Database className='size-4' />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-base font-semibold">文件存储</CardTitle>
|
||||
<CardDescription className="text-xs">
|
||||
<CardTitle className='text-base font-semibold'>
|
||||
文件存储
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs'>
|
||||
默认使用本地存储。配置系统文件的存储媒介,切换存储类型且已有文件时,系统会自动进入维护模式并迁移文件。
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-6">
|
||||
<FieldGroup className="space-y-6">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<Field className="flex flex-col gap-1.5 md:col-span-2">
|
||||
<FieldLabel className="text-xs font-semibold">存储类型</FieldLabel>
|
||||
<CardContent className='pt-6'>
|
||||
<FieldGroup className='space-y-6'>
|
||||
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
|
||||
<Field className='flex flex-col gap-1.5 md:col-span-2'>
|
||||
<FieldLabel className='text-xs font-semibold'>
|
||||
存储类型
|
||||
</FieldLabel>
|
||||
<Select
|
||||
value={config.driver}
|
||||
disabled={isFormDisabled}
|
||||
onValueChange={(value) => setConfig({...config, driver: value as StorageDriver})}
|
||||
onValueChange={(value) =>
|
||||
setConfig({ ...config, driver: value as StorageDriver })
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full border-dashed bg-card text-xs">
|
||||
<SelectTrigger className='w-full border-dashed bg-card text-xs'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{(Object.keys(driverLabels) as StorageDriver[]).map((driver) => (
|
||||
<SelectItem key={driver} value={driver}>{driverLabels[driver]}</SelectItem>
|
||||
))}
|
||||
{(Object.keys(driverLabels) as StorageDriver[]).map(
|
||||
(driver) => (
|
||||
<SelectItem key={driver} value={driver}>
|
||||
{driverLabels[driver]}
|
||||
</SelectItem>
|
||||
),
|
||||
)}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
{config.driver === "local" && (
|
||||
<div className="md:col-span-2">
|
||||
{config.driver === 'local' && (
|
||||
<div className='md:col-span-2'>
|
||||
<TextField
|
||||
label="根目录"
|
||||
label='根目录'
|
||||
value={config.local.root}
|
||||
placeholder="."
|
||||
onChange={(root) => setConfig({...config, local: {root}})}
|
||||
placeholder='.'
|
||||
onChange={(root) =>
|
||||
setConfig({ ...config, local: { root } })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(config.driver === "s3" || config.driver === "r2" || config.driver === "minio" || config.driver === "oss") && (
|
||||
{(config.driver === 's3' ||
|
||||
config.driver === 'r2' ||
|
||||
config.driver === 'minio' ||
|
||||
config.driver === 'oss') && (
|
||||
<ObjectFields
|
||||
driver={config.driver as "s3" | "r2" | "minio" | "oss"}
|
||||
value={config[config.driver as "s3" | "r2" | "minio" | "oss"]}
|
||||
onChange={(patch) => updateObject(config.driver as "s3" | "r2" | "minio" | "oss", patch)}
|
||||
driver={config.driver as 's3' | 'r2' | 'minio' | 'oss'}
|
||||
value={config[config.driver as 's3' | 'r2' | 'minio' | 'oss']}
|
||||
onChange={(patch) =>
|
||||
updateObject(
|
||||
config.driver as 's3' | 'r2' | 'minio' | 'oss',
|
||||
patch,
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{config.driver === "webdav" && (
|
||||
{config.driver === 'webdav' && (
|
||||
<>
|
||||
<div className="md:col-span-2">
|
||||
<TextField label="服务地址" value={config.webdav.endpoint} placeholder="https://dav.example.com" onChange={(endpoint) => setConfig({...config, webdav: {...config.webdav, endpoint}})} />
|
||||
<div className='md:col-span-2'>
|
||||
<TextField
|
||||
label='服务地址'
|
||||
value={config.webdav.endpoint}
|
||||
placeholder='https://dav.example.com'
|
||||
onChange={(endpoint) =>
|
||||
setConfig({
|
||||
...config,
|
||||
webdav: { ...config.webdav, endpoint },
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<TextField label="用户名" value={config.webdav.username} onChange={(username) => setConfig({...config, webdav: {...config.webdav, username}})} />
|
||||
<TextField label="密码" type="password" value={config.webdav.password} onChange={(password) => setConfig({...config, webdav: {...config.webdav, password}})} />
|
||||
<div className="md:col-span-2">
|
||||
<TextField label="基础路径" value={config.webdav.base_path} placeholder="openflare" onChange={(base_path) => setConfig({...config, webdav: {...config.webdav, base_path}})} />
|
||||
<TextField
|
||||
label='用户名'
|
||||
value={config.webdav.username}
|
||||
onChange={(username) =>
|
||||
setConfig({
|
||||
...config,
|
||||
webdav: { ...config.webdav, username },
|
||||
})
|
||||
}
|
||||
/>
|
||||
<TextField
|
||||
label='密码'
|
||||
type='password'
|
||||
value={config.webdav.password}
|
||||
onChange={(password) =>
|
||||
setConfig({
|
||||
...config,
|
||||
webdav: { ...config.webdav, password },
|
||||
})
|
||||
}
|
||||
/>
|
||||
<div className='md:col-span-2'>
|
||||
<TextField
|
||||
label='基础路径'
|
||||
value={config.webdav.base_path}
|
||||
placeholder='openflare'
|
||||
onChange={(base_path) =>
|
||||
setConfig({
|
||||
...config,
|
||||
webdav: { ...config.webdav, base_path },
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</FieldGroup>
|
||||
</CardContent>
|
||||
<CardFooter className="justify-end gap-2 flex-col sm:flex-row items-end sm:items-center border-t border-dashed pt-4 mt-6">
|
||||
<CardFooter className='justify-end gap-2 flex-col sm:flex-row items-end sm:items-center border-t border-dashed pt-4 mt-6'>
|
||||
{config.driver !== query.data?.config.driver && (
|
||||
<span className="text-xs text-amber-500 mr-auto text-left max-w-md">
|
||||
⚠️ 您已切换存储类型。点击「保存配置」将立即切换活动存储引擎,并同步更新已有文件的存储驱动标记。仅在需要复制物理文件时才使用「开始迁移」。
|
||||
<span className='text-xs text-amber-500 mr-auto text-left max-w-md'>
|
||||
⚠️
|
||||
您已切换存储类型。点击「保存配置」将立即切换活动存储引擎,并同步更新已有文件的存储驱动标记。仅在需要复制物理文件时才使用「开始迁移」。
|
||||
</span>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
variant="outline"
|
||||
variant='outline'
|
||||
disabled={isFormDisabled}
|
||||
onClick={() => saveMutation.mutate(config)}
|
||||
className="border-dashed"
|
||||
className='border-dashed'
|
||||
>
|
||||
{saveMutation.isPending ? <Loader2 data-icon="inline-start" className="animate-spin" /> : <Save data-icon="inline-start" />}
|
||||
{saveMutation.isPending ? (
|
||||
<Loader2 data-icon='inline-start' className='animate-spin' />
|
||||
) : (
|
||||
<Save data-icon='inline-start' />
|
||||
)}
|
||||
保存配置
|
||||
</Button>
|
||||
{config.driver !== query.data?.config.driver && (
|
||||
@@ -334,7 +472,11 @@ export function StorageConfigTab() {
|
||||
disabled={isFormDisabled}
|
||||
onClick={() => migrateMutation.mutate(config)}
|
||||
>
|
||||
{migrateMutation.isPending ? <Loader2 data-icon="inline-start" className="animate-spin" /> : <Play data-icon="inline-start" />}
|
||||
{migrateMutation.isPending ? (
|
||||
<Loader2 data-icon='inline-start' className='animate-spin' />
|
||||
) : (
|
||||
<Play data-icon='inline-start' />
|
||||
)}
|
||||
开始迁移
|
||||
</Button>
|
||||
)}
|
||||
@@ -342,7 +484,7 @@ export function StorageConfigTab() {
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function ObjectFields({
|
||||
@@ -350,41 +492,87 @@ function ObjectFields({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
driver: "s3" | "r2" | "minio" | "oss"
|
||||
value: ObjectStorageConfig
|
||||
onChange: (patch: Partial<ObjectStorageConfig>) => void
|
||||
driver: 's3' | 'r2' | 'minio' | 'oss';
|
||||
value: ObjectStorageConfig;
|
||||
onChange: (patch: Partial<ObjectStorageConfig>) => void;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{driver === "r2" && (
|
||||
<div className="md:col-span-2">
|
||||
<TextField label="Account ID" value={value.account_id || ""} onChange={(account_id) => onChange({account_id})} />
|
||||
{driver === 'r2' && (
|
||||
<div className='md:col-span-2'>
|
||||
<TextField
|
||||
label='Account ID'
|
||||
value={value.account_id || ''}
|
||||
onChange={(account_id) => onChange({ account_id })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{driver !== "s3" && (
|
||||
<div className="md:col-span-2">
|
||||
<TextField label="Endpoint" value={value.endpoint} placeholder="https://..." onChange={(endpoint) => onChange({endpoint})} />
|
||||
{driver !== 's3' && (
|
||||
<div className='md:col-span-2'>
|
||||
<TextField
|
||||
label='Endpoint'
|
||||
value={value.endpoint}
|
||||
placeholder='https://...'
|
||||
onChange={(endpoint) => onChange({ endpoint })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<TextField label="Region" value={value.region} onChange={(region) => onChange({region})} />
|
||||
<TextField label="Bucket" value={value.bucket} onChange={(bucket) => onChange({bucket})} />
|
||||
<TextField label="Access Key ID" value={value.access_key_id} onChange={(access_key_id) => onChange({access_key_id})} />
|
||||
<TextField label="Secret Access Key" type="password" value={value.secret_access_key} onChange={(secret_access_key) => onChange({secret_access_key})} />
|
||||
<TextField label="对象前缀" value={value.key_prefix} placeholder="uploads" onChange={(key_prefix) => onChange({key_prefix})} />
|
||||
<TextField label="CDN 地址" value={value.cdn_url} placeholder="https://cdn.example.com" onChange={(cdn_url) => onChange({cdn_url})} />
|
||||
{(driver === "s3" || driver === "minio") && (
|
||||
<div className="md:col-span-2">
|
||||
<Field orientation="horizontal" className="flex items-center justify-between border border-dashed rounded-lg p-4 bg-muted/30">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<FieldLabel className="text-xs font-semibold cursor-pointer">Path Style</FieldLabel>
|
||||
<FieldDescription className="text-[11px] leading-relaxed text-muted-foreground">MinIO 等自托管 S3 通常需要开启。</FieldDescription>
|
||||
<TextField
|
||||
label='Region'
|
||||
value={value.region}
|
||||
onChange={(region) => onChange({ region })}
|
||||
/>
|
||||
<TextField
|
||||
label='Bucket'
|
||||
value={value.bucket}
|
||||
onChange={(bucket) => onChange({ bucket })}
|
||||
/>
|
||||
<TextField
|
||||
label='Access Key ID'
|
||||
value={value.access_key_id}
|
||||
onChange={(access_key_id) => onChange({ access_key_id })}
|
||||
/>
|
||||
<TextField
|
||||
label='Secret Access Key'
|
||||
type='password'
|
||||
value={value.secret_access_key}
|
||||
onChange={(secret_access_key) => onChange({ secret_access_key })}
|
||||
/>
|
||||
<TextField
|
||||
label='对象前缀'
|
||||
value={value.key_prefix}
|
||||
placeholder='uploads'
|
||||
onChange={(key_prefix) => onChange({ key_prefix })}
|
||||
/>
|
||||
<TextField
|
||||
label='CDN 地址'
|
||||
value={value.cdn_url}
|
||||
placeholder='https://cdn.example.com'
|
||||
onChange={(cdn_url) => onChange({ cdn_url })}
|
||||
/>
|
||||
{(driver === 's3' || driver === 'minio') && (
|
||||
<div className='md:col-span-2'>
|
||||
<Field
|
||||
orientation='horizontal'
|
||||
className='flex items-center justify-between border border-dashed rounded-lg p-4 bg-muted/30'
|
||||
>
|
||||
<div className='flex flex-col gap-0.5'>
|
||||
<FieldLabel className='text-xs font-semibold cursor-pointer'>
|
||||
Path Style
|
||||
</FieldLabel>
|
||||
<FieldDescription className='text-[11px] leading-relaxed text-muted-foreground'>
|
||||
MinIO 等自托管 S3 通常需要开启。
|
||||
</FieldDescription>
|
||||
</div>
|
||||
<Switch checked={value.path_style} onCheckedChange={(path_style) => onChange({path_style})} />
|
||||
<Switch
|
||||
checked={value.path_style}
|
||||
onCheckedChange={(path_style) => onChange({ path_style })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function TextField({
|
||||
@@ -392,24 +580,24 @@ function TextField({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
type = "text",
|
||||
type = 'text',
|
||||
}: {
|
||||
label: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
type?: React.HTMLInputTypeAttribute
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
type?: React.HTMLInputTypeAttribute;
|
||||
}) {
|
||||
return (
|
||||
<Field className="flex flex-col gap-1.5">
|
||||
<FieldLabel className="text-xs font-semibold">{label}</FieldLabel>
|
||||
<Field className='flex flex-col gap-1.5'>
|
||||
<FieldLabel className='text-xs font-semibold'>{label}</FieldLabel>
|
||||
<Input
|
||||
type={type}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
className="border-dashed bg-card text-xs"
|
||||
className='border-dashed bg-card text-xs'
|
||||
/>
|
||||
</Field>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,59 +1,65 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {motion} from "motion/react"
|
||||
import {FolderOpen} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { FolderOpen } from 'lucide-react';
|
||||
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
|
||||
import {FileStats} from "./components/file-stats"
|
||||
import {FileList} from "./components/file-list"
|
||||
import {StorageConfigTab} from "./components/storage-config-tab"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { FileStats } from './components/file-stats';
|
||||
import { FileList } from './components/file-list';
|
||||
import { StorageConfigTab } from './components/storage-config-tab';
|
||||
|
||||
export default function FilesPage() {
|
||||
const [activeTab, setActiveTab] = React.useState("stats")
|
||||
const [activeTab, setActiveTab] = React.useState('stats');
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 15 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.35, ease: "easeOut" }}
|
||||
className="flex w-full flex-col gap-6 py-6"
|
||||
transition={{ duration: 0.35, ease: 'easeOut' }}
|
||||
className='flex w-full flex-col gap-6 py-6'
|
||||
>
|
||||
{/* 顶部标题区 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderOpen className="size-5 text-primary" />
|
||||
<div className='flex items-center gap-2'>
|
||||
<FolderOpen className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">存储管理</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>存储管理</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
|
||||
<TabsList variant="line" className="w-fit inline-flex gap-8 mb-6">
|
||||
<TabsTrigger value="stats" className="px-0 pb-2 text-xs font-semibold">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className='w-full'>
|
||||
<TabsList variant='line' className='w-fit inline-flex gap-8 mb-6'>
|
||||
<TabsTrigger
|
||||
value='stats'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
文件存储信息
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="list" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger value='list' className='px-0 pb-2 text-xs font-semibold'>
|
||||
文件列表
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="storage" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='storage'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
存储配置
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* ──────── TAB 1: 统计看板 ──────── */}
|
||||
<TabsContent value="stats" className="outline-hidden">
|
||||
{activeTab === "stats" ? <FileStats /> : null}
|
||||
<TabsContent value='stats' className='outline-hidden'>
|
||||
{activeTab === 'stats' ? <FileStats /> : null}
|
||||
</TabsContent>
|
||||
|
||||
{/* ──────── TAB 2: 文件列表 ──────── */}
|
||||
<TabsContent value="list" className="outline-hidden">
|
||||
{activeTab === "list" ? <FileList /> : null}
|
||||
<TabsContent value='list' className='outline-hidden'>
|
||||
{activeTab === 'list' ? <FileList /> : null}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="storage" className="outline-hidden">
|
||||
{activeTab === "storage" ? <StorageConfigTab /> : null}
|
||||
<TabsContent value='storage' className='outline-hidden'>
|
||||
{activeTab === 'storage' ? <StorageConfigTab /> : null}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</motion.div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {AdminUsersProvider} from "@/contexts/admin-users-context"
|
||||
import {RequireAdminAuth} from "@/components/auth/require-auth"
|
||||
import { AdminUsersProvider } from '@/contexts/admin-users-context';
|
||||
import { RequireAdminAuth } from '@/components/auth/require-auth';
|
||||
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<RequireAdminAuth>
|
||||
<AdminUsersProvider>
|
||||
{children}
|
||||
</AdminUsersProvider>
|
||||
<AdminUsersProvider>{children}</AdminUsersProvider>
|
||||
</RequireAdminAuth>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,209 +14,282 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useCallback, useEffect, useState} from "react"
|
||||
import {BarChart3, Globe, RefreshCw, TrendingUp, Users, XCircle} from "lucide-react"
|
||||
import {Area, AreaChart, CartesianGrid, XAxis, YAxis} from "recharts"
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
BarChart3,
|
||||
Globe,
|
||||
RefreshCw,
|
||||
TrendingUp,
|
||||
Users,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from 'recharts';
|
||||
|
||||
import services from "@/lib/services"
|
||||
import {ErrorInline} from "@/components/layout/error"
|
||||
import {LoadingStateWithBorder} from "@/components/layout/loading"
|
||||
import {EmptyStateWithBorder} from "@/components/layout/empty"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent} from "@/components/ui/chart"
|
||||
import {Spinner} from "@/components/ui/spinner"
|
||||
import services from '@/lib/services';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import {
|
||||
ChartConfig,
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
} from '@/components/ui/chart';
|
||||
import { Spinner } from '@/components/ui/spinner';
|
||||
|
||||
interface TrendData {
|
||||
date: string
|
||||
count: number
|
||||
date: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface BrowserData {
|
||||
browser: string
|
||||
count: number
|
||||
browser: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface TopUserData {
|
||||
user_id: string
|
||||
username: string
|
||||
nickname: string
|
||||
count: number
|
||||
user_id: string;
|
||||
username: string;
|
||||
nickname: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
const chartConfig = {
|
||||
count: {
|
||||
label: "请求量",
|
||||
color: "hsl(var(--primary))",
|
||||
label: '请求量',
|
||||
color: 'hsl(var(--primary))',
|
||||
},
|
||||
} satisfies ChartConfig
|
||||
} satisfies ChartConfig;
|
||||
|
||||
// Format YYYY-MM-DD to MM/DD
|
||||
function formatDateLabel(dateStr: string) {
|
||||
if (!dateStr || dateStr.length < 10) return dateStr
|
||||
const parts = dateStr.split("-")
|
||||
if (!dateStr || dateStr.length < 10) return dateStr;
|
||||
const parts = dateStr.split('-');
|
||||
if (parts.length === 3) {
|
||||
return `${parts[1]}/${parts[2]}`
|
||||
return `${parts[1]}/${parts[2]}`;
|
||||
}
|
||||
return dateStr
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
export function AccessAnalytics() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<Error | null>(null)
|
||||
const [clickhouseDisabled, setClickhouseDisabled] = useState(false)
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [clickhouseDisabled, setClickhouseDisabled] = useState(false);
|
||||
|
||||
const [trend, setTrend] = useState<TrendData[]>([])
|
||||
const [browsers, setBrowsers] = useState<BrowserData[]>([])
|
||||
const [topUsers, setTopUsers] = useState<TopUserData[]>([])
|
||||
const [trend, setTrend] = useState<TrendData[]>([]);
|
||||
const [browsers, setBrowsers] = useState<BrowserData[]>([]);
|
||||
const [topUsers, setTopUsers] = useState<TopUserData[]>([]);
|
||||
|
||||
const fetchAnalytics = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
const data = await services.adminLog.getLogsAnalytics()
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const data = await services.adminLog.getLogsAnalytics();
|
||||
|
||||
// Formats the date labels for the X-axis representation
|
||||
const formattedTrend = (data.trend || []).map(item => ({
|
||||
const formattedTrend = (data.trend || []).map((item) => ({
|
||||
...item,
|
||||
formattedDate: formatDateLabel(item.date)
|
||||
}))
|
||||
formattedDate: formatDateLabel(item.date),
|
||||
}));
|
||||
|
||||
setTrend(formattedTrend)
|
||||
setBrowsers(data.browsers || [])
|
||||
setTopUsers(data.top_users || [])
|
||||
setClickhouseDisabled(false)
|
||||
setTrend(formattedTrend);
|
||||
setBrowsers(data.browsers || []);
|
||||
setTopUsers(data.top_users || []);
|
||||
setClickhouseDisabled(false);
|
||||
} catch (err) {
|
||||
const errorInstance = err instanceof Error ? err : new Error("获取数据统计失败")
|
||||
const errMsg = errorInstance.message || ""
|
||||
if (errMsg.includes("ClickHouse") || errMsg.includes("未启用")) {
|
||||
setClickhouseDisabled(true)
|
||||
const errorInstance =
|
||||
err instanceof Error ? err : new Error('获取数据统计失败');
|
||||
const errMsg = errorInstance.message || '';
|
||||
if (errMsg.includes('ClickHouse') || errMsg.includes('未启用')) {
|
||||
setClickhouseDisabled(true);
|
||||
} else {
|
||||
setError(errorInstance)
|
||||
setError(errorInstance);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setLoading(false);
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAnalytics()
|
||||
}, [fetchAnalytics])
|
||||
fetchAnalytics();
|
||||
}, [fetchAnalytics]);
|
||||
|
||||
const totalBrowserRequests = browsers.reduce((sum, item) => sum + item.count, 0)
|
||||
const totalTrendRequests = trend.reduce((sum, item) => sum + item.count, 0)
|
||||
const totalBrowserRequests = browsers.reduce(
|
||||
(sum, item) => sum + item.count,
|
||||
0,
|
||||
);
|
||||
const totalTrendRequests = trend.reduce((sum, item) => sum + item.count, 0);
|
||||
|
||||
if (clickhouseDisabled) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 border border-dashed rounded-lg bg-card text-center my-6 min-h-[300px]">
|
||||
<XCircle className="size-10 text-muted-foreground mb-3" />
|
||||
<h3 className="text-base font-semibold">ClickHouse 未启用</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 max-w-[400px] mb-4">
|
||||
当前系统配置未启用 ClickHouse 存储,系统不会收集用户访问日志。如需使用此功能,请在后端 `config.yaml` 配置文件中配置并启用 ClickHouse。
|
||||
<div className='flex flex-col items-center justify-center p-8 border border-dashed rounded-lg bg-card text-center my-6 min-h-[300px]'>
|
||||
<XCircle className='size-10 text-muted-foreground mb-3' />
|
||||
<h3 className='text-base font-semibold'>ClickHouse 未启用</h3>
|
||||
<p className='text-sm text-muted-foreground mt-1 max-w-[400px] mb-4'>
|
||||
当前系统配置未启用 ClickHouse
|
||||
存储,系统不会收集用户访问日志。如需使用此功能,请在后端 `config.yaml`
|
||||
配置文件中配置并启用 ClickHouse。
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <ErrorInline error={error} onRetry={fetchAnalytics} />
|
||||
return <ErrorInline error={error} onRetry={fetchAnalytics} />;
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <LoadingStateWithBorder icon={BarChart3} description="加载访问统计指标中..." />
|
||||
return (
|
||||
<LoadingStateWithBorder
|
||||
icon={BarChart3}
|
||||
description='加载访问统计指标中...'
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className='space-y-6'>
|
||||
{/* Overview Cards */}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Card className="bg-card/25 border-border/40">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-sm font-semibold tracking-tight">近 7 天总请求数</CardTitle>
|
||||
<TrendingUp className="size-4 text-muted-foreground" />
|
||||
<div className='grid gap-4 sm:grid-cols-2 lg:grid-cols-3'>
|
||||
<Card className='bg-card/25 border-border/40'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-sm font-semibold tracking-tight'>
|
||||
近 7 天总请求数
|
||||
</CardTitle>
|
||||
<TrendingUp className='size-4 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono">{totalTrendRequests.toLocaleString()}</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">系统记录的所有成功认证的访问总频次</p>
|
||||
<div className='text-2xl font-bold font-mono'>
|
||||
{totalTrendRequests.toLocaleString()}
|
||||
</div>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
系统记录的所有成功认证的访问总频次
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="bg-card/25 border-border/40">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-sm font-semibold tracking-tight">活跃终端分类数</CardTitle>
|
||||
<Globe className="size-4 text-muted-foreground" />
|
||||
<Card className='bg-card/25 border-border/40'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-sm font-semibold tracking-tight'>
|
||||
活跃终端分类数
|
||||
</CardTitle>
|
||||
<Globe className='size-4 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono">{browsers.length}</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">在一周内发起请求的浏览器代理大类统计</p>
|
||||
<div className='text-2xl font-bold font-mono'>
|
||||
{browsers.length}
|
||||
</div>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
在一周内发起请求的浏览器代理大类统计
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="bg-card/25 border-border/40 sm:col-span-2 lg:col-span-1">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<CardTitle className="text-sm font-semibold tracking-tight">活跃独立用户数</CardTitle>
|
||||
<Users className="size-4 text-muted-foreground" />
|
||||
<Card className='bg-card/25 border-border/40 sm:col-span-2 lg:col-span-1'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<CardTitle className='text-sm font-semibold tracking-tight'>
|
||||
活跃独立用户数
|
||||
</CardTitle>
|
||||
<Users className='size-4 text-muted-foreground' />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold font-mono">{topUsers.length}</div>
|
||||
<p className="text-[10px] text-muted-foreground mt-1">一周内累计发起高频请求的注册账户总量</p>
|
||||
<div className='text-2xl font-bold font-mono'>
|
||||
{topUsers.length}
|
||||
</div>
|
||||
<p className='text-[10px] text-muted-foreground mt-1'>
|
||||
一周内累计发起高频请求的注册账户总量
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Access Trend Chart */}
|
||||
<Card className="bg-card/20 border-border/40">
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<Card className='bg-card/20 border-border/40'>
|
||||
<CardHeader className='flex flex-row items-center justify-between'>
|
||||
<div>
|
||||
<CardTitle className="text-base font-bold">一周访问量趋势</CardTitle>
|
||||
<CardDescription className="text-xs">
|
||||
<CardTitle className='text-base font-bold'>
|
||||
一周访问量趋势
|
||||
</CardTitle>
|
||||
<CardDescription className='text-xs'>
|
||||
展现系统最近 7 天内的每日 API 请求曲线
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" className="size-8" onClick={fetchAnalytics} disabled={loading}>
|
||||
{loading ? <Spinner className="size-4" /> : <RefreshCw className="size-4 text-muted-foreground" />}
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='size-8'
|
||||
onClick={fetchAnalytics}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<Spinner className='size-4' />
|
||||
) : (
|
||||
<RefreshCw className='size-4 text-muted-foreground' />
|
||||
)}
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="pl-2 pr-4 pt-2">
|
||||
<CardContent className='pl-2 pr-4 pt-2'>
|
||||
{trend.length === 0 ? (
|
||||
<EmptyStateWithBorder icon={TrendingUp} description="暂无趋势数据" />
|
||||
<EmptyStateWithBorder
|
||||
icon={TrendingUp}
|
||||
description='暂无趋势数据'
|
||||
/>
|
||||
) : (
|
||||
<div className="h-[280px] w-full">
|
||||
<ChartContainer config={chartConfig} className="w-full h-full aspect-auto">
|
||||
<div className='h-[280px] w-full'>
|
||||
<ChartContainer
|
||||
config={chartConfig}
|
||||
className='w-full h-full aspect-auto'
|
||||
>
|
||||
<AreaChart
|
||||
data={trend}
|
||||
margin={{ top: 10, right: 10, left: -20, bottom: 0 }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="colorCount" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="var(--color-count)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="var(--color-count)" stopOpacity={0.01} />
|
||||
<linearGradient id='colorCount' x1='0' y1='0' x2='0' y2='1'>
|
||||
<stop
|
||||
offset='5%'
|
||||
stopColor='var(--color-count)'
|
||||
stopOpacity={0.3}
|
||||
/>
|
||||
<stop
|
||||
offset='95%'
|
||||
stopColor='var(--color-count)'
|
||||
stopOpacity={0.01}
|
||||
/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<CartesianGrid strokeDasharray='3 3' vertical={false} />
|
||||
<XAxis
|
||||
dataKey="formattedDate"
|
||||
dataKey='formattedDate'
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
dy={10}
|
||||
className="font-mono"
|
||||
className='font-mono'
|
||||
/>
|
||||
<YAxis
|
||||
tickLine={false}
|
||||
axisLine={false}
|
||||
dx={-10}
|
||||
className="font-mono"
|
||||
className='font-mono'
|
||||
/>
|
||||
<ChartTooltip content={<ChartTooltipContent />} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="count"
|
||||
stroke="var(--color-count)"
|
||||
type='monotone'
|
||||
dataKey='count'
|
||||
stroke='var(--color-count)'
|
||||
strokeWidth={2}
|
||||
fillOpacity={1}
|
||||
fill="url(#colorCount)"
|
||||
name="请求次数"
|
||||
fill='url(#colorCount)'
|
||||
name='请求次数'
|
||||
/>
|
||||
</AreaChart>
|
||||
</ChartContainer>
|
||||
@@ -226,46 +299,56 @@ export function AccessAnalytics() {
|
||||
</Card>
|
||||
|
||||
{/* Two Columns for Ranking Statistics */}
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<div className='grid gap-6 md:grid-cols-2'>
|
||||
{/* Browser Rankings */}
|
||||
<Card className="bg-card/20 border-border/40 flex flex-col h-full">
|
||||
<Card className='bg-card/20 border-border/40 flex flex-col h-full'>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-bold flex items-center gap-1.5">
|
||||
<Globe className="size-4.5 text-muted-foreground" />
|
||||
<CardTitle className='text-base font-bold flex items-center gap-1.5'>
|
||||
<Globe className='size-4.5 text-muted-foreground' />
|
||||
使用的浏览器排行
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs">
|
||||
<CardDescription className='text-xs'>
|
||||
基于请求头 User-Agent 智能分类的一周占比统计
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex-1">
|
||||
<CardContent className='flex-1'>
|
||||
{browsers.length === 0 ? (
|
||||
<EmptyStateWithBorder icon={Globe} description="暂无浏览器排行数据" />
|
||||
<EmptyStateWithBorder
|
||||
icon={Globe}
|
||||
description='暂无浏览器排行数据'
|
||||
/>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className='space-y-4'>
|
||||
{browsers.map((item, index) => {
|
||||
const percent = totalBrowserRequests > 0 ? (item.count / totalBrowserRequests) * 100 : 0
|
||||
const percent =
|
||||
totalBrowserRequests > 0
|
||||
? (item.count / totalBrowserRequests) * 100
|
||||
: 0;
|
||||
return (
|
||||
<div key={item.browser} className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs font-medium">
|
||||
<span className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="px-1.5 py-0 h-5 font-mono text-[10px] select-none">
|
||||
<div key={item.browser} className='space-y-1.5'>
|
||||
<div className='flex items-center justify-between text-xs font-medium'>
|
||||
<span className='flex items-center gap-2'>
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='px-1.5 py-0 h-5 font-mono text-[10px] select-none'
|
||||
>
|
||||
{index + 1}
|
||||
</Badge>
|
||||
<span className="font-semibold">{item.browser}</span>
|
||||
<span className='font-semibold'>{item.browser}</span>
|
||||
</span>
|
||||
<span className="text-muted-foreground font-mono text-xs">
|
||||
{item.count.toLocaleString()} 次 ({percent.toFixed(1)}%)
|
||||
<span className='text-muted-foreground font-mono text-xs'>
|
||||
{item.count.toLocaleString()} 次 ({percent.toFixed(1)}
|
||||
%)
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 w-full rounded-full bg-muted overflow-hidden">
|
||||
<div className='h-2 w-full rounded-full bg-muted overflow-hidden'>
|
||||
<div
|
||||
className="h-full bg-primary rounded-full transition-all duration-500"
|
||||
className='h-full bg-primary rounded-full transition-all duration-500'
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
@@ -273,39 +356,50 @@ export function AccessAnalytics() {
|
||||
</Card>
|
||||
|
||||
{/* Top Users */}
|
||||
<Card className="bg-card/20 border-border/40 flex flex-col h-full">
|
||||
<Card className='bg-card/20 border-border/40 flex flex-col h-full'>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-bold flex items-center gap-1.5">
|
||||
<Users className="size-4.5 text-muted-foreground" />
|
||||
<CardTitle className='text-base font-bold flex items-center gap-1.5'>
|
||||
<Users className='size-4.5 text-muted-foreground' />
|
||||
最活跃的用户排行 (Top 10)
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs">
|
||||
<CardDescription className='text-xs'>
|
||||
统计最近一周发起接口访问请求数量最多的账户
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex-1">
|
||||
<CardContent className='flex-1'>
|
||||
{topUsers.length === 0 ? (
|
||||
<EmptyStateWithBorder icon={Users} description="暂无活跃用户数据" />
|
||||
<EmptyStateWithBorder
|
||||
icon={Users}
|
||||
description='暂无活跃用户数据'
|
||||
/>
|
||||
) : (
|
||||
<div className="divide-y divide-border/40">
|
||||
<div className='divide-y divide-border/40'>
|
||||
{topUsers.map((user) => (
|
||||
<div key={user.user_id} className="flex items-center justify-between py-2.5 first:pt-0 last:pb-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary font-bold text-xs select-none">
|
||||
{(user.username || "U").slice(0, 1).toUpperCase()}
|
||||
<div
|
||||
key={user.user_id}
|
||||
className='flex items-center justify-between py-2.5 first:pt-0 last:pb-0'
|
||||
>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary font-bold text-xs select-none'>
|
||||
{(user.username || 'U').slice(0, 1).toUpperCase()}
|
||||
</div>
|
||||
<div className="truncate max-w-[180px] sm:max-w-xs">
|
||||
<div className="text-xs font-bold leading-tight truncate">
|
||||
{user.username || "未知"}
|
||||
<div className='truncate max-w-[180px] sm:max-w-xs'>
|
||||
<div className='text-xs font-bold leading-tight truncate'>
|
||||
{user.username || '未知'}
|
||||
</div>
|
||||
<div className="text-[10px] text-muted-foreground leading-normal truncate">
|
||||
{user.nickname ? `(${user.nickname})` : "(无昵称)"} | ID: {user.user_id}
|
||||
<div className='text-[10px] text-muted-foreground leading-normal truncate'>
|
||||
{user.nickname ? `(${user.nickname})` : '(无昵称)'} |
|
||||
ID: {user.user_id}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right shrink-0">
|
||||
<div className="text-xs font-bold font-mono">{user.count.toLocaleString()}</div>
|
||||
<div className="text-[9px] text-muted-foreground uppercase font-bold tracking-wider">次请求</div>
|
||||
<div className='text-right shrink-0'>
|
||||
<div className='text-xs font-bold font-mono'>
|
||||
{user.count.toLocaleString()}
|
||||
</div>
|
||||
<div className='text-[9px] text-muted-foreground uppercase font-bold tracking-wider'>
|
||||
次请求
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -315,5 +409,5 @@ export function AccessAnalytics() {
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,441 +14,540 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useMemo, useState} from "react"
|
||||
import {useQuery} from "@tanstack/react-query"
|
||||
import {toast} from "sonner"
|
||||
import {format} from "date-fns"
|
||||
import {Activity, ChevronLeft, ChevronRight, Copy, Eye, RotateCcw, Search, XCircle} from "lucide-react"
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { format } from 'date-fns';
|
||||
import {
|
||||
Activity,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Copy,
|
||||
Eye,
|
||||
RotateCcw,
|
||||
Search,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
|
||||
import services from "@/lib/services"
|
||||
import {ErrorInline} from "@/components/layout/error"
|
||||
import {LoadingStateWithBorder} from "@/components/layout/loading"
|
||||
import {EmptyStateWithBorder} from "@/components/layout/empty"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Label} from "@/components/ui/label"
|
||||
import {Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle} from "@/components/ui/sheet"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow} from "@/components/ui/table"
|
||||
import services from '@/lib/services';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
|
||||
interface AccessLog {
|
||||
id: string
|
||||
user_id: string
|
||||
username: string
|
||||
nickname: string
|
||||
path: string
|
||||
method: string
|
||||
ip: string
|
||||
user_agent: string
|
||||
headers: string
|
||||
status: number
|
||||
latency: number
|
||||
created_at: string
|
||||
id: string;
|
||||
user_id: string;
|
||||
username: string;
|
||||
nickname: string;
|
||||
path: string;
|
||||
method: string;
|
||||
ip: string;
|
||||
user_agent: string;
|
||||
headers: string;
|
||||
status: number;
|
||||
latency: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 15
|
||||
const PAGE_SIZE = 15;
|
||||
|
||||
function formatDateTime(value?: string | null) {
|
||||
if (!value) return "-"
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) return value
|
||||
return format(date, "yyyy-MM-dd HH:mm:ss")
|
||||
if (!value) return '-';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return format(date, 'yyyy-MM-dd HH:mm:ss');
|
||||
}
|
||||
|
||||
function formatLatency(ms: number) {
|
||||
if (ms < 1000) return `${ms}ms`
|
||||
return `${(ms / 1000).toFixed(2)}s`
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
return `${(ms / 1000).toFixed(2)}s`;
|
||||
}
|
||||
|
||||
function statusVariant(status: number) {
|
||||
if (status >= 500) return "destructive"
|
||||
if (status >= 400) return "destructive"
|
||||
if (status >= 300) return "outline"
|
||||
return "secondary"
|
||||
if (status >= 500) return 'destructive';
|
||||
if (status >= 400) return 'destructive';
|
||||
if (status >= 300) return 'outline';
|
||||
return 'secondary';
|
||||
}
|
||||
|
||||
function isClickhouseDisabledError(error: Error) {
|
||||
const errMsg = error.message || ""
|
||||
return errMsg.includes("ClickHouse") || errMsg.includes("未启用")
|
||||
const errMsg = error.message || '';
|
||||
return errMsg.includes('ClickHouse') || errMsg.includes('未启用');
|
||||
}
|
||||
|
||||
export function AccessLogs() {
|
||||
const [page, setPage] = useState(1)
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
// 搜索过滤条件
|
||||
const [usernameFilter, setUsernameFilter] = useState("")
|
||||
const [pathFilter, setPathFilter] = useState("")
|
||||
const [startTimeFilter, setStartTimeFilter] = useState("")
|
||||
const [endTimeFilter, setEndTimeFilter] = useState("")
|
||||
// 搜索过滤条件
|
||||
const [usernameFilter, setUsernameFilter] = useState('');
|
||||
const [pathFilter, setPathFilter] = useState('');
|
||||
const [startTimeFilter, setStartTimeFilter] = useState('');
|
||||
const [endTimeFilter, setEndTimeFilter] = useState('');
|
||||
|
||||
// 实际提交的搜索条件
|
||||
const [searchParams, setSearchParams] = useState({
|
||||
username: "",
|
||||
path: "",
|
||||
start_time: "",
|
||||
end_time: "",
|
||||
})
|
||||
// 实际提交的搜索条件
|
||||
const [searchParams, setSearchParams] = useState({
|
||||
username: '',
|
||||
path: '',
|
||||
start_time: '',
|
||||
end_time: '',
|
||||
});
|
||||
|
||||
const [selectedLog, setSelectedLog] = useState<AccessLog | null>(null)
|
||||
const [detailOpen, setDetailOpen] = useState(false)
|
||||
const [selectedLog, setSelectedLog] = useState<AccessLog | null>(null);
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
|
||||
const logsQuery = useQuery({
|
||||
queryKey: ["admin", "access-logs", page, searchParams],
|
||||
queryFn: async () => {
|
||||
let startISO = ""
|
||||
if (searchParams.start_time) {
|
||||
startISO = new Date(searchParams.start_time).toISOString()
|
||||
}
|
||||
let endISO = ""
|
||||
if (searchParams.end_time) {
|
||||
endISO = new Date(searchParams.end_time).toISOString()
|
||||
}
|
||||
const logsQuery = useQuery({
|
||||
queryKey: ['admin', 'access-logs', page, searchParams],
|
||||
queryFn: async () => {
|
||||
let startISO = '';
|
||||
if (searchParams.start_time) {
|
||||
startISO = new Date(searchParams.start_time).toISOString();
|
||||
}
|
||||
let endISO = '';
|
||||
if (searchParams.end_time) {
|
||||
endISO = new Date(searchParams.end_time).toISOString();
|
||||
}
|
||||
|
||||
return services.adminLog.getAccessLogs({
|
||||
page,
|
||||
page_size: PAGE_SIZE,
|
||||
username: searchParams.username || undefined,
|
||||
path: searchParams.path || undefined,
|
||||
start_time: startISO || undefined,
|
||||
end_time: endISO || undefined,
|
||||
})
|
||||
},
|
||||
retry: false,
|
||||
})
|
||||
return services.adminLog.getAccessLogs({
|
||||
page,
|
||||
page_size: PAGE_SIZE,
|
||||
username: searchParams.username || undefined,
|
||||
path: searchParams.path || undefined,
|
||||
start_time: startISO || undefined,
|
||||
end_time: endISO || undefined,
|
||||
});
|
||||
},
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const logs = logsQuery.data?.list ?? []
|
||||
const total = logsQuery.data?.total ?? 0
|
||||
const loading = logsQuery.isPending || logsQuery.isFetching
|
||||
const clickhouseDisabled = logsQuery.isError && isClickhouseDisabledError(logsQuery.error)
|
||||
const error = logsQuery.isError && !clickhouseDisabled ? logsQuery.error : null
|
||||
const logs = logsQuery.data?.list ?? [];
|
||||
const total = logsQuery.data?.total ?? 0;
|
||||
const loading = logsQuery.isPending || logsQuery.isFetching;
|
||||
const clickhouseDisabled =
|
||||
logsQuery.isError && isClickhouseDisabledError(logsQuery.error);
|
||||
const error =
|
||||
logsQuery.isError && !clickhouseDisabled ? logsQuery.error : null;
|
||||
|
||||
const totalPages = useMemo(() => Math.max(1, Math.ceil(total / PAGE_SIZE)), [total])
|
||||
const totalPages = useMemo(
|
||||
() => Math.max(1, Math.ceil(total / PAGE_SIZE)),
|
||||
[total],
|
||||
);
|
||||
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setPage(1)
|
||||
setSearchParams({
|
||||
username: usernameFilter.trim(),
|
||||
path: pathFilter.trim(),
|
||||
start_time: startTimeFilter,
|
||||
end_time: endTimeFilter,
|
||||
})
|
||||
}
|
||||
const handleSearch = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setPage(1);
|
||||
setSearchParams({
|
||||
username: usernameFilter.trim(),
|
||||
path: pathFilter.trim(),
|
||||
start_time: startTimeFilter,
|
||||
end_time: endTimeFilter,
|
||||
});
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setUsernameFilter("")
|
||||
setPathFilter("")
|
||||
setStartTimeFilter("")
|
||||
setEndTimeFilter("")
|
||||
setPage(1)
|
||||
setSearchParams({
|
||||
username: "",
|
||||
path: "",
|
||||
start_time: "",
|
||||
end_time: "",
|
||||
})
|
||||
}
|
||||
const handleReset = () => {
|
||||
setUsernameFilter('');
|
||||
setPathFilter('');
|
||||
setStartTimeFilter('');
|
||||
setEndTimeFilter('');
|
||||
setPage(1);
|
||||
setSearchParams({
|
||||
username: '',
|
||||
path: '',
|
||||
start_time: '',
|
||||
end_time: '',
|
||||
});
|
||||
};
|
||||
|
||||
const handlePageChange = (newPage: number) => {
|
||||
setPage(newPage)
|
||||
}
|
||||
const handlePageChange = (newPage: number) => {
|
||||
setPage(newPage);
|
||||
};
|
||||
|
||||
const copyToClipboard = (text: string, subject: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
toast.success(`${subject}已复制到剪贴板`)
|
||||
}
|
||||
const copyToClipboard = (text: string, subject: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
toast.success(`${subject}已复制到剪贴板`);
|
||||
};
|
||||
|
||||
// Prettify Headers JSON string
|
||||
const getPrettyHeaders = (headersRaw?: string) => {
|
||||
if (!headersRaw) return "暂无头部数据"
|
||||
try {
|
||||
const parsed = JSON.parse(headersRaw)
|
||||
return JSON.stringify(parsed, null, 2)
|
||||
} catch {
|
||||
return headersRaw
|
||||
}
|
||||
}
|
||||
// Prettify Headers JSON string
|
||||
const getPrettyHeaders = (headersRaw?: string) => {
|
||||
if (!headersRaw) return '暂无头部数据';
|
||||
try {
|
||||
const parsed = JSON.parse(headersRaw);
|
||||
return JSON.stringify(parsed, null, 2);
|
||||
} catch {
|
||||
return headersRaw;
|
||||
}
|
||||
};
|
||||
|
||||
if (clickhouseDisabled) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 border border-dashed rounded-lg bg-card text-center my-6 min-h-[300px]">
|
||||
<XCircle className="size-10 text-muted-foreground mb-3" />
|
||||
<h3 className="text-base font-semibold">ClickHouse 未启用</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1 max-w-[400px] mb-4">
|
||||
当前系统配置未启用 ClickHouse 存储,系统不会收集用户访问日志。如需使用此功能,请在后端 `config.yaml` 配置文件中配置并启用 ClickHouse。
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (clickhouseDisabled) {
|
||||
return (
|
||||
<div className='flex flex-col items-center justify-center p-8 border border-dashed rounded-lg bg-card text-center my-6 min-h-[300px]'>
|
||||
<XCircle className='size-10 text-muted-foreground mb-3' />
|
||||
<h3 className='text-base font-semibold'>ClickHouse 未启用</h3>
|
||||
<p className='text-sm text-muted-foreground mt-1 max-w-[400px] mb-4'>
|
||||
当前系统配置未启用 ClickHouse
|
||||
存储,系统不会收集用户访问日志。如需使用此功能,请在后端 `config.yaml`
|
||||
配置文件中配置并启用 ClickHouse。
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return <ErrorInline error={error} onRetry={() => void logsQuery.refetch()} />
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<ErrorInline error={error} onRetry={() => void logsQuery.refetch()} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Filters */}
|
||||
<form onSubmit={handleSearch} className="grid gap-3 p-4 border rounded-lg bg-card/30 md:grid-cols-5 items-end">
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="search-user" className="text-xs">用户名</Label>
|
||||
<Input
|
||||
id="search-user"
|
||||
placeholder="输入用户名搜索..."
|
||||
value={usernameFilter}
|
||||
onChange={(e) => setUsernameFilter(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="search-path" className="text-xs">接口路径</Label>
|
||||
<Input
|
||||
id="search-path"
|
||||
placeholder="模糊匹配路径..."
|
||||
value={pathFilter}
|
||||
onChange={(e) => setPathFilter(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="search-start" className="text-xs">起始时间</Label>
|
||||
<Input
|
||||
id="search-start"
|
||||
type="datetime-local"
|
||||
value={startTimeFilter}
|
||||
onChange={(e) => setStartTimeFilter(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="search-end" className="text-xs">结束时间</Label>
|
||||
<Input
|
||||
id="search-end"
|
||||
type="datetime-local"
|
||||
value={endTimeFilter}
|
||||
onChange={(e) => setEndTimeFilter(e.target.value)}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit" size="sm" className="h-8 flex-1">
|
||||
<Search className="size-3.5 mr-1" />
|
||||
搜索
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleReset} className="h-8 flex-1">
|
||||
<RotateCcw className="size-3.5 mr-1" />
|
||||
重置
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
return (
|
||||
<div className='space-y-4'>
|
||||
{/* Filters */}
|
||||
<form
|
||||
onSubmit={handleSearch}
|
||||
className='grid gap-3 p-4 border rounded-lg bg-card/30 md:grid-cols-5 items-end'
|
||||
>
|
||||
<div className='grid gap-1.5'>
|
||||
<Label htmlFor='search-user' className='text-xs'>
|
||||
用户名
|
||||
</Label>
|
||||
<Input
|
||||
id='search-user'
|
||||
placeholder='输入用户名搜索...'
|
||||
value={usernameFilter}
|
||||
onChange={(e) => setUsernameFilter(e.target.value)}
|
||||
className='h-8 text-xs'
|
||||
/>
|
||||
</div>
|
||||
<div className='grid gap-1.5'>
|
||||
<Label htmlFor='search-path' className='text-xs'>
|
||||
接口路径
|
||||
</Label>
|
||||
<Input
|
||||
id='search-path'
|
||||
placeholder='模糊匹配路径...'
|
||||
value={pathFilter}
|
||||
onChange={(e) => setPathFilter(e.target.value)}
|
||||
className='h-8 text-xs'
|
||||
/>
|
||||
</div>
|
||||
<div className='grid gap-1.5'>
|
||||
<Label htmlFor='search-start' className='text-xs'>
|
||||
起始时间
|
||||
</Label>
|
||||
<Input
|
||||
id='search-start'
|
||||
type='datetime-local'
|
||||
value={startTimeFilter}
|
||||
onChange={(e) => setStartTimeFilter(e.target.value)}
|
||||
className='h-8 text-xs'
|
||||
/>
|
||||
</div>
|
||||
<div className='grid gap-1.5'>
|
||||
<Label htmlFor='search-end' className='text-xs'>
|
||||
结束时间
|
||||
</Label>
|
||||
<Input
|
||||
id='search-end'
|
||||
type='datetime-local'
|
||||
value={endTimeFilter}
|
||||
onChange={(e) => setEndTimeFilter(e.target.value)}
|
||||
className='h-8 text-xs'
|
||||
/>
|
||||
</div>
|
||||
<div className='flex gap-2'>
|
||||
<Button type='submit' size='sm' className='h-8 flex-1'>
|
||||
<Search className='size-3.5 mr-1' />
|
||||
搜索
|
||||
</Button>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={handleReset}
|
||||
className='h-8 flex-1'
|
||||
>
|
||||
<RotateCcw className='size-3.5 mr-1' />
|
||||
重置
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Loading Table */}
|
||||
{loading && logs.length === 0 ? (
|
||||
<LoadingStateWithBorder icon={Activity} description="加载访问日志中..." />
|
||||
) : logs.length === 0 ? (
|
||||
<EmptyStateWithBorder icon={Activity} description="未查询到任何访问日志数据" />
|
||||
) : (
|
||||
<div className="rounded-lg border bg-card overflow-hidden">
|
||||
<Table className="min-w-[900px]">
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent">
|
||||
<TableHead className="w-[100px]">请求方法</TableHead>
|
||||
<TableHead className="min-w-[200px]">路径</TableHead>
|
||||
<TableHead className="w-[150px]">用户</TableHead>
|
||||
<TableHead className="w-[120px]">IP</TableHead>
|
||||
<TableHead className="w-[90px]">状态</TableHead>
|
||||
<TableHead className="w-[100px]">耗时</TableHead>
|
||||
<TableHead className="w-[170px]">请求时间</TableHead>
|
||||
<TableHead className="w-[80px] text-center">详情</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{logs.map((log) => (
|
||||
<TableRow key={log.id} className="hover:bg-muted/30">
|
||||
<TableCell>
|
||||
<Badge variant="outline" className="font-mono font-semibold uppercase text-xs">
|
||||
{log.method}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-xs break-all max-w-[280px]">
|
||||
{log.path}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-xs font-medium">{log.username || "未知用户"}</span>
|
||||
{log.nickname && (
|
||||
<span className="text-[10px] text-muted-foreground">({log.nickname})</span>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||
{log.ip}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={statusVariant(log.status)}>
|
||||
{log.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-xs text-muted-foreground">
|
||||
{formatLatency(log.latency)}
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-[11px] text-muted-foreground">
|
||||
{formatDateTime(log.created_at)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 hover:bg-muted"
|
||||
onClick={() => {
|
||||
setSelectedLog(log)
|
||||
setDetailOpen(true)
|
||||
}}
|
||||
>
|
||||
<Eye className="size-3.5" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
{/* Loading Table */}
|
||||
{loading && logs.length === 0 ? (
|
||||
<LoadingStateWithBorder
|
||||
icon={Activity}
|
||||
description='加载访问日志中...'
|
||||
/>
|
||||
) : logs.length === 0 ? (
|
||||
<EmptyStateWithBorder
|
||||
icon={Activity}
|
||||
description='未查询到任何访问日志数据'
|
||||
/>
|
||||
) : (
|
||||
<div className='rounded-lg border bg-card overflow-hidden'>
|
||||
<Table className='min-w-[900px]'>
|
||||
<TableHeader>
|
||||
<TableRow className='hover:bg-transparent'>
|
||||
<TableHead className='w-[100px]'>请求方法</TableHead>
|
||||
<TableHead className='min-w-[200px]'>路径</TableHead>
|
||||
<TableHead className='w-[150px]'>用户</TableHead>
|
||||
<TableHead className='w-[120px]'>IP</TableHead>
|
||||
<TableHead className='w-[90px]'>状态</TableHead>
|
||||
<TableHead className='w-[100px]'>耗时</TableHead>
|
||||
<TableHead className='w-[170px]'>请求时间</TableHead>
|
||||
<TableHead className='w-[80px] text-center'>详情</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{logs.map((log) => (
|
||||
<TableRow key={log.id} className='hover:bg-muted/30'>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant='outline'
|
||||
className='font-mono font-semibold uppercase text-xs'
|
||||
>
|
||||
{log.method}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className='font-mono text-xs break-all max-w-[280px]'>
|
||||
{log.path}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-xs font-medium'>
|
||||
{log.username || '未知用户'}
|
||||
</span>
|
||||
{log.nickname && (
|
||||
<span className='text-[10px] text-muted-foreground'>
|
||||
({log.nickname})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className='font-mono text-xs text-muted-foreground'>
|
||||
{log.ip}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={statusVariant(log.status)}>
|
||||
{log.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className='font-mono text-xs text-muted-foreground'>
|
||||
{formatLatency(log.latency)}
|
||||
</TableCell>
|
||||
<TableCell className='font-mono text-[11px] text-muted-foreground'>
|
||||
{formatDateTime(log.created_at)}
|
||||
</TableCell>
|
||||
<TableCell className='text-center'>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='size-7 hover:bg-muted'
|
||||
onClick={() => {
|
||||
setSelectedLog(log);
|
||||
setDetailOpen(true);
|
||||
}}
|
||||
>
|
||||
<Eye className='size-3.5' />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{logs.length > 0 && (
|
||||
<div className="flex items-center justify-between py-1">
|
||||
<div className="text-xs text-muted-foreground">
|
||||
共 {total} 条记录,当前第 {page}/{totalPages} 页
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePageChange(Math.max(1, page - 1))}
|
||||
disabled={page <= 1 || loading}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<ChevronLeft className="size-3.5 mr-1" />
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePageChange(Math.min(totalPages, page + 1))}
|
||||
disabled={page >= totalPages || loading}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
下一页
|
||||
<ChevronRight className="size-3.5 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Pagination */}
|
||||
{logs.length > 0 && (
|
||||
<div className='flex items-center justify-between py-1'>
|
||||
<div className='text-xs text-muted-foreground'>
|
||||
共 {total} 条记录,当前第 {page}/{totalPages} 页
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() => handlePageChange(Math.max(1, page - 1))}
|
||||
disabled={page <= 1 || loading}
|
||||
className='h-8 text-xs'
|
||||
>
|
||||
<ChevronLeft className='size-3.5 mr-1' />
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() => handlePageChange(Math.min(totalPages, page + 1))}
|
||||
disabled={page >= totalPages || loading}
|
||||
className='h-8 text-xs'
|
||||
>
|
||||
下一页
|
||||
<ChevronRight className='size-3.5 ml-1' />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Detail Drawer */}
|
||||
<Sheet open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
<SheetContent className="w-full p-0 sm:max-w-[640px] flex flex-col h-full bg-background border-l">
|
||||
<SheetHeader className="border-b px-5 py-4 shrink-0">
|
||||
<SheetTitle className="text-lg font-bold">访问日志详情</SheetTitle>
|
||||
<SheetDescription className="text-xs">
|
||||
访问 ID: {selectedLog?.id}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
{/* Detail Drawer */}
|
||||
<Sheet open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
<SheetContent className='w-full p-0 sm:max-w-[640px] flex flex-col h-full bg-background border-l'>
|
||||
<SheetHeader className='border-b px-5 py-4 shrink-0'>
|
||||
<SheetTitle className='text-lg font-bold'>访问日志详情</SheetTitle>
|
||||
<SheetDescription className='text-xs'>
|
||||
访问 ID: {selectedLog?.id}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
{selectedLog ? (
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4 space-y-5">
|
||||
{/* Summary Details */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
<div className="rounded-lg border p-3 bg-muted/10">
|
||||
<div className="text-[10px] text-muted-foreground uppercase font-bold tracking-wider">请求方法</div>
|
||||
<div className="mt-1 font-mono text-sm font-bold uppercase">{selectedLog.method}</div>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3 bg-muted/10">
|
||||
<div className="text-[10px] text-muted-foreground uppercase font-bold tracking-wider">响应状态</div>
|
||||
<div className="mt-1">
|
||||
<Badge variant={statusVariant(selectedLog.status)}>
|
||||
{selectedLog.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3 bg-muted/10">
|
||||
<div className="text-[10px] text-muted-foreground uppercase font-bold tracking-wider">耗时</div>
|
||||
<div className="mt-1 font-mono text-sm">{formatLatency(selectedLog.latency)}</div>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3 bg-muted/10 col-span-2 sm:col-span-1">
|
||||
<div className="text-[10px] text-muted-foreground uppercase font-bold tracking-wider">IP 地址</div>
|
||||
<div className="mt-1 font-mono text-sm">{selectedLog.ip}</div>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3 bg-muted/10 col-span-2">
|
||||
<div className="text-[10px] text-muted-foreground uppercase font-bold tracking-wider">用户</div>
|
||||
<div className="mt-1 text-sm font-medium">
|
||||
{selectedLog.username ? `${selectedLog.username} (${selectedLog.nickname || '无昵称'})` : "未知/游客"}
|
||||
<span className="block font-mono text-[10px] text-muted-foreground mt-0.5">ID: {selectedLog.user_id}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{selectedLog ? (
|
||||
<div className='flex-1 overflow-y-auto px-5 py-4 space-y-5'>
|
||||
{/* Summary Details */}
|
||||
<div className='grid grid-cols-2 gap-3 sm:grid-cols-3'>
|
||||
<div className='rounded-lg border p-3 bg-muted/10'>
|
||||
<div className='text-[10px] text-muted-foreground uppercase font-bold tracking-wider'>
|
||||
请求方法
|
||||
</div>
|
||||
<div className='mt-1 font-mono text-sm font-bold uppercase'>
|
||||
{selectedLog.method}
|
||||
</div>
|
||||
</div>
|
||||
<div className='rounded-lg border p-3 bg-muted/10'>
|
||||
<div className='text-[10px] text-muted-foreground uppercase font-bold tracking-wider'>
|
||||
响应状态
|
||||
</div>
|
||||
<div className='mt-1'>
|
||||
<Badge variant={statusVariant(selectedLog.status)}>
|
||||
{selectedLog.status}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className='rounded-lg border p-3 bg-muted/10'>
|
||||
<div className='text-[10px] text-muted-foreground uppercase font-bold tracking-wider'>
|
||||
耗时
|
||||
</div>
|
||||
<div className='mt-1 font-mono text-sm'>
|
||||
{formatLatency(selectedLog.latency)}
|
||||
</div>
|
||||
</div>
|
||||
<div className='rounded-lg border p-3 bg-muted/10 col-span-2 sm:col-span-1'>
|
||||
<div className='text-[10px] text-muted-foreground uppercase font-bold tracking-wider'>
|
||||
IP 地址
|
||||
</div>
|
||||
<div className='mt-1 font-mono text-sm'>{selectedLog.ip}</div>
|
||||
</div>
|
||||
<div className='rounded-lg border p-3 bg-muted/10 col-span-2'>
|
||||
<div className='text-[10px] text-muted-foreground uppercase font-bold tracking-wider'>
|
||||
用户
|
||||
</div>
|
||||
<div className='mt-1 text-sm font-medium'>
|
||||
{selectedLog.username
|
||||
? `${selectedLog.username} (${selectedLog.nickname || '无昵称'})`
|
||||
: '未知/游客'}
|
||||
<span className='block font-mono text-[10px] text-muted-foreground mt-0.5'>
|
||||
ID: {selectedLog.user_id}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Path */}
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-xs font-bold text-muted-foreground">请求路径</Label>
|
||||
<div className="rounded-md border bg-muted/30 px-3 py-2 font-mono text-xs break-all">
|
||||
{selectedLog.path}
|
||||
</div>
|
||||
</div>
|
||||
{/* Path */}
|
||||
<div className='grid gap-2'>
|
||||
<Label className='text-xs font-bold text-muted-foreground'>
|
||||
请求路径
|
||||
</Label>
|
||||
<div className='rounded-md border bg-muted/30 px-3 py-2 font-mono text-xs break-all'>
|
||||
{selectedLog.path}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Request Time */}
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-xs font-bold text-muted-foreground">请求时间</Label>
|
||||
<div className="font-mono text-xs">{formatDateTime(selectedLog.created_at)}</div>
|
||||
</div>
|
||||
{/* Request Time */}
|
||||
<div className='grid gap-2'>
|
||||
<Label className='text-xs font-bold text-muted-foreground'>
|
||||
请求时间
|
||||
</Label>
|
||||
<div className='font-mono text-xs'>
|
||||
{formatDateTime(selectedLog.created_at)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* User Agent */}
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-bold text-muted-foreground">User-Agent</Label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => copyToClipboard(selectedLog.user_agent, "User-Agent")}
|
||||
title="复制 User-Agent"
|
||||
>
|
||||
<Copy className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-md border bg-muted/20 px-3 py-2 text-xs font-mono break-all max-h-24 overflow-y-auto leading-relaxed">
|
||||
{selectedLog.user_agent}
|
||||
</div>
|
||||
</div>
|
||||
{/* User Agent */}
|
||||
<div className='grid gap-2'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className='text-xs font-bold text-muted-foreground'>
|
||||
User-Agent
|
||||
</Label>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='size-6 text-muted-foreground hover:text-foreground'
|
||||
onClick={() =>
|
||||
copyToClipboard(selectedLog.user_agent, 'User-Agent')
|
||||
}
|
||||
title='复制 User-Agent'
|
||||
>
|
||||
<Copy className='size-3' />
|
||||
</Button>
|
||||
</div>
|
||||
<div className='rounded-md border bg-muted/20 px-3 py-2 text-xs font-mono break-all max-h-24 overflow-y-auto leading-relaxed'>
|
||||
{selectedLog.user_agent}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Headers */}
|
||||
<div className="grid gap-2 flex-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-bold text-muted-foreground">Request Headers</Label>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => copyToClipboard(getPrettyHeaders(selectedLog.headers), "Headers")}
|
||||
title="复制 Headers"
|
||||
>
|
||||
<Copy className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="overflow-auto rounded-md border bg-[#0d1117] p-3 text-xs leading-relaxed text-gray-300 font-mono max-h-[300px]">
|
||||
{getPrettyHeaders(selectedLog.headers)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-grow flex items-center justify-center">
|
||||
<EmptyStateWithBorder icon={Activity} description="未选中日志明细" />
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{/* Headers */}
|
||||
<div className='grid gap-2 flex-1'>
|
||||
<div className='flex items-center justify-between'>
|
||||
<Label className='text-xs font-bold text-muted-foreground'>
|
||||
Request Headers
|
||||
</Label>
|
||||
<Button
|
||||
variant='ghost'
|
||||
size='icon'
|
||||
className='size-6 text-muted-foreground hover:text-foreground'
|
||||
onClick={() =>
|
||||
copyToClipboard(
|
||||
getPrettyHeaders(selectedLog.headers),
|
||||
'Headers',
|
||||
)
|
||||
}
|
||||
title='复制 Headers'
|
||||
>
|
||||
<Copy className='size-3' />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className='overflow-auto rounded-md border bg-[#0d1117] p-3 text-xs leading-relaxed text-gray-300 font-mono max-h-[300px]'>
|
||||
{getPrettyHeaders(selectedLog.headers)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className='flex-grow flex items-center justify-center'>
|
||||
<EmptyStateWithBorder
|
||||
icon={Activity}
|
||||
description='未选中日志明细'
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,92 +14,103 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {memo, useCallback, useEffect, useRef, useState} from "react"
|
||||
import {useVirtualizer} from "@tanstack/react-virtual"
|
||||
import {toast} from "sonner"
|
||||
import {ArrowDown, ChevronUp, Loader2} from "lucide-react"
|
||||
import { memo, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { toast } from 'sonner';
|
||||
import { ArrowDown, ChevronUp, Loader2 } from 'lucide-react';
|
||||
|
||||
import services from "@/lib/services"
|
||||
import {ErrorInline} from "@/components/layout/error"
|
||||
import {LoadingStateWithBorder} from "@/components/layout/loading"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import services from '@/lib/services';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface LogEntry {
|
||||
index: number
|
||||
data: string
|
||||
index: number;
|
||||
data: string;
|
||||
}
|
||||
|
||||
// Distance (px) from bottom to treat as "at bottom"
|
||||
const BOTTOM_THRESHOLD = 40
|
||||
const LOG_LINE_ESTIMATE_PX = 20
|
||||
const LOG_VIRTUAL_OVERSCAN = 24
|
||||
const BOTTOM_THRESHOLD = 40;
|
||||
const LOG_LINE_ESTIMATE_PX = 20;
|
||||
const LOG_VIRTUAL_OVERSCAN = 24;
|
||||
|
||||
const LogLine = memo(function LogLine({data}: {data: string}) {
|
||||
const level = parseLogLevel(data)
|
||||
const color = level === "error"
|
||||
? "text-red-400"
|
||||
: level === "warn"
|
||||
? "text-yellow-400"
|
||||
: level === "debug"
|
||||
? "text-gray-500"
|
||||
: "text-gray-300"
|
||||
const LogLine = memo(function LogLine({ data }: { data: string }) {
|
||||
const level = parseLogLevel(data);
|
||||
const color =
|
||||
level === 'error'
|
||||
? 'text-red-400'
|
||||
: level === 'warn'
|
||||
? 'text-yellow-400'
|
||||
: level === 'debug'
|
||||
? 'text-gray-500'
|
||||
: 'text-gray-300';
|
||||
|
||||
return (
|
||||
<div className={`${color} whitespace-pre-wrap break-all px-2 py-0.5 rounded hover:bg-white/5`}>
|
||||
<div
|
||||
className={`${color} whitespace-pre-wrap break-all px-2 py-0.5 rounded hover:bg-white/5`}
|
||||
>
|
||||
{data}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
function getApiBaseUrl(): string {
|
||||
if (typeof window !== "undefined") {
|
||||
if (typeof window !== 'undefined') {
|
||||
// If NEXT_PUBLIC_WAVELET_BACKEND_URL is set, use it. Otherwise, use origin.
|
||||
const base = process.env.NEXT_PUBLIC_WAVELET_BACKEND_URL || ""
|
||||
if (base.startsWith("http")) return base
|
||||
const base = process.env.NEXT_PUBLIC_WAVELET_BACKEND_URL || '';
|
||||
if (base.startsWith('http')) return base;
|
||||
|
||||
// Relative URL fallback
|
||||
const proto = window.location.protocol
|
||||
const host = window.location.host
|
||||
return `${proto}//${host}${base}`
|
||||
const proto = window.location.protocol;
|
||||
const host = window.location.host;
|
||||
return `${proto}//${host}${base}`;
|
||||
}
|
||||
return process.env.NEXT_PUBLIC_WAVELET_BACKEND_URL || ""
|
||||
return process.env.NEXT_PUBLIC_WAVELET_BACKEND_URL || '';
|
||||
}
|
||||
|
||||
function buildWsUrl(): string {
|
||||
const base = getApiBaseUrl()
|
||||
const wsBase = base.replace(/^http/, "ws")
|
||||
return `${wsBase}/api/v1/admin/logs/ws`
|
||||
const base = getApiBaseUrl();
|
||||
const wsBase = base.replace(/^http/, 'ws');
|
||||
return `${wsBase}/api/v1/admin/logs/ws`;
|
||||
}
|
||||
|
||||
function parseLogLevel(line: string): "debug" | "info" | "warn" | "error" | "unknown" {
|
||||
const lower = line.toLowerCase()
|
||||
if (lower.includes("\"level\":\"error\"") || lower.includes("level=error")) return "error"
|
||||
if (lower.includes("\"level\":\"warn\"") || lower.includes("level=warn")) return "warn"
|
||||
if (lower.includes("\"level\":\"debug\"") || lower.includes("level=debug")) return "debug"
|
||||
if (lower.includes("\"level\":\"info\"") || lower.includes("level=info")) return "info"
|
||||
return "unknown"
|
||||
function parseLogLevel(
|
||||
line: string,
|
||||
): 'debug' | 'info' | 'warn' | 'error' | 'unknown' {
|
||||
const lower = line.toLowerCase();
|
||||
if (lower.includes('"level":"error"') || lower.includes('level=error'))
|
||||
return 'error';
|
||||
if (lower.includes('"level":"warn"') || lower.includes('level=warn'))
|
||||
return 'warn';
|
||||
if (lower.includes('"level":"debug"') || lower.includes('level=debug'))
|
||||
return 'debug';
|
||||
if (lower.includes('"level":"info"') || lower.includes('level=info'))
|
||||
return 'info';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
export function AppLogs() {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<Error | null>(null)
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const [logs, setLogs] = useState<LogEntry[]>([])
|
||||
const [hasMore, setHasMore] = useState(false)
|
||||
const [nextCursor, setNextCursor] = useState(0)
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
const [logs, setLogs] = useState<LogEntry[]>([]);
|
||||
const [hasMore, setHasMore] = useState(false);
|
||||
const [nextCursor, setNextCursor] = useState(0);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
|
||||
// autoScroll = true → new logs auto-scroll to bottom
|
||||
const [autoScroll, setAutoScroll] = useState(true)
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const wsRef = useRef<WebSocket | null>(null)
|
||||
const autoScrollRef = useRef(autoScroll)
|
||||
const isUserScrolling = useRef(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
const autoScrollRef = useRef(autoScroll);
|
||||
const isUserScrolling = useRef(false);
|
||||
|
||||
useEffect(() => { autoScrollRef.current = autoScroll }, [autoScroll])
|
||||
useEffect(() => {
|
||||
autoScrollRef.current = autoScroll;
|
||||
}, [autoScroll]);
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: logs.length,
|
||||
@@ -107,200 +118,222 @@ export function AppLogs() {
|
||||
estimateSize: () => LOG_LINE_ESTIMATE_PX,
|
||||
overscan: LOG_VIRTUAL_OVERSCAN,
|
||||
measureElement: (element) => element.getBoundingClientRect().height,
|
||||
})
|
||||
});
|
||||
|
||||
// ---- Scroll detection ------------------------------------------------
|
||||
const handleScroll = useCallback(() => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
|
||||
if (!isUserScrolling.current) return
|
||||
if (!isUserScrolling.current) return;
|
||||
|
||||
const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < BOTTOM_THRESHOLD
|
||||
const atBottom =
|
||||
el.scrollHeight - el.scrollTop - el.clientHeight < BOTTOM_THRESHOLD;
|
||||
if (atBottom && !autoScrollRef.current) {
|
||||
setAutoScroll(true)
|
||||
setAutoScroll(true);
|
||||
} else if (!atBottom && autoScrollRef.current) {
|
||||
setAutoScroll(false)
|
||||
setAutoScroll(false);
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
const handleWheel = useCallback(() => { isUserScrolling.current = true }, [])
|
||||
const handleTouchStart = useCallback(() => { isUserScrolling.current = true }, [])
|
||||
const handleWheel = useCallback(() => {
|
||||
isUserScrolling.current = true;
|
||||
}, []);
|
||||
const handleTouchStart = useCallback(() => {
|
||||
isUserScrolling.current = true;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const onScrollEnd = () => {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => { isUserScrolling.current = false }, 150)
|
||||
}
|
||||
el.addEventListener("scroll", onScrollEnd, { passive: true })
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
isUserScrolling.current = false;
|
||||
}, 150);
|
||||
};
|
||||
el.addEventListener('scroll', onScrollEnd, { passive: true });
|
||||
return () => {
|
||||
el.removeEventListener("scroll", onScrollEnd)
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [])
|
||||
el.removeEventListener('scroll', onScrollEnd);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ---- Auto-scroll to bottom when new logs arrive ----------------------
|
||||
useEffect(() => {
|
||||
if (!autoScroll || !containerRef.current) return
|
||||
isUserScrolling.current = false
|
||||
const el = containerRef.current
|
||||
if (!autoScroll || !containerRef.current) return;
|
||||
isUserScrolling.current = false;
|
||||
const el = containerRef.current;
|
||||
requestAnimationFrame(() => {
|
||||
el.scrollTop = el.scrollHeight
|
||||
})
|
||||
}, [logs, autoScroll])
|
||||
el.scrollTop = el.scrollHeight;
|
||||
});
|
||||
}, [logs, autoScroll]);
|
||||
|
||||
// ---- Data fetching ---------------------------------------------------
|
||||
const fetchLogs = useCallback(async (cursor: number = 0) => {
|
||||
try {
|
||||
return await services.adminLog.getLogs(cursor)
|
||||
return await services.adminLog.getLogs(cursor);
|
||||
} catch (err) {
|
||||
throw err instanceof Error ? err : new Error("获取日志失败")
|
||||
throw err instanceof Error ? err : new Error('获取日志失败');
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
const loadHistory = useCallback(async (cursor: number = 0) => {
|
||||
const isInitial = cursor === 0
|
||||
if (isInitial) {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
} else {
|
||||
setLoadingMore(true)
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await fetchLogs(cursor)
|
||||
const loadHistory = useCallback(
|
||||
async (cursor: number = 0) => {
|
||||
const isInitial = cursor === 0;
|
||||
if (isInitial) {
|
||||
setLogs(data.lines || [])
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
} else {
|
||||
const el = containerRef.current
|
||||
const previousScrollHeight = el?.scrollHeight ?? 0
|
||||
setLogs(prev => [...(data.lines || []), ...prev])
|
||||
setLoadingMore(true);
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
if (!el) return
|
||||
isUserScrolling.current = false
|
||||
el.scrollTop = el.scrollHeight - previousScrollHeight
|
||||
})
|
||||
try {
|
||||
const data = await fetchLogs(cursor);
|
||||
if (isInitial) {
|
||||
setLogs(data.lines || []);
|
||||
} else {
|
||||
const el = containerRef.current;
|
||||
const previousScrollHeight = el?.scrollHeight ?? 0;
|
||||
setLogs((prev) => [...(data.lines || []), ...prev]);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
if (!el) return;
|
||||
isUserScrolling.current = false;
|
||||
el.scrollTop = el.scrollHeight - previousScrollHeight;
|
||||
});
|
||||
}
|
||||
setHasMore(data.has_more);
|
||||
setNextCursor(data.next_cursor);
|
||||
} catch (err) {
|
||||
if (isInitial) {
|
||||
setError(err instanceof Error ? err : new Error('获取日志失败'));
|
||||
} else {
|
||||
toast.error('加载更早日志失败');
|
||||
}
|
||||
} finally {
|
||||
if (isInitial) setLoading(false);
|
||||
else setLoadingMore(false);
|
||||
}
|
||||
setHasMore(data.has_more)
|
||||
setNextCursor(data.next_cursor)
|
||||
} catch (err) {
|
||||
if (isInitial) {
|
||||
setError(err instanceof Error ? err : new Error("获取日志失败"))
|
||||
} else {
|
||||
toast.error("加载更早日志失败")
|
||||
}
|
||||
} finally {
|
||||
if (isInitial) setLoading(false)
|
||||
else setLoadingMore(false)
|
||||
}
|
||||
}, [fetchLogs])
|
||||
},
|
||||
[fetchLogs],
|
||||
);
|
||||
|
||||
// ---- WebSocket -------------------------------------------------------
|
||||
const connectWs = useCallback(() => {
|
||||
if (wsRef.current) wsRef.current.close()
|
||||
if (wsRef.current) wsRef.current.close();
|
||||
|
||||
const ws = new WebSocket(buildWsUrl())
|
||||
wsRef.current = ws
|
||||
const ws = new WebSocket(buildWsUrl());
|
||||
wsRef.current = ws;
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data)
|
||||
if (msg.type === "log" && msg.data) {
|
||||
const entry: LogEntry = msg.data
|
||||
setLogs(prev => {
|
||||
const next = [...prev, entry]
|
||||
return next.length > 2000 ? next.slice(-2000) : next
|
||||
})
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.type === 'log' && msg.data) {
|
||||
const entry: LogEntry = msg.data;
|
||||
setLogs((prev) => {
|
||||
const next = [...prev, entry];
|
||||
return next.length > 2000 ? next.slice(-2000) : next;
|
||||
});
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => { wsRef.current = null }
|
||||
}, [])
|
||||
ws.onclose = () => {
|
||||
wsRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ---- Initialize ------------------------------------------------------
|
||||
useEffect(() => {
|
||||
loadHistory(0).then(() => connectWs())
|
||||
loadHistory(0).then(() => connectWs());
|
||||
return () => {
|
||||
wsRef.current?.close()
|
||||
wsRef.current = null
|
||||
}
|
||||
wsRef.current?.close();
|
||||
wsRef.current = null;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
// ---- Actions ---------------------------------------------------------
|
||||
const scrollToBottom = useCallback(() => {
|
||||
setAutoScroll(true)
|
||||
setAutoScroll(true);
|
||||
requestAnimationFrame(() => {
|
||||
if (containerRef.current) {
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight;
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleLoadMore = useCallback(() => {
|
||||
if (nextCursor > 0) loadHistory(nextCursor)
|
||||
}, [nextCursor, loadHistory])
|
||||
if (nextCursor > 0) loadHistory(nextCursor);
|
||||
}, [nextCursor, loadHistory]);
|
||||
|
||||
// ---- Render ----------------------------------------------------------
|
||||
if (loading) return <LoadingStateWithBorder />
|
||||
if (error) return <ErrorInline error={error} onRetry={() => loadHistory(0)} />
|
||||
if (loading) return <LoadingStateWithBorder />;
|
||||
if (error)
|
||||
return <ErrorInline error={error} onRetry={() => loadHistory(0)} />;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full relative">
|
||||
<div className='flex flex-col h-full relative'>
|
||||
{/* Log viewer — fixed height, scrollable */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
onScroll={handleScroll}
|
||||
onWheel={handleWheel}
|
||||
onTouchStart={handleTouchStart}
|
||||
className="h-[calc(100vh-270px)] overflow-y-auto overflow-x-hidden rounded-lg border border-border/40 bg-[#0d1117] font-mono text-[13px] leading-5 relative"
|
||||
className='h-[calc(100vh-270px)] overflow-y-auto overflow-x-hidden rounded-lg border border-border/40 bg-[#0d1117] font-mono text-[13px] leading-5 relative'
|
||||
>
|
||||
{/* Load older logs */}
|
||||
{hasMore && (
|
||||
<div className="sticky top-0 z-10 flex justify-center py-1.5 bg-[#0d1117]/90 backdrop-blur-sm">
|
||||
<div className='sticky top-0 z-10 flex justify-center py-1.5 bg-[#0d1117]/90 backdrop-blur-sm'>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
variant='ghost'
|
||||
size='sm'
|
||||
onClick={handleLoadMore}
|
||||
disabled={loadingMore}
|
||||
className="text-muted-foreground hover:text-foreground h-7 text-xs"
|
||||
className='text-muted-foreground hover:text-foreground h-7 text-xs'
|
||||
>
|
||||
{loadingMore
|
||||
? <><Loader2 className="size-3 mr-1.5 animate-spin" />加载中...</>
|
||||
: <><ChevronUp className="size-3 mr-1.5" />加载更早日志</>
|
||||
}
|
||||
{loadingMore ? (
|
||||
<>
|
||||
<Loader2 className='size-3 mr-1.5 animate-spin' />
|
||||
加载中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronUp className='size-3 mr-1.5' />
|
||||
加载更早日志
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{logs.length === 0 ? (
|
||||
<div className="px-4 py-8 text-center text-gray-500">暂无日志</div>
|
||||
<div className='px-4 py-8 text-center text-gray-500'>暂无日志</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative px-3 py-3"
|
||||
style={{height: `${rowVirtualizer.getTotalSize()}px`}}
|
||||
className='relative px-3 py-3'
|
||||
style={{ height: `${rowVirtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{rowVirtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const entry = logs[virtualRow.index]
|
||||
if (!entry) return null
|
||||
const entry = logs[virtualRow.index];
|
||||
if (!entry) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={entry.index}
|
||||
ref={rowVirtualizer.measureElement}
|
||||
data-index={virtualRow.index}
|
||||
className="absolute top-0 left-0 w-full"
|
||||
style={{transform: `translateY(${virtualRow.start}px)`}}
|
||||
className='absolute top-0 left-0 w-full'
|
||||
style={{ transform: `translateY(${virtualRow.start}px)` }}
|
||||
>
|
||||
<LogLine data={entry.data} />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
@@ -308,18 +341,18 @@ export function AppLogs() {
|
||||
|
||||
{/* Floating "back to latest" button */}
|
||||
{!autoScroll && (
|
||||
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-20">
|
||||
<div className='absolute bottom-6 left-1/2 -translate-x-1/2 z-20'>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={scrollToBottom}
|
||||
className="shadow-lg bg-background/80 backdrop-blur-sm border-border/50"
|
||||
className='shadow-lg bg-background/80 backdrop-blur-sm border-border/50'
|
||||
>
|
||||
<ArrowDown className="size-3.5 mr-1.5" />
|
||||
<ArrowDown className='size-3.5 mr-1.5' />
|
||||
回到最新
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,66 +1,76 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import dynamic from "next/dynamic"
|
||||
import {Activity, BarChart3, Terminal} from "lucide-react"
|
||||
import dynamic from 'next/dynamic';
|
||||
import { Activity, BarChart3, Terminal } from 'lucide-react';
|
||||
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
|
||||
const tabFallback = (
|
||||
<div className="h-64 animate-pulse rounded-lg border border-border/40 bg-muted/20" />
|
||||
)
|
||||
<div className='h-64 animate-pulse rounded-lg border border-border/40 bg-muted/20' />
|
||||
);
|
||||
|
||||
const AccessAnalytics = dynamic(
|
||||
() => import("./components/access-analytics").then((mod) => mod.AccessAnalytics),
|
||||
() =>
|
||||
import('./components/access-analytics').then((mod) => mod.AccessAnalytics),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const AccessLogs = dynamic(
|
||||
() => import("./components/access-logs").then((mod) => mod.AccessLogs),
|
||||
() => import('./components/access-logs').then((mod) => mod.AccessLogs),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const AppLogs = dynamic(
|
||||
() => import("./components/app-logs").then((mod) => mod.AppLogs),
|
||||
() => import('./components/app-logs').then((mod) => mod.AppLogs),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
export function LogsPageClient() {
|
||||
return (
|
||||
<div className="flex flex-col h-full space-y-6 py-6">
|
||||
<div className='flex flex-col h-full space-y-6 py-6'>
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="size-5 text-primary" />
|
||||
<div className='flex items-center gap-2'>
|
||||
<Terminal className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">系统日志</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>系统日志</h1>
|
||||
</div>
|
||||
</div>
|
||||
{/* Tabs Layout */}
|
||||
<Tabs defaultValue="analytics" className="w-full">
|
||||
<TabsList variant="line" className="w-fit inline-flex gap-8 mb-6">
|
||||
<TabsTrigger value="analytics" className="px-0 pb-2 text-xs font-semibold flex items-center gap-1.5">
|
||||
<BarChart3 className="size-3.5" />
|
||||
<Tabs defaultValue='analytics' className='w-full'>
|
||||
<TabsList variant='line' className='w-fit inline-flex gap-8 mb-6'>
|
||||
<TabsTrigger
|
||||
value='analytics'
|
||||
className='px-0 pb-2 text-xs font-semibold flex items-center gap-1.5'
|
||||
>
|
||||
<BarChart3 className='size-3.5' />
|
||||
访问分析
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="access" className="px-0 pb-2 text-xs font-semibold flex items-center gap-1.5">
|
||||
<Activity className="size-3.5" />
|
||||
<TabsTrigger
|
||||
value='access'
|
||||
className='px-0 pb-2 text-xs font-semibold flex items-center gap-1.5'
|
||||
>
|
||||
<Activity className='size-3.5' />
|
||||
用户访问日志
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="app" className="px-0 pb-2 text-xs font-semibold flex items-center gap-1.5">
|
||||
<Terminal className="size-3.5" />
|
||||
<TabsTrigger
|
||||
value='app'
|
||||
className='px-0 pb-2 text-xs font-semibold flex items-center gap-1.5'
|
||||
>
|
||||
<Terminal className='size-3.5' />
|
||||
应用运行日志
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="analytics" className="mt-0 outline-none flex-1">
|
||||
<TabsContent value='analytics' className='mt-0 outline-none flex-1'>
|
||||
<AccessAnalytics />
|
||||
</TabsContent>
|
||||
<TabsContent value="access" className="mt-0 outline-none flex-1">
|
||||
<TabsContent value='access' className='mt-0 outline-none flex-1'>
|
||||
<AccessLogs />
|
||||
</TabsContent>
|
||||
<TabsContent value="app" className="mt-0 outline-none flex-1">
|
||||
<TabsContent value='app' className='mt-0 outline-none flex-1'>
|
||||
<AppLogs />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import {LogsPageClient} from "./page-client"
|
||||
import { LogsPageClient } from './page-client';
|
||||
|
||||
export default function LogsPage() {
|
||||
return <LogsPageClient />
|
||||
}
|
||||
return <LogsPageClient />;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,21 +1,40 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useQuery} from "@tanstack/react-query"
|
||||
import {ChevronLeft, ChevronRight, History, RefreshCw, Search,} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
History,
|
||||
RefreshCw,
|
||||
Search,
|
||||
} from 'lucide-react';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow,} from "@/components/ui/table"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
|
||||
import {ErrorInline} from "@/components/layout/error"
|
||||
import {LoadingStateWithBorder} from "@/components/layout/loading"
|
||||
import {cn} from "@/lib/utils"
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import {
|
||||
Dialog,
|
||||
@@ -24,156 +43,205 @@ import {
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
import type {PushHistory} from "@/lib/services/push"
|
||||
import {PushService} from "@/lib/services/push"
|
||||
import type { PushHistory } from '@/lib/services/push';
|
||||
import { PushService } from '@/lib/services/push';
|
||||
|
||||
function getLevelBadgeVariant(level: string): "outline" | "secondary" | "destructive" | "default" {
|
||||
function getLevelBadgeVariant(
|
||||
level: string,
|
||||
): 'outline' | 'secondary' | 'destructive' | 'default' {
|
||||
switch (level) {
|
||||
case "CRITICAL":
|
||||
return "destructive"
|
||||
case "IMPORTANT":
|
||||
return "default"
|
||||
case 'CRITICAL':
|
||||
return 'destructive';
|
||||
case 'IMPORTANT':
|
||||
return 'default';
|
||||
default:
|
||||
return "outline"
|
||||
return 'outline';
|
||||
}
|
||||
}
|
||||
|
||||
export function HistoriesTab() {
|
||||
const [historyPage, setHistoryPage] = React.useState(1)
|
||||
const [historySearch, setHistorySearch] = React.useState("")
|
||||
const [historyStatus, setHistoryStatus] = React.useState("all")
|
||||
const [historyPage, setHistoryPage] = React.useState(1);
|
||||
const [historySearch, setHistorySearch] = React.useState('');
|
||||
const [historyStatus, setHistoryStatus] = React.useState('all');
|
||||
|
||||
const [detailOpen, setDetailOpen] = React.useState(false)
|
||||
const [selectedHistory, setSelectedHistory] = React.useState<PushHistory | null>(null)
|
||||
const [detailOpen, setDetailOpen] = React.useState(false);
|
||||
const [selectedHistory, setSelectedHistory] =
|
||||
React.useState<PushHistory | null>(null);
|
||||
|
||||
const handleRowClick = (hist: PushHistory) => {
|
||||
setSelectedHistory(hist)
|
||||
setDetailOpen(true)
|
||||
}
|
||||
setSelectedHistory(hist);
|
||||
setDetailOpen(true);
|
||||
};
|
||||
|
||||
const historiesQuery = useQuery({
|
||||
queryKey: ["admin", "push-histories", historyPage, historySearch, historyStatus],
|
||||
queryKey: [
|
||||
'admin',
|
||||
'push-histories',
|
||||
historyPage,
|
||||
historySearch,
|
||||
historyStatus,
|
||||
],
|
||||
queryFn: () =>
|
||||
PushService.listHistories({
|
||||
page: historyPage,
|
||||
page_size: 10,
|
||||
event_key: historySearch || undefined,
|
||||
status: historyStatus === "all" ? undefined : historyStatus,
|
||||
status: historyStatus === 'all' ? undefined : historyStatus,
|
||||
}),
|
||||
})
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="pt-4 space-y-4">
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
|
||||
<div className='pt-4 space-y-4'>
|
||||
<div className='flex flex-col sm:flex-row gap-2'>
|
||||
<div className='relative flex-1'>
|
||||
<Search className='absolute left-2.5 top-2.5 size-4 text-muted-foreground' />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="输入事件键过滤..."
|
||||
className="pl-8 text-xs h-9"
|
||||
type='text'
|
||||
placeholder='输入事件键过滤...'
|
||||
className='pl-8 text-xs h-9'
|
||||
value={historySearch}
|
||||
onChange={e => {
|
||||
setHistorySearch(e.target.value)
|
||||
setHistoryPage(1)
|
||||
onChange={(e) => {
|
||||
setHistorySearch(e.target.value);
|
||||
setHistoryPage(1);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="w-[150px]">
|
||||
<div className='w-[150px]'>
|
||||
<Select
|
||||
value={historyStatus}
|
||||
onValueChange={val => {
|
||||
setHistoryStatus(val)
|
||||
setHistoryPage(1)
|
||||
onValueChange={(val) => {
|
||||
setHistoryStatus(val);
|
||||
setHistoryPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="text-xs h-9">
|
||||
<SelectValue placeholder="发送状态" />
|
||||
<SelectTrigger className='text-xs h-9'>
|
||||
<SelectValue placeholder='发送状态' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all" className="text-xs">全部状态</SelectItem>
|
||||
<SelectItem value="success" className="text-xs">发送成功</SelectItem>
|
||||
<SelectItem value="failed" className="text-xs">发送失败</SelectItem>
|
||||
<SelectItem value='all' className='text-xs'>
|
||||
全部状态
|
||||
</SelectItem>
|
||||
<SelectItem value='success' className='text-xs'>
|
||||
发送成功
|
||||
</SelectItem>
|
||||
<SelectItem value='failed' className='text-xs'>
|
||||
发送失败
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
variant='outline'
|
||||
size='icon'
|
||||
className='h-9 w-9 shrink-0'
|
||||
onClick={() => historiesQuery.refetch()}
|
||||
>
|
||||
<RefreshCw className={cn("size-3.5", historiesQuery.isFetching && "animate-spin")} />
|
||||
<RefreshCw
|
||||
className={cn(
|
||||
'size-3.5',
|
||||
historiesQuery.isFetching && 'animate-spin',
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<div className='border rounded-lg overflow-hidden'>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="bg-muted/30">
|
||||
<TableHead className="text-xs font-semibold">事件</TableHead>
|
||||
<TableHead className="text-xs font-semibold">渠道</TableHead>
|
||||
<TableHead className="text-xs font-semibold">目标</TableHead>
|
||||
<TableHead className="text-xs font-semibold">标题</TableHead>
|
||||
<TableHead className="text-xs font-semibold">等级</TableHead>
|
||||
<TableHead className="text-xs font-semibold">状态</TableHead>
|
||||
<TableHead className="text-xs font-semibold">时间</TableHead>
|
||||
<TableRow className='bg-muted/30'>
|
||||
<TableHead className='text-xs font-semibold'>事件</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>渠道</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>目标</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>标题</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>等级</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>状态</TableHead>
|
||||
<TableHead className='text-xs font-semibold'>时间</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{historiesQuery.isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="h-32">
|
||||
<LoadingStateWithBorder icon={History} description="加载推送历史记录中..." className="border-0 shadow-none" />
|
||||
<TableCell colSpan={7} className='h-32'>
|
||||
<LoadingStateWithBorder
|
||||
icon={History}
|
||||
description='加载推送历史记录中...'
|
||||
className='border-0 shadow-none'
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : historiesQuery.isError ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="h-32">
|
||||
<ErrorInline error={historiesQuery.error} onRetry={() => historiesQuery.refetch()} className="justify-center" />
|
||||
<TableCell colSpan={7} className='h-32'>
|
||||
<ErrorInline
|
||||
error={historiesQuery.error}
|
||||
onRetry={() => historiesQuery.refetch()}
|
||||
className='justify-center'
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (historiesQuery.data?.results ?? []).length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="h-32 text-center text-xs text-muted-foreground">
|
||||
<TableCell
|
||||
colSpan={7}
|
||||
className='h-32 text-center text-xs text-muted-foreground'
|
||||
>
|
||||
无推送历史数据
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
(historiesQuery.data?.results ?? []).map(hist => (
|
||||
(historiesQuery.data?.results ?? []).map((hist) => (
|
||||
<TableRow
|
||||
key={hist.id}
|
||||
className="hover:bg-muted/10 cursor-pointer transition-colors"
|
||||
className='hover:bg-muted/10 cursor-pointer transition-colors'
|
||||
onClick={() => handleRowClick(hist)}
|
||||
>
|
||||
<TableCell className="text-xs font-mono font-medium">{hist.event_key}</TableCell>
|
||||
<TableCell className="text-xs uppercase font-semibold text-muted-foreground">
|
||||
{hist.channel === "email" ? "邮件" : hist.channel}
|
||||
<TableCell className='text-xs font-mono font-medium'>
|
||||
{hist.event_key}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs font-mono text-muted-foreground max-w-[120px] truncate" title={hist.target}>
|
||||
<TableCell className='text-xs uppercase font-semibold text-muted-foreground'>
|
||||
{hist.channel === 'email' ? '邮件' : hist.channel}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className='text-xs font-mono text-muted-foreground max-w-[120px] truncate'
|
||||
title={hist.target}
|
||||
>
|
||||
{hist.target}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs max-w-[180px] truncate" title={hist.content}>{hist.title}</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
<Badge variant={getLevelBadgeVariant(hist.level)} className="text-[10px] font-semibold">
|
||||
<TableCell
|
||||
className='text-xs max-w-[180px] truncate'
|
||||
title={hist.content}
|
||||
>
|
||||
{hist.title}
|
||||
</TableCell>
|
||||
<TableCell className='text-xs'>
|
||||
<Badge
|
||||
variant={getLevelBadgeVariant(hist.level)}
|
||||
className='text-[10px] font-semibold'
|
||||
>
|
||||
{hist.level}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-xs">
|
||||
<TableCell className='text-xs'>
|
||||
<Badge
|
||||
variant={hist.status === "success" ? "secondary" : "destructive"}
|
||||
className="text-[10px] font-semibold"
|
||||
variant={
|
||||
hist.status === 'success' ? 'secondary' : 'destructive'
|
||||
}
|
||||
className='text-[10px] font-semibold'
|
||||
>
|
||||
{hist.status === "success" ? "成功" : "失败"}
|
||||
{hist.status === 'success' ? '成功' : '失败'}
|
||||
</Badge>
|
||||
{hist.status !== "success" && hist.error_msg && (
|
||||
<div className="text-[10px] text-muted-foreground font-mono truncate max-w-[180px] mt-1" title={hist.error_msg}>
|
||||
{hist.status !== 'success' && hist.error_msg && (
|
||||
<div
|
||||
className='text-[10px] text-muted-foreground font-mono truncate max-w-[180px] mt-1'
|
||||
title={hist.error_msg}
|
||||
>
|
||||
{hist.error_msg}
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-[11px] text-muted-foreground whitespace-nowrap">
|
||||
<TableCell className='text-[11px] text-muted-foreground whitespace-nowrap'>
|
||||
{new Date(hist.created_at).toLocaleString()}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -184,27 +252,27 @@ export function HistoriesTab() {
|
||||
</div>
|
||||
|
||||
{historiesQuery.data && historiesQuery.data.total > 0 && (
|
||||
<div className="flex justify-between items-center text-xs text-muted-foreground">
|
||||
<div className='flex justify-between items-center text-xs text-muted-foreground'>
|
||||
<span>共 {historiesQuery.data.total} 条历史记录</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
variant='outline'
|
||||
size='icon'
|
||||
disabled={historyPage === 1}
|
||||
onClick={() => setHistoryPage(p => Math.max(1, p - 1))}
|
||||
className="h-8 w-8"
|
||||
onClick={() => setHistoryPage((p) => Math.max(1, p - 1))}
|
||||
className='h-8 w-8'
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
<ChevronLeft className='size-4' />
|
||||
</Button>
|
||||
<span className="text-xs font-medium px-2">{historyPage}</span>
|
||||
<span className='text-xs font-medium px-2'>{historyPage}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
variant='outline'
|
||||
size='icon'
|
||||
disabled={historyPage * 10 >= historiesQuery.data.total}
|
||||
onClick={() => setHistoryPage(p => p + 1)}
|
||||
className="h-8 w-8"
|
||||
onClick={() => setHistoryPage((p) => p + 1)}
|
||||
className='h-8 w-8'
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
<ChevronRight className='size-4' />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -212,10 +280,10 @@ export function HistoriesTab() {
|
||||
|
||||
{/* ==================== 对话框:推送详情 ==================== */}
|
||||
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
|
||||
<DialogContent className="sm:max-w-[550px] max-h-[85vh] overflow-y-auto">
|
||||
<DialogContent className='sm:max-w-[550px] max-h-[85vh] overflow-y-auto'>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<History className="size-5 text-primary" />
|
||||
<DialogTitle className='flex items-center gap-2'>
|
||||
<History className='size-5 text-primary' />
|
||||
推送通知详情
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -224,76 +292,109 @@ export function HistoriesTab() {
|
||||
</DialogHeader>
|
||||
|
||||
{selectedHistory && (
|
||||
<div className="space-y-4 py-4 text-xs">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">事件标识</span>
|
||||
<div className="font-mono bg-muted/40 p-2 rounded border">{selectedHistory.event_key}</div>
|
||||
<div className='space-y-4 py-4 text-xs'>
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
事件标识
|
||||
</span>
|
||||
<div className='font-mono bg-muted/40 p-2 rounded border'>
|
||||
{selectedHistory.event_key}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">发送渠道</span>
|
||||
<div className="bg-muted/40 p-2 rounded border uppercase font-medium">
|
||||
{selectedHistory.channel === "email" ? "邮件推送" : selectedHistory.channel}
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
发送渠道
|
||||
</span>
|
||||
<div className='bg-muted/40 p-2 rounded border uppercase font-medium'>
|
||||
{selectedHistory.channel === 'email'
|
||||
? '邮件推送'
|
||||
: selectedHistory.channel}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">推送目标</span>
|
||||
<div className="font-mono bg-muted/40 p-2 rounded border truncate" title={selectedHistory.target}>
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
推送目标
|
||||
</span>
|
||||
<div
|
||||
className='font-mono bg-muted/40 p-2 rounded border truncate'
|
||||
title={selectedHistory.target}
|
||||
>
|
||||
{selectedHistory.target}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">发送时间</span>
|
||||
<div className="bg-muted/40 p-2 rounded border">
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
发送时间
|
||||
</span>
|
||||
<div className='bg-muted/40 p-2 rounded border'>
|
||||
{new Date(selectedHistory.created_at).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">通知等级</span>
|
||||
<div className='grid grid-cols-2 gap-4'>
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
通知等级
|
||||
</span>
|
||||
<div>
|
||||
<Badge variant={getLevelBadgeVariant(selectedHistory.level)} className="text-[10px] font-semibold py-0.5 px-2">
|
||||
<Badge
|
||||
variant={getLevelBadgeVariant(selectedHistory.level)}
|
||||
className='text-[10px] font-semibold py-0.5 px-2'
|
||||
>
|
||||
{selectedHistory.level}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">发送状态</span>
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
发送状态
|
||||
</span>
|
||||
<div>
|
||||
<Badge
|
||||
variant={selectedHistory.status === "success" ? "secondary" : "destructive"}
|
||||
className="text-[10px] font-semibold py-0.5 px-2"
|
||||
variant={
|
||||
selectedHistory.status === 'success'
|
||||
? 'secondary'
|
||||
: 'destructive'
|
||||
}
|
||||
className='text-[10px] font-semibold py-0.5 px-2'
|
||||
>
|
||||
{selectedHistory.status === "success" ? "成功" : "失败"}
|
||||
{selectedHistory.status === 'success' ? '成功' : '失败'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedHistory.status === "failed" && selectedHistory.error_msg && (
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-destructive block">失败原因</span>
|
||||
<div className="font-mono text-destructive bg-destructive/10 p-2.5 rounded border border-destructive/20 whitespace-pre-wrap break-all">
|
||||
{selectedHistory.error_msg}
|
||||
{selectedHistory.status === 'failed' &&
|
||||
selectedHistory.error_msg && (
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-destructive block'>
|
||||
失败原因
|
||||
</span>
|
||||
<div className='font-mono text-destructive bg-destructive/10 p-2.5 rounded border border-destructive/20 whitespace-pre-wrap break-all'>
|
||||
{selectedHistory.error_msg}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">通知标题</span>
|
||||
<div className="bg-muted/30 p-2.5 rounded border font-medium text-[13px]">
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
通知标题
|
||||
</span>
|
||||
<div className='bg-muted/30 p-2.5 rounded border font-medium text-[13px]'>
|
||||
{selectedHistory.title}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<span className="font-semibold text-muted-foreground block">通知内容</span>
|
||||
<div className="bg-muted/30 p-3 rounded border whitespace-pre-wrap break-all leading-relaxed font-sans text-xs">
|
||||
<div className='space-y-1.5'>
|
||||
<span className='font-semibold text-muted-foreground block'>
|
||||
通知内容
|
||||
</span>
|
||||
<div className='bg-muted/30 p-3 rounded border whitespace-pre-wrap break-all leading-relaxed font-sans text-xs'>
|
||||
{selectedHistory.content}
|
||||
</div>
|
||||
</div>
|
||||
@@ -301,12 +402,17 @@ export function HistoriesTab() {
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" size="sm" onClick={() => setDetailOpen(false)} className="h-9 text-xs">
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={() => setDetailOpen(false)}
|
||||
className='h-9 text-xs'
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,65 +1,76 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {motion} from "motion/react"
|
||||
import {Bell, History, Layers, Settings} from "lucide-react"
|
||||
import * as React from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Bell, History, Layers, Settings } from 'lucide-react';
|
||||
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
|
||||
import {EventsTab} from "./components/events-tab"
|
||||
import {HistoriesTab} from "./components/histories-tab"
|
||||
import {SettingsTab} from "./components/settings-tab"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { EventsTab } from './components/events-tab';
|
||||
import { HistoriesTab } from './components/histories-tab';
|
||||
import { SettingsTab } from './components/settings-tab';
|
||||
|
||||
export default function PushAdminPage() {
|
||||
const [activeTab, setActiveTab] = React.useState("events")
|
||||
const [activeTab, setActiveTab] = React.useState('events');
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 15 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3, ease: "easeOut" }}
|
||||
className="w-full py-6 space-y-6"
|
||||
transition={{ duration: 0.3, ease: 'easeOut' }}
|
||||
className='w-full py-6 space-y-6'
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Bell className="size-5 text-primary" />
|
||||
<div className='flex items-center gap-2'>
|
||||
<Bell className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">通知推送管理</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>
|
||||
通知推送管理
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
|
||||
<TabsList variant="line" className="w-fit inline-flex gap-8">
|
||||
<TabsTrigger value="events" className="px-0 pb-2 text-xs font-semibold">
|
||||
<Layers className="size-3.5 mr-1" />
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className='w-full'>
|
||||
<TabsList variant='line' className='w-fit inline-flex gap-8'>
|
||||
<TabsTrigger
|
||||
value='events'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
<Layers className='size-3.5 mr-1' />
|
||||
事件管理
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="histories" className="px-0 pb-2 text-xs font-semibold">
|
||||
<History className="size-3.5 mr-1" />
|
||||
<TabsTrigger
|
||||
value='histories'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
<History className='size-3.5 mr-1' />
|
||||
通知历史
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="settings" className="px-0 pb-2 text-xs font-semibold">
|
||||
<Settings className="size-3.5 mr-1" />
|
||||
<TabsTrigger
|
||||
value='settings'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
<Settings className='size-3.5 mr-1' />
|
||||
通道管理与设置
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* ==================== 1. 事件管理 TAB ==================== */}
|
||||
<TabsContent value="events" className="focus-visible:outline-none">
|
||||
<TabsContent value='events' className='focus-visible:outline-none'>
|
||||
<EventsTab />
|
||||
</TabsContent>
|
||||
|
||||
{/* ==================== 2. 通知历史 TAB ==================== */}
|
||||
<TabsContent value="histories" className="focus-visible:outline-none">
|
||||
<TabsContent value='histories' className='focus-visible:outline-none'>
|
||||
<HistoriesTab />
|
||||
</TabsContent>
|
||||
|
||||
{/* ==================== 3. 通道管理与设置 TAB ==================== */}
|
||||
<TabsContent value="settings" className="focus-visible:outline-none">
|
||||
<TabsContent value='settings' className='focus-visible:outline-none'>
|
||||
<SettingsTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</motion.div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,183 +1,264 @@
|
||||
import type {OptionItem} from "@/lib/services/openflare"
|
||||
import type { OptionItem } from '@/lib/services/openflare';
|
||||
|
||||
export type OpenFlareOpsFields = {
|
||||
agent_heartbeat_interval: string
|
||||
agent_websocket_upgrade_enabled: boolean
|
||||
node_offline_threshold: string
|
||||
agent_update_repo: string
|
||||
geoip_provider: string
|
||||
server_address: string
|
||||
uptime_kuma_enabled: boolean
|
||||
uptime_kuma_url: string
|
||||
uptime_kuma_username: string
|
||||
uptime_kuma_password: string
|
||||
uptime_kuma_monitor_scope: string
|
||||
uptime_kuma_selected_sites: string
|
||||
uptime_kuma_sync_interval: string
|
||||
uptime_kuma_interval: string
|
||||
uptime_kuma_retry: string
|
||||
uptime_kuma_retry_interval: string
|
||||
uptime_kuma_timeout: string
|
||||
database_auto_cleanup_enabled: boolean
|
||||
database_auto_cleanup_retention_days: string
|
||||
}
|
||||
agent_heartbeat_interval: string;
|
||||
agent_websocket_upgrade_enabled: boolean;
|
||||
node_offline_threshold: string;
|
||||
agent_update_repo: string;
|
||||
geoip_provider: string;
|
||||
server_address: string;
|
||||
uptime_kuma_enabled: boolean;
|
||||
uptime_kuma_url: string;
|
||||
uptime_kuma_username: string;
|
||||
uptime_kuma_password: string;
|
||||
uptime_kuma_monitor_scope: string;
|
||||
uptime_kuma_selected_sites: string;
|
||||
uptime_kuma_sync_interval: string;
|
||||
uptime_kuma_interval: string;
|
||||
uptime_kuma_retry: string;
|
||||
uptime_kuma_retry_interval: string;
|
||||
uptime_kuma_timeout: string;
|
||||
database_auto_cleanup_enabled: boolean;
|
||||
database_auto_cleanup_retention_days: string;
|
||||
pages_max_package_size_mb: string;
|
||||
pages_max_history_count: string;
|
||||
};
|
||||
|
||||
export const defaultOpenFlareOpsFields: OpenFlareOpsFields = {
|
||||
agent_heartbeat_interval: "10000",
|
||||
agent_heartbeat_interval: '3000',
|
||||
agent_websocket_upgrade_enabled: true,
|
||||
node_offline_threshold: "120000",
|
||||
agent_update_repo: "Rain-kl/OpenFlare",
|
||||
geoip_provider: "ipinfo",
|
||||
server_address: "",
|
||||
node_offline_threshold: '60000',
|
||||
agent_update_repo: 'Rain-kl/OpenFlare',
|
||||
geoip_provider: 'ipinfo',
|
||||
server_address: '',
|
||||
uptime_kuma_enabled: false,
|
||||
uptime_kuma_url: "",
|
||||
uptime_kuma_username: "",
|
||||
uptime_kuma_password: "",
|
||||
uptime_kuma_monitor_scope: "all",
|
||||
uptime_kuma_selected_sites: "",
|
||||
uptime_kuma_sync_interval: "5",
|
||||
uptime_kuma_interval: "60",
|
||||
uptime_kuma_retry: "0",
|
||||
uptime_kuma_retry_interval: "60",
|
||||
uptime_kuma_timeout: "48",
|
||||
uptime_kuma_url: '',
|
||||
uptime_kuma_username: '',
|
||||
uptime_kuma_password: '',
|
||||
uptime_kuma_monitor_scope: 'all',
|
||||
uptime_kuma_selected_sites: '',
|
||||
uptime_kuma_sync_interval: '5',
|
||||
uptime_kuma_interval: '60',
|
||||
uptime_kuma_retry: '0',
|
||||
uptime_kuma_retry_interval: '60',
|
||||
uptime_kuma_timeout: '48',
|
||||
database_auto_cleanup_enabled: false,
|
||||
database_auto_cleanup_retention_days: "30",
|
||||
}
|
||||
database_auto_cleanup_retention_days: '30',
|
||||
pages_max_package_size_mb: '100',
|
||||
pages_max_history_count: '20',
|
||||
};
|
||||
|
||||
export const INSTALLER_SCRIPT_URL =
|
||||
"https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh"
|
||||
'https://raw.githubusercontent.com/Rain-kl/OpenFlare/main/scripts/install-agent.sh';
|
||||
|
||||
export function optionsToMap(options: OptionItem[]) {
|
||||
return options.reduce<Record<string, string>>((accumulator, option) => {
|
||||
accumulator[option.key] = option.value
|
||||
return accumulator
|
||||
}, {})
|
||||
accumulator[option.key] = option.value;
|
||||
return accumulator;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function toBoolean(value: string | undefined, fallback: boolean) {
|
||||
if (value === undefined) return fallback
|
||||
return value === "true"
|
||||
if (value === undefined) return fallback;
|
||||
return value === 'true';
|
||||
}
|
||||
|
||||
export function mapOptionsToOpsFields(
|
||||
optionMap: Record<string, string>,
|
||||
serverAddress = "",
|
||||
serverAddress = '',
|
||||
): OpenFlareOpsFields {
|
||||
return {
|
||||
agent_heartbeat_interval: optionMap.agent_heartbeat_interval ?? "10000",
|
||||
agent_websocket_upgrade_enabled: toBoolean(optionMap.agent_websocket_upgrade_enabled, true),
|
||||
node_offline_threshold: optionMap.node_offline_threshold ?? "120000",
|
||||
agent_update_repo: optionMap.agent_update_repo ?? "Rain-kl/OpenFlare",
|
||||
geoip_provider: optionMap.geoip_provider ?? "ipinfo",
|
||||
agent_heartbeat_interval: optionMap.agent_heartbeat_interval ?? '3000',
|
||||
agent_websocket_upgrade_enabled: toBoolean(
|
||||
optionMap.agent_websocket_upgrade_enabled,
|
||||
true,
|
||||
),
|
||||
node_offline_threshold: optionMap.node_offline_threshold ?? '60000',
|
||||
agent_update_repo: optionMap.agent_update_repo ?? 'Rain-kl/OpenFlare',
|
||||
geoip_provider: optionMap.geoip_provider ?? 'ipinfo',
|
||||
server_address: optionMap.server_address || serverAddress,
|
||||
uptime_kuma_enabled: toBoolean(optionMap.uptime_kuma_enabled, false),
|
||||
uptime_kuma_url: optionMap.uptime_kuma_url ?? "",
|
||||
uptime_kuma_username: optionMap.uptime_kuma_username ?? "",
|
||||
uptime_kuma_password: "",
|
||||
uptime_kuma_monitor_scope: optionMap.uptime_kuma_monitor_scope ?? "all",
|
||||
uptime_kuma_selected_sites: optionMap.uptime_kuma_selected_sites ?? "",
|
||||
uptime_kuma_sync_interval: optionMap.uptime_kuma_sync_interval ?? "5",
|
||||
uptime_kuma_interval: optionMap.uptime_kuma_interval ?? "60",
|
||||
uptime_kuma_retry: optionMap.uptime_kuma_retry ?? "0",
|
||||
uptime_kuma_retry_interval: optionMap.uptime_kuma_retry_interval ?? "60",
|
||||
uptime_kuma_timeout: optionMap.uptime_kuma_timeout ?? "48",
|
||||
database_auto_cleanup_enabled: toBoolean(optionMap.database_auto_cleanup_enabled, false),
|
||||
database_auto_cleanup_retention_days: optionMap.database_auto_cleanup_retention_days ?? "30",
|
||||
}
|
||||
uptime_kuma_url: optionMap.uptime_kuma_url ?? '',
|
||||
uptime_kuma_username: optionMap.uptime_kuma_username ?? '',
|
||||
uptime_kuma_password: '',
|
||||
uptime_kuma_monitor_scope: optionMap.uptime_kuma_monitor_scope ?? 'all',
|
||||
uptime_kuma_selected_sites: optionMap.uptime_kuma_selected_sites ?? '',
|
||||
uptime_kuma_sync_interval: optionMap.uptime_kuma_sync_interval ?? '5',
|
||||
uptime_kuma_interval: optionMap.uptime_kuma_interval ?? '60',
|
||||
uptime_kuma_retry: optionMap.uptime_kuma_retry ?? '0',
|
||||
uptime_kuma_retry_interval: optionMap.uptime_kuma_retry_interval ?? '60',
|
||||
uptime_kuma_timeout: optionMap.uptime_kuma_timeout ?? '48',
|
||||
database_auto_cleanup_enabled: toBoolean(
|
||||
optionMap.database_auto_cleanup_enabled,
|
||||
false,
|
||||
),
|
||||
database_auto_cleanup_retention_days:
|
||||
optionMap.database_auto_cleanup_retention_days ?? '30',
|
||||
pages_max_package_size_mb: optionMap.pages_max_package_size_mb ?? '100',
|
||||
pages_max_history_count: optionMap.pages_max_history_count ?? '20',
|
||||
};
|
||||
}
|
||||
|
||||
export function formatDurationLabel(value: string) {
|
||||
const milliseconds = Number.parseInt(value, 10)
|
||||
if (Number.isNaN(milliseconds)) return value
|
||||
if (milliseconds >= 60000) return `${milliseconds / 60000} 分钟`
|
||||
return `${milliseconds / 1000} 秒`
|
||||
const milliseconds = Number.parseInt(value, 10);
|
||||
if (Number.isNaN(milliseconds)) return value;
|
||||
if (milliseconds >= 60000) return `${milliseconds / 60000} 分钟`;
|
||||
return `${milliseconds / 1000} 秒`;
|
||||
}
|
||||
|
||||
export function normalizeServerUrl(value: string) {
|
||||
return value.trim().replace(/\/+$/, "")
|
||||
return value.trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function getBrowserOrigin() {
|
||||
if (typeof window === "undefined") return ""
|
||||
return normalizeServerUrl(window.location.origin)
|
||||
if (typeof window === 'undefined') return '';
|
||||
return normalizeServerUrl(window.location.origin);
|
||||
}
|
||||
|
||||
export function buildDiscoveryCommand(serverUrl: string, discoveryToken: string) {
|
||||
export function buildDiscoveryCommand(
|
||||
serverUrl: string,
|
||||
discoveryToken: string,
|
||||
) {
|
||||
return [
|
||||
`curl -fsSL ${INSTALLER_SCRIPT_URL} | bash -s -- \\`,
|
||||
` --server-url ${normalizeServerUrl(serverUrl)} \\`,
|
||||
` --discovery-token ${discoveryToken}`,
|
||||
].join("\n")
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
export function validateAgentFields(fields: OpenFlareOpsFields) {
|
||||
const heartbeat = Number.parseInt(fields.agent_heartbeat_interval, 10)
|
||||
const offline = Number.parseInt(fields.node_offline_threshold, 10)
|
||||
if (Number.isNaN(heartbeat) || heartbeat < 5000) {
|
||||
throw new Error("心跳间隔不能小于 5000 毫秒。")
|
||||
const heartbeat = Number.parseInt(fields.agent_heartbeat_interval, 10);
|
||||
const offline = Number.parseInt(fields.node_offline_threshold, 10);
|
||||
if (Number.isNaN(heartbeat) || heartbeat < 1000) {
|
||||
throw new Error('心跳间隔不能小于 1000 毫秒。');
|
||||
}
|
||||
if (Number.isNaN(offline) || offline < 10000) {
|
||||
throw new Error("离线阈值不能小于 10000 毫秒。")
|
||||
throw new Error('离线阈值不能小于 10000 毫秒。');
|
||||
}
|
||||
if (offline < heartbeat * 3) {
|
||||
throw new Error('离线阈值建议至少为心跳间隔的 3 倍。');
|
||||
}
|
||||
}
|
||||
|
||||
export function validateUptimeKumaFields(fields: OpenFlareOpsFields) {
|
||||
const syncInt = Number.parseInt(fields.uptime_kuma_sync_interval, 10)
|
||||
const interval = Number.parseInt(fields.uptime_kuma_interval, 10)
|
||||
const retry = Number.parseInt(fields.uptime_kuma_retry, 10)
|
||||
const retryInt = Number.parseInt(fields.uptime_kuma_retry_interval, 10)
|
||||
const timeout = Number.parseInt(fields.uptime_kuma_timeout, 10)
|
||||
const syncInt = Number.parseInt(fields.uptime_kuma_sync_interval, 10);
|
||||
const interval = Number.parseInt(fields.uptime_kuma_interval, 10);
|
||||
const retry = Number.parseInt(fields.uptime_kuma_retry, 10);
|
||||
const retryInt = Number.parseInt(fields.uptime_kuma_retry_interval, 10);
|
||||
const timeout = Number.parseInt(fields.uptime_kuma_timeout, 10);
|
||||
|
||||
if (fields.uptime_kuma_enabled) {
|
||||
if (!fields.uptime_kuma_url.trim()) throw new Error("请输入 Uptime Kuma 地址。")
|
||||
if (!fields.uptime_kuma_username.trim()) throw new Error("请输入 Uptime Kuma 用户名。")
|
||||
if (!fields.uptime_kuma_url.trim())
|
||||
throw new Error('请输入 Uptime Kuma 地址。');
|
||||
if (!fields.uptime_kuma_username.trim())
|
||||
throw new Error('请输入 Uptime Kuma 用户名。');
|
||||
}
|
||||
if (Number.isNaN(syncInt) || syncInt <= 0) throw new Error("同步间隔必须为正整数。")
|
||||
if (Number.isNaN(interval) || interval <= 0) throw new Error("心跳间隔必须为正整数。")
|
||||
if (Number.isNaN(retry) || retry < 0) throw new Error("重试次数必须为非负整数。")
|
||||
if (Number.isNaN(retryInt) || retryInt <= 0) throw new Error("心跳重试间隔必须为正整数。")
|
||||
if (Number.isNaN(timeout) || timeout <= 0) throw new Error("请求超时必须为正整数。")
|
||||
if (Number.isNaN(syncInt) || syncInt <= 0)
|
||||
throw new Error('同步间隔必须为正整数。');
|
||||
if (Number.isNaN(interval) || interval <= 0)
|
||||
throw new Error('心跳间隔必须为正整数。');
|
||||
if (Number.isNaN(retry) || retry < 0)
|
||||
throw new Error('重试次数必须为非负整数。');
|
||||
if (Number.isNaN(retryInt) || retryInt <= 0)
|
||||
throw new Error('心跳重试间隔必须为正整数。');
|
||||
if (Number.isNaN(timeout) || timeout <= 0)
|
||||
throw new Error('请求超时必须为正整数。');
|
||||
}
|
||||
|
||||
export function validateDatabaseAutoCleanup(fields: OpenFlareOpsFields) {
|
||||
const retentionDays = Number.parseInt(fields.database_auto_cleanup_retention_days, 10)
|
||||
const retentionDays = Number.parseInt(
|
||||
fields.database_auto_cleanup_retention_days,
|
||||
10,
|
||||
);
|
||||
if (Number.isNaN(retentionDays) || retentionDays < 1) {
|
||||
throw new Error("自动清理保留天数至少为 1 天。")
|
||||
throw new Error('自动清理保留天数至少为 1 天。');
|
||||
}
|
||||
}
|
||||
|
||||
export function agentOptionEntries(fields: OpenFlareOpsFields): OptionItem[] {
|
||||
validateAgentFields(fields)
|
||||
validateAgentFields(fields);
|
||||
return [
|
||||
{ key: "agent_heartbeat_interval", value: fields.agent_heartbeat_interval },
|
||||
{ key: "agent_websocket_upgrade_enabled", value: String(fields.agent_websocket_upgrade_enabled) },
|
||||
{ key: "node_offline_threshold", value: fields.node_offline_threshold },
|
||||
{ key: "agent_update_repo", value: fields.agent_update_repo.trim() },
|
||||
{ key: "geoip_provider", value: fields.geoip_provider },
|
||||
]
|
||||
{ key: 'agent_heartbeat_interval', value: fields.agent_heartbeat_interval },
|
||||
{
|
||||
key: 'agent_websocket_upgrade_enabled',
|
||||
value: String(fields.agent_websocket_upgrade_enabled),
|
||||
},
|
||||
{ key: 'node_offline_threshold', value: fields.node_offline_threshold },
|
||||
{ key: 'agent_update_repo', value: fields.agent_update_repo.trim() },
|
||||
{ key: 'geoip_provider', value: fields.geoip_provider },
|
||||
];
|
||||
}
|
||||
|
||||
export function uptimeKumaOptionEntries(fields: OpenFlareOpsFields): OptionItem[] {
|
||||
validateUptimeKumaFields(fields)
|
||||
export function uptimeKumaOptionEntries(
|
||||
fields: OpenFlareOpsFields,
|
||||
): OptionItem[] {
|
||||
validateUptimeKumaFields(fields);
|
||||
return [
|
||||
{ key: "uptime_kuma_enabled", value: String(fields.uptime_kuma_enabled) },
|
||||
{ key: "uptime_kuma_url", value: fields.uptime_kuma_url.trim() },
|
||||
{ key: "uptime_kuma_username", value: fields.uptime_kuma_username.trim() },
|
||||
{ key: "uptime_kuma_password", value: fields.uptime_kuma_password },
|
||||
{ key: "uptime_kuma_monitor_scope", value: fields.uptime_kuma_monitor_scope },
|
||||
{ key: "uptime_kuma_selected_sites", value: fields.uptime_kuma_selected_sites },
|
||||
{ key: "uptime_kuma_sync_interval", value: fields.uptime_kuma_sync_interval },
|
||||
{ key: "uptime_kuma_interval", value: fields.uptime_kuma_interval },
|
||||
{ key: "uptime_kuma_retry", value: fields.uptime_kuma_retry },
|
||||
{ key: "uptime_kuma_retry_interval", value: fields.uptime_kuma_retry_interval },
|
||||
{ key: "uptime_kuma_timeout", value: fields.uptime_kuma_timeout },
|
||||
]
|
||||
{ key: 'uptime_kuma_enabled', value: String(fields.uptime_kuma_enabled) },
|
||||
{ key: 'uptime_kuma_url', value: fields.uptime_kuma_url.trim() },
|
||||
{ key: 'uptime_kuma_username', value: fields.uptime_kuma_username.trim() },
|
||||
{ key: 'uptime_kuma_password', value: fields.uptime_kuma_password },
|
||||
{
|
||||
key: 'uptime_kuma_monitor_scope',
|
||||
value: fields.uptime_kuma_monitor_scope,
|
||||
},
|
||||
{
|
||||
key: 'uptime_kuma_selected_sites',
|
||||
value: fields.uptime_kuma_selected_sites,
|
||||
},
|
||||
{
|
||||
key: 'uptime_kuma_sync_interval',
|
||||
value: fields.uptime_kuma_sync_interval,
|
||||
},
|
||||
{ key: 'uptime_kuma_interval', value: fields.uptime_kuma_interval },
|
||||
{ key: 'uptime_kuma_retry', value: fields.uptime_kuma_retry },
|
||||
{
|
||||
key: 'uptime_kuma_retry_interval',
|
||||
value: fields.uptime_kuma_retry_interval,
|
||||
},
|
||||
{ key: 'uptime_kuma_timeout', value: fields.uptime_kuma_timeout },
|
||||
];
|
||||
}
|
||||
|
||||
export function databaseAutoCleanupEntries(fields: OpenFlareOpsFields): OptionItem[] {
|
||||
validateDatabaseAutoCleanup(fields)
|
||||
export function databaseAutoCleanupEntries(
|
||||
fields: OpenFlareOpsFields,
|
||||
): OptionItem[] {
|
||||
validateDatabaseAutoCleanup(fields);
|
||||
return [
|
||||
{ key: "database_auto_cleanup_enabled", value: String(fields.database_auto_cleanup_enabled) },
|
||||
{ key: "database_auto_cleanup_retention_days", value: fields.database_auto_cleanup_retention_days },
|
||||
]
|
||||
{
|
||||
key: 'database_auto_cleanup_enabled',
|
||||
value: String(fields.database_auto_cleanup_enabled),
|
||||
},
|
||||
{
|
||||
key: 'database_auto_cleanup_retention_days',
|
||||
value: fields.database_auto_cleanup_retention_days,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function validatePagesFields(fields: OpenFlareOpsFields) {
|
||||
const packageSize = Number.parseInt(fields.pages_max_package_size_mb, 10);
|
||||
const historyCount = Number.parseInt(fields.pages_max_history_count, 10);
|
||||
if (Number.isNaN(packageSize) || packageSize < 1 || packageSize > 2048) {
|
||||
throw new Error('Pages 部署包大小上限必须为 1~2048 MiB。');
|
||||
}
|
||||
if (Number.isNaN(historyCount) || historyCount < 0) {
|
||||
throw new Error(
|
||||
'Pages 历史保留数必须为大于等于 0 的整数(0 表示不限制)。',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function pagesOptionEntries(fields: OpenFlareOpsFields): OptionItem[] {
|
||||
validatePagesFields(fields);
|
||||
return [
|
||||
{
|
||||
key: 'pages_max_package_size_mb',
|
||||
value: String(Number.parseInt(fields.pages_max_package_size_mb, 10)),
|
||||
},
|
||||
{
|
||||
key: 'pages_max_history_count',
|
||||
value: String(Number.parseInt(fields.pages_max_history_count, 10)),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,206 +1,242 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import * as React from "react"
|
||||
import {useCallback, useEffect, useRef, useState} from "react"
|
||||
import {toast} from "sonner"
|
||||
import {Activity, Cpu, Database, HardDrive, Layers, RefreshCw} from "lucide-react"
|
||||
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card"
|
||||
import {Button} from "@/components/ui/button"
|
||||
import {Switch} from "@/components/ui/switch"
|
||||
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "@/components/ui/select"
|
||||
import {Badge} from "@/components/ui/badge"
|
||||
import {Progress} from "@/components/ui/progress"
|
||||
import {Skeleton} from "@/components/ui/skeleton"
|
||||
import type {SystemStatus} from "@/lib/services/admin"
|
||||
import services from "@/lib/services"
|
||||
import * as React from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
Activity,
|
||||
Cpu,
|
||||
Database,
|
||||
HardDrive,
|
||||
Layers,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import type { SystemStatus } from '@/lib/services/admin';
|
||||
import services from '@/lib/services';
|
||||
|
||||
/**
|
||||
* 格式化数字,每3位加逗号
|
||||
*/
|
||||
const formatNumber = (num: number | string) => {
|
||||
if (num === undefined || num === null) return "0"
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ",")
|
||||
}
|
||||
if (num === undefined || num === null) return '0';
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\B))/g, ',');
|
||||
};
|
||||
|
||||
/**
|
||||
* 运行时系统状态展示与管理组件
|
||||
*/
|
||||
export function SystemStatusManager() {
|
||||
const [status, setStatus] = useState<SystemStatus | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [wavelet, setWavelet] = useState(false)
|
||||
const [autoRefresh, setAutoRefresh] = useState(true)
|
||||
const [intervalTime, setIntervalTime] = useState("5000") // 默认5秒
|
||||
const [status, setStatus] = useState<SystemStatus | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [wavelet, setWavelet] = useState(false);
|
||||
const [autoRefresh, setAutoRefresh] = useState(true);
|
||||
const [intervalTime, setIntervalTime] = useState('5000'); // 默认5秒
|
||||
|
||||
const intervalRef = useRef<NodeJS.Timeout | null>(null)
|
||||
const prevStatusRef = useRef<SystemStatus | null>(null)
|
||||
const [changedFields, setChangedFields] = useState<Record<string, boolean>>({})
|
||||
const intervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const prevStatusRef = useRef<SystemStatus | null>(null);
|
||||
const [changedFields, setChangedFields] = useState<Record<string, boolean>>(
|
||||
{},
|
||||
);
|
||||
|
||||
// 获取状态数据
|
||||
const fetchStatus = useCallback(async (isSilent = false) => {
|
||||
if (!isSilent) setWavelet(true)
|
||||
if (!isSilent) setWavelet(true);
|
||||
try {
|
||||
const data = await services.adminStatus.getSystemStatus()
|
||||
const data = await services.adminStatus.getSystemStatus();
|
||||
|
||||
// 检测变化的字段用于微动画效果
|
||||
if (prevStatusRef.current) {
|
||||
const changes: Record<string, boolean> = {}
|
||||
const changes: Record<string, boolean> = {};
|
||||
Object.keys(data).forEach((key) => {
|
||||
const k = key as keyof SystemStatus
|
||||
const k = key as keyof SystemStatus;
|
||||
if (prevStatusRef.current && prevStatusRef.current[k] !== data[k]) {
|
||||
changes[k] = true
|
||||
changes[k] = true;
|
||||
}
|
||||
})
|
||||
setChangedFields(changes)
|
||||
});
|
||||
setChangedFields(changes);
|
||||
// 1秒后清除变化状态
|
||||
setTimeout(() => {
|
||||
setChangedFields({})
|
||||
}, 1000)
|
||||
setChangedFields({});
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
setStatus(data)
|
||||
prevStatusRef.current = data
|
||||
setStatus(data);
|
||||
prevStatusRef.current = data;
|
||||
} catch (err) {
|
||||
toast.error("获取系统状态失败", {
|
||||
description: err instanceof Error ? err.message : "请求时发生未知错误"
|
||||
})
|
||||
toast.error('获取系统状态失败', {
|
||||
description: err instanceof Error ? err.message : '请求时发生未知错误',
|
||||
});
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setWavelet(false)
|
||||
setLoading(false);
|
||||
setWavelet(false);
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
// 轮询逻辑
|
||||
useEffect(() => {
|
||||
// 首次加载
|
||||
fetchStatus()
|
||||
}, [fetchStatus])
|
||||
fetchStatus();
|
||||
}, [fetchStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current)
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
|
||||
if (autoRefresh) {
|
||||
const time = parseInt(intervalTime, 10)
|
||||
const time = parseInt(intervalTime, 10);
|
||||
intervalRef.current = setInterval(() => {
|
||||
fetchStatus(true)
|
||||
}, time)
|
||||
fetchStatus(true);
|
||||
}, time);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current)
|
||||
clearInterval(intervalRef.current);
|
||||
}
|
||||
}
|
||||
}, [autoRefresh, intervalTime, fetchStatus])
|
||||
};
|
||||
}, [autoRefresh, intervalTime, fetchStatus]);
|
||||
|
||||
// 计算内存分配百分比 (Alloc / Sys)
|
||||
const getMemoryUsagePercent = () => {
|
||||
if (!status) return 0
|
||||
if (!status) return 0;
|
||||
|
||||
const parseSizeToBytes = (sizeStr: string): number => {
|
||||
const parts = sizeStr.split(" ")
|
||||
if (parts.length < 2) return 0
|
||||
const value = parseFloat(parts[0])
|
||||
const unit = parts[1].toLowerCase()
|
||||
const parts = sizeStr.split(' ');
|
||||
if (parts.length < 2) return 0;
|
||||
const value = parseFloat(parts[0]);
|
||||
const unit = parts[1].toLowerCase();
|
||||
|
||||
if (unit.startsWith("gib")) return value * 1024 * 1024 * 1024
|
||||
if (unit.startsWith("mib")) return value * 1024 * 1024
|
||||
if (unit.startsWith("kib")) return value * 1024
|
||||
return value
|
||||
}
|
||||
if (unit.startsWith('gib')) return value * 1024 * 1024 * 1024;
|
||||
if (unit.startsWith('mib')) return value * 1024 * 1024;
|
||||
if (unit.startsWith('kib')) return value * 1024;
|
||||
return value;
|
||||
};
|
||||
|
||||
const alloc = parseSizeToBytes(status.alloc)
|
||||
const sys = parseSizeToBytes(status.sys)
|
||||
if (sys === 0) return 0
|
||||
return Math.min(Math.round((alloc / sys) * 100), 100)
|
||||
}
|
||||
const alloc = parseSizeToBytes(status.alloc);
|
||||
const sys = parseSizeToBytes(status.sys);
|
||||
if (sys === 0) return 0;
|
||||
return Math.min(Math.round((alloc / sys) * 100), 100);
|
||||
};
|
||||
|
||||
// 闪烁动画类
|
||||
const getPulseClass = (field: string) => {
|
||||
return changedFields[field] ? "animate-pulse text-primary font-bold transition-all duration-300 scale-105 inline-block" : "transition-all duration-300"
|
||||
}
|
||||
return changedFields[field]
|
||||
? 'animate-pulse text-primary font-bold transition-all duration-300 scale-105 inline-block'
|
||||
: 'transition-all duration-300';
|
||||
};
|
||||
|
||||
const RenderMetricRow = ({ label, value, field }: { label: string; value: string | number; field?: string }) => (
|
||||
<div className="flex items-center justify-between py-2 border-b border-dashed border-border/40 last:border-b-0 hover:bg-muted/30 px-2 rounded-sm transition-colors duration-150">
|
||||
<span className="text-xs font-medium text-muted-foreground">{label}</span>
|
||||
<span className={`text-xs font-mono font-medium ${field ? getPulseClass(field) : ""}`}>
|
||||
{typeof value === "number" ? formatNumber(value) : value}
|
||||
const RenderMetricRow = ({
|
||||
label,
|
||||
value,
|
||||
field,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | number;
|
||||
field?: string;
|
||||
}) => (
|
||||
<div className='flex items-center justify-between py-2 border-b border-dashed border-border/40 last:border-b-0 hover:bg-muted/30 px-2 rounded-sm transition-colors duration-150'>
|
||||
<span className='text-xs font-medium text-muted-foreground'>{label}</span>
|
||||
<span
|
||||
className={`text-xs font-mono font-medium ${field ? getPulseClass(field) : ''}`}
|
||||
>
|
||||
{typeof value === 'number' ? formatNumber(value) : value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-6 p-1">
|
||||
<div className="flex items-center justify-between border-b border-border/40 pb-4">
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-6 w-32" />
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<div className='space-y-6 p-1'>
|
||||
<div className='flex items-center justify-between border-b border-border/40 pb-4'>
|
||||
<div className='space-y-1'>
|
||||
<Skeleton className='h-6 w-32' />
|
||||
<Skeleton className='h-4 w-48' />
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="h-8 w-24" />
|
||||
<Skeleton className="h-8 w-16" />
|
||||
<Skeleton className="h-8 w-8" />
|
||||
<div className='flex items-center gap-3'>
|
||||
<Skeleton className='h-8 w-24' />
|
||||
<Skeleton className='h-8 w-16' />
|
||||
<Skeleton className='h-8 w-8' />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<Skeleton className="h-48 w-full" />
|
||||
<Skeleton className="h-48 w-full" />
|
||||
<Skeleton className="h-48 w-full" />
|
||||
<Skeleton className="h-48 w-full" />
|
||||
<Skeleton className="h-48 w-full" />
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'>
|
||||
<Skeleton className='h-48 w-full' />
|
||||
<Skeleton className='h-48 w-full' />
|
||||
<Skeleton className='h-48 w-full' />
|
||||
<Skeleton className='h-48 w-full' />
|
||||
<Skeleton className='h-48 w-full' />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6">
|
||||
<div className='py-6 px-1 space-y-6'>
|
||||
{/* 顶部控制栏 */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between pb-4 gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Activity className="size-5 text-primary" />
|
||||
<div className='flex flex-col sm:flex-row sm:items-center sm:justify-between pb-4 gap-4'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Activity className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">系统状态</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>系统状态</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center flex-wrap gap-4 bg-muted/30 p-1.5 rounded-lg border border-border/40 backdrop-blur-sm">
|
||||
<div className="flex items-center gap-2 px-1">
|
||||
<div className='flex items-center flex-wrap gap-4 bg-muted/30 p-1.5 rounded-lg border border-border/40 backdrop-blur-sm'>
|
||||
<div className='flex items-center gap-2 px-1'>
|
||||
<Switch
|
||||
id="auto-refresh"
|
||||
id='auto-refresh'
|
||||
checked={autoRefresh}
|
||||
onCheckedChange={setAutoRefresh}
|
||||
/>
|
||||
<label htmlFor="auto-refresh" className="text-xs font-medium cursor-pointer select-none">
|
||||
<label
|
||||
htmlFor='auto-refresh'
|
||||
className='text-xs font-medium cursor-pointer select-none'
|
||||
>
|
||||
自动刷新
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{autoRefresh && (
|
||||
<Select value={intervalTime} onValueChange={setIntervalTime}>
|
||||
<SelectTrigger className="h-7 w-20 text-[11px] bg-background border-border/40">
|
||||
<SelectTrigger className='h-7 w-20 text-[11px] bg-background border-border/40'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="1000">1s</SelectItem>
|
||||
<SelectItem value="2000">2s</SelectItem>
|
||||
<SelectItem value="5000">5s</SelectItem>
|
||||
<SelectItem value="10000">10s</SelectItem>
|
||||
<SelectItem value='1000'>1s</SelectItem>
|
||||
<SelectItem value='2000'>2s</SelectItem>
|
||||
<SelectItem value='5000'>5s</SelectItem>
|
||||
<SelectItem value='10000'>10s</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-7 text-[11px] gap-1.5"
|
||||
size='sm'
|
||||
variant='secondary'
|
||||
className='h-7 text-[11px] gap-1.5'
|
||||
onClick={() => fetchStatus()}
|
||||
disabled={wavelet}
|
||||
>
|
||||
<RefreshCw className={`size-3 ${wavelet ? "animate-spin" : ""}`} />
|
||||
<RefreshCw className={`size-3 ${wavelet ? 'animate-spin' : ''}`} />
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
@@ -209,130 +245,277 @@ export function SystemStatusManager() {
|
||||
{status && (
|
||||
<>
|
||||
{/* 主网格排版 */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'>
|
||||
{/* 1. 服务概览 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-sm font-semibold">服务概览</CardTitle>
|
||||
<CardDescription className="text-[10px]">服务的基础生命指标</CardDescription>
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<div className='space-y-0.5'>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
服务概览
|
||||
</CardTitle>
|
||||
<CardDescription className='text-[10px]'>
|
||||
服务的基础生命指标
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
|
||||
<Activity className="size-4" />
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='p-1 rounded-full bg-primary/10 text-primary border-none'
|
||||
>
|
||||
<Activity className='size-4' />
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
<RenderMetricRow label="服务运行时间" value={status.uptime} field="uptime" />
|
||||
<RenderMetricRow label="当前 Goroutines 数量" value={status.num_goroutine} field="num_goroutine" />
|
||||
<RenderMetricRow label="Heap 对象数量" value={status.heap_objects} field="heap_objects" />
|
||||
<CardContent className='space-y-1'>
|
||||
<RenderMetricRow
|
||||
label='服务运行时间'
|
||||
value={status.uptime}
|
||||
field='uptime'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='当前 Goroutines 数量'
|
||||
value={status.num_goroutine}
|
||||
field='num_goroutine'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='Heap 对象数量'
|
||||
value={status.heap_objects}
|
||||
field='heap_objects'
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 2. 内存统计 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-sm font-semibold">内存统计</CardTitle>
|
||||
<CardDescription className="text-[10px]">主内存消耗概览</CardDescription>
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<div className='space-y-0.5'>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
内存统计
|
||||
</CardTitle>
|
||||
<CardDescription className='text-[10px]'>
|
||||
主内存消耗概览
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
|
||||
<Cpu className="size-4" />
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='p-1 rounded-full bg-primary/10 text-primary border-none'
|
||||
>
|
||||
<Cpu className='size-4' />
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<RenderMetricRow label="当前内存使用量" value={status.alloc} field="alloc" />
|
||||
<RenderMetricRow label="所有已分配的内存" value={status.total_alloc} field="total_alloc" />
|
||||
<RenderMetricRow label="内存占用量" value={status.sys} field="sys" />
|
||||
<RenderMetricRow label="下次 GC 内存回收量" value={status.next_gc} field="next_gc" />
|
||||
<CardContent className='space-y-3'>
|
||||
<div className='space-y-1'>
|
||||
<RenderMetricRow
|
||||
label='当前内存使用量'
|
||||
value={status.alloc}
|
||||
field='alloc'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='所有已分配的内存'
|
||||
value={status.total_alloc}
|
||||
field='total_alloc'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='内存占用量'
|
||||
value={status.sys}
|
||||
field='sys'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='下次 GC 内存回收量'
|
||||
value={status.next_gc}
|
||||
field='next_gc'
|
||||
/>
|
||||
</div>
|
||||
{/* 物理内存水位比例 */}
|
||||
<div className="space-y-1 px-1 pt-1">
|
||||
<div className="flex justify-between text-[10px] text-muted-foreground">
|
||||
<div className='space-y-1 px-1 pt-1'>
|
||||
<div className='flex justify-between text-[10px] text-muted-foreground'>
|
||||
<span>当前使用率 (Alloc / Sys)</span>
|
||||
<span className="font-mono">{getMemoryUsagePercent()}%</span>
|
||||
<span className='font-mono'>
|
||||
{getMemoryUsagePercent()}%
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={getMemoryUsagePercent()} className="h-1.5" />
|
||||
<Progress value={getMemoryUsagePercent()} className='h-1.5' />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 3. 堆/栈详情 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-sm font-semibold">堆/栈详情</CardTitle>
|
||||
<CardDescription className="text-[10px]">运行时堆栈内存空间细节</CardDescription>
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<div className='space-y-0.5'>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
堆/栈详情
|
||||
</CardTitle>
|
||||
<CardDescription className='text-[10px]'>
|
||||
运行时堆栈内存空间细节
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
|
||||
<Database className="size-4" />
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='p-1 rounded-full bg-primary/10 text-primary border-none'
|
||||
>
|
||||
<Database className='size-4' />
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
<RenderMetricRow label="当前 Heap 内存使用量" value={status.heap_alloc} field="heap_alloc" />
|
||||
<RenderMetricRow label="Heap 内存占用量" value={status.heap_sys} field="heap_sys" />
|
||||
<RenderMetricRow label="Heap 内存空闲量" value={status.heap_idle} field="heap_idle" />
|
||||
<RenderMetricRow label="正在使用的 Heap 内存" value={status.heap_inuse} field="heap_inuse" />
|
||||
<RenderMetricRow label="已释放的 Heap 内存" value={status.heap_released} field="heap_released" />
|
||||
<RenderMetricRow label="启动 Stack 使用量" value={status.stack_inuse} field="stack_inuse" />
|
||||
<RenderMetricRow label="已分配的 Stack 内存" value={status.stack_sys} field="stack_sys" />
|
||||
<CardContent className='space-y-1'>
|
||||
<RenderMetricRow
|
||||
label='当前 Heap 内存使用量'
|
||||
value={status.heap_alloc}
|
||||
field='heap_alloc'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='Heap 内存占用量'
|
||||
value={status.heap_sys}
|
||||
field='heap_sys'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='Heap 内存空闲量'
|
||||
value={status.heap_idle}
|
||||
field='heap_idle'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='正在使用的 Heap 内存'
|
||||
value={status.heap_inuse}
|
||||
field='heap_inuse'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='已释放的 Heap 内存'
|
||||
value={status.heap_released}
|
||||
field='heap_released'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='启动 Stack 使用量'
|
||||
value={status.stack_inuse}
|
||||
field='stack_inuse'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='已分配的 Stack 内存'
|
||||
value={status.stack_sys}
|
||||
field='stack_sys'
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 4. 底层组件与结构体 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-sm font-semibold">底层及结构体内存</CardTitle>
|
||||
<CardDescription className="text-[10px]">运行时底层管理结构体开销</CardDescription>
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<div className='space-y-0.5'>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
底层及结构体内存
|
||||
</CardTitle>
|
||||
<CardDescription className='text-[10px]'>
|
||||
运行时底层管理结构体开销
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
|
||||
<HardDrive className="size-4" />
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='p-1 rounded-full bg-primary/10 text-primary border-none'
|
||||
>
|
||||
<HardDrive className='size-4' />
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
<RenderMetricRow label="MSpan 结构内存使用量" value={status.mspan_inuse} field="mspan_inuse" />
|
||||
<RenderMetricRow label="已分配的 MSpan 结构内存" value={status.mspan_sys} field="mspan_sys" />
|
||||
<RenderMetricRow label="MCache 结构内存使用量" value={status.mcache_inuse} field="mcache_inuse" />
|
||||
<RenderMetricRow label="已分配的 MCache 结构内存" value={status.mcache_sys} field="mcache_sys" />
|
||||
<RenderMetricRow label="已分配的剖析哈希表内存" value={status.buck_hash_sys} field="buck_hash_sys" />
|
||||
<RenderMetricRow label="已分配的 GC 元数据内存" value={status.gc_sys} field="gc_sys" />
|
||||
<RenderMetricRow label="其它已分配的系统内存" value={status.other_sys} field="other_sys" />
|
||||
<CardContent className='space-y-1'>
|
||||
<RenderMetricRow
|
||||
label='MSpan 结构内存使用量'
|
||||
value={status.mspan_inuse}
|
||||
field='mspan_inuse'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='已分配的 MSpan 结构内存'
|
||||
value={status.mspan_sys}
|
||||
field='mspan_sys'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='MCache 结构内存使用量'
|
||||
value={status.mcache_inuse}
|
||||
field='mcache_inuse'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='已分配的 MCache 结构内存'
|
||||
value={status.mcache_sys}
|
||||
field='mcache_sys'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='已分配的剖析哈希表内存'
|
||||
value={status.buck_hash_sys}
|
||||
field='buck_hash_sys'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='已分配的 GC 元数据内存'
|
||||
value={status.gc_sys}
|
||||
field='gc_sys'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='其它已分配的系统内存'
|
||||
value={status.other_sys}
|
||||
field='other_sys'
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 5. 垃圾回收与分配计数 */}
|
||||
<Card className="shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300 md:col-span-2">
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0">
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-sm font-semibold">垃圾回收与分配计数</CardTitle>
|
||||
<CardDescription className="text-[10px]">GC 历史数据与分配频次</CardDescription>
|
||||
<Card className='shadow-sm border-border/40 bg-card/50 backdrop-blur-md hover:border-primary/20 transition-all duration-300 md:col-span-2'>
|
||||
<CardHeader className='flex flex-row items-center justify-between pb-2 space-y-0'>
|
||||
<div className='space-y-0.5'>
|
||||
<CardTitle className='text-sm font-semibold'>
|
||||
垃圾回收与分配计数
|
||||
</CardTitle>
|
||||
<CardDescription className='text-[10px]'>
|
||||
GC 历史数据与分配频次
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant="secondary" className="p-1 rounded-full bg-primary/10 text-primary border-none">
|
||||
<Layers className="size-4" />
|
||||
<Badge
|
||||
variant='secondary'
|
||||
className='p-1 rounded-full bg-primary/10 text-primary border-none'
|
||||
>
|
||||
<Layers className='size-4' />
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6">
|
||||
<div className='grid grid-cols-1 sm:grid-cols-2 gap-x-6'>
|
||||
<div>
|
||||
<RenderMetricRow label="GC 执行次数" value={status.num_gc} field="num_gc" />
|
||||
<RenderMetricRow label="距离上次 GC 时间" value={status.last_gc_time} field="last_gc_time" />
|
||||
<RenderMetricRow label="GC 暂停时间总量" value={status.pause_total_ns} field="pause_total_ns" />
|
||||
<RenderMetricRow label="上次 GC 暂停时间" value={status.last_pause} field="last_pause" />
|
||||
<RenderMetricRow
|
||||
label='GC 执行次数'
|
||||
value={status.num_gc}
|
||||
field='num_gc'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='距离上次 GC 时间'
|
||||
value={status.last_gc_time}
|
||||
field='last_gc_time'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='GC 暂停时间总量'
|
||||
value={status.pause_total_ns}
|
||||
field='pause_total_ns'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='上次 GC 暂停时间'
|
||||
value={status.last_pause}
|
||||
field='last_pause'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<RenderMetricRow label="内存分配次数" value={status.mallocs} field="mallocs" />
|
||||
<RenderMetricRow label="内存释放次数" value={status.frees} field="frees" />
|
||||
<RenderMetricRow label="指针查找次数" value={status.lookups} field="lookups" />
|
||||
<RenderMetricRow
|
||||
label='内存分配次数'
|
||||
value={status.mallocs}
|
||||
field='mallocs'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='内存释放次数'
|
||||
value={status.frees}
|
||||
field='frees'
|
||||
/>
|
||||
<RenderMetricRow
|
||||
label='指针查找次数'
|
||||
value={status.lookups}
|
||||
field='lookups'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import {useEffect, useMemo, useState} from "react"
|
||||
import {useQuery} from "@tanstack/react-query"
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import {Button} from "@/components/ui/button"
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -11,17 +11,17 @@ import {
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import {Input} from "@/components/ui/input"
|
||||
import {Label} from "@/components/ui/label"
|
||||
import {ProxyRouteService} from "@/lib/services/openflare"
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ProxyRouteService } from '@/lib/services/openflare';
|
||||
|
||||
type UptimeKumaSiteSelectModalProps = {
|
||||
open: boolean
|
||||
selectedSites: string[]
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSave: (sites: string[]) => void
|
||||
}
|
||||
open: boolean;
|
||||
selectedSites: string[];
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSave: (sites: string[]) => void;
|
||||
};
|
||||
|
||||
export function UptimeKumaSiteSelectModal({
|
||||
open,
|
||||
@@ -29,60 +29,66 @@ export function UptimeKumaSiteSelectModal({
|
||||
onOpenChange,
|
||||
onSave,
|
||||
}: UptimeKumaSiteSelectModalProps) {
|
||||
const [searchTerm, setSearchTerm] = useState("")
|
||||
const [tempSelected, setTempSelected] = useState<Set<string>>(new Set())
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [tempSelected, setTempSelected] = useState<Set<string>>(new Set());
|
||||
|
||||
const routesQuery = useQuery({
|
||||
queryKey: ["openflare", "proxy-routes"],
|
||||
queryKey: ['openflare', 'proxy-routes'],
|
||||
queryFn: () => ProxyRouteService.list(),
|
||||
enabled: open,
|
||||
})
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setTempSelected(new Set(selectedSites.map((site) => site.trim()).filter(Boolean)))
|
||||
setSearchTerm("")
|
||||
}, [open, selectedSites])
|
||||
if (!open) return;
|
||||
setTempSelected(
|
||||
new Set(selectedSites.map((site) => site.trim()).filter(Boolean)),
|
||||
);
|
||||
setSearchTerm('');
|
||||
}, [open, selectedSites]);
|
||||
|
||||
const filteredRoutes = useMemo(() => {
|
||||
const routes = routesQuery.data ?? []
|
||||
const keyword = searchTerm.trim().toLowerCase()
|
||||
if (!keyword) return routes
|
||||
return routes.filter(
|
||||
(route) =>
|
||||
const routes = routesQuery.data ?? [];
|
||||
const keyword = searchTerm.trim().toLowerCase();
|
||||
if (!keyword) return routes;
|
||||
return routes.filter((route) => {
|
||||
const domains = (route.zone_domains ?? [])
|
||||
.map((item) => item.domain)
|
||||
.join(' ');
|
||||
return (
|
||||
route.site_name.toLowerCase().includes(keyword) ||
|
||||
route.primary_domain.toLowerCase().includes(keyword),
|
||||
)
|
||||
}, [routesQuery.data, searchTerm])
|
||||
domains.toLowerCase().includes(keyword)
|
||||
);
|
||||
});
|
||||
}, [routesQuery.data, searchTerm]);
|
||||
|
||||
const toggleSite = (siteName: string) => {
|
||||
setTempSelected((previous) => {
|
||||
const next = new Set(previous)
|
||||
if (next.has(siteName)) next.delete(siteName)
|
||||
else next.add(siteName)
|
||||
return next
|
||||
})
|
||||
}
|
||||
const next = new Set(previous);
|
||||
if (next.has(siteName)) next.delete(siteName);
|
||||
else next.add(siteName);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
setTempSelected((previous) => {
|
||||
const next = new Set(previous)
|
||||
filteredRoutes.forEach((route) => next.add(route.site_name))
|
||||
return next
|
||||
})
|
||||
}
|
||||
const next = new Set(previous);
|
||||
filteredRoutes.forEach((route) => next.add(route.site_name));
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeselectAll = () => {
|
||||
setTempSelected((previous) => {
|
||||
const next = new Set(previous)
|
||||
filteredRoutes.forEach((route) => next.delete(route.site_name))
|
||||
return next
|
||||
})
|
||||
}
|
||||
const next = new Set(previous);
|
||||
filteredRoutes.forEach((route) => next.delete(route.site_name));
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogContent className='max-w-2xl'>
|
||||
<DialogHeader>
|
||||
<DialogTitle>选择监控站点</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -90,86 +96,111 @@ export function UptimeKumaSiteSelectModal({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<div className='space-y-4'>
|
||||
<div className='space-y-1.5'>
|
||||
<Label>搜索站点</Label>
|
||||
<Input
|
||||
value={searchTerm}
|
||||
onChange={(event) => setSearchTerm(event.target.value)}
|
||||
placeholder="按名称或域名搜索..."
|
||||
placeholder='按名称或域名搜索...'
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleSelectAll}>
|
||||
<div className='flex flex-wrap gap-2'>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={handleSelectAll}
|
||||
>
|
||||
全选过滤项
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleDeselectAll}>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
size='sm'
|
||||
onClick={handleDeselectAll}
|
||||
>
|
||||
清空过滤项
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="max-h-72 overflow-y-auto rounded-lg border">
|
||||
<div className='max-h-72 overflow-y-auto rounded-lg border'>
|
||||
{routesQuery.isLoading ? (
|
||||
<p className="p-4 text-sm text-muted-foreground">加载站点列表...</p>
|
||||
<p className='p-4 text-sm text-muted-foreground'>
|
||||
加载站点列表...
|
||||
</p>
|
||||
) : routesQuery.isError ? (
|
||||
<p className="p-4 text-sm text-destructive">
|
||||
<p className='p-4 text-sm text-destructive'>
|
||||
{routesQuery.error instanceof Error
|
||||
? routesQuery.error.message
|
||||
: "加载站点失败"}
|
||||
: '加载站点失败'}
|
||||
</p>
|
||||
) : filteredRoutes.length === 0 ? (
|
||||
<p className="p-4 text-sm text-muted-foreground">无匹配的站点</p>
|
||||
<p className='p-4 text-sm text-muted-foreground'>无匹配的站点</p>
|
||||
) : (
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="sticky top-0 bg-muted/60 text-xs uppercase text-muted-foreground">
|
||||
<table className='w-full text-left text-sm'>
|
||||
<thead className='sticky top-0 bg-muted/60 text-xs uppercase text-muted-foreground'>
|
||||
<tr>
|
||||
<th className="w-12 px-3 py-2">选择</th>
|
||||
<th className="px-3 py-2">站点名称</th>
|
||||
<th className="px-3 py-2">主域名</th>
|
||||
<th className='w-12 px-3 py-2'>选择</th>
|
||||
<th className='px-3 py-2'>站点名称</th>
|
||||
<th className='px-3 py-2'>主域名</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
<tbody className='divide-y'>
|
||||
{filteredRoutes.map((route) => {
|
||||
const checked = tempSelected.has(route.site_name)
|
||||
const checked = tempSelected.has(route.site_name);
|
||||
return (
|
||||
<tr
|
||||
key={route.id}
|
||||
className="cursor-pointer hover:bg-muted/30"
|
||||
className='cursor-pointer hover:bg-muted/30'
|
||||
onClick={() => toggleSite(route.site_name)}
|
||||
>
|
||||
<td className="px-3 py-2" onClick={(event) => event.stopPropagation()}>
|
||||
<td
|
||||
className='px-3 py-2'
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
type='checkbox'
|
||||
checked={checked}
|
||||
onChange={() => toggleSite(route.site_name)}
|
||||
className="size-4 rounded border-input"
|
||||
className='size-4 rounded border-input'
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2 font-medium">{route.site_name}</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">{route.primary_domain}</td>
|
||||
<td className='px-3 py-2 font-medium'>
|
||||
{route.site_name}
|
||||
</td>
|
||||
<td className='px-3 py-2 text-muted-foreground'>
|
||||
{(route.zone_domains ?? [])
|
||||
.map((item) => item.domain)
|
||||
.join(', ') || '—'}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-right text-xs text-muted-foreground">
|
||||
<p className='text-right text-xs text-muted-foreground'>
|
||||
已选择 {tempSelected.size} 个监控站点
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
<Button
|
||||
type='button'
|
||||
variant='outline'
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
type='button'
|
||||
onClick={() => {
|
||||
onSave(Array.from(tempSelected))
|
||||
onOpenChange(false)
|
||||
onSave(Array.from(tempSelected));
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
保存选择
|
||||
@@ -177,5 +208,5 @@ export function UptimeKumaSiteSelectModal({
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,155 +1,225 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
"use client"
|
||||
'use client';
|
||||
|
||||
import dynamic from "next/dynamic"
|
||||
import {useEffect, useMemo} from "react"
|
||||
import {useQuery} from "@tanstack/react-query"
|
||||
import {Loader2, Settings} from "lucide-react"
|
||||
import {useRouter} from "next/navigation"
|
||||
import {motion} from "motion/react"
|
||||
import dynamic from 'next/dynamic';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Loader2, Settings } from 'lucide-react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { motion } from 'motion/react';
|
||||
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs"
|
||||
import {useAuth} from "@/components/providers/auth-provider"
|
||||
import services from "@/lib/services"
|
||||
import type {SystemConfig} from "@/lib/services/admin"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { useAuth } from '@/components/providers/auth-provider';
|
||||
import services from '@/lib/services';
|
||||
import type { SystemConfig } from '@/lib/services/admin';
|
||||
|
||||
const tabFallback = (
|
||||
<div className="h-64 animate-pulse rounded-lg border border-border/40 bg-muted/20" />
|
||||
)
|
||||
<div className='h-64 animate-pulse rounded-lg border border-border/40 bg-muted/20' />
|
||||
);
|
||||
|
||||
const SecurityTab = dynamic(
|
||||
() => import("@/components/common/settings/security-tab").then((mod) => mod.SecurityTab),
|
||||
() =>
|
||||
import('@/components/common/settings/security-tab').then(
|
||||
(mod) => mod.SecurityTab,
|
||||
),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const OperationTab = dynamic(
|
||||
() => import("@/components/common/settings/operation-tab").then((mod) => mod.OperationTab),
|
||||
() =>
|
||||
import('@/components/common/settings/operation-tab').then(
|
||||
(mod) => mod.OperationTab,
|
||||
),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const SystemTab = dynamic(
|
||||
() => import("@/components/common/settings/system-tab").then((mod) => mod.SystemTab),
|
||||
() =>
|
||||
import('@/components/common/settings/system-tab').then(
|
||||
(mod) => mod.SystemTab,
|
||||
),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const OtherTab = dynamic(
|
||||
() => import("@/components/common/settings/other-tab").then((mod) => mod.OtherTab),
|
||||
() =>
|
||||
import('@/components/common/settings/other-tab').then(
|
||||
(mod) => mod.OtherTab,
|
||||
),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const InfoTab = dynamic(
|
||||
() => import("@/components/common/settings/info-tab").then((mod) => mod.InfoTab),
|
||||
() =>
|
||||
import('@/components/common/settings/info-tab').then((mod) => mod.InfoTab),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const SystemStatusManager = dynamic(
|
||||
() => import("./components/system-status").then((mod) => mod.SystemStatusManager),
|
||||
() =>
|
||||
import('./components/system-status').then((mod) => mod.SystemStatusManager),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
const OpenFlareOpsSettings = dynamic(
|
||||
() => import("./components/openflare-ops").then((mod) => mod.OpenFlareOpsSettings),
|
||||
() =>
|
||||
import('./components/openflare-ops').then(
|
||||
(mod) => mod.OpenFlareOpsSettings,
|
||||
),
|
||||
{ loading: () => tabFallback },
|
||||
)
|
||||
);
|
||||
|
||||
function systemConfigMap(configs: SystemConfig[]) {
|
||||
return configs.reduce<Record<string, SystemConfig>>((accumulator, config) => {
|
||||
accumulator[config.key] = config
|
||||
return accumulator
|
||||
}, {})
|
||||
accumulator[config.key] = config;
|
||||
return accumulator;
|
||||
}, {});
|
||||
}
|
||||
|
||||
export function AdminSettingsPageClient() {
|
||||
const { user, loading } = useAuth()
|
||||
const router = useRouter()
|
||||
const { user, loading } = useAuth();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const activeTab = useMemo(() => {
|
||||
const rawTab = searchParams.get('tab');
|
||||
const validTabs = [
|
||||
'openflare-ops',
|
||||
'security',
|
||||
'operation',
|
||||
'system',
|
||||
'other',
|
||||
'status',
|
||||
'info',
|
||||
];
|
||||
return rawTab && validTabs.includes(rawTab) ? rawTab : 'openflare-ops';
|
||||
}, [searchParams]);
|
||||
|
||||
const handleTabChange = (value: string) => {
|
||||
router.push(`/admin/settings?tab=${value}`);
|
||||
};
|
||||
|
||||
const systemConfigsQuery = useQuery({
|
||||
queryKey: ["admin", "system-configs"],
|
||||
queryFn: () => services.adminSystemConfig.listSystemConfigs("system"),
|
||||
queryKey: ['admin', 'system-configs'],
|
||||
queryFn: () => services.adminSystemConfig.listSystemConfigs('system'),
|
||||
enabled: !!user?.is_admin,
|
||||
})
|
||||
});
|
||||
|
||||
const configs = useMemo(
|
||||
() => systemConfigMap(systemConfigsQuery.data ?? []),
|
||||
[systemConfigsQuery.data],
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && (!user || !user.is_admin)) {
|
||||
router.replace("/settings/profile")
|
||||
router.replace('/settings/profile');
|
||||
}
|
||||
}, [user, loading, router])
|
||||
}, [user, loading, router]);
|
||||
|
||||
if (loading || !user || !user.is_admin) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<Loader2 className="size-6 animate-spin text-indigo-500" />
|
||||
<div className='flex items-center justify-center min-h-[400px]'>
|
||||
<Loader2 className='size-6 animate-spin text-primary' />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 15 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.35, ease: "easeOut" }}
|
||||
className="py-6 space-y-6 w-full"
|
||||
transition={{ duration: 0.35, ease: 'easeOut' }}
|
||||
className='py-6 space-y-6 w-full'
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Settings className="size-5 text-primary" />
|
||||
<div className='flex items-center gap-2'>
|
||||
<Settings className='size-5 text-primary' />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">系统设置</h1>
|
||||
<h1 className='text-2xl font-semibold tracking-tight'>系统设置</h1>
|
||||
</div>
|
||||
</div>
|
||||
<Tabs defaultValue="security" className="w-full">
|
||||
<TabsList variant="line" className="w-fit inline-flex gap-8 mb-6">
|
||||
<TabsTrigger value="openflare-ops" className="px-0 pb-2 text-xs font-semibold">
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={handleTabChange}
|
||||
className='w-full'
|
||||
>
|
||||
<TabsList variant='line' className='w-fit inline-flex gap-8 mb-6'>
|
||||
<TabsTrigger
|
||||
value='openflare-ops'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
OpenFlare
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="security" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='security'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
安全设置
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="operation" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='operation'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
业务设置
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="system" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='system'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
系统设置
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="other" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='other'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
其他设置
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="status" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger
|
||||
value='status'
|
||||
className='px-0 pb-2 text-xs font-semibold'
|
||||
>
|
||||
系统状态
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="info" className="px-0 pb-2 text-xs font-semibold">
|
||||
<TabsTrigger value='info' className='px-0 pb-2 text-xs font-semibold'>
|
||||
系统信息
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="security" className="focus-visible:outline-none">
|
||||
<SecurityTab configs={configs} systemConfigsQuery={systemConfigsQuery} />
|
||||
<TabsContent value='security' className='focus-visible:outline-none'>
|
||||
<SecurityTab
|
||||
configs={configs}
|
||||
systemConfigsQuery={systemConfigsQuery}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="operation" className="focus-visible:outline-none">
|
||||
<OperationTab configs={configs} systemConfigsQuery={systemConfigsQuery} />
|
||||
<TabsContent value='operation' className='focus-visible:outline-none'>
|
||||
<OperationTab
|
||||
configs={configs}
|
||||
systemConfigsQuery={systemConfigsQuery}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="system" className="focus-visible:outline-none">
|
||||
<SystemTab configs={configs} systemConfigsQuery={systemConfigsQuery} />
|
||||
<TabsContent value='system' className='focus-visible:outline-none'>
|
||||
<SystemTab
|
||||
configs={configs}
|
||||
systemConfigsQuery={systemConfigsQuery}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="status" className="focus-visible:outline-none">
|
||||
<TabsContent value='status' className='focus-visible:outline-none'>
|
||||
<SystemStatusManager />
|
||||
</TabsContent>
|
||||
<TabsContent value="other" className="focus-visible:outline-none">
|
||||
<TabsContent value='other' className='focus-visible:outline-none'>
|
||||
<OtherTab configs={configs} />
|
||||
</TabsContent>
|
||||
<TabsContent value="info" className="focus-visible:outline-none">
|
||||
<TabsContent value='info' className='focus-visible:outline-none'>
|
||||
<InfoTab />
|
||||
</TabsContent>
|
||||
<TabsContent value="openflare-ops" className="focus-visible:outline-none">
|
||||
<TabsContent
|
||||
value='openflare-ops'
|
||||
className='focus-visible:outline-none'
|
||||
>
|
||||
<OpenFlareOpsSettings />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</motion.div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user