Files
pulsenode/lib/config/loader.ts
T
valknarandClaude Sonnet 5 7727ca8e97
CI / Static checks (push) Successful in 37s
CI / Build and push image (push) Skipped
feat: add structured backend logging
Collector failures, service-API errors, WS connection lifecycle, and
config reload/discovery events were previously invisible outside the
browser (or, for a few config/discovery cases, logged with an
inconsistent ad-hoc console.error). Add a small scoped logger
(lib/logger.ts, level via LOG_LEVEL) and wire it through server.ts,
the scheduler, service collector, config loader/effective store, and
the WS server so operators can see failures via `docker logs`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-19 09:39:30 +02:00

134 lines
4.2 KiB
TypeScript

import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import dotenv from "dotenv";
import chokidar, { type FSWatcher } from "chokidar";
import { parse as parseYaml } from "yaml";
import { configSchema, type Config } from "./schema";
import { interpolateEnv } from "./interpolate";
import { createLogger } from "@/lib/logger";
const log = createLogger("config");
const CONFIG_DIR = path.join(process.cwd(), "config");
const CONFIG_PATH = path.join(CONFIG_DIR, "config.yml");
const ENV_PATH = path.join(CONFIG_DIR, ".env");
function widgetCount(config: Config): number {
return config.groups.reduce((sum, group) => sum + group.widgets.length, 0);
}
export class ConfigError extends Error {}
function loadEnv(): Record<string, string | undefined> {
if (!existsSync(ENV_PATH)) return { ...process.env };
const parsed = dotenv.parse(readFileSync(ENV_PATH));
return { ...process.env, ...parsed };
}
export function readConfig(): Config {
if (!existsSync(CONFIG_PATH)) {
throw new ConfigError(`Config file not found at ${CONFIG_PATH}`);
}
const raw = readFileSync(CONFIG_PATH, "utf-8");
const env = loadEnv();
let interpolated: string;
try {
interpolated = interpolateEnv(raw, env);
} catch (err) {
throw new ConfigError((err as Error).message);
}
let parsedYaml: unknown;
try {
parsedYaml = parseYaml(interpolated);
} catch (err) {
throw new ConfigError(`Failed to parse config.yml: ${(err as Error).message}`);
}
const result = configSchema.safeParse(parsedYaml);
if (!result.success) {
const issues = result.error.issues
.map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`)
.join("\n");
throw new ConfigError(`config.yml failed validation:\n${issues}`);
}
return result.data;
}
type ConfigListener = (config: Config) => void;
type ConfigErrorListener = (error: ConfigError) => void;
class ConfigStore {
private current: Config | null = null;
private watcher: FSWatcher | null = null;
private readonly listeners = new Set<ConfigListener>();
private readonly errorListeners = new Set<ConfigErrorListener>();
load(): Config {
this.current = readConfig();
log.info("config loaded", { groups: this.current.groups.length, widgets: widgetCount(this.current) });
return this.current;
}
get(): Config {
return this.current ?? this.load();
}
onUpdate(listener: ConfigListener): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
onError(listener: ConfigErrorListener): () => void {
this.errorListeners.add(listener);
return () => this.errorListeners.delete(listener);
}
watch(): void {
if (this.watcher) return;
this.watcher = chokidar.watch([CONFIG_PATH, ENV_PATH], {
awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 },
ignoreInitial: true,
});
this.watcher.on("all", (event) => {
log.debug("watched file changed", { event });
this.reload();
});
log.info("watching config files", { paths: [CONFIG_PATH, ENV_PATH] });
}
stop(): void {
this.watcher?.close();
this.watcher = null;
}
private reload(): void {
try {
const next = readConfig();
this.current = next;
log.info("config reloaded", { groups: next.groups.length, widgets: widgetCount(next) });
for (const listener of this.listeners) listener(next);
} catch (err) {
const configError = err instanceof ConfigError ? err : new ConfigError((err as Error).message);
log.error("config reload failed", { error: configError.message });
for (const listener of this.errorListeners) listener(configError);
}
}
}
// Next.js bundles app/** through its own compiler pass, giving it a module
// registry separate from server.ts (loaded directly via tsx). A plain module
// singleton would end up duplicated - one instance watched by server.ts,
// another frozen instance used by SSR. Both still share the same Node
// process/heap, so keying off globalThis gives every module graph the same
// instance.
declare global {
var __pulsenodeConfigStore: ConfigStore | undefined;
}
export const configStore = globalThis.__pulsenodeConfigStore ?? new ConfigStore();
globalThis.__pulsenodeConfigStore = configStore;