mirror of
https://github.com/luckjiawei/podux.git
synced 2026-11-30 00:56:47 +00:00
docs: relocate and translate agent development guides
This commit is contained in:
1 parent
8a44a6ed87
commit
1136797a36
9 files changed
+354
-356
No files matched your search
@@ -1,48 +1,49 @@
|
||||
# Podux Agent 开发指南
|
||||
# Podux Agent Development Guide
|
||||
|
||||
## 项目定位与技术栈
|
||||
## Project Scope and Technology Stack
|
||||
|
||||
Podux 是集中管理 frpc 服务器配置、代理、连接状态、网络延迟和运行日志的 Web 管理平台。当前代码基线为 Go 1.25.5、PocketBase 0.35.0 和内嵌的 frp 0.68.0;业务前端位于 `site/`,使用 React 19、TypeScript 5.9、Vite 7、Radix Themes 3、Tailwind CSS 4。`docs/` 是 VitePress 1 文档站,其 Vue 依赖不代表业务前端使用 Vue。
|
||||
Podux is a web management platform for centrally managing frpc server configurations, proxies, connection status, network latency, and runtime logs. The current codebase uses Go 1.25.5, PocketBase 0.35.0, and embedded frp 0.68.0. The application frontend is under `site/` and uses React 19, TypeScript 5.9, Vite 7, Radix Themes 3, and Tailwind CSS 4. `docs/` is a VitePress 1 documentation site; its Vue dependency does not mean that the application frontend uses Vue.
|
||||
|
||||
版本号及依赖以 `go.mod`、`site/package.json` 和 `docs/package.json` 为准,不要从文档示例反推版本。
|
||||
Treat `go.mod`, `site/package.json`, and `docs/package.json` as the sources of truth for versions and dependencies. Do not infer versions from documentation examples.
|
||||
|
||||
## 目录地图
|
||||
## Directory Map
|
||||
|
||||
| 路径 | 职责 |
|
||||
| Path | Responsibility |
|
||||
| --- | --- |
|
||||
| `main.go` | PocketBase 启动与依赖装配、hook/自定义路由、监控调度、静态资源服务入口 |
|
||||
| `internal/domain/` | server/proxy 领域模型和 repository 接口 |
|
||||
| `internal/application/` | dashboard、frpc、importer、monitoring、proxy、server、system、version 等用例服务 |
|
||||
| `internal/infrastructure/persistence/` | 基于 PocketBase/dbx 的 repository 实现 |
|
||||
| `internal/interfaces/http/` | 自定义 HTTP handler 和鉴权中间件 |
|
||||
| `migrations/` | PocketBase collection schema 的唯一版本化事实来源 |
|
||||
| `pkg/` | build info、响应、通用类型和工具 |
|
||||
| `site/` | React 业务前端;可直接调用 PocketBase collection API,也调用 `/api/*` 自定义接口 |
|
||||
| `docs/` | 独立 VitePress 文档站 |
|
||||
| `pb_public/` | `site/dist` 的复制目标;由 `main.go` 的 `go:embed` 打入 Go 二进制,不提交 |
|
||||
| `pb_data/` | PocketBase SQLite、上传文件及 `frpc/<server-id>` 日志/证书运行数据,不提交 |
|
||||
| `build/`、`deploy/` | 多平台构建脚本和 Docker 部署文件 |
|
||||
| `main.go` | PocketBase startup and dependency wiring, hooks/custom routes, monitoring scheduler, and static asset serving entry point |
|
||||
| `internal/domain/` | Server/proxy domain models and repository interfaces |
|
||||
| `internal/application/` | Use-case services for dashboard, frpc, importer, monitoring, proxy, server, system, version, and related features |
|
||||
| `internal/infrastructure/persistence/` | Repository implementations based on PocketBase/dbx |
|
||||
| `internal/interfaces/http/` | Custom HTTP handlers and authentication middleware |
|
||||
| `migrations/` | The sole version-controlled source of truth for PocketBase collection schemas |
|
||||
| `pkg/` | Build information, responses, shared types, and utilities |
|
||||
| `site/` | React application frontend; calls both the PocketBase collection API and custom `/api/*` endpoints |
|
||||
| `docs/` | Independent VitePress documentation site |
|
||||
| `development/` | Development design documents for agents and maintainers; not part of the web documentation site |
|
||||
| `pb_public/` | Copy destination for `site/dist`; embedded into the Go binary by `main.go` via `go:embed`; not committed |
|
||||
| `pb_data/` | PocketBase SQLite data, uploads, and `frpc/<server-id>` runtime logs/certificates; not committed |
|
||||
| `build/`, `deploy/` | Multi-platform build scripts and Docker deployment files |
|
||||
|
||||
完整设计入口见 [开发设计文档](docs/development/README.md)。
|
||||
See the [development design documentation](development/README.md) for the full design index.
|
||||
|
||||
## 本地开发与验证
|
||||
## Local Development and Verification
|
||||
|
||||
前置条件:`go.mod` 所要求的 Go 1.25.5、Node.js 20(CI 基线)和 pnpm 10(CI 基线)。
|
||||
Prerequisites: Go 1.25.5 as required by `go.mod`, Node.js 20 (CI baseline), and pnpm 10 (CI baseline).
|
||||
|
||||
```bash
|
||||
# 后端(先确保 pb_public/index.html 存在;完整前端构建见下)
|
||||
# Backend (ensure pb_public/index.html exists first; see the full frontend build below)
|
||||
go run . serve
|
||||
|
||||
# 业务前端;Vite 将 /api 代理到 127.0.0.1:8090
|
||||
# Application frontend; Vite proxies /api to 127.0.0.1:8090
|
||||
pnpm --dir site install --frozen-lockfile
|
||||
pnpm --dir site run dev
|
||||
|
||||
# 文档站
|
||||
# Documentation site
|
||||
pnpm --dir docs install --frozen-lockfile
|
||||
pnpm --dir docs run docs:dev
|
||||
```
|
||||
|
||||
提交前执行:
|
||||
Run before submitting:
|
||||
|
||||
```bash
|
||||
pnpm --dir site install --frozen-lockfile
|
||||
@@ -51,7 +52,7 @@ pnpm --dir site run build
|
||||
pnpm --dir docs install --frozen-lockfile
|
||||
pnpm --dir docs run docs:build
|
||||
|
||||
# Go 工具加载 main package 前必须先满足 go:embed
|
||||
# go:embed must be satisfied before Go tooling loads the main package
|
||||
rm -rf pb_public
|
||||
mkdir -p pb_public
|
||||
cp -R site/dist/. pb_public/
|
||||
@@ -60,31 +61,31 @@ go test ./...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
`build/build.sh` 会构建前端、复制 `site/dist` 到 `pb_public`、执行 `go mod tidy` 并构建平台包;它会改写生成目录和可能调整模块文件,不应作为普通文档或局部改动的首选验证命令。
|
||||
`build/build.sh` builds the frontend, copies `site/dist` to `pb_public`, runs `go mod tidy`, and builds platform packages. It rewrites generated directories and may modify module files, so it is not the preferred verification command for documentation-only or narrowly scoped changes.
|
||||
|
||||
## 修改约定
|
||||
## Change Conventions
|
||||
|
||||
- 后端:依赖方向保持 `interfaces -> application -> domain`,基础设施实现 domain repository;在 `main.go` 统一装配。handler 负责传输层校验/响应,业务编排进入 application service。
|
||||
- 前端:保持 React + TypeScript;页面沿用 `index.tsx`(状态/编排)、`*.view.tsx`(展示)的现有分工,优先复用 `site/src/components/` 和 Radix Themes。API 请求复用 `site/src/lib/api.ts` 或 `pocketbase.ts`。
|
||||
- migration:schema 变更必须新增可审查、可回滚的 `migrations/*.go`,以 migration 为事实来源;不得直接修改运行中 SQLite 或通过管理 UI 攚改生产 schema 来替代 migration。
|
||||
- API:自定义路由放在 `internal/interfaces/http/` 并默认使用 `requireAuth`;PocketBase collection rule 也必须同步审查。改变路径、请求/响应、鉴权或 collection 字段时同步更新相关设计文档。
|
||||
- 样式:遵循 [UI 规范](docs/development/ui-spec.md),优先 Radix token、组件 props 和 Tailwind utility;不要新增另一套无依据的品牌 token。
|
||||
- 国际化:用户可见文案同时更新 `site/src/locales/zh.json`、`en.json`,通过 `react-i18next` 的 `t()` 使用;避免新增裸字符串。
|
||||
- 文档:实现变化触发 [架构](docs/development/architecture.md)、[数据库](docs/development/database-design.md) 或 [UI](docs/development/ui-spec.md) 同步更新;文档事实要链接到仓库路径或注明“待确认”。
|
||||
- Backend: preserve the `interfaces -> application -> domain` dependency direction. Infrastructure implements domain repositories, and `main.go` performs central wiring. Handlers own transport-level validation and responses; business orchestration belongs in application services.
|
||||
- Frontend: keep React + TypeScript and follow the existing split between `index.tsx` (state/orchestration) and `*.view.tsx` (presentation). Prefer components from `site/src/components/` and Radix Themes. Reuse `site/src/lib/api.ts` or `pocketbase.ts` for API requests.
|
||||
- Migrations: schema changes must add a reviewable, reversible `migrations/*.go` migration. Migrations are the source of truth; never replace one by modifying a live SQLite database or production schema through the admin UI.
|
||||
- API: place custom routes in `internal/interfaces/http/` and use `requireAuth` by default. Review PocketBase collection rules as well. When paths, request/response contracts, authentication, or collection fields change, update the relevant design documents.
|
||||
- Styling: follow the [UI specification](development/ui-spec.md). Prefer Radix tokens, component props, and Tailwind utilities; do not introduce another unsupported set of brand tokens.
|
||||
- Internationalization: update both `site/src/locales/zh.json` and `en.json` for user-visible text, and access it through `react-i18next`'s `t()`. Avoid new hard-coded strings.
|
||||
- Documentation: implementation changes must update the [architecture](development/architecture.md), [database design](development/database-design.md), or [UI specification](development/ui-spec.md) when applicable. Documentation claims must link to repository paths or be marked "To be confirmed."
|
||||
|
||||
## 安全边界
|
||||
## Security Boundaries
|
||||
|
||||
- 不提交密钥、token、证书、用户数据、`pb_data/`、`pb_public/`、`site/dist/`、`docs/.vitepress/dist/` 或构建包。
|
||||
- `fh_servers.auth`、TLS 私钥、用户密码/tokenKey 等为敏感数据;禁止记录原值。涉及 SSE 查询参数 token 时避免日志、复制和外泄。
|
||||
- 不用手工数据库操作代替 migration;删除关系当前均未配置级联,删除父记录前必须评估孤儿数据。
|
||||
- 不做与任务无关的全仓格式化,不覆盖工作树中已有改动。
|
||||
- 接口、鉴权规则或数据结构变更必须同时更新测试/调用方与本目录设计文档。
|
||||
- Do not commit secrets, tokens, certificates, user data, `pb_data/`, `pb_public/`, `site/dist/`, `docs/.vitepress/dist/`, or build packages.
|
||||
- `fh_servers.auth`, TLS private keys, user passwords, and token keys are sensitive. Never log their original values. Avoid logging, copying, or exposing tokens used in SSE query parameters.
|
||||
- Do not substitute manual database operations for migrations. Relations currently have no cascading deletes; assess orphaned-data risks before deleting parent records.
|
||||
- Do not perform unrelated repository-wide formatting or overwrite existing worktree changes.
|
||||
- Changes to endpoints, authentication rules, or data structures must update tests, callers, and the design documents in this directory.
|
||||
|
||||
## 提交前检查清单
|
||||
## Pre-Submission Checklist
|
||||
|
||||
- [ ] `git diff` 只包含目标范围,未混入运行数据、构建产物或无关格式化。
|
||||
- [ ] Go vet/test/build、业务前端 lint/build、文档 build 均执行并如实记录结果。
|
||||
- [ ] 新增或修改的 API、collection、关系、rule 已同步数据库/架构文档。
|
||||
- [ ] UI 复用了公共组件,双主题、760px 移动布局、中英文和基本键盘操作已检查。
|
||||
- [ ] Markdown 相对链接有效,Mermaid 名称与代码一致且可渲染。
|
||||
- [ ] 敏感值未进入代码、日志、截图或提交历史。
|
||||
- [ ] `git diff` contains only the intended scope, with no runtime data, build artifacts, or unrelated formatting.
|
||||
- [ ] Go vet/test/build, frontend lint/build, and documentation build were run and their results reported accurately.
|
||||
- [ ] New or changed APIs, collections, relations, and rules are reflected in the database/architecture documentation.
|
||||
- [ ] The UI reuses shared components; both themes, the 760px mobile layout, Chinese/English text, and basic keyboard operation were checked.
|
||||
- [ ] Relative Markdown links work, and Mermaid names match the code and render correctly.
|
||||
- [ ] No sensitive values appear in code, logs, screenshots, or commit history.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Podux Development Design Documentation
|
||||
|
||||
This directory documents the verifiable design of the current `main` baseline and serves as the entry point for future development and agent changes:
|
||||
|
||||
- [System architecture](architecture.md): in-process components, layering, request/startup flows, build and deployment, and CI boundaries.
|
||||
- [Database design](database-design.md): all application collections, relations, rules, indexes, lifecycles, and implementation discrepancies.
|
||||
- [UI specification](ui-spec.md): themes, actual tokens, layouts, and component reuse rules for the React application frontend.
|
||||
|
||||
## Sources of Truth and Scope
|
||||
|
||||
These documents are based on repository code and configuration, not speculation about a target architecture. For the database, `migrations/*.go` is the primary source of truth and is cross-checked against domain models, repositories, application services, HTTP handlers, and callers under `site/src/`. For the UI, the sources are `site/src/index.css`, theme contexts, layouts, shared components, and pages. Build and deployment facts come from `go.mod`, package manifests, `main.go`, CI, `build/build.sh`, and Docker files.
|
||||
|
||||
"Verified current state" describes the present implementation. "Current discrepancy / To be confirmed" and "Technical debt" identify gaps that the code cannot resolve or constraints that are not yet unified; they do not authorize schema or behavior changes.
|
||||
|
||||
## Update Triggers
|
||||
|
||||
- Update the architecture document when component boundaries, startup flow, custom routes, background tasks, persistence, or deployment change.
|
||||
- Update the database document when migrations, collection rules/indexes/relations, field mappings, or retention/deletion policies change.
|
||||
- Update the UI document when theme configuration, design tokens, layout breakpoints, shared components, interaction states, internationalization, or accessibility constraints change.
|
||||
- Update the repository-root `AGENT.md` when any of the changes above also affect agent working conventions.
|
||||
@@ -0,0 +1,97 @@
|
||||
# System Architecture
|
||||
|
||||
## Verified Current State
|
||||
|
||||
Podux is a single Go/PocketBase service that hosts the API, SQLite persistence, background monitoring, frpc client services, and the React static site. The code calls running instances `processes`, but `internal/application/frpc/service.go` actually creates in-process `frp/client.Service` instances and runs them in goroutines; it does not launch separate `frpc` OS processes.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B[Browser / React Web<br/>site/src] -->|PocketBase collection API| PB[PocketBase / Go<br/>main.go]
|
||||
B -->|custom /api routes| H[HTTP handlers<br/>internal/interfaces/http]
|
||||
H --> A[Application services<br/>internal/application]
|
||||
PB --> H
|
||||
A --> D[Domain contracts/models<br/>internal/domain]
|
||||
A --> R[Repository implementations<br/>internal/infrastructure/persistence]
|
||||
R --> DB[(SQLite / PocketBase collections<br/>pb_data)]
|
||||
PB --> DB
|
||||
A --> F[frp client.Service instances<br/>in-process goroutines]
|
||||
F --> FRPS[Remote frps servers]
|
||||
A --> M[MonitorService + MetricsScheduler]
|
||||
M --> DB
|
||||
PB --> E[Embedded React assets<br/>pb_public]
|
||||
```
|
||||
|
||||
### Layers and Entry Points
|
||||
|
||||
- `main.go` creates the PocketBase app, registers migration commands, constructs repositories/services/handlers, binds the `fh_proxies` update hook, and initializes state, starts background tasks, registers routes, and configures the static-file fallback in `OnServe`.
|
||||
- `internal/domain` currently defines lightweight models, status values, and repository interfaces only for servers and proxies.
|
||||
- `internal/application` handles statistics, imports, frpc configuration/lifecycle, networking and metrics, system settings, and version queries.
|
||||
- `internal/infrastructure/persistence` implements server and proxy repositories with dbx/PocketBase.
|
||||
- `internal/interfaces/http` exposes `/api/dashboard/*`, `/api/frpc/*`, `/api/import/*`, `/api/servers*`, `/api/system/*`, and `/api/frp/version`. Except for initialization-status and initialization endpoints, registered custom routes use `requireAuth`.
|
||||
- React also uses the PocketBase SDK directly for `fh_users`, `fh_servers`, and `fh_proxies`; collection API rules control that access boundary.
|
||||
|
||||
### Typical Request Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as React Servers page
|
||||
participant H as FrpcHandler
|
||||
participant S as frpc.Service
|
||||
participant R as server/proxy repositories
|
||||
participant DB as PocketBase/SQLite
|
||||
participant C as frp client.Service
|
||||
UI->>H: POST /api/frpc/launch {id}
|
||||
H->>H: requireAuth + 15-char id validation
|
||||
H->>S: LaunchFrpc(id)
|
||||
S->>DB: load fh_servers
|
||||
S->>R: FindEnabledByServerID(id)
|
||||
R->>DB: query fh_proxies
|
||||
S->>C: NewService + Run(ctx)
|
||||
S->>R: bootStatus = running
|
||||
H-->>UI: 200 / error
|
||||
loop every 5 seconds
|
||||
S->>C: StatusExporter
|
||||
S->>R: proxy bootStatus online/offline
|
||||
end
|
||||
```
|
||||
|
||||
Standard server/proxy CRUD primarily uses the PocketBase SDK. Server lists, dashboard data, imports, settings, and runtime controls use custom APIs. After a successful `fh_proxies` update, a hook calls `ReloadFrpc` if the owning server is running.
|
||||
|
||||
### Startup Flow and Background Tasks
|
||||
|
||||
1. Go `init` loads `migrations`; `main` registers the migrate command and wires dependencies.
|
||||
2. PocketBase `serve` triggers `OnServe`, which sets every server to `stopped` and every proxy to `offline`.
|
||||
3. After a 10-second delay, servers with `autoConnection=true` start automatically.
|
||||
4. `MonitorService` immediately runs TCP latency and missing-geolocation checks, then repeats them at intervals from `fh_settings.general`; server-side defaults are 5 seconds and 24 hours.
|
||||
5. PocketBase cron aggregates raw metrics into hourly metrics at minute 5 of every hour. At 01:05 each day it aggregates daily metrics and deletes raw data older than 7 days and hourly data older than 30 days.
|
||||
6. After handlers are registered, `pb_public` is served through `embed.FS` with an SPA fallback; `/_/` remains the PocketBase Admin UI.
|
||||
|
||||
### Frontend Build and Embedding
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
SRC[site/src React + TypeScript] -->|pnpm run build| DIST[site/dist]
|
||||
DIST -->|build/build.sh copy| PUBLIC[pb_public]
|
||||
PUBLIC -->|go:embed all:pb_public| BIN[Podux Go binary]
|
||||
BIN -->|apis.Static fallback| WEB[Browser]
|
||||
```
|
||||
|
||||
The Vite development server listens on `0.0.0.0` and proxies `/api` to `127.0.0.1:8090`. Production builds do not automatically copy files to `pb_public`; CI performs that step through artifact downloads, while `build/build.sh` copies them explicitly. Go compilation still requires the directory to exist when `pb_public/index.html` is missing, and runtime logs a warning.
|
||||
|
||||
## Configuration, Persistence, and Deployment Boundaries
|
||||
|
||||
- PocketBase uses `pb_data/` as its default data root; the Docker volume mounts `/app/pb_data`. The database, uploads, and `pb_data/frpc/<id>/logs|certs` are runtime data.
|
||||
- Server connection/authentication/transport/logging/metadata settings are stored in collection JSON fields. TLS certificate contents are written to a server-specific certificates directory at startup, with private-key permissions set to `0600`. Never commit this content.
|
||||
- The fixed system-settings record ID is `wcstsqmz8hur331`; the initialization transaction creates both the first `fh_users` record and the settings record.
|
||||
- Geolocation and version queries access external services and depend on network availability. frpc instance status exists only in memory; database statuses are reset together on restart.
|
||||
- The Dockerfile builds React and then compiles a static Go binary; deployment files define ports and volumes. This document makes no claims about production reverse proxies, backups, or high availability that are not verified in repository configuration.
|
||||
|
||||
## CI and Quality Boundaries
|
||||
|
||||
`.github/workflows/ci.yml` runs on pushes to main/dev and pull requests to main. It performs a frozen frontend install, permissive type checking (`continue-on-error`), and a production build; it then downloads the frontend artifact and runs `go vet` and a Linux amd64 build. CI currently does not run `go test`, frontend lint, or the documentation build, but this project's pre-submission baseline requires those checks locally. Pushes to dev also build and publish a multi-architecture container.
|
||||
|
||||
## To Be Confirmed
|
||||
|
||||
- `github_handler.go` and its service exist, but their wiring and registration are commented out in `main.go`; they must not be treated as a published API.
|
||||
- No graceful-shutdown hook for `MonitorService` was found; it currently relies on process termination.
|
||||
- No formal repository-level backup/restore, horizontal-scaling, or multi-instance mutual-exclusion design was found.
|
||||
@@ -0,0 +1,121 @@
|
||||
# Database Design
|
||||
|
||||
## Sources of Truth and Migration Constraints
|
||||
|
||||
PocketBase uses SQLite and registers Go migrations through the blank import of `migrations` in `main.go`; `migratecmd` enables `Automigrate: true`. The only current migration is `migrations/1774402980_collections_snapshot.go`, which imports a collection snapshot with `ImportCollectionsByMarshaledJSON(..., false)`; its rollback function is currently empty. The migration, not any running `pb_data/data.db`, is therefore the primary schema source of truth.
|
||||
|
||||
Every structure/rule/index change must add a reviewable migration with an appropriate rollback. Never modify production SQLite directly or make changes only through the PocketBase Admin UI. "Default" below records only snapshot autogeneration behavior; fields without an explicit statement have no verified schema default.
|
||||
|
||||
The snapshot also contains PocketBase system collections such as `_mfas`, `_otps`, `_externalAuths`, `_authOrigins`, and `_superusers`, which are not individually modeled here. There are nine application collections: `fh_users`, `fh_servers`, `fh_proxies`, `fh_version`, `fh_settings`, `fh_metrics_targets`, `fh_metrics_raw`, `fh_metrics_hourly`, and `fh_metrics_daily`.
|
||||
|
||||
Every base collection has a required system text primary key named `id`, automatically generated as 15 lowercase alphanumeric characters. Collections with `created`/`updated` use autodate fields. In the descriptions below, `—` means an empty rule, so only a superuser may perform that operation through the PocketBase Record API; this does not restrict internal server-side database/service access.
|
||||
|
||||
## Relationship Diagram
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
fh_servers ||--o{ fh_proxies : "serverId (no cascade)"
|
||||
fh_servers ||--o{ fh_metrics_targets : "serverId (optional, no cascade)"
|
||||
fh_proxies ||--o{ fh_metrics_targets : "proxyId (optional, no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_raw : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_hourly : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_daily : "targetId (no cascade)"
|
||||
```
|
||||
|
||||
All relation fields use `maxSelect: 1`. The schema neither guarantees that each metrics target is bound exclusively to a server or a proxy nor defines a unique `(serverId, proxyId)` index.
|
||||
|
||||
## Collection Design
|
||||
|
||||
### `fh_users` (auth)
|
||||
|
||||
Purpose: Podux login users. System fields: `password` (required, hidden, minimum 8 characters), `tokenKey` (required, hidden, 30–60 characters, automatically generated with 50 characters), `email` (required), `emailVisibility`, `verified`, `created`, and `updated`. Application fields: optional `nickname` text with max length 255; optional `avatar` file with at most one JPEG/PNG/SVG/GIF/WebP file; optional `passwordChangedAt` date.
|
||||
|
||||
Unique indexes: `tokenKey` and non-empty `email`. Password authentication is enabled with email as the identity; OAuth2, MFA, and OTP are disabled. The create rule is `@collection.fh_settings.initialized = false`; list/view/update/delete are restricted to `id = @request.auth.id`; the auth rule is empty, allowing authentication.
|
||||
|
||||
Mapping: `system.Service.InitializeSystem` creates the user; Login uses PocketBase `authWithPassword`; Settings/Profile reads and updates the user and avatar; ChangePasswordDialog updates the password.
|
||||
|
||||
### `fh_servers`
|
||||
|
||||
Purpose: remote frps connections and shared frpc configuration.
|
||||
|
||||
| Field | Type | Required/default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `serverName` | text | Required | Display name |
|
||||
| `serverAddr` | text | Required | frps address |
|
||||
| `serverPort` | text | Required | Read/edited as an integer by the service/frontend |
|
||||
| `description` | text | Optional | Description |
|
||||
| `auth` | json | Optional | frp authentication; may contain tokens/secrets |
|
||||
| `transport` | json | Optional | frp transport/TLS; may contain certificate private keys |
|
||||
| `metadatas` | json | Optional | frp metadata |
|
||||
| `log` | json | Optional | frp logging configuration |
|
||||
| `serverVersion` | text | Required, auto `built-in` | Current frp source marker |
|
||||
| `bootStatus` | text | Required, auto `stopped` | Runtime status; code uses running/stopped |
|
||||
| `autoConnection` | bool | Optional | Connect automatically after startup |
|
||||
| `geoLocation` | json | Optional | Populated by MonitorService |
|
||||
| `user` | text | Optional | frp user |
|
||||
| `created`,`updated` | autodate | Automatic | Creation/update timestamps |
|
||||
|
||||
Index: non-unique `bootStatus`. All list/view/create/update/delete rules require authentication. Mapping: there is no complete Go domain model; `ServerRecord` covers only ID/name. The server repository, frpc service, monitor service, and custom `/api/servers` handler read it; React Servers, ServerDetail, and ServerForm use it.
|
||||
|
||||
### `fh_proxies`
|
||||
|
||||
Purpose: frpc proxy configuration under a server.
|
||||
|
||||
| Field | Type | Required/default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | text | Required | Proxy name; the record ID is appended to the runtime name |
|
||||
| `proxyType` | select | Required | One of tcp, udp, http, or https |
|
||||
| `serverId` | relation -> `fh_servers` | Required, N:1 | No cascading delete |
|
||||
| `localIP`,`localPort`,`remotePort`,`subdomain` | text | Optional | Endpoint configuration; Go maps ports with NullableInt |
|
||||
| `customDomains` | json | Optional | Domain array |
|
||||
| `transport`,`plugin` | json | Optional | Extended proxy configuration |
|
||||
| `status` | select | Required | enabled/disabled |
|
||||
| `bootStatus` | select | Required | online/offline |
|
||||
| `created`,`updated` | autodate | Automatic | Creation/update timestamps |
|
||||
|
||||
Indexes: non-unique `serverId`, `proxyType`, and `status`. All CRUD/list/view rules require authentication. Mapping: `domain/proxy.Proxy`, the proxy repository/service, frpc configuration generation, and dashboard; used by React Proxies, ProxyForm, and ServerDetail. A successful update hook reloads a running server.
|
||||
|
||||
### `fh_settings`
|
||||
|
||||
Purpose: system initialization state and general settings. Fields are optional `initialized` bool, optional `general` JSON, and autodate `created`/`updated`; there are no application indexes. All list/view/create/update/delete rules require authentication, but the unauthenticated custom initialization API writes the fixed ID `wcstsqmz8hur331` inside a server-side transaction. Used `general` keys include `defaultLanguage`, `latencyCheckInterval`, and `locationCheckInterval`.
|
||||
|
||||
Mapping: `application/system.Service`, the system handler, React GeneralSettings, and the initialization flow.
|
||||
|
||||
### `fh_version`
|
||||
|
||||
Purpose: version name/path records. Optional text fields `version_name` and `version_path`, plus `created`/`updated`. It has no application indexes, and all Record API rules are `null`. The current version service returns the frp version from compile-time dependencies, while the system version uses buildinfo/an external release API. No application read/write path for this collection was found; its actual purpose remains to be confirmed.
|
||||
|
||||
### `fh_metrics_targets`
|
||||
|
||||
Purpose: bind a metric series to a server or proxy. `serverId` is an optional relation to `fh_servers`; `proxyId` is an optional relation to `fh_proxies`; neither cascades on deletion. There are no `created`/`updated` fields or indexes, and all Record API rules are `null`. `MetricsService` currently creates only targets with a populated `serverId` and empty `proxyId`, and caches server-to-target mappings in memory.
|
||||
|
||||
### `fh_metrics_raw`
|
||||
|
||||
Purpose: raw metric points. Required non-cascading `targetId` relation to `fh_metrics_targets`; optional `metricKey` select (currently only `frps_delay`); required `t` date; optional `val` number. The composite non-unique index is ordered `(targetId, t, metricKey)`. There are no autodate fields, and all Record API rules are `null`. MonitorService writes non-negative latency for reachable servers; the 01:05 daily job deletes data older than 7 days.
|
||||
|
||||
### `fh_metrics_hourly`
|
||||
|
||||
Purpose: hourly aggregates. Optional relation `targetId`, optional select `metricKey`, optional date `t`, and optional numbers `valAvg`/`valMax`/`valMin`. It has a composite non-unique `(metricKey, targetId, t)` index, no autodate fields, and `null` for all Record API rules. At minute 5 of every hour, the previous complete hour is aggregated and then updated or inserted after lookup by target/key/time. Data older than 30 days is deleted daily.
|
||||
|
||||
### `fh_metrics_daily`
|
||||
|
||||
Purpose: daily aggregates. Fields match hourly, and all three value fields are optional numbers. It has a composite non-unique `(targetId, metricKey, t)` index, no autodate fields, and `null` for all Record API rules. At 01:05 daily, the previous day's hourly values are aggregated and upserted; the code currently writes only `valAvg`. No retention policy for daily data was found.
|
||||
|
||||
## Lifecycle, Deletion, and Sensitivity
|
||||
|
||||
- Server/proxy runtime statuses are reset at startup. Status is a transient runtime projection; configuration itself is persistent.
|
||||
- Aggregation follows raw -> hourly -> daily. Raw data is retained for 7 days and hourly data for 30 days; no verified limit exists for daily data.
|
||||
- Every relation uses `cascadeDelete: false`. The schema does not automatically delete proxies/metrics targets with a server, and deleting proxies/targets may also leave related records. Although the UI shows a confirmation dialog, no server-side transactional cleanup was found; treat this as an orphaning risk.
|
||||
- PocketBase protects `fh_users.password/tokenKey`; `fh_servers.auth/transport` may contain tokens, OIDC secrets, and TLS private keys. Logs mask common JSON key names, but original values must still never be exported, committed, or echoed.
|
||||
- Migration workflow: identify callers -> add forward/down migrations -> update models/repositories/services/UI -> update this document -> verify upgrade and rollback against a temporary database -> run the full checks. Never rewrite the snapshot to falsify existing deployment history.
|
||||
|
||||
## Current Discrepancies / To Be Confirmed
|
||||
|
||||
- `domain/proxy.Proxy` declares and serializes `description`, but the `fh_proxies` migration has no such field; form payloads also include description. Do not assume here that the field exists.
|
||||
- The `/api/servers` handler reads and returns `sendRate` and `recvRate`, but the migration defines neither field.
|
||||
- ProfileSettings submits both `name` and `nickname`, while the migration defines only `nickname`.
|
||||
- The migration defines `serverPort/localPort/remotePort` as text; some Go/frontend paths treat them as numbers. Preserve conversion compatibility and confirm the long-term type strategy.
|
||||
- `fh_metrics_targets` has no uniqueness constraint. An in-process application lock only prevents concurrent duplicates within one process; multi-instance and pre-existing duplicate risks remain to be confirmed.
|
||||
- Metric aggregation performs application-level "lookup then write" operations. Composite indexes are non-unique, so the database does not guarantee idempotent uniqueness.
|
||||
- No caller for `fh_version` was found; its purpose remains to be confirmed.
|
||||
- The snapshot migration has an empty down function and cannot automatically restore the pre-import schema; rollback strategy remains technical debt.
|
||||
@@ -0,0 +1,67 @@
|
||||
# UI Specification
|
||||
|
||||
## Technology Stack, Entry Point, and Theme
|
||||
|
||||
The application UI under `site/` uses React 19, TypeScript, and Vite 7 together with Radix Themes, Tailwind CSS 4, Iconify, Framer Motion, Recharts, Sonner, and react-i18next; it does not use Vue. Vue is used only by the VitePress site under `docs/`.
|
||||
|
||||
`site/src/main.tsx` loads Radix CSS, `index.css`, and i18n in that order, then wraps the application in `ThemeProvider`, `LanguageProvider`, and Radix `<Theme>`. Theme settings are `accentColor="indigo"`, `grayColor="slate"`, and `radius="large"`. Appearance is light/dark, initially taken from the system `prefers-color-scheme` and then stored in `localStorage.theme`. `index.css` is the entry point for Tailwind and global status-dot styles. `App.css` is an unused Vite template remnant not imported by `App.tsx`; do not treat it as the current UI baseline.
|
||||
|
||||
## Design Tokens in Use
|
||||
|
||||
The project has no custom token file. It primarily consumes Radix CSS variables and component size/gap scales directly.
|
||||
|
||||
| Category | Verified values/usage |
|
||||
| --- | --- |
|
||||
| Brand/accent | Radix indigo mappings `--accent-2/3/4/6/9/10/11` and `--accent-a3`; do not hard-code a new "Podux blue" |
|
||||
| Neutrals/surfaces | Slate mappings `--gray-1..12`, alpha gray, `--color-background`, and `--color-panel-solid`; main page background is `--gray-2` |
|
||||
| Status colors | Radix green/red/amber/orange/blue/purple scales; online dot `--green-9`, offline dot `--red-9`, unknown dot `--gray-9` |
|
||||
| Typography | No project font family; inherits Radix/browser. Body text commonly uses `<Text size="1|2|3|4">`, page titles use `<Heading size="6">`, and section titles commonly use size 3/4 |
|
||||
| Spacing | Prefer Radix `gap/mb/px/py` scales and Tailwind (for example px-4, sm:px-6, lg:px-8); local values commonly include 8/12/16/20/24/32px |
|
||||
| Radius | Radix global `large`; variables `--radius-2/3`; local 8/12/16/24px and full circles |
|
||||
| Borders | Usually `1px solid var(--gray-5|6)`; highlighted areas use `--accent-6` |
|
||||
| Shadows | A few local `0 4px 12px rgba(0,0,0,.05/.2)` and `0 4px 16px rgba(0,0,0,.1)` values; prefer Card/Dialog defaults |
|
||||
| Stacking | Sticky top bar uses `z-50`; full-screen Loading uses `z-index: 9999`; otherwise prefer component overlay defaults |
|
||||
|
||||
Hard-coded values such as `#22c55e`, `#E5484D`, `#30A46C`, and `#6b7280` remain scattered through charts/status implementations. Prefer existing Radix tokens. Cleanup requires a separate task that verifies SVG chart compatibility; do not replace these values in bulk during ordinary feature work.
|
||||
|
||||
## Layout and Component Patterns
|
||||
|
||||
- Application shell: reuse `layouts/MainLayout.tsx`. Desktop uses a sticky top bar with logo, Dashboard/Servers/Proxies navigation, and controls on the right. Below `760px`, mobile uses bottom navigation. Content uses `max-w-7xl`, supports a minimum viewport width of 320px, and reserves space for the mobile bottom bar.
|
||||
- Page titles: reuse `components/PageHeader.tsx`, keeping title, description, and right-side actions at a consistent hierarchy. Reuse `SectionHeading` for section titles.
|
||||
- Forms: prefer Radix `TextField/Select/Switch/Button`; reuse `FormItem` for labels and required markers. Keep page state and submission logic in hooks/index files and layout in views.
|
||||
- Cards and statistics: use Radix `Card` for general content. Reuse `StatCard` and `AnimateNumber` for dashboard value cards rather than duplicating animation/color decisions.
|
||||
- Lists: Servers/Proxies establish the desktop-table + mobile-card, search, pagination, Badge, and DropdownMenu pattern. Prefer it for new resources of the same kind.
|
||||
- Dialogs: use Radix `AlertDialog` for delete confirmation and Radix `Dialog` for editing, passwords, and similar tasks. Mark dangerous actions red, separate cancel and confirm, and prevent duplicate submissions during async work.
|
||||
- Charts: reuse `LatencyChart/ProbeHistory` for latency trends and Dashboard `TopologyChart` for topology. Containers must be responsive, with sufficient contrast in both themes.
|
||||
- Notifications: prefer `sonner` toast for operation success/failure (global top-center with richColors). Do not add alerts; the existing `alert` in ProfileSettings is technical debt.
|
||||
- Empty/loading/error: reuse `EmptyState` for empty lists and `Loading` for route/page loading. Errors should explain the problem and offer a recovery action. There is no unified ErrorState/ErrorBoundary yet; before adding one, assess whether it should become a shared component.
|
||||
|
||||
## Reference Pages
|
||||
|
||||
- Dashboard: `site/src/pages/Dashboard/DashboardPage.view.tsx` combines `PageHeader`, `StatCard`, Radix Grid/Card, and `TopologyChart`; data orchestration is in `useDashboard.ts`.
|
||||
- Servers/Proxies: `site/src/pages/Servers/ServersPage.view.tsx` and `site/src/pages/Proxies/ProxiesPage.view.tsx` are the primary references for responsive lists, status badges, action menus, and AlertDialog. Their forms are under the corresponding `*FormPage` directories.
|
||||
- Settings: `site/src/pages/Settings/SettingsPage.view.tsx` and `SettingsPage.css` use a 240px sidebar, active accent state, and content area. `GeneralSettings.tsx` demonstrates `FormItem`, loading, and save toast; `ProfileSettings.tsx` demonstrates profile cards and security sections.
|
||||
|
||||
## Responsiveness, Themes, Internationalization, and Accessibility
|
||||
|
||||
- Responsiveness: the actual application-shell breakpoint is `max-width: 760px` (the 640px comment is stale). Test at least 320px mobile and desktop widths. On mobile, table content must use cards or controlled scrolling and must not require hover for actions.
|
||||
- Themes: new colors should use `var(--accent-*)`, `var(--gray-*)`, and semantic colors. Avoid fixed white backgrounds/black text. Check charts, overlays, borders, and focus states in light and dark themes.
|
||||
- Internationalization: route all user-facing text through `t()` and update both `locales/zh.json` and `en.json`. LanguageContext/localStorage owns language selection; do not use hard-coded Chinese or English as fallback UI.
|
||||
- Accessibility: use semantic Radix components. Icon-only buttons need accessible names/tooltips; images need alt text; form labels must associate with controls; keyboard focus must remain visible. `index.css` currently forces the Recharts surface outline off and must be limited to non-interactive charts; reassess it if keyboard chart interaction is added.
|
||||
- Motion: the standard page transition is `PageTransition` at 0.3s cubic-bezier; titles use 0.5s easeOut; status dots loop every 1.6–2.5s. Lightweight hover/tap effects are acceptable but must not block interaction. Only the unused Vite-template `App.css` currently observes `prefers-reduced-motion`; actual Framer/status-dot animations do not support it consistently and remain technical debt.
|
||||
|
||||
## Reuse and Addition Rules
|
||||
|
||||
1. Check Radix Themes first, then `site/src/components/`, then neighboring page view/hook patterns.
|
||||
2. Extract a shared component only when a semantically stable pattern spans at least two pages; keep page-specific compositions in the page directory.
|
||||
3. New shared components must use tokens, support `className` and necessary props, cover loading/disabled/error states, and be verified in both themes and mobile layouts.
|
||||
4. Local styles are acceptable for third-party charts, complex layouts, or states difficult to express with Radix props/Tailwind. Scope names to the page/component and avoid global selectors and `!important`. Existing `!important` usage in Settings CSS is a compatibility condition, not a pattern for new styles.
|
||||
5. Do not restore or extend unused `App.css` template styles. Put necessary global rules in `index.css` and document their impact.
|
||||
|
||||
## Technical Debt
|
||||
|
||||
- There is no centralized project-owned set of spacing, shadow, z-index, or motion tokens; the UI relies on Radix scales mixed with local pixel values.
|
||||
- Settings has only a desktop 240px sidebar, with no dedicated mobile adaptation rules found; verify on a real device.
|
||||
- Error state, ErrorBoundary, and form-error presentation do not yet follow a unified shared pattern.
|
||||
- ProfileSettings uses native `alert`, Loading defaults to English `Loading...`, and internationalization remains inconsistent.
|
||||
- Actual interaction animations do not yet systematically honor `prefers-reduced-motion`.
|
||||
@@ -1,20 +0,0 @@
|
||||
# Podux 开发设计文档
|
||||
|
||||
本目录记录当前 `main` 基线的可验证设计,为后续开发和 Agent 改动提供入口:
|
||||
|
||||
- [系统架构](architecture.md):进程内组件、分层、请求/启动链路、构建部署和 CI 边界。
|
||||
- [数据库设计](database-design.md):全部业务 collection、关系、规则、索引、生命周期和实现差异。
|
||||
- [UI 规范](ui-spec.md):React 业务前端的主题、真实 token、布局和组件复用规则。
|
||||
|
||||
## 事实来源与适用范围
|
||||
|
||||
文档基于仓库代码和配置,而不是目标架构推测。数据库以 `migrations/*.go` 为首要事实来源,并用 domain model、repository、application service、HTTP handler 和 `site/src/` 调用交叉校验;UI 以 `site/src/index.css`、主题上下文、布局、公共组件和页面为准;构建与部署以 `go.mod`、package manifest、`main.go`、CI、`build/build.sh`、Docker 文件为准。
|
||||
|
||||
“已验证现状”描述当前实现;“现状差异/待确认”及“待治理”表示代码无法闭环或尚无统一约束,不能据此擅自改变 schema 或行为。
|
||||
|
||||
## 同步更新触发条件
|
||||
|
||||
- 组件边界、启动流程、自定义路由、后台任务、持久化或部署方式改变时更新架构文档。
|
||||
- migration、collection rule/index/relation、字段映射或保留/删除策略改变时更新数据库文档。
|
||||
- 主题配置、design token、布局断点、公共组件、交互状态、国际化或可访问性约束改变时更新 UI 文档。
|
||||
- 上述变更同时影响 Agent 工作约定时更新仓库根目录 `AGENT.md`。
|
||||
@@ -1,98 +0,0 @@
|
||||
# 系统架构
|
||||
|
||||
## 已验证现状
|
||||
|
||||
Podux 是单个 Go/PocketBase 服务承载 API、SQLite 持久化、后台监控、frpc client service 和 React 静态站点的应用。代码将运行实例命名为 `processes`,但 `internal/application/frpc/service.go` 实际创建的是进程内 `frp/client.Service` 并在 goroutine 中运行,不会启动独立的 `frpc` OS 子进程。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
B[Browser / React Web<br/>site/src] -->|PocketBase collection API| PB[PocketBase / Go<br/>main.go]
|
||||
B -->|custom /api routes| H[HTTP handlers<br/>internal/interfaces/http]
|
||||
H --> A[Application services<br/>internal/application]
|
||||
PB --> H
|
||||
A --> D[Domain contracts/models<br/>internal/domain]
|
||||
A --> R[Repository implementations<br/>internal/infrastructure/persistence]
|
||||
R --> DB[(SQLite / PocketBase collections<br/>pb_data)]
|
||||
PB --> DB
|
||||
A --> F[frp client.Service instances<br/>in-process goroutines]
|
||||
F --> FRPS[Remote frps servers]
|
||||
A --> M[MonitorService + MetricsScheduler]
|
||||
M --> DB
|
||||
PB --> E[Embedded React assets<br/>pb_public]
|
||||
```
|
||||
|
||||
### 分层与入口
|
||||
|
||||
- `main.go` 创建 PocketBase app、注册 migration 命令、构造 repository/service/handler,绑定 `fh_proxies` 更新 hook,并在 `OnServe` 中初始化状态、启动后台任务、注册路由和静态文件兜底。
|
||||
- `internal/domain` 目前只为 server/proxy 定义轻量模型、状态值和 repository 接口。
|
||||
- `internal/application` 承担统计、导入、frpc 配置/生命周期、网络与指标、系统设置和版本查询。
|
||||
- `internal/infrastructure/persistence` 用 dbx/PocketBase 实现 server/proxy repository。
|
||||
- `internal/interfaces/http` 暴露 `/api/dashboard/*`、`/api/frpc/*`、`/api/import/*`、`/api/servers*`、`/api/system/*`、`/api/frp/version`;除初始化状态/初始化接口外,注册中的自定义路由使用 `requireAuth`。
|
||||
- React 还直接使用 PocketBase SDK 操作 `fh_users`、`fh_servers`、`fh_proxies`,访问边界由 collection API rule 控制。
|
||||
|
||||
### 典型请求链路
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as React Servers page
|
||||
participant H as FrpcHandler
|
||||
participant S as frpc.Service
|
||||
participant R as server/proxy repositories
|
||||
participant DB as PocketBase/SQLite
|
||||
participant C as frp client.Service
|
||||
UI->>H: POST /api/frpc/launch {id}
|
||||
H->>H: requireAuth + 15-char id validation
|
||||
H->>S: LaunchFrpc(id)
|
||||
S->>DB: load fh_servers
|
||||
S->>R: FindEnabledByServerID(id)
|
||||
R->>DB: query fh_proxies
|
||||
S->>C: NewService + Run(ctx)
|
||||
S->>R: bootStatus = running
|
||||
H-->>UI: 200 / error
|
||||
loop every 5 seconds
|
||||
S->>C: StatusExporter
|
||||
S->>R: proxy bootStatus online/offline
|
||||
end
|
||||
```
|
||||
|
||||
普通服务器/代理 CRUD 主要走 PocketBase SDK;服务器列表、dashboard、导入、设置和运行控制走自定义 API。`fh_proxies` 成功更新 hook 会在所属服务器运行时调用 `ReloadFrpc`。
|
||||
|
||||
### 启动流程与后台任务
|
||||
|
||||
1. Go `init` 加载 `migrations`,`main` 注册 migrate command 并完成依赖装配。
|
||||
2. PocketBase `serve` 触发 `OnServe`:所有 server 置 `stopped`、proxy 置 `offline`。
|
||||
3. 10 秒延迟后自动启动 `autoConnection=true` 的服务器。
|
||||
4. `MonitorService` 立即并按 `fh_settings.general` 间隔执行 TCP 延迟与缺失地理位置查询;服务端默认间隔是 5 秒/24 小时。
|
||||
5. PocketBase cron 在每小时第 5 分钟聚合 raw 到 hourly;每日 01:05 聚合 daily,并清理 7 天前 raw、30 天前 hourly。
|
||||
6. handler 注册后,`pb_public` 通过 `embed.FS` 提供 SPA fallback;`/_/` 仍是 PocketBase Admin UI。
|
||||
|
||||
### 前端构建与嵌入
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
SRC[site/src React + TypeScript] -->|pnpm run build| DIST[site/dist]
|
||||
DIST -->|build/build.sh copy| PUBLIC[pb_public]
|
||||
PUBLIC -->|go:embed all:pb_public| BIN[Podux Go binary]
|
||||
BIN -->|apis.Static fallback| WEB[Browser]
|
||||
```
|
||||
|
||||
Vite dev server监听 `0.0.0.0`,将 `/api` 代理到 `127.0.0.1:8090`。生产构建不会自动复制到 `pb_public`;CI 通过 artifact 下载完成该步骤,`build/build.sh` 则显式复制。`pb_public/index.html` 缺失时 Go 编译仍要求目录存在,运行时会记录警告。
|
||||
|
||||
## 配置、持久化与部署边界
|
||||
|
||||
- PocketBase 默认数据根是 `pb_data/`;Docker volume 挂载 `/app/pb_data`。数据库、上传和 `pb_data/frpc/<id>/logs|certs` 都是运行数据。
|
||||
- 服务器连接/auth/transport/log/metadata 存于 collection JSON 字段;TLS 证书内容启动时写入 server 专属 certs 目录,私钥权限为 `0600`。不得提交这些内容。
|
||||
- 系统设置固定记录 ID 为 `wcstsqmz8hur331`;初始化事务同时创建首个 `fh_users` 记录和 settings 记录。
|
||||
- 地理位置查询与版本查询会访问外部服务;具体可用性受网络影响。frpc 实例状态仅在内存中,重启时数据库状态先统一重置。
|
||||
- Dockerfile 构建 React 后编译静态 Go 二进制;部署文件负责端口/volume。本文不声明未在仓库配置中验证的生产反向代理、备份或高可用方案。
|
||||
|
||||
## CI 与质量边界
|
||||
|
||||
`.github/workflows/ci.yml` 在 main/dev push 和 main PR 上运行:前端 frozen install、宽松的 type-check(`continue-on-error`)、正式 build;随后下载前端 artifact,执行 `go vet` 和 Linux amd64 build。CI 当前没有 `go test`、前端 lint 或 docs build 步骤,但本项目提交前基线要求本地补充执行。dev 分支 push 另构建并推送多架构容器。
|
||||
|
||||
## 待确认
|
||||
|
||||
- `github_handler.go` 和对应 service 存在,但 `main.go` 注释掉了装配与注册;不应视为已发布 API。
|
||||
- 尚未发现优雅停止 `MonitorService` 的 hook;当前进程退出依赖进程生命周期。
|
||||
- 尚未发现仓库内正式备份/恢复、水平扩展或多实例互斥设计。
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
# 数据库设计
|
||||
|
||||
## 事实来源与迁移约束
|
||||
|
||||
PocketBase 使用 SQLite,并通过 `main.go` 空导入 `migrations` 注册 Go migration;`migratecmd` 开启 `Automigrate: true`。当前唯一 migration 是 `migrations/1774402980_collections_snapshot.go`,以 `ImportCollectionsByMarshaledJSON(..., false)` 导入 collection snapshot;回滚函数当前为空。因此 schema 的首要事实来源是 migration,而不是某个运行中 `pb_data/data.db`。
|
||||
|
||||
所有结构/rule/index 变更必须新增可审查 migration 并提供适当回滚,不得直接改生产 SQLite 或只在 PocketBase Admin UI 修改。下文“默认”只记录 snapshot 的 autogenerate 行为;未声明即无已验证 schema 默认值。
|
||||
|
||||
snapshot 还包含 `_mfas`、`_otps`、`_externalAuths`、`_authOrigins`、`_superusers` 等 PocketBase 系统 collection,本文不将其逐一建模。业务 collection 共 9 个:`fh_users`、`fh_servers`、`fh_proxies`、`fh_version`、`fh_settings`、`fh_metrics_targets`、`fh_metrics_raw`、`fh_metrics_hourly`、`fh_metrics_daily`。
|
||||
|
||||
所有 base collection 的 `id` 均为系统 text 主键、必填、自动生成 15 位小写字母数字;含 `created/updated` 的 collection 使用 autodate。表中 `—` 表示空规则,即只有 superuser 可经 PocketBase Record API 执行该操作;这不限制服务端内部 DB/service 访问。
|
||||
|
||||
## 关系图
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
fh_servers ||--o{ fh_proxies : "serverId (no cascade)"
|
||||
fh_servers ||--o{ fh_metrics_targets : "serverId (optional, no cascade)"
|
||||
fh_proxies ||--o{ fh_metrics_targets : "proxyId (optional, no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_raw : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_hourly : "targetId (no cascade)"
|
||||
fh_metrics_targets ||--o{ fh_metrics_daily : "targetId (no cascade)"
|
||||
```
|
||||
|
||||
关系字段全部 `maxSelect: 1`。schema 不保证每个 metrics target 只绑定 server 或 proxy,也没有 `(serverId, proxyId)` 唯一索引。
|
||||
|
||||
## Collection 设计
|
||||
|
||||
### `fh_users`(auth)
|
||||
|
||||
用途:Podux 登录用户。系统字段:`password`(必填、隐藏、min 8)、`tokenKey`(必填隐藏,30–60 字符,自动 50 字符)、`email`(必填)、`emailVisibility`、`verified`、`created`、`updated`。业务字段:`nickname` text 可选 max 255;`avatar` file 可选、最多 1 个、允许 JPEG/PNG/SVG/GIF/WebP;`passwordChangedAt` date 可选。
|
||||
|
||||
唯一索引:`tokenKey`;非空 `email`。password auth 启用且 identity 为 email;OAuth2、MFA、OTP 均关闭。create rule 为 `@collection.fh_settings.initialized = false`;list/view/update 仅 `id = @request.auth.id`;delete 同样仅本人;auth rule 为空(允许认证)。
|
||||
|
||||
映射:`system.Service.InitializeSystem` 创建用户;Login 用 PocketBase `authWithPassword`;Settings/Profile 读取/更新用户和头像,ChangePasswordDialog 更新密码。
|
||||
|
||||
### `fh_servers`
|
||||
|
||||
用途:远程 frps 连接及 frpc 公共配置。
|
||||
|
||||
| 字段 | 类型 | 必填/默认 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `serverName` | text | 必填 | 显示名 |
|
||||
| `serverAddr` | text | 必填 | frps 地址 |
|
||||
| `serverPort` | text | 必填 | service/frontend 以 int 读取/编辑 |
|
||||
| `description` | text | 可选 | 描述 |
|
||||
| `auth` | json | 可选 | frp auth,可能含 token/secret |
|
||||
| `transport` | json | 可选 | frp transport/TLS,可能含证书私钥 |
|
||||
| `metadatas` | json | 可选 | frp metadata |
|
||||
| `log` | json | 可选 | frp log config |
|
||||
| `serverVersion` | text | 必填,自动 `built-in` | 当前 frp 来源标记 |
|
||||
| `bootStatus` | text | 必填,自动 `stopped` | 运行状态;代码使用 running/stopped |
|
||||
| `autoConnection` | bool | 可选 | 启动后自动连接 |
|
||||
| `geoLocation` | json | 可选 | MonitorService 回填 |
|
||||
| `user` | text | 可选 | frp user |
|
||||
| `created`,`updated` | autodate | 自动 | 创建/更新时间 |
|
||||
|
||||
索引:`bootStatus` 非唯一。list/view/create/update/delete rule 均要求已认证。映射:无完整 Go domain model,`ServerRecord` 只覆盖 id/name;server repository、frpc service、monitor service、custom `/api/servers` handler 读取;React Servers/ServerDetail/ServerForm 使用。
|
||||
|
||||
### `fh_proxies`
|
||||
|
||||
用途:某个 server 下的 frpc proxy 配置。
|
||||
|
||||
| 字段 | 类型 | 必填/默认 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `name` | text | 必填 | proxy 名;运行名追加 record id |
|
||||
| `proxyType` | select | 必填 | tcp、udp、http、https 单选 |
|
||||
| `serverId` | relation -> `fh_servers` | 必填,N:1 | 不级联删除 |
|
||||
| `localIP`,`localPort`,`remotePort`,`subdomain` | text | 可选 | 端点配置;Go 对 port 用 NullableInt 映射 |
|
||||
| `customDomains` | json | 可选 | 域名数组 |
|
||||
| `transport`,`plugin` | json | 可选 | proxy 扩展配置 |
|
||||
| `status` | select | 必填 | enabled/disabled |
|
||||
| `bootStatus` | select | 必填 | online/offline |
|
||||
| `created`,`updated` | autodate | 自动 | 创建/更新时间 |
|
||||
|
||||
索引:`serverId`、`proxyType`、`status`,均非唯一。全部 CRUD/list/view rule 要求已认证。映射:`domain/proxy.Proxy`、proxy repository/service、frpc config 生成与 dashboard;React Proxies、ProxyForm、ServerDetail 使用。更新成功 hook 对运行中的 server reload。
|
||||
|
||||
### `fh_settings`
|
||||
|
||||
用途:系统初始化状态和通用设置。字段为 `initialized` bool 可选、`general` json 可选、`created/updated` autodate,无业务索引。list/view/create/update/delete rule 均要求已认证,但初始化由无认证 custom API 在服务端事务内写入固定 ID `wcstsqmz8hur331`。`general` 已使用键包括 `defaultLanguage`、`latencyCheckInterval`、`locationCheckInterval`。
|
||||
|
||||
映射:`application/system.Service`、system handler、React GeneralSettings/初始化流程。
|
||||
|
||||
### `fh_version`
|
||||
|
||||
用途:版本名称/路径记录;字段 `version_name`、`version_path` 均为可选 text,加 `created/updated`。无业务索引,所有 Record API rule 都为 `null`。当前 version service 返回编译依赖中的 frp 版本,系统版本走 buildinfo/外部 release API;未找到对该 collection 的业务读写调用,实际用途待确认。
|
||||
|
||||
### `fh_metrics_targets`
|
||||
|
||||
用途:把指标序列绑定到 server 或 proxy。`serverId` 可选 relation -> `fh_servers`;`proxyId` 可选 relation -> `fh_proxies`;均不级联。无 `created/updated`、无索引、所有 Record API rule 为 `null`。`MetricsService` 当前只创建 `serverId` 有值且 `proxyId` 为空的 target,并以内存 map 缓存 server->target。
|
||||
|
||||
### `fh_metrics_raw`
|
||||
|
||||
用途:原始指标点。`targetId` 必填 relation -> `fh_metrics_targets`、不级联;`metricKey` 可选 select(当前仅 `frps_delay`);`t` 必填 date;`val` 可选 number。复合非唯一索引顺序为 `(targetId, t, metricKey)`;无 autodate;所有 Record API rule 为 `null`。MonitorService 写入可达服务器的非负延迟;每日 01:05 删除 7 天前数据。
|
||||
|
||||
### `fh_metrics_hourly`
|
||||
|
||||
用途:每小时聚合。`targetId` 可选 relation、`metricKey` 可选 select、`t` 可选 date、`valAvg/valMax/valMin` 可选 number。复合非唯一索引 `(metricKey, targetId, t)`;无 autodate;所有 Record API rule 为 `null`。每小时第 5 分钟聚合上一完整小时并按 target/key/time 查找后更新或插入;每日删除 30 天前数据。
|
||||
|
||||
### `fh_metrics_daily`
|
||||
|
||||
用途:每日聚合。字段与 hourly 相同且三个 value 字段均为可选 number;复合非唯一索引 `(targetId, metricKey, t)`;无 autodate;所有 Record API rule 为 `null`。每日 01:05 从前一日 hourly 聚合并 upsert;代码当前只写 `valAvg`。未发现 daily 数据清理策略。
|
||||
|
||||
## 生命周期、删除与敏感性
|
||||
|
||||
- 启动时 server/proxy 运行状态被重置;状态属于瞬时运行投影,配置本身持久化。
|
||||
- raw -> hourly -> daily 分层聚合;raw 保留 7 天、hourly 30 天,daily 无已验证上限。
|
||||
- 所有 relation 都是 `cascadeDelete: false`。删除 server 不会由 schema 自动删除 proxy/metrics target,删除 proxy/target也可能留下关联记录;UI 删除前虽有确认框,但未发现服务端事务清理,需视为孤儿风险。
|
||||
- `fh_users.password/tokenKey` 由 PocketBase 保护;`fh_servers.auth/transport` 可含 token、OIDC secret、TLS 私钥。日志虽对常见 JSON 密钥名做遮罩,但设计上仍不得导出、提交或回显原值。
|
||||
- migration 变更流程:确认调用方 -> 新增 forward/down migration -> 更新 model/repository/service/UI -> 更新本文 -> 在临时数据库验证升级和回滚 -> 执行完整检查;禁止改 snapshot 伪造已有部署历史。
|
||||
|
||||
## 现状差异 / 待确认
|
||||
|
||||
- `domain/proxy.Proxy` 声明并序列化 `description`,但 `fh_proxies` migration 没有该字段;表单 payload 也包含 description。不得在本文假定字段已存在。
|
||||
- `/api/servers` handler 读取并返回 `sendRate`、`recvRate`,migration 未定义两字段。
|
||||
- ProfileSettings 同时提交 `name` 和 `nickname`,migration 只定义 `nickname`。
|
||||
- migration 定义 `serverPort/localPort/remotePort` 为 text;Go/前端部分路径按数字使用,需保持转换兼容并确认长期类型策略。
|
||||
- `fh_metrics_targets` 无唯一约束,仅应用进程内锁避免同一进程并发重复;多实例或已有重复数据风险待确认。
|
||||
- metrics 聚合是应用层“先查再写”,复合索引非唯一,数据库不保证幂等唯一性。
|
||||
- `fh_version` 没有已发现调用路径;用途待确认。
|
||||
- snapshot migration 的 down 函数为空,无法自动恢复导入前 schema;迁移回滚策略待治理。
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
# UI 规范
|
||||
|
||||
## 技术栈、入口与主题
|
||||
|
||||
业务 UI 是 `site/` 下的 React 19 + TypeScript + Vite 7 应用,使用 Radix Themes、Tailwind CSS 4、Iconify、Framer Motion、Recharts、Sonner、react-i18next;不是 Vue。Vue 只服务于 `docs/` 的 VitePress。
|
||||
|
||||
`site/src/main.tsx` 依次载入 Radix CSS、`index.css` 和 i18n,并将应用包在 `ThemeProvider`、`LanguageProvider` 与 Radix `<Theme>` 中。主题配置为 `accentColor="indigo"`、`grayColor="slate"`、`radius="large"`;appearance 为 light/dark,初次取系统 `prefers-color-scheme`,随后存入 `localStorage.theme`。`index.css` 是 Tailwind 和全局状态点样式入口;`App.css` 仍是 Vite 模板残留且未被 `App.tsx` 导入,不应当作当前页面基线。
|
||||
|
||||
## 已使用的 design tokens
|
||||
|
||||
当前没有项目自定义 token 文件,主要直接消费 Radix CSS variables 和组件 size/gap 标度。
|
||||
|
||||
| 类别 | 已验证取值/用法 |
|
||||
| --- | --- |
|
||||
| 品牌/强调色 | Radix indigo 映射的 `--accent-2/3/4/6/9/10/11`、`--accent-a3`;不要硬编码一个新的“Podux 蓝” |
|
||||
| 中性色/表面 | slate 映射的 `--gray-1..12`、alpha gray、`--color-background`、`--color-panel-solid`;主页面背景 `--gray-2` |
|
||||
| 状态色 | Radix green/red/amber/orange/blue/purple scales;在线点 `--green-9`,离线点 `--red-9`,未知点 `--gray-9` |
|
||||
| 字体 | 未设置项目字体族,继承 Radix/browser;正文常用 `<Text size="1|2|3|4">`,页标题 `<Heading size="6">`,区块标题常用 size 3/4 |
|
||||
| 间距 | 优先 Radix `gap/mb/px/py` 标度和 Tailwind(如 px-4、sm:px-6、lg:px-8);局部常见 8/12/16/20/24/32px |
|
||||
| 圆角 | Radix 全局 `large`;变量 `--radius-2/3`;局部 8/12/16/24px 与 full circle |
|
||||
| 边框 | 通常 `1px solid var(--gray-5|6)`,强调区域用 `--accent-6` |
|
||||
| 阴影 | 少量局部 `0 4px 12px rgba(0,0,0,.05/.2)`、`0 4px 16px rgba(0,0,0,.1)`;Card/Dialog 优先组件默认 |
|
||||
| 层级 | 顶栏 `z-50` sticky;全屏 Loading `z-index: 9999`;其余优先组件自身 overlay 层级 |
|
||||
|
||||
硬编码 `#22c55e`、`#E5484D`、`#30A46C`、`#6b7280` 等仍散落在图表/状态实现中;应优先使用现有 Radix token,清理需单独任务验证图表 SVG 兼容,不能在普通功能改动中批量替换。
|
||||
|
||||
## 布局与组件模式
|
||||
|
||||
- 应用壳:复用 `layouts/MainLayout.tsx`。桌面为 sticky 顶栏、logo、Dashboard/Servers/Proxies 导航与右侧控制;移动端在 `760px` 以下切换底部导航。内容宽度使用 `max-w-7xl`,最小视口宽度 320px,并给移动底栏留空间。
|
||||
- 页面标题:复用 `components/PageHeader.tsx`,标题/说明/右侧操作保持同一层级;区块标题复用 `SectionHeading`。
|
||||
- 表单:优先 Radix `TextField/Select/Switch/Button`,标签和 required 标记复用 `FormItem`;页面状态与提交逻辑保留在 hook/index,view 负责布局。
|
||||
- 卡片与统计:一般内容用 Radix `Card`;dashboard 数值卡复用 `StatCard` 和 `AnimateNumber`,不要复制动画/颜色判定。
|
||||
- 列表:Servers/Proxies 已形成桌面 table + 移动 card、搜索、分页、Badge/DropdownMenu 模式。新增同类资源应优先沿用。
|
||||
- 对话框:确认删除使用 Radix `AlertDialog`;编辑/密码等用 Radix `Dialog`。危险动作明确使用 red、取消和确认分离,异步期间禁用重复提交。
|
||||
- 图表:延迟趋势复用 `LatencyChart/ProbeHistory`,拓扑复用 Dashboard `TopologyChart`;容器需可响应,颜色在深浅主题均有足够对比。
|
||||
- 通知:操作成功/失败优先 `sonner` toast(全局 top-center richColors);不要新增 alert,现有 ProfileSettings 的 `alert` 是待治理遗留。
|
||||
- 空/加载/错误:空列表复用 `EmptyState`;路由/页面加载复用 `Loading`;错误应提供用户可理解提示及可恢复动作。当前尚无统一 ErrorState/ErrorBoundary,新增前先评估是否应形成公共组件。
|
||||
|
||||
## 真实页面参考
|
||||
|
||||
- Dashboard:`site/src/pages/Dashboard/DashboardPage.view.tsx` 使用 `PageHeader`、`StatCard`、Radix Grid/Card 和 `TopologyChart` 组合统计及拓扑;数据编排位于 `useDashboard.ts`。
|
||||
- Servers/Proxies:`site/src/pages/Servers/ServersPage.view.tsx` 与 `site/src/pages/Proxies/ProxiesPage.view.tsx` 是响应式列表、状态 Badge、操作菜单和 AlertDialog 的主要参考;表单分别位于对应 `*FormPage`。
|
||||
- Settings:`site/src/pages/Settings/SettingsPage.view.tsx` + `SettingsPage.css` 使用 240px 侧栏、active accent 状态和内容区;`GeneralSettings.tsx` 展示 `FormItem`、loading、save toast,`ProfileSettings.tsx` 展示资料卡和安全区块。
|
||||
|
||||
## 响应式、主题、国际化与可访问性
|
||||
|
||||
- 响应式:应用壳真实断点为 `max-width: 760px`(注释中的 640px 已过时)。测试至少覆盖 320px 移动宽度和桌面;表格内容在移动端采用卡片或可控滚动,不依赖 hover 才能操作。
|
||||
- 双主题:所有新颜色优先 `var(--accent-*)`、`var(--gray-*)` 与语义色;避免固定白底/黑字。图表、overlay、边框、focus 在 light/dark 都需检查。
|
||||
- 国际化:所有用户文案通过 `t()`,并同步 `locales/zh.json` 与 `en.json`。LanguageContext/localStorage 负责语言;不要以中文或英文裸字符串作为 fallback UI。
|
||||
- 可访问性:使用 Radix 语义组件,Icon-only button 必须有可访问名称/tooltip;图片提供 alt;表单 label 与控件关联;键盘焦点不可隐藏。`index.css` 当前对 Recharts surface 强制移除 outline,只能限于非交互图表;若加入图表键盘交互需重新评估。
|
||||
- 动效:页面切换标准为 `PageTransition` 的 0.3s cubic-bezier;标题 0.5s easeOut;状态点 1.6–2.5s 循环。交互可用轻量 hover/tap,不应阻塞操作。当前仅 Vite 模板残留 `App.css` 使用 `prefers-reduced-motion`,实际 Framer/状态点尚未统一尊重 reduced motion,属于待治理项。
|
||||
|
||||
## 复用与新增规则
|
||||
|
||||
1. 先查 Radix Themes,再查 `site/src/components/`,再查相邻页面的 view/hook 模式。
|
||||
2. 跨两个以上页面且语义稳定的模式才提取公共组件;页面专属组合留在页面目录。
|
||||
3. 新公共组件应使用 token、支持 className/必要 props、覆盖 loading/disabled/error,并在双主题和移动布局验证。
|
||||
4. 局部样式可用于第三方图表、复杂布局或 Radix props/Tailwind 难表达的状态;命名限定页面/组件,避免全局选择器和 `!important`。现有 Settings CSS 的 `!important` 是兼容性现状,不是新增样式范式。
|
||||
5. 不恢复或扩展未使用的 `App.css` 模板样式;需要全局规则时进入 `index.css` 并说明影响面。
|
||||
|
||||
## 待治理项
|
||||
|
||||
- 没有集中定义的自有 spacing、shadow、z-index、motion token;当前依赖 Radix 标度并夹杂局部像素值。
|
||||
- Settings 仅有桌面 240px sidebar,未发现专门移动适配规则,需要实机确认。
|
||||
- error state、ErrorBoundary、表单错误呈现尚未形成统一公共模式。
|
||||
- ProfileSettings 使用原生 `alert`,Loading 默认英文 `Loading...`,仍有国际化不一致。
|
||||
- 实际交互动效尚未系统支持 `prefers-reduced-motion`。
|
||||
|
||||
Reference in new issue
Block a user