Files
seal-use/src/domains/seal/rule-version-snapshot.ts
T

145 lines
5.0 KiB
TypeScript

import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { formatBeijingIso } from "../../core/config/timestamps.js";
import { SEAL_STATE_DIR } from "../../core/paths.js";
import type { ApprovalRule, RuleSetVersion } from "./types.js";
export const MAX_RETAINED_RULE_SNAPSHOTS = 20;
export type PersistedRuleIdentity = {
stableId: string;
code?: string | number;
description: string;
scope: string;
strictness: string;
};
export type PersistedRuleVersionSnapshot = {
corpId: string;
versionId: string;
versionNumber: number;
capturedAt: string;
rules: PersistedRuleIdentity[];
};
function normalizeCode(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined;
const raw = String(value).trim().toLowerCase().replace(/^rule[-_:]?/, "").replace(/^#/, "");
if (!raw) return undefined;
return /^\d+$/.test(raw) ? String(Number(raw)) : raw;
}
function signature(rule: { description?: string; scope?: string; strictness?: string }): string {
return JSON.stringify([rule.description ?? "", rule.scope ?? "", rule.strictness ?? ""]);
}
export function getRuleVersionSnapshotsDir(): string {
return process.env.SEAL_USE_RULE_VERSION_SNAPSHOTS_DIR?.trim() ||
join(SEAL_STATE_DIR, "snapshots");
}
function safeCorpId(corpId: string): string {
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
function snapshotPath(corpId: string, versionNumber: number): string {
return join(getRuleVersionSnapshotsDir(), `${safeCorpId(corpId)}-v${versionNumber}.json`);
}
export function savePublishedRuleVersionSnapshot(
corpId: string,
version: RuleSetVersion,
draftRules: ApprovalRule[]
): string {
const byCode = new Map<string, ApprovalRule[]>();
const bySignature = new Map<string, ApprovalRule[]>();
for (const draft of draftRules) {
const code = normalizeCode(draft.code);
if (code) byCode.set(code, [...(byCode.get(code) ?? []), draft]);
const key = signature(draft);
bySignature.set(key, [...(bySignature.get(key) ?? []), draft]);
}
const rules: PersistedRuleIdentity[] = [];
for (const published of version.rules ?? []) {
const code = normalizeCode(published.code);
const codeMatches = code ? byCode.get(code) ?? [] : [];
const signatureMatches = bySignature.get(signature(published)) ?? [];
const match = codeMatches.length === 1 ? codeMatches[0] : signatureMatches.length === 1 ? signatureMatches[0] : undefined;
if (!match) continue;
rules.push({
stableId: match.id,
...(published.code !== undefined ? { code: published.code } : {}),
description: published.description,
scope: published.scope,
strictness: published.strictness
});
}
const snapshot: PersistedRuleVersionSnapshot = {
corpId,
versionId: version.id,
versionNumber: version.versionNumber,
capturedAt: formatBeijingIso(),
rules
};
const dir = getRuleVersionSnapshotsDir();
mkdirSync(dir, { recursive: true, mode: 0o700 });
const path = snapshotPath(corpId, version.versionNumber);
const temp = `${path}.${process.pid}.tmp`;
writeFileSync(temp, `${JSON.stringify(snapshot, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
renameSync(temp, path);
try {
const files = readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
.map((entry) => {
const fullPath = join(dir, entry.name);
return { path: fullPath, mtimeMs: statSync(fullPath).mtimeMs };
})
.sort((a, b) => b.mtimeMs - a.mtimeMs);
if (files.length > MAX_RETAINED_RULE_SNAPSHOTS) {
for (const extra of files.slice(MAX_RETAINED_RULE_SNAPSHOTS)) {
unlinkSync(extra.path);
}
}
} catch {
// Non-fatal if LRU pruning fails
}
return path;
}
export function loadPublishedRuleVersionSnapshot(
corpId: string,
version: Pick<RuleSetVersion, "versionNumber">
): PersistedRuleVersionSnapshot | null {
const path = snapshotPath(corpId, version.versionNumber);
if (!existsSync(path)) return null;
try {
return JSON.parse(readFileSync(path, "utf8")) as PersistedRuleVersionSnapshot;
} catch {
return null;
}
}
export function hydrateRuleVersionStableIds(corpId: string, version: RuleSetVersion): RuleSetVersion {
const snapshot = loadPublishedRuleVersionSnapshot(corpId, version);
if (!snapshot?.rules.length) return version;
const byCode = new Map(snapshot.rules.flatMap((rule) => {
const code = normalizeCode(rule.code);
return code ? [[code, rule] as const] : [];
}));
const bySignature = new Map(snapshot.rules.map((rule) => [signature(rule), rule]));
return {
...version,
rules: version.rules.map((rule) => {
if (rule.id !== undefined || rule.ruleId !== undefined || rule.stableId !== undefined) return rule;
const match = (normalizeCode(rule.code) ? byCode.get(normalizeCode(rule.code)!) : undefined) ?? bySignature.get(signature(rule));
return match ? { ...rule, stableId: match.stableId } : rule;
})
};
}