refactor(db,persistence): unify EventStore and WorkflowAlertStore onto core/db SQLite

This commit is contained in:
gitea committed 2026-09-30 00:26:49 +08:00
1 parent 5a0c277993
commit 3864f0ffd0
7 files changed
+228 -34

No files matched your search

+93 -12
View File
@@ -1,5 +1,7 @@
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;
@@ -21,31 +23,110 @@ export interface WorkflowAlertCheckResult {
newAlerts: WorkflowErrorAlert[];
}
/** 本地持久化工作流错误指纹,避免定时检查时重复提醒同一错误计数。 */
/** 本地持久化工作流错误指纹(统一落盘至 core/db SQLite,兼容显式 JSON 状态文件)。 */
export class WorkflowAlertStore {
constructor(private readonly filePath: string) {}
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 {
if (!existsSync(this.filePath)) return { version: 1, alerts: {} };
try {
const value = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedAlerts>;
return { version: 1, alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {} };
} catch {
return { version: 1, alerts: {} };
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<string, { errorCount: number; lastSeen: number }> = {};
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<PersistedAlerts>;
return {
version: 1,
alerts: value.alerts && typeof value.alerts === "object" ? value.alerts : {},
};
} catch {
return { version: 1, alerts: {} };
}
}
return { version: 1, alerts: {} };
}
observe(alerts: WorkflowErrorAlert[]): 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 newAlerts = alerts.filter(
(alert) => data.alerts[alert.id]?.errorCount !== alert.errorCount
);
const updated = { ...data.alerts };
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 };
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`, { mode: 0o600 });
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[]) => {
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);
if (this.jsonPath) {
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
writeFileSync(
this.jsonPath,
`${JSON.stringify({ version: 1, alerts: updated }, null, 2)}\n`,
{ mode: 0o600 }
);
}
return { activeAlerts: alerts, newAlerts };
}
}