Files
hose-use/src/domains/platform/workflow/alert/index.ts
T
gitea cedc4249e5 test(workflow): 补齐条件比较符、节点类型与错误指纹的测试覆盖
- 新增 branch/evaluate-rule.test.ts:覆盖 eq/neq、empty/not_empty、in/not_in、
  include/not_include、gt/gte/lt/lte 全部比较符,含无法确定(返回 null)的边界,
  以及 @{value(...)} / @{choose(...)} 描述符解析。此前只有 eq 与 gt 有用例。
- 新增未知节点类型与权限证据边界用例:UNKNOWN_TASK_TYPE 硬软门禁、
  以及拿不到开通清单(availableNodeTypes 为空)时既不谎报通过也不误报缺失。

错误指纹:
- alert observe() 原先在 SQLite 事务提交后直接 writeFileSync,
  落盘失败会把整轮巡检打成失败;而此刻指纹其实已经写入,
  下一轮会被当成「未观察过」从而重复提醒。改为捕获异常并以 exportError 返回,
  SQLite 仍作为唯一事实来源。
- 新增 alert/index.test.ts,并把原先写在 state/index.test.ts 里的告警用例迁移回来,
  修正模块归属错位。

覆盖 1004 个用例,`bun run check` 无错误。
2026-11-01 22:09:18 +08:00

146 lines
4.5 KiB
TypeScript

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<string, { errorCount: number; lastSeen: number }>;
}
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<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[], 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 } : {}) };
}
}