Skip to content

性能自动调优系统

模块概述

版本: v1.0.0 状态: ✅ 已实现 IPC处理器: 25个 (12+13) 最后更新: 2026-03-05

三层性能监控与自动调优系统:统一采集器收集系统指标,性能监控器聚合分析,自动调优器基于规则引擎执行优化动作。支持 5 种内置规则、滞后保护和环形缓冲区时序存储。

核心特性

  • 三层架构: 采集器 → 监控器 → 调优器
  • 5 种内置规则: 数据库慢查询、真空清理、LLM延迟、内存压力、P2P连接
  • 环形缓冲区: 8640 样本 × 10s 间隔 = 24h 时序数据
  • 滞后保护: 连续计数 + 冷却期,防止规则频繁触发
  • IPC 拦截器: 自动测量所有 IPC 调用性能
  • 数据库包装: SQL 查询自动性能追踪

1. 架构设计

1.1 整体架构图

┌──────────────────────────────────────────────────────────────────┐
│                        前端 (Vue3)                                │
├──────────────────────────────────────────────────────────────────┤
│           Pinia Store: performance-monitor.ts (502行)             │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────────────┐   │
│  │ 系统指标  │ │ 规则状态  │ │ 调优历史  │ │ 实时图表          │   │
│  └──────────┘ └──────────┘ └──────────┘ └───────────────────┘   │
└──────────────────────────────────────────────────────────────────┘
                    ↕ IPC (12 auto-tuner + 13 performance)
┌──────────────────────────────────────────────────────────────────┐
│                        主进程 (Electron)                          │
├──────────────────────────────────────────────────────────────────┤
│  auto-tuner-ipc.js (199行)  │  performance-ipc.js (165行)        │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │              AutoTuner (664行, extends EventEmitter)        │  │
│  │  ┌──────────────────────────────────────────────────────┐  │  │
│  │  │  5 Built-in Rules (with hysteresis)                  │  │  │
│  │  │  db-slow-queries │ db-vacuum │ llm-high-latency      │  │  │
│  │  │  memory-pressure │ p2p-connections                    │  │  │
│  │  └──────────────────────────────────────────────────────┘  │  │
│  └────────────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │        PerformanceMonitor (435行, extends EventEmitter)    │  │
│  │   ─────────────────┐  ┌─────────────────┐                 │  │
│  │  │ Ring Buffer      │  │ Alert Thresholds│                 │  │
│  │  │ 8640 samples     │  │ cpu/mem/disk    │                 │  │
│  │  │ 10s interval     │  │                 │                 │  │
│  │  └─────────────────┘  └─────────────────┘                 │  │
│  └────────────────────────────────────────────────────────────┘  │
│  ┌────────────────────────────────────────────────────────────┐  │
│  │  UnifiedPerformanceCollector (616行)                        │  │
│  │  ┌──────────────┐  ┌──────────────────┐                    │  │
│  │  │ IPC拦截器     │  │ 数据库包装器      │                    │  │
│  │  │ (110行)       │  │ (165行)           │                    │  │
│  │  └──────────────┘  └──────────────────┘                    │  │
│  └────────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────┘

1.2 数据流

系统指标采集 (10s 间隔)
    ↓ os.cpus(), os.freemem(), process.memoryUsage()
UnifiedPerformanceCollector → 聚合指标

PerformanceMonitor → Ring Buffer (8640 samples)
    ↓ 阈值检查
AutoTuner → 规则评估 (5 rules)
    ↓ 滞后保护通过
执行优化动作 → 发送事件通知

1.3 核心组件

组件文件行数说明
AutoTunerauto-tuner.js664规则引擎 + 自动优化
PerformanceMonitorperformance-monitor.js435指标聚合 + 环形缓冲
UnifiedPerformanceCollectorunified-performance-collector.js616统一采集器
IPCPerformanceInterceptoripc-performance-interceptor.js110IPC调用拦截
DatabasePerformanceWrapperdatabase-performance-wrapper.js165SQL性能追踪
AutoTuner IPCauto-tuner-ipc.js19912个IPC处理器
Performance IPCperformance-ipc.js16513个IPC处理器
Pinia Storeperformance-monitor.ts502前端状态管理

2. 核心模块

2.1 AutoTuner

javascript
class AutoTuner extends EventEmitter {
  async initialize(deps)           // 初始化 (database, performanceMonitor)

  // 规则管理
  addRule(rule)                    // 添加自定义规则
  removeRule(ruleId)               // 移除规则
  enableRule(ruleId)               // 启用规则
  disableRule(ruleId)              // 禁用规则
  getRules()                       // 获取所有规则

  // 调优操作
  async evaluate()                 // 手动评估所有规则
  async getRecommendations()       // 获取优化建议
  async applyRecommendation(id)    // 应用建议

  // 历史
  async getHistory(options?)       // 获取调优历史
  async getStats()                 // 获取统计信息

  // 生命周期
  start()                          // 启动自动调优
  stop()                           // 停止自动调优
  updateConfig(config)             // 更新配置
  getConfig()                      // 获取配置
}

2.2 内置规则 (5种)

规则ID触发条件优化动作冷却期
db-slow-queries慢查询数 > 阈值创建索引/分析查询5分钟
db-vacuum数据库碎片率 > 阈值执行 VACUUM30分钟
llm-high-latencyLLM 响应延迟 > 阈值调整模型参数/切换模型3分钟
memory-pressure内存使用 > 80%清理缓存/GC2分钟
p2p-connections连接数异常重连/限流5分钟

2.3 滞后保护 (Hysteresis)

