Files
pulsenode/lib/config/effective.ts
T

78 lines
2.3 KiB
TypeScript
Raw Permalink Normal View History

import { configStore } from "./loader";
import { discoverDockerWidgets } from "@/lib/discovery/traefik-labels";
import type { Config, Widget } from "./schema";
const DISCOVERY_INTERVAL_MS = 60_000;
type Listener = (config: Config) => void;
function mergeDiscovered(config: Config, discovered: Widget[]): Config {
if (discovered.length === 0) return config;
return { ...config, groups: [...config.groups, { name: "Discovered", widgets: discovered }] };
}
function discoveredKey(widget: Widget): string {
return widget.type === "docker" || widget.type === "database" ? widget.containerName : "";
}
function sameDiscoveredSet(a: Widget[], b: Widget[]): boolean {
if (a.length !== b.length) return false;
const setA = new Set(a.map(discoveredKey));
return b.every((widget) => setA.has(discoveredKey(widget)));
}
class EffectiveConfigStore {
private discovered: Widget[] = [];
private timer: ReturnType<typeof setInterval> | null = null;
private readonly listeners = new Set<Listener>();
get(): Config {
return mergeDiscovered(configStore.get(), this.discovered);
}
onUpdate(listener: Listener): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
async start(): Promise<void> {
configStore.onUpdate(() => {
this.emit();
void this.scan();
});
await this.scan();
this.timer = setInterval(() => void this.scan(), DISCOVERY_INTERVAL_MS);
}
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
private async scan(): Promise<void> {
try {
const next = await discoverDockerWidgets(configStore.get());
if (!sameDiscoveredSet(this.discovered, next)) {
this.discovered = next;
this.emit();
}
} catch (err) {
console.error(`[discovery] ${(err as Error).message}`);
}
}
private emit(): void {
const effective = this.get();
for (const listener of this.listeners) listener(effective);
}
}
// See lib/config/loader.ts for why this is keyed off globalThis rather than
// exported as a plain module singleton.
declare global {
var __pulsenodeEffectiveConfigStore: EffectiveConfigStore | undefined;
}
export const effectiveConfigStore = globalThis.__pulsenodeEffectiveConfigStore ?? new EffectiveConfigStore();
globalThis.__pulsenodeEffectiveConfigStore = effectiveConfigStore;