[P1/优化] SessionRecorder appendFileSync 在高频写入时阻塞主进程 #35

Open
opened 2026-07-21 21:56:00 +08:00 by thzxx · 0 comments
Owner

问题类型

优化 / 高 / 后端服务

文件位置

electron/services/session-recorder.service.ts

问题描述

SessionRecorder 使用 fs.appendFileSync 同步写入 trace 文件。
流式事件频率 30-50 次/秒,每次 IO 阻塞主进程 1-5ms,累计:

  • 每秒 30-50 次同步 IO
  • 每次阻塞 1-5ms
  • 主进程 30-50% 时间被阻塞
  • UI 卡顿、IPC 延迟

影响

  • UI 响应延迟
  • 流式输出卡顿
  • 长时间运行后越来越严重

建议修复

  1. 批量异步写入:在内存缓冲,定时 flush
private buffer: string[] = [];
private flushTimer: NodeJS.Timeout | null = null;

record(event) {
  this.buffer.push(JSON.stringify(event));
  if (!this.flushTimer) {
    this.flushTimer = setTimeout(() => this.flush(), 100);
  }
}

private async flush() {
  if (this.buffer.length === 0) return;
  const data = this.buffer.join('\n') + '\n';
  this.buffer = [];
  this.flushTimer = null;
  await fs.promises.appendFile(this.filePath, data);
}
  1. 使用 worker_threads:将 IO 移至 worker
  2. 配置开关:允许用户关闭 trace 录制
## 问题类型 优化 / 高 / 后端服务 ## 文件位置 `electron/services/session-recorder.service.ts` ## 问题描述 SessionRecorder 使用 `fs.appendFileSync` 同步写入 trace 文件。 流式事件频率 30-50 次/秒,每次 IO 阻塞主进程 1-5ms,累计: - 每秒 30-50 次同步 IO - 每次阻塞 1-5ms - 主进程 30-50% 时间被阻塞 - UI 卡顿、IPC 延迟 ## 影响 - UI 响应延迟 - 流式输出卡顿 - 长时间运行后越来越严重 ## 建议修复 1. **批量异步写入**:在内存缓冲,定时 flush ```ts private buffer: string[] = []; private flushTimer: NodeJS.Timeout | null = null; record(event) { this.buffer.push(JSON.stringify(event)); if (!this.flushTimer) { this.flushTimer = setTimeout(() => this.flush(), 100); } } private async flush() { if (this.buffer.length === 0) return; const data = this.buffer.join('\n') + '\n'; this.buffer = []; this.flushTimer = null; await fs.promises.appendFile(this.filePath, data); } ``` 2. **使用 worker_threads**:将 IO 移至 worker 3. **配置开关**:允许用户关闭 trace 录制
thzxx added the ??????? labels 2026-07-21 21:56:00 +08:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: MetonaTeam/metona-ai-desktop#35