import type { Database } from "bun:sqlite"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; import { getDatabase } from "../../../../core/db/index.js"; export interface WorkflowErrorAlert { id: string; pipelineId: string; platformId: string; pipelineName: string; errorCount: number; state: number; observedAt: number; } interface PersistedAlerts { version: 1; alerts: Record; } export interface WorkflowAlertCheckResult { activeAlerts: WorkflowErrorAlert[]; newAlerts: WorkflowErrorAlert[]; /** * JSON 副本导出失败的原因。SQLite 已是唯一事实来源, * 导出失败不能让整轮巡检判定失败——那会让调用方以为观察没完成, * 从而在下一次巡检时漏报新增告警。 */ exportError?: string; } /** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */ export class WorkflowAlertStore { private readonly scopeKey: string; private readonly jsonPath?: string; private readonly customDb?: Database; constructor(scopeOrFilePath = "default", db?: Database) { this.scopeKey = scopeOrFilePath; this.customDb = db; if (scopeOrFilePath.endsWith(".json")) { this.jsonPath = scopeOrFilePath; } } private get db(): Database { return this.customDb ?? getDatabase(); } private read(): PersistedAlerts { const dbRows = this.db .query( "SELECT id, error_count, observed_at FROM workflow_error_alerts WHERE scope_key = ?" ) .all(this.scopeKey) as Array<{ id: string; error_count: number; observed_at: number; }>; if (dbRows.length > 0) { const alerts: Record = {}; for (const row of dbRows) { alerts[row.id] = { errorCount: row.error_count, lastSeen: row.observed_at }; } return { version: 1, alerts }; } if (this.jsonPath && existsSync(this.jsonPath)) { try { const value = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial; return { version: 1, alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {}, }; } catch { return { version: 1, alerts: {} }; } } return { version: 1, alerts: {} }; } observe(alerts: WorkflowErrorAlert[], options: { complete?: boolean } = {}): WorkflowAlertCheckResult { const data = this.read(); const activeIds = new Set(alerts.map((alert) => alert.id)); const newAlerts = alerts.filter( (alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount ); const updated = { ...data.alerts }; if (options.complete !== false) { for (const id of Object.keys(updated)) { if (!activeIds.has(id)) delete updated[id]; } } for (const alert of alerts) { updated[alert.id] = { errorCount: alert.errorCount, lastSeen: alert.observedAt }; } const db = this.db; const upsert = db.prepare(` INSERT INTO workflow_error_alerts ( scope_key, id, pipeline_id, platform_id, pipeline_name, error_count, state, observed_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(scope_key, id) DO UPDATE SET pipeline_name = excluded.pipeline_name, error_count = excluded.error_count, state = excluded.state, observed_at = excluded.observed_at `); const tx = db.transaction((items: WorkflowErrorAlert[]) => { if (options.complete !== false) db.run("DELETE FROM workflow_error_alerts WHERE scope_key = ?", [this.scopeKey]); for (const alert of items) { upsert.run( this.scopeKey, alert.id, alert.pipelineId, alert.platformId, alert.pipelineName, alert.errorCount, alert.state, alert.observedAt ); } }); tx(alerts); let exportError: string | undefined; if (this.jsonPath) { try { mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 }); writeFileSync( this.jsonPath, `${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`, { mode: 0o600 } ); } catch (error) { exportError = error instanceof Error ? error.message : String(error); } } return { activeAlerts: alerts, newAlerts, ...(exportError ? { exportError } : {}) }; } }