javascript
{
  consecutiveRequired: 3,    // 连续触发次数要求
  cooldownMs: 300000,        // 冷却期 (5分钟)

  // 评估流程:
  // 1. 检查规则条件
  // 2. 条件满足 → consecutiveCount++
  // 3. consecutiveCount >= consecutiveRequired → 检查冷却期
  // 4. 冷却期已过 → 执行动作, 重置计数器
  // 5. 条件不满足 → 重置 consecutiveCount
}

2.4 PerformanceMonitor

javascript
class PerformanceMonitor extends EventEmitter {
  async initialize(config?)        // 初始化

  // 指标
  async getMetrics()               // 获取当前指标
  async getMetricsHistory(duration?) // 获取历史指标
  async getSystemInfo()            // 获取系统信息

  // 报告
  async getPerformanceReport()     // 生成性能报告
  async getAlerts()                // 获取性能告警

  // 生命周期
  start()                          // 启动监控
  stop()                           // 停止监控
}

环形缓冲区配置:

javascript
{
  maxSamples: 8640,          // 最大样本数
  intervalMs: 10000,         // 采样间隔 (10秒)
  retentionMs: 86400000,     // 保留时长 (24小时)
  // 8640 × 10s = 86400s = 24h
}

2.5 UnifiedPerformanceCollector

javascript
class UnifiedPerformanceCollector {
  async initialize(deps)           // 初始化

  // 采集
  collectSystemMetrics()           // CPU/内存/磁盘
  collectProcessMetrics()          // Electron进程指标
  collectDatabaseMetrics()         // 数据库指标
  collectNetworkMetrics()          // P2P网络指标
  collectLLMMetrics()              // LLM调用指标

  // 聚合
  getAggregatedMetrics()           // 获取聚合指标
  getMetricsSummary()              // 获取摘要
}

3. 数据模型

本模块无数据库表,所有性能数据存储在内存中 (环形缓冲区)。调优历史通过 EventEmitter 事件记录。

3.1 内存数据结构

javascript
// 环形缓冲区样本
{
  timestamp: Date.now(),
  cpu: { usage: 45.2, cores: 8 },
  memory: { used: 4096, total: 16384, percent: 25 },
  disk: { read: 1024, write: 512 },
  process: { heapUsed: 256, rss: 512, handles: 42 },
  network: { peers: 5, bandwidth: { in: 1024, out: 512 } },
  llm: { avgLatency: 1200, requestCount: 15 },
  database: { queryCount: 100, avgTime: 5.2, slowQueries: 2 },
}

4. IPC接口 (25个)

4.1 自动调优 (12个)

通道说明参数
auto-tuner:initialize初始化调优器-
auto-tuner:start启动自动调优-
auto-tuner:stop停止自动调优-
auto-tuner:evaluate手动评估规则-
auto-tuner:get-rules获取规则列表-
auto-tuner:add-rule添加规则rule
auto-tuner:remove-rule移除规则ruleId
auto-tuner:enable-rule启用规则ruleId
auto-tuner:disable-rule禁用规则ruleId
auto-tuner:get-recommendations获取优化建议-
auto-tuner:apply-recommendation应用建议recommendationId
auto-tuner:get-history获取调优历史options?

4.2 性能监控 (13个)

通道说明参数
performance:initialize初始化监控器config?
performance:start启动监控-
performance:stop停止监控-
performance:get-metrics获取当前指标-
performance:get-metrics-history获取历史指标duration?
performance:get-system-info获取系统信息-
performance:get-report获取性能报告-
performance:get-alerts获取告警-
performance:get-stats获取统计-
performance:get-config获取配置-
performance:update-config更新配置config
performance:collect-now立即采集-
performance:clear-history清除历史-

5. 事件

事件负载说明
rule:triggered规则触发
rule:cooldown规则冷却中
recommendation:new新优化建议
metrics:updated指标更新
alert:threshold阈值告警

6. 前端页面

6.1 Pinia Store: performance-monitor.ts

typescript
interface PerformanceState {
  metrics: SystemMetrics | null;
  metricsHistory: MetricsSample[];
  rules: TunerRule[];
  recommendations: Recommendation[];
  tunerHistory: TunerAction[];
  alerts: Alert[];
  systemInfo: SystemInfo | null;
  isMonitoring: boolean;
  isTunerRunning: boolean;
  loading: boolean;
}

// Getters
cpuUsage; // CPU使用率
memoryUsage; // 内存使用率
activeRules; // 活跃规则数
pendingRecommendations; // 待处理建议数
recentAlerts; // 最近告警

// Actions
initializeMonitor(); // 初始化
startMonitoring(); // 启动监控
stopMonitoring(); // 停止监控
startTuner(); // 启动调优
stopTuner(); // 停止调优
fetchMetrics(); // 获取指标
fetchRules(); // 获取规则
applyRecommendation(); // 应用建议

7. 文件结构

desktop-app-vue/src/main/performance/
├── auto-tuner.js                    # 规则引擎+自动优化 (664行)
├── auto-tuner-ipc.js                # 12个IPC处理器 (199行)
├── performance-monitor.js           # 指标聚合+环形缓冲 (435行)
├── performance-ipc.js               # 13个IPC处理器 (165行)
├── unified-performance-collector.js # 统一采集器 (616行)
├── ipc-performance-interceptor.js   # IPC调用拦截 (110行)
└── database-performance-wrapper.js  # SQL性能追踪 (165行)

desktop-app-vue/src/renderer/
└── stores/performance-monitor.ts    # 性能监控状态管理 (502行)

8. 相关文档


文档版本: 1.0 最后更新: 2026-03-05

基于 MIT 许可发布