refactor(db,persistence): unify EventStore and WorkflowAlertStore onto core/db SQLite
This commit is contained in:
1 parent
5a0c277993
commit
3864f0ffd0
7 files changed
+228
-34
No files matched your search
@@ -25,10 +25,11 @@ export async function handleServiceCommand(
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
const limit = numberOption(parsed.options, ["limit", "count", "n"], 50) || 50;
|
||||
const store = new EventStore(join(SERVICE_STATE_DIR, `events-${corpId}.json`));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
|
||||
const store = new EventStore(stateFile || `corp:${corpId}`);
|
||||
const result = await pollEvents(client, corpId, store, limit);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "事件状态文件": join(SERVICE_STATE_DIR, `events-${corpId}.json`) })}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "存储后端": stateFile || "SQLite (observed_events)" })}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const config: ServiceConfig = {
|
||||
|
||||
@@ -751,15 +751,16 @@ async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
state: workflow.state,
|
||||
observedAt,
|
||||
}));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]) || join(WORKFLOW_STATE_DIR, `workflow-alerts-${runtime.selectedCorp!.id}.json`);
|
||||
const check = new WorkflowAlertStore(stateFile).observe(activeAlerts);
|
||||
const explicitStateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
|
||||
const stateFile = explicitStateFile || `sqlite:workflow_error_alerts:${runtime.selectedCorp!.id}`;
|
||||
const check = new WorkflowAlertStore(explicitStateFile || `corp:${runtime.selectedCorp!.id}`).observe(activeAlerts);
|
||||
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
|
||||
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
|
||||
const scanErrorCount = result.errors.length + logErrors.length;
|
||||
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态文件: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态存储: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
}
|
||||
|
||||
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
|
||||
@@ -37,6 +37,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(tableNames.has("approval_findings")).toBe(true);
|
||||
expect(tableNames.has("aipro_logs")).toBe(true);
|
||||
expect(tableNames.has("cache_entries")).toBe(true);
|
||||
expect(tableNames.has("observed_events")).toBe(true);
|
||||
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
||||
|
||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||
const indices = db
|
||||
@@ -51,6 +53,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(indexNames.has("idx_findings_rule_id")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_namespace")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
||||
});
|
||||
|
||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||
|
||||
@@ -184,6 +184,38 @@ export const migrations: DatabaseMigration[] = [
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 3,
|
||||
name: "003_events_and_workflow_alerts_tables",
|
||||
up(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS observed_events (
|
||||
scope_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
corp_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
observed_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (scope_key, id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_observed_events_scope ON observed_events(scope_key, observed_at);");
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS workflow_error_alerts (
|
||||
scope_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
pipeline_id TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
pipeline_name TEXT,
|
||||
error_count INTEGER NOT NULL,
|
||||
state INTEGER NOT NULL DEFAULT 0,
|
||||
observed_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (scope_key, id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_workflow_alerts_scope ON workflow_error_alerts(scope_key);");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { getDatabase } from "../../core/db/index.js";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { getApprovalDatabase } from "./db.js";
|
||||
import { parseRuleBody, validatePreferenceText } from "./parser.js";
|
||||
import {
|
||||
AiProLogRecord,
|
||||
@@ -45,7 +45,7 @@ export class ApprovalRepository {
|
||||
private db: Database;
|
||||
|
||||
constructor(db?: Database) {
|
||||
this.db = db ?? getApprovalDatabase();
|
||||
this.db = db ?? getDatabase();
|
||||
}
|
||||
|
||||
// ===================== 规约管理 (Rules) =====================
|
||||
|
||||
+90
-15
@@ -1,27 +1,102 @@
|
||||
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";
|
||||
import type { EventRecord } from "./types.js";
|
||||
|
||||
interface PersistedEvents { version: 1; events: Record<string, number>; }
|
||||
interface PersistedEvents {
|
||||
version: 1;
|
||||
events: Record<string, number>;
|
||||
}
|
||||
|
||||
const MAX_EVENTS = 2000;
|
||||
|
||||
export class EventStore {
|
||||
constructor(private readonly filePath: string) {}
|
||||
private read(): PersistedEvents {
|
||||
if (!existsSync(this.filePath)) return { version: 1, events: {} };
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedEvents>;
|
||||
return { version: 1, events: parsed.events && typeof parsed.events === "object" ? parsed.events : {} };
|
||||
} catch { return { version: 1, events: {} }; }
|
||||
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;
|
||||
}
|
||||
}
|
||||
has(id: string): boolean { return Object.prototype.hasOwnProperty.call(this.read().events, id); }
|
||||
|
||||
private get db(): Database {
|
||||
return this.customDb ?? getDatabase();
|
||||
}
|
||||
|
||||
private readJson(): PersistedEvents {
|
||||
if (!this.jsonPath || !existsSync(this.jsonPath)) {
|
||||
return { version: 1, events: {} };
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.jsonPath, "utf8")) as Partial<PersistedEvents>;
|
||||
return {
|
||||
version: 1,
|
||||
events: parsed.events && typeof parsed.events === "object" ? parsed.events : {},
|
||||
};
|
||||
} catch {
|
||||
return { version: 1, events: {} };
|
||||
}
|
||||
}
|
||||
|
||||
has(id: string): boolean {
|
||||
if (this.jsonPath && existsSync(this.jsonPath)) {
|
||||
if (Object.prototype.hasOwnProperty.call(this.readJson().events, id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const row = this.db
|
||||
.query("SELECT 1 FROM observed_events WHERE scope_key = ? AND id = ? LIMIT 1")
|
||||
.get(this.scopeKey, id);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
commit(records: EventRecord[]): void {
|
||||
if (!records.length) return;
|
||||
const data = this.read();
|
||||
const merged = { ...data.events };
|
||||
for (const record of records) merged[record.id] = record.observedAt;
|
||||
const entries = Object.entries(merged).sort((a, b) => a[1] - b[1]).slice(-MAX_EVENTS);
|
||||
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 });
|
||||
|
||||
const db = this.db;
|
||||
const upsert = db.prepare(`
|
||||
INSERT INTO observed_events (scope_key, id, corp_id, kind, observed_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(scope_key, id) DO UPDATE SET observed_at = excluded.observed_at
|
||||
`);
|
||||
|
||||
const tx = db.transaction((items: EventRecord[]) => {
|
||||
for (const record of items) {
|
||||
upsert.run(this.scopeKey, record.id, record.corpId, record.kind, record.observedAt);
|
||||
}
|
||||
db.run(
|
||||
`
|
||||
DELETE FROM observed_events
|
||||
WHERE scope_key = ? AND id NOT IN (
|
||||
SELECT id FROM observed_events
|
||||
WHERE scope_key = ?
|
||||
ORDER BY observed_at DESC
|
||||
LIMIT ?
|
||||
)
|
||||
`,
|
||||
[this.scopeKey, this.scopeKey, MAX_EVENTS]
|
||||
);
|
||||
});
|
||||
tx(records);
|
||||
|
||||
if (this.jsonPath) {
|
||||
const data = this.readJson();
|
||||
const merged = { ...data.events };
|
||||
for (const record of records) merged[record.id] = record.observedAt;
|
||||
const entries = Object.entries(merged)
|
||||
.sort((a, b) => a[1] - b[1])
|
||||
.slice(-MAX_EVENTS);
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
`${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`,
|
||||
{ mode: 0o600 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user