Files
2026-06-30 15:14:37 +08:00

747 lines
28 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# MeshRay 技术架构文档
## 📋 目录
- [系统架构](#系统架构)
- [技术栈](#技术栈)
- [核心模块](#核心模块)
- [数据流](#数据流)
- [部署架构](#部署架构)
---
## 系统架构
### 整体架构图
```
┌─────────────────────────────────────────────────────┐
│ Client Layer │
│ (Web Browser) │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Vue 3 + TypeScript Frontend │ │
│ │ - Element Plus UI Components │ │
│ │ - Axios HTTP Client │ │
│ │ - Vue Router │ │
│ │ - Notification Center │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
│ HTTPS/HTTP
│ RESTful API
┌─────────────────────────────────────────────────────┐
│ API Gateway │
│ (Gin Framework) │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Middleware Layer │ │
│ │ - JWT Authentication │ │
│ │ - CORS Handler │ │
│ │ - Request Logger │ │
│ │ - Error Recovery │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Handler Layer │ │
│ │ - NetworkHandler │ │
│ │ - DeviceHandler │ │
│ │ - ServiceHandler │ │
│ │ - DDNSHandler │ │
│ │ - BackupHandler │ │
│ │ - NotificationHandler │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
│ Business Logic
┌─────────────────────────────────────────────────────┐
│ Service Layer │
│ (Business Logic) │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ Core Services: │ │
│ │ - UserService (bcrypt auth) │ │
│ │ - NetworkService (WireGuard mgmt) │ │
│ │ - DeviceService (peer mgmt) │ │
│ │ - DDNSService (DNS operations) │ │
│ │ - IPDetectionService │ │
│ │ - NotificationService │ │
│ │ - BackupRestoreService │ │
│ │ - RestartCoreService │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
│ Data Access
┌─────────────────────────────────────────────────────┐
│ Data Layer │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ SQLite Database (GORM ORM) │ │
│ │ - Users │ │
│ │ - Networks │ │
│ │ - Devices │ │
│ │ - Services │ │
│ │ - Notifications │ │
│ │ - AuditLogs │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ External APIs: │ │
│ │ - Cloudflare DNS API │ │
│ │ - Tencent Cloud DNSPod API │ │
│ │ - GitHub Releases API │ │
│ │ - IP Detection Services │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
│ System Integration
┌─────────────────────────────────────────────────────┐
│ Infrastructure Layer │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ WireGuard Core: │ │
│ │ - wg-quick │ │
│ │ - wg tool │ │
│ │ - Kernel module / Userspace │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ System Services: │ │
│ │ - DNS Provider (libdns) │ │
│ │ - Task Scheduler │ │
│ │ - Log Management │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
```
---
## 技术栈
### 后端技术栈
| 组件 | 技术 | 版本 | 用途 |
|------|------|------|------|
| **语言** | Go | 1.21+ | 主要编程语言 |
| **Web 框架** | Gin | v1.9+ | HTTP 服务器和路由 |
| **ORM** | GORM | v2.5+ | 数据库操作 |
| **数据库** | SQLite | v3 | 嵌入式数据库 |
| **日志** | Zap | v1.26+ | 结构化日志 |
| **DNS 库** | libdns | latest | DNS Provider 集成 |
| **认证** | bcrypt | latest | 密码加密 |
| **JWT** | golang-jwt | v5 | Token 认证 |
### 前端技术栈
| 组件 | 技术 | 版本 | 用途 |
|------|------|------|------|
| **框架** | Vue | 3.x | 渐进式框架 |
| **语言** | TypeScript | 5.x | 类型安全 |
| **UI 库** | Element Plus | 2.x | UI 组件库 |
| **构建工具** | Vite | 4.x | 快速构建 |
| **HTTP** | Axios | 1.x | HTTP 客户端 |
| **路由** | Vue Router | 4.x | SPA 路由 |
| **图标** | @element-plus/icons-vue | latest | 图标库 |
| **图表** | ECharts | 5.x | 数据可视化 |
### 运维技术栈
| 组件 | 技术 | 版本 | 用途 |
|------|------|------|------|
| **容器化** | Docker | latest | 容器部署 |
| **编排** | Docker Compose | latest | 多容器管理 |
| **反向代理** | Nginx | latest | 负载均衡 |
| **SSL** | Let's Encrypt | latest | HTTPS 证书 |
| **监控** | Prometheus | latest | 指标收集 |
| **可视化** | Grafana | latest | 监控面板 |
---
## 核心模块
### 1. DNS Provider 抽象层
#### 架构设计
```
┌─────────────────────────────────────┐
│ DNSProvider Interface │
│ - CreateRecord() error │
│ - UpdateRecord() error │
│ - DeleteRecord() error │
│ - GetRecords() ([]Record, error) │
└─────────────────────────────────────┘
│ implements
┌─────────┼─────────┬──────────┐
│ │ │ │
┌───┴───┐ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐
│Cloud- │ │Tencent│ │Aliyun │ │ Mock │
│flare │ │Cloud │ │(TODO) │ │ │
│Provider│ │Provider│ │Provider│ │ │
└───────┘ └───────┘ └───────┘ └───────┘
```
#### 代码结构
```go
// internal/dnsprovider/provider.go
type DNSProvider interface {
CreateRecord(ctx context.Context, req CreateRequest) error
UpdateRecord(ctx context.Context, req UpdateRequest) error
DeleteRecord(ctx context.Context, req DeleteRequest) error
GetRecords(ctx context.Context, domain string) ([]Record, error)
}
// internal/dnsprovider/cloudflare.go
type CloudflareProvider struct {
apiToken string
zoneID string
client *http.Client
}
func (p *CloudflareProvider) CreateRecord(...) error {
// 调用 Cloudflare API
}
// internal/dnsprovider/tencentcloud.go
type TencentCloudProvider struct {
secretId string
secretKey string
client *dns.Client
}
func (p *TencentCloudProvider) CreateRecord(...) error {
// 调用腾讯云 API
}
```
---
### 2. DDNS Service 层
#### 架构设计
```
┌─────────────────────────────────────┐
│ DDNSService (Coordinator) │
│ - CreateDDNSService() │
│ - UpdateDDNSService() │
│ - DeleteDDNSService() │
│ - StartAutoSync() │
└─────────────────────────────────────┘
│ │ │
┌────┘ ┌────┘ ┌────┘
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────────┐
│IP Detect│ │DNS Ops │ │Scheduler │
│Service │ │Service │ │Service │
└────────┘ └────────┘ └──────────┘
```
#### 核心流程
```go
// 创建 DDNS 服务
func (s *DDNSService) CreateDDNSService(req *CreateRequest) (*Service, error) {
// 1. 验证凭证
provider := s.createProvider(req.ProviderType, req.Credentials)
// 2. 检测当前 IP
currentIP, err := s.ipDetection.DetectIP(req.RecordType)
// 3. 创建 DNS 记录
err = provider.CreateRecord(ctx, CreateRequest{
Domain: req.Domain,
Type: req.RecordType,
Value: currentIP,
})
// 4. 保存到数据库
service := &model.Service{
Name: req.Name,
RecordType: req.RecordType,
TargetIP: currentIP,
// ...
}
s.store.DB().Create(service)
return service, nil
}
```
---
### 3. WebSocket 实时通知推送
#### 架构设计
```
┌─────────────────────────────────────┐
│ NotificationService (Backend) │
│ - clients: map[uint]*Client │
│ - broadcastCh: chan Message │
│ - db: *gorm.DB │
└─────────────────────────────────────┘
│ │
┌────┘ └────┐
▼ ▼
┌──────────┐ ┌──────────┐
│Unicast │ │Broadcast │
│SendToUser│ │All Users │
└──────────┘ └──────────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│Save to │ │Save to │
│DB (user) │ │DB (all) │
└──────────┘ └──────────┘
│ │
▼ ▼
┌──────────┐ ┌──────────┐
│WebSocket │ │WebSocket │
│Channel │ │Channels │
└──────────┘ └──────────┘
```
#### 数据模型
```go
// internal/model/models.go
type Notification struct {
ID uint `gorm:"primaryKey"`
UserID uint `gorm:"index"`
Type string // alert/system/update/ddns
Priority int // 1=low, 2=medium, 3=high
Title string
Message string
Data string // JSON
IsRead bool `gorm:"index"`
ReadAt *time.Time
CreatedAt time.Time `gorm:"index"`
}
```
#### 核心实现
```go
// internal/service/notification.go
func (s *NotificationService) SendToUser(userID uint, msg Message) {
// 1. 保存到数据库
notification := model.Notification{
UserID: userID,
Type: msg.Type,
Priority: msg.Priority,
Title: msg.Title,
Message: msg.Message,
}
s.db.Create(&notification)
// 2. 发送到 WebSocket 通道
if client, ok := s.clients[userID]; ok {
select {
case client.msgCh <- msg:
// 发送成功
default:
// 通道已满
}
}
}
func (s *NotificationService) Broadcast(msg Message) {
// 1. 保存到所有用户的数据库记录
for userID := range s.clients {
notification := model.Notification{
UserID: userID,
Type: msg.Type,
// ...
}
s.db.Create(&notification)
}
// 2. 广播到所有客户端
s.broadcastCh <- msg
}
```
---
### 4. 备份恢复系统
#### 架构设计
```
┌─────────────────────────────────────┐
│ BackupHandler │
│ - CreateBackup() │
│ - ListBackups() │
│ - RestoreBackup() │
│ - DeleteBackup() │
│ - DownloadBackup() │
└─────────────────────────────────────┘
┌────┴────┬────────┬────────┐
▼ ▼ ▼ ▼
┌────────┐ ┌────────┐ ┌──────┐ ┌──────┐
│Export │ │Copy │ │Zip │ │Save │
│DB Data │ │Config │ │Files │ │File │
└────────┘ └────────┘ └──────┘ └──────┘
```
#### 备份流程
```go
// internal/handler/backup.go
func (h *BackupHandler) CreateBackup(c *gin.Context) {
// 1. 生成备份文件名
timestamp := time.Now().Format("20060102_150405")
backupFile := filepath.Join("data", "backups",
fmt.Sprintf("meshray_backup_%s.zip", timestamp))
// 2. 确保备份目录存在
os.MkdirAll(filepath.Dir(backupFile), 0755)
// 3. TODO: 实现真实备份逻辑
// - 导出数据库数据到 SQL 文件
// - 复制配置文件
// - 打包成 zip 文件
c.JSON(http.StatusOK, gin.H{
"message": "备份创建成功",
"data": gin.H{
"filename": filepath.Base(backupFile),
"path": backupFile,
},
})
}
```
---
## 数据流
### 1. DDNS 自动更新流程
```
用户创建 DDNS 服务
后端验证凭证并创建 DNS Provider
调用 IP 检测服务获取当前公网 IP
调用 DNS Provider API 创建 DNS 记录
├─▶ 成功:保存到数据库
│ └─▶ 返回成功响应
└─▶ 失败:回滚事务
└─▶ 返回错误信息
后台任务(每 5 分钟):
检测公网 IP 变化
├─▶ IP 未变化:重置计数器
└─▶ IP 变化:计数器 +1
连续 2 次检测到不同?
├─▶ 否:等待下次检测
└─▶ 是:调用 DNS Provider API 更新记录
发送 WebSocket 通知
Dashboard 实时更新
```
---
### 2. 通知推送流程
```
系统事件触发
├─▶ DDNS IP 变化
├─▶ 发现新版本
├─▶ 系统告警
└─▶ 重要通知
NotificationService.SendXXX()
├─▶ 单播:SendToUser(userID, msg)
│ │
│ ├─▶ 保存到数据库(该用户)
│ │
│ └─▶ 发送到 WebSocket 通道
└─▶ 广播:Broadcast(msg)
├─▶ 保存到数据库(所有在线用户)
└─▶ 广播到所有 WebSocket 通道
前端轮询(每 30 秒)
├─▶ 获取未读数量
│ └─▶ 更新角标数字
└─▶ 获取通知列表
└─▶ 显示在通知中心
```
---
### 3. 用户认证流程
```
用户登录请求
验证用户名和密码
├─▶ 失败:返回错误
└─▶ 成功:生成 JWT Token
返回 Token 和用户信息
前端存储 TokenlocalStorage
后续请求携带 Token
JWT 中间件验证 Token
├─▶ 无效:返回 401
└─▶ 有效:提取用户信息到上下文
Handler 获取用户 ID
执行授权操作
```
---
## 部署架构
### 单机部署架构
```
┌─────────────────────────────────────┐
│ Single Server │
│ (Windows/Linux/Mac) │
│ │
│ ┌───────────────────────────────┐ │
│ │ MeshRay Application │ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ Gin Web Server │ │ │
│ │ │ (Port: 9531) │ │ │
│ │ └─────────────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ Business Logic │ │ │
│ │ │ (Services) │ │ │
│ │ └─────────────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ SQLite Database │ │ │
│ │ │ (data/meshray.db) │ │ │
│ │ └─────────────────────────┘ │ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ WireGuard Core │ │ │
│ │ │ (wg0 interface) │ │ │
│ │ └─────────────────────────┘ │ │
│ └───────────────────────────────┘ │
│ │
│ ┌───────────────────────────────┐ │
│ │ Nginx (Optional) │ │
│ │ - Reverse Proxy │ │
│ │ - SSL Termination │ │
│ └───────────────────────────────┘ │
└─────────────────────────────────────┘
│ HTTPS/HTTP
┌─────────────────────────────────────┐
│ Clients │
│ - Web Browsers │
│ - Mobile Devices │
└─────────────────────────────────────┘
```
---
### Docker 部署架构
```
┌─────────────────────────────────────┐
│ Docker Host │
│ │
│ ┌───────────────────────────────┐ │
│ │ meshray Container │ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ MeshRay App │ │ │
│ │ │ (Port: 9531) │ │ │
│ │ └─────────────────────────┘ │ │
│ │ │ │
│ │ Volumes: │ │
│ │ - ./data:/root/data │ │
│ │ - ./config:/root/config │ │
│ └───────────────────────────────┘ │
│ │
│ ┌───────────────────────────────┐ │
│ │ nginx Container (Optional) │ │
│ │ - Reverse Proxy │ │
│ │ - SSL Termination │ │
│ └───────────────────────────────┘ │
└─────────────────────────────────────┘
```
---
## 安全架构
### 多层安全防护
```
┌─────────────────────────────────────┐
│ Layer 1: Network Security │
│ - Firewall Rules │
│ - Port Whitelist │
│ - DDoS Protection │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ Layer 2: Transport Security │
│ - HTTPS/TLS │
│ - Certificate Validation │
│ - HSTS │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ Layer 3: Application Security │
│ - JWT Authentication │
│ - Role-based Authorization │
│ - Input Validation │
│ - SQL Injection Prevention │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ Layer 4: Data Security │
│ - Password Hashing (bcrypt) │
│ - Sensitive Data Encryption │
│ - Audit Logging │
└─────────────────────────────────────┘
```
---
## 性能优化
### 数据库优化
```sql
-- 启用 WAL 模式
PRAGMA journal_mode=WAL;
-- 优化同步策略
PRAGMA synchronous=NORMAL;
-- 增加缓存大小
PRAGMA cache_size=10000;
-- 定期清理过期数据
DELETE FROM notifications WHERE created_at < datetime('now', '-30 days');
```
### 缓存策略
```go
// 内存缓存示例
var ipCache = sync.Map{}
func (s *IPDetectionService) GetCachedIP(recordType string) (string, error) {
if cached, ok := ipCache.Load(recordType); ok {
return cached.(string), nil
}
// 缓存未命中,调用外部 API
ip, err := s.detectIP(recordType)
if err == nil {
ipCache.Store(recordType, ip)
// 5 分钟后过期
go func() {
time.Sleep(5 * time.Minute)
ipCache.Delete(recordType)
}()
}
return ip, err
}
```
---
## 监控指标
### 关键指标
| 指标 | 阈值 | 说明 |
|------|------|------|
| API 响应时间 | < 100ms | 本地请求 |
| 数据库查询 | < 50ms | 简单查询 |
| 并发连接数 | > 100 | 同时在线 |
| CPU 使用率 | < 80% | 持续 5 分钟 |
| 内存使用 | < 512MB | 峰值 |
| 磁盘空间 | > 1GB | 可用空间 |
---
## 扩展性设计
### 水平扩展
- ✅ 无状态设计,支持多实例部署
- ✅ 数据库可替换为 PostgreSQL/MySQL
- ✅ 支持 Redis 作为缓存层
- ✅ 支持负载均衡
### 垂直扩展
- ✅ 模块化设计,易于添加新功能
- ✅ 接口抽象,支持新云服务商
- ✅ 插件化架构,支持自定义扩展
---
**最后更新**: 2026-03-20
**维护人员**: MeshRay Team
**文档版本**: v1.0