feat(config): implement ConfigManager with atomic writes, chokidar hot-reload, isolated fallback, presets, and revisions
This commit is contained in:
parent
05abda3417
commit
6520b81d82
3 changed files with 1335 additions and 0 deletions
906
src/server/config/config-manager.ts
Normal file
906
src/server/config/config-manager.ts
Normal file
|
|
@ -0,0 +1,906 @@
|
|||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type Database from 'better-sqlite3';
|
||||
import chokidar, { type FSWatcher } from 'chokidar';
|
||||
import type { ZodError, ZodSchema } from 'zod';
|
||||
import {
|
||||
AlertsFileSchema,
|
||||
ServerConfigSchema,
|
||||
SettingsSchema,
|
||||
SnippetsFileSchema,
|
||||
SystemConfigSchema,
|
||||
WorkflowConfigSchema,
|
||||
type AlertsFile,
|
||||
type ServerConfig,
|
||||
type SettingsConfig,
|
||||
type SnippetsFile,
|
||||
type SystemConfig,
|
||||
type WorkflowConfig,
|
||||
} from '../../shared/schemas/index.js';
|
||||
import type { ConfigError, ConfigWarning } from '../../shared/ws-protocol.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import { computeLineDiff, type DiffResult } from './diff.js';
|
||||
import { seedDefaultConfigs } from './presets.js';
|
||||
|
||||
export type ConfigEntityType =
|
||||
| 'server'
|
||||
| 'system'
|
||||
| 'workflow'
|
||||
| 'snippets'
|
||||
| 'alerts'
|
||||
| 'settings';
|
||||
|
||||
export type RevisionSource = 'seed' | 'ui' | 'disk' | 'rollback';
|
||||
|
||||
export interface ConfigRevisionRecord {
|
||||
id: number;
|
||||
filePath: string;
|
||||
sha256: string;
|
||||
source: string;
|
||||
summary: string | null;
|
||||
content: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface ConfigChangeEvent {
|
||||
entityType: ConfigEntityType | 'all';
|
||||
id?: string;
|
||||
relPath: string;
|
||||
warnings: ConfigWarning[];
|
||||
errors: ConfigError[];
|
||||
}
|
||||
|
||||
interface ParsedTarget {
|
||||
relPath: string;
|
||||
entityType: ConfigEntityType;
|
||||
expectedId?: string;
|
||||
schema: ZodSchema<unknown>;
|
||||
}
|
||||
|
||||
const SINGLETON_TARGETS: Record<string, { entityType: ConfigEntityType; schema: ZodSchema<unknown> }> = {
|
||||
'settings.json': { entityType: 'settings', schema: SettingsSchema },
|
||||
'alerts.json': { entityType: 'alerts', schema: AlertsFileSchema },
|
||||
'snippets.json': { entityType: 'snippets', schema: SnippetsFileSchema },
|
||||
};
|
||||
|
||||
const COLLECTION_TARGETS: Record<string, { entityType: ConfigEntityType; schema: ZodSchema<unknown> }> = {
|
||||
servers: { entityType: 'server', schema: ServerConfigSchema },
|
||||
systems: { entityType: 'system', schema: SystemConfigSchema },
|
||||
workflows: { entityType: 'workflow', schema: WorkflowConfigSchema },
|
||||
};
|
||||
|
||||
function sha256Text(text: string): string {
|
||||
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
function formatZodIssues(err: ZodError): Array<{ path: string; message: string }> {
|
||||
return err.issues.map((issue) => ({
|
||||
path: issue.path.join('.') || '(root)',
|
||||
message: issue.message,
|
||||
}));
|
||||
}
|
||||
|
||||
export class ConfigManager {
|
||||
private servers = new Map<string, ServerConfig>();
|
||||
private systems = new Map<string, SystemConfig>();
|
||||
private workflows = new Map<string, WorkflowConfig>();
|
||||
private snippets: SnippetsFile = SnippetsFileSchema.parse({});
|
||||
private alerts: AlertsFile = AlertsFileSchema.parse({});
|
||||
private settings: SettingsConfig = SettingsSchema.parse({});
|
||||
|
||||
private errors = new Map<string, ConfigError>();
|
||||
private warnings: ConfigWarning[] = [];
|
||||
private knownFiles = new Set<string>();
|
||||
|
||||
private watcher: FSWatcher | null = null;
|
||||
private readonly debounceTimers = new Map<string, NodeJS.Timeout>();
|
||||
private readonly recentSelfWrites = new Map<string, { sha256: string; ts: number }>();
|
||||
private readonly changeListeners = new Set<(event: ConfigChangeEvent) => void>();
|
||||
|
||||
constructor(
|
||||
private readonly configDir: string,
|
||||
private readonly db: Database.Database,
|
||||
private readonly vault?: VaultService,
|
||||
) {}
|
||||
|
||||
async init(options: { watch?: boolean } = {}): Promise<void> {
|
||||
const seeded = seedDefaultConfigs(this.configDir);
|
||||
const seededSet = new Set(seeded);
|
||||
|
||||
const files = this.discoverAllConfigPaths();
|
||||
for (const relPath of files) {
|
||||
this.knownFiles.add(relPath);
|
||||
this.loadFileFromDisk(relPath, seededSet.has(relPath) ? 'seed' : 'disk', false);
|
||||
}
|
||||
|
||||
this.recomputeWarnings();
|
||||
|
||||
if (options.watch !== false) {
|
||||
this.startWatcher();
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
for (const timer of this.debounceTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.debounceTimers.clear();
|
||||
|
||||
if (this.watcher) {
|
||||
await this.watcher.close();
|
||||
this.watcher = null;
|
||||
}
|
||||
}
|
||||
|
||||
onChange(listener: (event: ConfigChangeEvent) => void): () => void {
|
||||
this.changeListeners.add(listener);
|
||||
return () => {
|
||||
this.changeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
getSettings(): SettingsConfig {
|
||||
return structuredClone(this.settings);
|
||||
}
|
||||
|
||||
getAlerts(): AlertsFile {
|
||||
return structuredClone(this.alerts);
|
||||
}
|
||||
|
||||
getSnippets(): SnippetsFile {
|
||||
return structuredClone(this.snippets);
|
||||
}
|
||||
|
||||
listServers(): ServerConfig[] {
|
||||
return [...this.servers.values()].map((s) => structuredClone(s));
|
||||
}
|
||||
|
||||
getServer(id: string): ServerConfig | undefined {
|
||||
const s = this.servers.get(id);
|
||||
return s ? structuredClone(s) : undefined;
|
||||
}
|
||||
|
||||
listSystems(): SystemConfig[] {
|
||||
return [...this.systems.values()].map((s) => structuredClone(s));
|
||||
}
|
||||
|
||||
getSystem(id: string): SystemConfig | undefined {
|
||||
const s = this.systems.get(id);
|
||||
return s ? structuredClone(s) : undefined;
|
||||
}
|
||||
|
||||
listWorkflows(): WorkflowConfig[] {
|
||||
return [...this.workflows.values()].map((w) => structuredClone(w));
|
||||
}
|
||||
|
||||
getWorkflow(id: string): WorkflowConfig | undefined {
|
||||
const w = this.workflows.get(id);
|
||||
return w ? structuredClone(w) : undefined;
|
||||
}
|
||||
|
||||
getDiagnostics(): { warnings: ConfigWarning[]; errors: ConfigError[] } {
|
||||
return {
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
};
|
||||
}
|
||||
|
||||
recomputeWarnings(): ConfigWarning[] {
|
||||
const next: ConfigWarning[] = [];
|
||||
|
||||
// 1. Server cross-references & jumpHost cycles
|
||||
for (const server of this.servers.values()) {
|
||||
const relPath = `servers/${server.id}.json`;
|
||||
|
||||
if (this.vault && this.vault.state === 'unlocked') {
|
||||
if (!this.vault.hasCredential(server.credentialId)) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_CREDENTIAL',
|
||||
message: `credentialId "${server.credentialId}" does not exist in Vault.`,
|
||||
});
|
||||
}
|
||||
if (server.sudoCredentialId && !this.vault.hasCredential(server.sudoCredentialId)) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_SUDO_CREDENTIAL',
|
||||
message: `sudoCredentialId "${server.sudoCredentialId}" does not exist in Vault.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (server.jumpHostId) {
|
||||
if (!this.servers.has(server.jumpHostId)) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_JUMP_HOST',
|
||||
message: `jumpHostId "${server.jumpHostId}" does not match any server config.`,
|
||||
});
|
||||
} else {
|
||||
// Cycle detection along jumpHost chain
|
||||
const visited = new Set<string>([server.id]);
|
||||
let cursor: string | undefined = server.jumpHostId;
|
||||
while (cursor) {
|
||||
if (visited.has(cursor)) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'JUMP_HOST_CYCLE',
|
||||
message: `jumpHostId chain forms a cycle involving "${cursor}".`,
|
||||
});
|
||||
break;
|
||||
}
|
||||
visited.add(cursor);
|
||||
cursor = this.servers.get(cursor)?.jumpHostId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const sysAttachment of server.systems) {
|
||||
if (!this.systems.has(sysAttachment.systemId)) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_SYSTEM',
|
||||
message: `Attached system "${sysAttachment.systemId}" is not defined in systems/.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Workflow cross-references
|
||||
for (const wf of this.workflows.values()) {
|
||||
const relPath = `workflows/${wf.id}.json`;
|
||||
for (const step of wf.steps) {
|
||||
if (step.type === 'system-action' && !this.systems.has(step.systemId)) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_SYSTEM',
|
||||
message: `Step "${step.id}" references missing system "${step.systemId}".`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
(step.type === 'exec' || step.type === 'read-file' || step.type === 'system-action') &&
|
||||
step.target.serverId &&
|
||||
!step.target.serverId.includes('{{') &&
|
||||
!this.servers.has(step.target.serverId)
|
||||
) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_SERVER',
|
||||
message: `Step "${step.id}" targets unknown server "${step.target.serverId}".`,
|
||||
});
|
||||
}
|
||||
if (step.type === 'transfer') {
|
||||
if (
|
||||
!step.source.serverId.includes('{{') &&
|
||||
!this.servers.has(step.source.serverId)
|
||||
) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_SERVER',
|
||||
message: `Transfer step "${step.id}" references unknown source server "${step.source.serverId}".`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
!step.destination.serverId.includes('{{') &&
|
||||
!this.servers.has(step.destination.serverId)
|
||||
) {
|
||||
next.push({
|
||||
filePath: relPath,
|
||||
code: 'MISSING_SERVER',
|
||||
message: `Transfer step "${step.id}" references unknown destination server "${step.destination.serverId}".`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Alerts cross-references
|
||||
const channelIds = new Set(this.alerts.channels.map((c) => c.id));
|
||||
if (this.vault && this.vault.state === 'unlocked') {
|
||||
for (const ch of this.alerts.channels) {
|
||||
if (!this.vault.hasCredential(ch.secretRef)) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'MISSING_CHANNEL_SECRET',
|
||||
message: `Alert channel "${ch.id}" references missing vault secret "${ch.secretRef}".`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (this.settings.ai.secretRef && !this.vault.hasCredential(this.settings.ai.secretRef)) {
|
||||
next.push({
|
||||
filePath: 'settings.json',
|
||||
code: 'MISSING_AI_SECRET',
|
||||
message: `AI secretRef "${this.settings.ai.secretRef}" does not exist in Vault.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const rule of this.alerts.rules) {
|
||||
for (const cid of rule.channelIds) {
|
||||
if (!channelIds.has(cid)) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'MISSING_ALERT_CHANNEL',
|
||||
message: `Rule "${rule.id}" references unknown channel "${cid}".`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rule.remediationWorkflowId && !this.workflows.has(rule.remediationWorkflowId)) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'MISSING_WORKFLOW',
|
||||
message: `Rule "${rule.id}" references missing remediationWorkflowId "${rule.remediationWorkflowId}".`,
|
||||
});
|
||||
}
|
||||
if (rule.target.serverId && !this.servers.has(rule.target.serverId)) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'MISSING_SERVER',
|
||||
message: `Rule "${rule.id}" targets unknown server "${rule.target.serverId}".`,
|
||||
});
|
||||
}
|
||||
if (rule.kind === 'system' && !this.systems.has(rule.systemId)) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'MISSING_SYSTEM',
|
||||
message: `Rule "${rule.id}" references missing system "${rule.systemId}".`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
this.warnings = next;
|
||||
return structuredClone(this.warnings);
|
||||
}
|
||||
|
||||
listFiles(): Array<{
|
||||
filePath: string;
|
||||
entityType: ConfigEntityType;
|
||||
id?: string;
|
||||
hasError: boolean;
|
||||
warningCount: number;
|
||||
}> {
|
||||
const allPaths = new Set(this.knownFiles);
|
||||
for (const p of this.discoverAllConfigPaths()) allPaths.add(p);
|
||||
|
||||
const out: Array<{
|
||||
filePath: string;
|
||||
entityType: ConfigEntityType;
|
||||
id?: string;
|
||||
hasError: boolean;
|
||||
warningCount: number;
|
||||
}> = [];
|
||||
|
||||
for (const relPath of [...allPaths].sort()) {
|
||||
const target = this.resolveTarget(relPath);
|
||||
if (!target) continue;
|
||||
out.push({
|
||||
filePath: relPath,
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
hasError: this.errors.has(relPath),
|
||||
warningCount: this.warnings.filter((w) => w.filePath === relPath).length,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
readRawFile(relPathInput: string): {
|
||||
filePath: string;
|
||||
entityType: ConfigEntityType;
|
||||
rawContent: string;
|
||||
activeConfig: unknown;
|
||||
error: ConfigError | null;
|
||||
warnings: ConfigWarning[];
|
||||
} {
|
||||
const target = this.resolveTargetStrict(relPathInput);
|
||||
const absPath = this.resolveSafeAbsPath(target.relPath);
|
||||
if (!fs.existsSync(absPath)) {
|
||||
throw new Error(`Config file not found: ${target.relPath}`);
|
||||
}
|
||||
const rawContent = fs.readFileSync(absPath, 'utf8');
|
||||
return {
|
||||
filePath: target.relPath,
|
||||
entityType: target.entityType,
|
||||
rawContent,
|
||||
activeConfig: this.getActiveEntity(target),
|
||||
error: this.errors.get(target.relPath) ?? null,
|
||||
warnings: this.warnings.filter((w) => w.filePath === target.relPath),
|
||||
};
|
||||
}
|
||||
|
||||
saveConfigText(
|
||||
relPathInput: string,
|
||||
rawJsonText: string,
|
||||
source: RevisionSource = 'ui',
|
||||
summary?: string,
|
||||
): {
|
||||
filePath: string;
|
||||
entityType: ConfigEntityType;
|
||||
id?: string;
|
||||
config: unknown;
|
||||
warnings: ConfigWarning[];
|
||||
} {
|
||||
const target = this.resolveTargetStrict(relPathInput);
|
||||
const validated = this.parseAndValidate(target, rawJsonText);
|
||||
const formatted = `${JSON.stringify(validated, null, 2)}\n`;
|
||||
const absPath = this.resolveSafeAbsPath(target.relPath);
|
||||
const hash = sha256Text(formatted);
|
||||
|
||||
this.recentSelfWrites.set(target.relPath, { sha256: hash, ts: Date.now() });
|
||||
this.writeAtomicFile(absPath, formatted);
|
||||
|
||||
this.knownFiles.add(target.relPath);
|
||||
this.errors.delete(target.relPath);
|
||||
this.storeActiveEntity(target, validated);
|
||||
this.recordRevision(target.relPath, formatted, hash, source, summary);
|
||||
this.recomputeWarnings();
|
||||
|
||||
const event: ConfigChangeEvent = {
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
relPath: target.relPath,
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
};
|
||||
this.emitChange(event);
|
||||
|
||||
return {
|
||||
filePath: target.relPath,
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
config: structuredClone(validated),
|
||||
warnings: this.warnings.filter((w) => w.filePath === target.relPath),
|
||||
};
|
||||
}
|
||||
|
||||
deleteEntityFile(relPathInput: string): boolean {
|
||||
const target = this.resolveTargetStrict(relPathInput);
|
||||
if (!target.expectedId) {
|
||||
throw new Error(`Cannot delete singleton config file: ${target.relPath}`);
|
||||
}
|
||||
const absPath = this.resolveSafeAbsPath(target.relPath);
|
||||
if (!fs.existsSync(absPath)) return false;
|
||||
|
||||
this.recentSelfWrites.set(target.relPath, { sha256: '__deleted__', ts: Date.now() });
|
||||
fs.unlinkSync(absPath);
|
||||
|
||||
this.removeActiveEntity(target);
|
||||
this.errors.delete(target.relPath);
|
||||
this.knownFiles.delete(target.relPath);
|
||||
this.recomputeWarnings();
|
||||
|
||||
this.emitChange({
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
relPath: target.relPath,
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
listRevisions(relPathInput: string, limit = 50): ConfigRevisionRecord[] {
|
||||
const target = this.resolveTargetStrict(relPathInput);
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT id, file_path AS filePath, sha256, source, summary, content, created_at AS createdAt
|
||||
FROM config_revisions
|
||||
WHERE file_path = ?
|
||||
ORDER BY id DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(target.relPath, Math.max(1, Math.min(200, limit))) as ConfigRevisionRecord[];
|
||||
return rows;
|
||||
}
|
||||
|
||||
getRevision(revisionId: number): ConfigRevisionRecord | undefined {
|
||||
const row = this.db
|
||||
.prepare(
|
||||
`SELECT id, file_path AS filePath, sha256, source, summary, content, created_at AS createdAt
|
||||
FROM config_revisions
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.get(revisionId) as ConfigRevisionRecord | undefined;
|
||||
return row;
|
||||
}
|
||||
|
||||
diffRevision(revisionId: number): {
|
||||
revision: ConfigRevisionRecord;
|
||||
currentContent: string;
|
||||
diff: DiffResult;
|
||||
} {
|
||||
const rev = this.getRevision(revisionId);
|
||||
if (!rev) {
|
||||
throw new Error(`Revision #${revisionId} not found`);
|
||||
}
|
||||
const target = this.resolveTargetStrict(rev.filePath);
|
||||
const absPath = this.resolveSafeAbsPath(target.relPath);
|
||||
const currentContent = fs.existsSync(absPath)
|
||||
? fs.readFileSync(absPath, 'utf8')
|
||||
: '';
|
||||
const diff = computeLineDiff(
|
||||
rev.content,
|
||||
currentContent,
|
||||
`revision#${rev.id} (${rev.source})`,
|
||||
`current (${rev.filePath})`,
|
||||
);
|
||||
return { revision: rev, currentContent, diff };
|
||||
}
|
||||
|
||||
rollbackRevision(revisionId: number): {
|
||||
filePath: string;
|
||||
entityType: ConfigEntityType;
|
||||
id?: string;
|
||||
config: unknown;
|
||||
warnings: ConfigWarning[];
|
||||
} {
|
||||
const rev = this.getRevision(revisionId);
|
||||
if (!rev) {
|
||||
throw new Error(`Revision #${revisionId} not found`);
|
||||
}
|
||||
return this.saveConfigText(
|
||||
rev.filePath,
|
||||
rev.content,
|
||||
'rollback',
|
||||
`Rollback to revision #${rev.id}`,
|
||||
);
|
||||
}
|
||||
|
||||
private startWatcher(): void {
|
||||
this.watcher = chokidar.watch(this.configDir, {
|
||||
ignoreInitial: true,
|
||||
persistent: true,
|
||||
depth: 2,
|
||||
});
|
||||
|
||||
const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => {
|
||||
if (!absPath.endsWith('.json')) return;
|
||||
const relRaw = path.relative(this.configDir, absPath).split(path.sep).join('/');
|
||||
if (relRaw.includes('.tmp')) return;
|
||||
if (!this.resolveTarget(relRaw)) return;
|
||||
|
||||
const prev = this.debounceTimers.get(relRaw);
|
||||
if (prev) clearTimeout(prev);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this.debounceTimers.delete(relRaw);
|
||||
if (kind === 'unlink') {
|
||||
this.handleExternalUnlink(relRaw);
|
||||
} else {
|
||||
this.handleExternalUpsert(relRaw);
|
||||
}
|
||||
}, 300);
|
||||
this.debounceTimers.set(relRaw, timer);
|
||||
};
|
||||
|
||||
this.watcher.on('add', (p) => scheduleReload(p, 'upsert'));
|
||||
this.watcher.on('change', (p) => scheduleReload(p, 'upsert'));
|
||||
this.watcher.on('unlink', (p) => scheduleReload(p, 'unlink'));
|
||||
}
|
||||
|
||||
private handleExternalUpsert(relPath: string): void {
|
||||
const target = this.resolveTarget(relPath);
|
||||
if (!target) return;
|
||||
|
||||
const absPath = this.resolveSafeAbsPath(relPath);
|
||||
if (!fs.existsSync(absPath)) return;
|
||||
const rawText = fs.readFileSync(absPath, 'utf8');
|
||||
const hash = sha256Text(rawText);
|
||||
|
||||
const selfWrite = this.recentSelfWrites.get(relPath);
|
||||
if (selfWrite && selfWrite.sha256 === hash && Date.now() - selfWrite.ts < 5000) {
|
||||
this.recentSelfWrites.delete(relPath);
|
||||
return;
|
||||
}
|
||||
|
||||
this.knownFiles.add(relPath);
|
||||
this.loadFileFromDisk(relPath, 'disk', true);
|
||||
}
|
||||
|
||||
private handleExternalUnlink(relPath: string): void {
|
||||
const target = this.resolveTarget(relPath);
|
||||
if (!target) return;
|
||||
|
||||
const selfWrite = this.recentSelfWrites.get(relPath);
|
||||
if (
|
||||
selfWrite &&
|
||||
selfWrite.sha256 === '__deleted__' &&
|
||||
Date.now() - selfWrite.ts < 5000
|
||||
) {
|
||||
this.recentSelfWrites.delete(relPath);
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.expectedId) {
|
||||
this.removeActiveEntity(target);
|
||||
this.errors.delete(relPath);
|
||||
this.knownFiles.delete(relPath);
|
||||
this.recomputeWarnings();
|
||||
this.emitChange({
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
relPath,
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
});
|
||||
} else {
|
||||
this.errors.set(relPath, {
|
||||
filePath: relPath,
|
||||
message: `Required config file ${relPath} was deleted on disk; retaining last valid configuration in memory.`,
|
||||
});
|
||||
this.emitChange({
|
||||
entityType: target.entityType,
|
||||
relPath,
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private loadFileFromDisk(
|
||||
relPath: string,
|
||||
source: RevisionSource,
|
||||
emitOnResult: boolean,
|
||||
): void {
|
||||
const target = this.resolveTarget(relPath);
|
||||
if (!target) return;
|
||||
const absPath = this.resolveSafeAbsPath(relPath);
|
||||
|
||||
let rawText: string;
|
||||
try {
|
||||
rawText = fs.readFileSync(absPath, 'utf8');
|
||||
} catch (err) {
|
||||
this.errors.set(relPath, {
|
||||
filePath: relPath,
|
||||
message: err instanceof Error ? err.message : 'Unable to read config file',
|
||||
});
|
||||
if (emitOnResult) {
|
||||
this.emitChange({
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
relPath,
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const validated = this.parseAndValidate(target, rawText);
|
||||
this.errors.delete(relPath);
|
||||
this.storeActiveEntity(target, validated);
|
||||
const formatted = `${JSON.stringify(validated, null, 2)}\n`;
|
||||
this.recordRevision(relPath, formatted, sha256Text(formatted), source);
|
||||
this.recomputeWarnings();
|
||||
} catch (err) {
|
||||
// Isolated fallback: preserve previous valid entity in memory; only flag this file
|
||||
if (err instanceof Error && 'issues' in err) {
|
||||
const zodErr = err as ZodError;
|
||||
this.errors.set(relPath, {
|
||||
filePath: relPath,
|
||||
message: 'Schema validation failed; retaining last valid config in memory.',
|
||||
issues: formatZodIssues(zodErr),
|
||||
});
|
||||
} else {
|
||||
this.errors.set(relPath, {
|
||||
filePath: relPath,
|
||||
message: `${err instanceof Error ? err.message : String(err)}; retaining last valid config in memory.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (emitOnResult) {
|
||||
this.emitChange({
|
||||
entityType: target.entityType,
|
||||
id: target.expectedId,
|
||||
relPath,
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private parseAndValidate(target: ParsedTarget, rawJsonText: string): unknown {
|
||||
const rawObj = JSON.parse(rawJsonText);
|
||||
const parsed = target.schema.parse(rawObj);
|
||||
|
||||
if (target.expectedId) {
|
||||
const id = (parsed as { id?: string }).id;
|
||||
if (id !== target.expectedId) {
|
||||
throw new Error(
|
||||
`Filename "${target.relPath}" expects id "${target.expectedId}", got "${String(id)}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private resolveTarget(relPathInput: string): ParsedTarget | null {
|
||||
const normalized = relPathInput.replace(/\\/g, '/').replace(/^\/+/, '');
|
||||
if (!normalized || normalized.includes('..')) return null;
|
||||
|
||||
const singleton = SINGLETON_TARGETS[normalized];
|
||||
if (singleton) {
|
||||
return {
|
||||
relPath: normalized,
|
||||
entityType: singleton.entityType,
|
||||
schema: singleton.schema,
|
||||
};
|
||||
}
|
||||
|
||||
const parts = normalized.split('/');
|
||||
if (parts.length !== 2) return null;
|
||||
const [folder, fileName] = parts;
|
||||
if (!folder || !fileName || !fileName.endsWith('.json')) return null;
|
||||
const collection = COLLECTION_TARGETS[folder];
|
||||
if (!collection) return null;
|
||||
|
||||
const expectedId = fileName.slice(0, -5);
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(expectedId)) return null;
|
||||
|
||||
return {
|
||||
relPath: `${folder}/${fileName}`,
|
||||
entityType: collection.entityType,
|
||||
expectedId,
|
||||
schema: collection.schema,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveTargetStrict(relPathInput: string): ParsedTarget {
|
||||
const target = this.resolveTarget(relPathInput);
|
||||
if (!target) {
|
||||
throw new Error(`Invalid config file path: ${relPathInput}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
private resolveSafeAbsPath(relPath: string): string {
|
||||
const resolved = path.resolve(this.configDir, relPath);
|
||||
const root = path.resolve(this.configDir);
|
||||
if (!resolved.startsWith(`${root}${path.sep}`)) {
|
||||
throw new Error(`Path escapes config directory: ${relPath}`);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private discoverAllConfigPaths(): string[] {
|
||||
const paths: string[] = [];
|
||||
for (const name of Object.keys(SINGLETON_TARGETS)) {
|
||||
if (fs.existsSync(path.join(this.configDir, name))) {
|
||||
paths.push(name);
|
||||
}
|
||||
}
|
||||
for (const folder of Object.keys(COLLECTION_TARGETS)) {
|
||||
const dir = path.join(this.configDir, folder);
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
if (!entry.endsWith('.json') || entry.includes('.tmp')) continue;
|
||||
const candidate = `${folder}/${entry}`;
|
||||
if (this.resolveTarget(candidate)) {
|
||||
paths.push(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
return paths.sort();
|
||||
}
|
||||
|
||||
private storeActiveEntity(target: ParsedTarget, value: unknown): void {
|
||||
switch (target.entityType) {
|
||||
case 'server':
|
||||
this.servers.set(target.expectedId!, value as ServerConfig);
|
||||
break;
|
||||
case 'system':
|
||||
this.systems.set(target.expectedId!, value as SystemConfig);
|
||||
break;
|
||||
case 'workflow':
|
||||
this.workflows.set(target.expectedId!, value as WorkflowConfig);
|
||||
break;
|
||||
case 'snippets':
|
||||
this.snippets = value as SnippetsFile;
|
||||
break;
|
||||
case 'alerts':
|
||||
this.alerts = value as AlertsFile;
|
||||
break;
|
||||
case 'settings':
|
||||
this.settings = value as SettingsConfig;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private removeActiveEntity(target: ParsedTarget): void {
|
||||
if (!target.expectedId) return;
|
||||
switch (target.entityType) {
|
||||
case 'server':
|
||||
this.servers.delete(target.expectedId);
|
||||
break;
|
||||
case 'system':
|
||||
this.systems.delete(target.expectedId);
|
||||
break;
|
||||
case 'workflow':
|
||||
this.workflows.delete(target.expectedId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private getActiveEntity(target: ParsedTarget): unknown {
|
||||
switch (target.entityType) {
|
||||
case 'server':
|
||||
return this.servers.get(target.expectedId!) ?? null;
|
||||
case 'system':
|
||||
return this.systems.get(target.expectedId!) ?? null;
|
||||
case 'workflow':
|
||||
return this.workflows.get(target.expectedId!) ?? null;
|
||||
case 'snippets':
|
||||
return this.snippets;
|
||||
case 'alerts':
|
||||
return this.alerts;
|
||||
case 'settings':
|
||||
return this.settings;
|
||||
}
|
||||
}
|
||||
|
||||
private writeAtomicFile(absPath: string, content: string): void {
|
||||
fs.mkdirSync(path.dirname(absPath), { recursive: true });
|
||||
const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, content, 'utf8');
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
fs.renameSync(tmpPath, absPath);
|
||||
}
|
||||
|
||||
private recordRevision(
|
||||
relPath: string,
|
||||
content: string,
|
||||
sha256: string,
|
||||
source: RevisionSource,
|
||||
summary?: string,
|
||||
): void {
|
||||
const latest = this.db
|
||||
.prepare(
|
||||
'SELECT sha256 FROM config_revisions WHERE file_path = ? ORDER BY id DESC LIMIT 1',
|
||||
)
|
||||
.get(relPath) as { sha256: string } | undefined;
|
||||
|
||||
if (latest && latest.sha256 === sha256) return;
|
||||
|
||||
const limit = this.settings.configRevisionLimit;
|
||||
const tx = this.db.transaction(() => {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO config_revisions (file_path, sha256, source, summary, content, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(relPath, sha256, source, summary ?? null, content, Date.now());
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
`DELETE FROM config_revisions
|
||||
WHERE file_path = ?
|
||||
AND id NOT IN (
|
||||
SELECT id FROM config_revisions
|
||||
WHERE file_path = ?
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
)`,
|
||||
)
|
||||
.run(relPath, relPath, limit);
|
||||
});
|
||||
tx();
|
||||
}
|
||||
|
||||
private emitChange(event: ConfigChangeEvent): void {
|
||||
for (const listener of this.changeListeners) {
|
||||
try {
|
||||
listener(event);
|
||||
} catch {
|
||||
// Isolate subscriber failures
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue