Adds the remaining monitor types: a systeminformation-backed system widget (single-flight cached so multiple widgets don't force concurrent samples), an http widget with per-widget consecutive- failure tracking, and a traefik widget that reads router/entrypoint/ middleware status from Traefik's own API. Also adds opt-in label-based docker auto-discovery (discovery.docker in config.yml): containers carrying traefik.enable=true are turned into docker widgets in a synthetic "Discovered" group, re-scanned on a timer and whenever config.yml changes, with manual widgets always taking precedence over a discovered one for the same container. Fixes a real bug surfaced while testing discovery: Next's App Router bundles app/** through its own compiler pass, separate from server.ts (run directly via tsx), so configStore/effectiveConfigStore were silently instantiated twice - one instance watched and updated by server.ts, another frozen instance read by SSR. Live config edits were never reflected on page load without a full process restart. Both stores now key their singleton off globalThis, which both module graphs share within the same process. Verified against a real Traefik v3 container (API-driven router list, ping-based http check) and a labeled nginx container (auto-discovery), including that a config.yml edit now shows up in a fresh page load without restarting the server, in both dev and the production build.
121 lines
3.7 KiB
TypeScript
121 lines
3.7 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";
|
|
|
|
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");
|
|
|
|
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();
|
|
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", () => this.reload());
|
|
}
|
|
|
|
stop(): void {
|
|
this.watcher?.close();
|
|
this.watcher = null;
|
|
}
|
|
|
|
private reload(): void {
|
|
try {
|
|
const next = readConfig();
|
|
this.current = next;
|
|
for (const listener of this.listeners) listener(next);
|
|
} catch (err) {
|
|
const configError = err instanceof ConfigError ? err : new ConfigError((err as Error).message);
|
|
console.error(`[config] ${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;
|