// 项目状态存储:单个 JSON 文件,原子写,读取时严格校验;损坏不静默回退。 import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' import { dirname } from 'node:path' import { emptyState, emptyProject, validateState } from '../shared/schema.js' import { seatBySessionId } from '../shared/roles.js' export class StoreError extends Error { constructor(code, message) { super(message); this.name = 'StoreError'; this.code = code } } export class SanshengStore { constructor(file) { this.file = file; this.state = emptyState(); this._queue = Promise.resolve() } async load() { let raw try { raw = await readFile(this.file, 'utf8') } catch (error) { if (error?.code === 'ENOENT') { this.state = emptyState(); return } throw new StoreError('sansheng/state-corrupt', `无法读取状态文件:${error?.message ?? error}`) } let parsed try { parsed = JSON.parse(raw) } catch (error) { throw new StoreError('sansheng/state-corrupt', `状态文件不是合法 JSON:${error.message}`) } const valid = validateState(parsed) if (!valid.ok) throw new StoreError('sansheng/state-corrupt', `状态文件损坏:${valid.error}`) this.state = valid.state } snapshot() { return structuredClone(this.state) } get(projectId) { return this.state.projects[projectId] } list() { return Object.values(this.state.projects) } seatBySession(sessionId) { return seatBySessionId(this.state.projects, sessionId) } // 所有写操作经此串行化:同一时刻只有一个 mutate 在跑,失败回滚内存状态。 async mutate(fn) { const run = async () => { const before = structuredClone(this.state) try { const result = await fn(this.state) this.state.seq = (this.state.seq ?? 0) + 1 await this.save() return result } catch (error) { this.state = before throw error } } this._queue = this._queue.then(run, run) return this._queue } async save() { await mkdir(dirname(this.file), { recursive: true }) const tmp = `${this.file}.${process.pid}.${Date.now()}.tmp` await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8') await rename(tmp, this.file) } // 确保项目记录存在;已存在则只补空字段,不覆盖既有会话/配置。 ensureProjectRecord({ id, name, workspaceId = null, path = null, now = Date.now() }) { let project = this.state.projects[id] if (!project) { project = emptyProject({ id, name: name ?? id, workspaceId, path, now }) this.state.projects[id] = project return project } if (name && !project.name) project.name = name if (workspaceId && !project.workspaceId) project.workspaceId = workspaceId if (path && !project.path) project.path = path project.updatedAt = now project.revision = (project.revision ?? 0) + 1 return project } }