All files / core/blong-gogo/src ConfigRuntime.ts

88.03% Statements 449/510
79.36% Branches 100/126
92.45% Functions 49/53
88.03% Lines 449/510

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 5111x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 875x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2762x 2762x 2762x 2762x 15x 15x 15x 15x 15x 15x 15x 15x 2762x 2762x 2762x 2762x 2762x 15x 15x 5108x 5108x 5108x 5670x       15x 15x 15x 15x 15x 15x 24091x 24091x 26853x 26853x 26853x 24091x 24091x 15x 15x 15x 15x 15x 4233x 683x 683x 683x 683x 13479x 13479x 839x                         4x 3859x 3859x 2868x 4x 683x 683x 668x 668x 683x 203x 203x 1957x 1957x   1957x 152x 152x 152x 152x 1957x 1788x 1788x 1788x 1788x 1788x 1289x 1349x 1349x 1349x 1349x 1349x   4439x 4439x 4439x 4439x 4439x   2884x 2884x 2884x 2884x           203x 99x 99x 99x 99x 99x 99x       99x 99x 203x 365x 365x 365x 365x 365x 365x 365x 365x 203x 203x 203x       203x   203x 203x 203x 203x 203x 203x 203x 203x 380x 380x 380x 74x 74x 380x 380x 59x     49x 49x 59x 44x 44x 44x 9x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 15x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 30x 30x 30x 30x                               23x 23x       50x 50x       3848x 3848x     33x 33x 33x 33x 7x 7x 33x 33x 7x 7x 7x 7x 7x 33x 7x 7x 7x 7x 7x 7x 7x 7x 30x 30x 30x 30x 30x 30x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x             1x 2x 2x 2x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 28x 28x 1x 1x 1x 1x 1x 25x 25x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 827x 827x 827x 827x 827x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 830x 7x 7x 7x 7x 3029x 3029x 3x 3x 3x 830x 830x 830x 830x 830x 830x 830x 830x 830x 830x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 189x 189x 189x 189x 189x 189x 189x 819x 819x 819x 4083x 4083x 4083x 4083x 819x 819x 189x 189x 189x 1x  
/**
 * ConfigRuntime — single authoritative owner of the full config lifecycle.
 *
 * Responsibilities:
 *  1. Load & merge configuration from all sources (blong-config)
 *  2. Expose the effective config through a stable, mutable-backing Proxy
 *  3. Diff old and new snapshots to compute which port namespaces changed
 *  4. Notify subscribers (adapter ports) and emit structured log events
 *  5. Provide a reload() entry-point that replaces the writeFileSync workaround
 *
 * Leaf-access rule:
 *   Adapter and handler code MUST read config values inside the handler/exec
 *   call (e.g. `this.config.db.host`), never at startup time into a closed-over
 *   variable (e.g. `const host = config.db.host` at module top-level).
 *   The proxy guarantees that reading a path always returns the latest value,
 *   but only when accessed through the proxy reference — not through a cached
 *   primitive.
 */
 
import loadBlong from '@feasibleone/blong-config';
import type {
    ConfigDiff,
    ConfigSubscriber,
    FactoryPhaseMode,
    IConfigRuntime,
    IConfigSources,
} from '@feasibleone/blong/types';
import merge from 'ut-function.merge';
 
// ---------------------------------------------------------------------------
// createConfigProxy
// ---------------------------------------------------------------------------
 
/**
 * Wraps `store` in a recursive Proxy so that property lookups always read from
 * the current value of `store`.  When `store` is replaced via `update()`, all
 * existing proxy references automatically see the new data because sub-proxies
 * are path-based views over the same root backing cell.
 *
 * IMPORTANT: the proxy is transparent — `typeof proxy`, `Array.isArray`, JSON
 * serialization, and property enumeration all behave as they would on the
 * underlying plain object.  This means existing code that treats `config` as a
 * plain object continues to work without modification.
 */
export function createConfigProxy<T extends object>(
    store: T,
    options: {
        /**
         * Called before every read, at every level of the proxy.
         *
         * A caller whose backing store has to be re-read from somewhere charges
         * the check here, so a node destructured once at startup (a handler's
         * `config.db`, say) refreshes on its own reads rather than only when the
         * root is touched.
         */
        beforeRead?: () => void;
    } = {},
): {
    proxy: T;
    update: (next: T) => void;
    enterConfig: (mode?: FactoryPhaseMode) => void;
    exitConfig: () => Error[];
} {
    // We keep a single mutable cell that holds the "current" backing object.
    // All proxy traps delegate through this cell so that replacing `current`
    // via update() is automatically reflected by every existing proxy reference.
    let current: T = store;
 
    // Cache sub-proxies by logical path so that reference equality is stable
    // between accesses, and proxies stay live across root updates because they
    // always re-traverse `current` on every property access.
    const subProxies = new Map<string, object>();
 
    // Unique numeric IDs for Symbol keys, so that different Symbols with the
    // same description do not collide in the path-key string.
    const symbolIds = new Map<symbol, number>();
    let symbolIdCounter = 0;
 
    // ---------------------------------------------------------------------------
    // Factory phase guard
    // ---------------------------------------------------------------------------
 
    const _factoryPhase: {active: boolean; mode: FactoryPhaseMode; errors: Error[]} = {
        active: false,
        mode: 'throw',
        errors: [],
    };
 
    /**
     * Mark the start of a handler factory call.  Any primitive value read from a
     * createConfigProxy proxy while the guard is active will either throw (mode =
     * 'throw', the default) or be recorded (mode = 'collect').
     *
     * Call exitConfigFactoryPhase() in a finally-block to restore safe state.
     */
    function enterConfig(mode: FactoryPhaseMode = 'throw'): void {
        _factoryPhase.active = true;
        _factoryPhase.mode = mode;
        _factoryPhase.errors = [];
    }
 
    /**
     * Mark the end of a handler factory call.
     *
     * Returns the list of collected errors (non-empty only when the phase was
     * entered with mode = 'collect').
     */
    function exitConfig(): Error[] {
        _factoryPhase.active = false;
        const errors = _factoryPhase.errors.slice();
        _factoryPhase.errors = [];
        return errors;
    }
 
    function makePathKey(path: (string | symbol)[]): string {
        // Use a separator unlikely to appear in property names.
        return path
            .map(part => {
                if (typeof part === 'string') return `s\x00${part}`;
                // Assign a stable numeric ID to each unique Symbol reference.
                let id = symbolIds.get(part);
                if (id === undefined) symbolIds.set(part, (id = symbolIdCounter++));
                return `y\x00${id}`;
            })
            .join('\x01');
    }
 
    function getNode(path: (string | symbol)[]): unknown {
        let node: unknown = current;
        for (const part of path) {
            if (node == null) return undefined;
            node = Reflect.get(node as object, part);
        }
        return node;
    }
 
    function createPathProxy(path: (string | symbol)[]): unknown {
        const key = makePathKey(path);
        if (path.length > 0) {
            const cached = subProxies.get(key);
            if (cached !== undefined) return cached;
        }
 
        const pathProxy = new Proxy({} as T, {
            get(_target, prop) {
                options.beforeRead?.();
                const container = getNode(path);
                const val = container == null ? undefined : Reflect.get(container as object, prop);
                if (
                    val === undefined ||
                    val === null ||
                    typeof val !== 'object' ||
                    val.constructor !== Object
                ) {
                    if (
                        _factoryPhase.active &&
                        val !== undefined &&
                        val !== null &&
                        typeof prop === 'string'
                    ) {
                        const error = new Error(
                            `Config hot-reload anti-pattern: '${prop}' is a primitive read from the config ` +
                                `proxy during handler factory initialization. The value will be captured once ` +
                                `and will NOT reflect future config reloads.\n` +
                                `Fix: read the value inside the handler body instead:\n` +
                                `  ✅  handler(({config}) => ({ fn: () => config.${prop} }))\n` +
                                `  ❌  handler(({config: {${prop}}}) => ({ fn: () => ${prop} }))`,
                        );
                        if (_factoryPhase.mode === 'throw') throw error;
                        _factoryPhase.errors.push(error);
                    }
                    return val;
                }
                return createPathProxy([...path, prop]);
            },
            set(_target, prop, value) {
                const container = getNode(path);
                if (container == null) return false;
                return Reflect.set(container as object, prop, value);
            },
            has(_target, prop) {
                options.beforeRead?.();
                const container = getNode(path);
                if (container == null) return false;
                return Reflect.has(container as object, prop);
            },
            ownKeys() {
                options.beforeRead?.();
                const container = getNode(path);
                if (container == null) return [];
                return Reflect.ownKeys(container as object);
            },
            getOwnPropertyDescriptor(_target, prop) {
                options.beforeRead?.();
                const container = getNode(path);
                if (container == null) return undefined;
                return Object.getOwnPropertyDescriptor(container as object, prop);
            },
            getPrototypeOf() {
                const container = getNode(path);
                if (container == null) return Object.getPrototypeOf({});
                return Object.getPrototypeOf(container as object);
            },
            deleteProperty(_target, prop) {
                const container = getNode(path);
                if (container == null) return false;
                return Reflect.deleteProperty(container as object, prop);
            },
        });
 
        if (path.length > 0) {
            subProxies.set(key, pathProxy);
        }
 
        return pathProxy;
    }

    // Root proxy corresponds to the empty path.
    const proxy = createPathProxy([]) as T;
 
    function update(next: T): void {
        // Replace the cell's backing data; path-based sub-proxies automatically
        // reflect the new data because they re-traverse `current` on every access.
        current = next;
    }
 
    return {
        proxy,
        update,
        enterConfig,
        exitConfig,
    };
}

// ---------------------------------------------------------------------------
// deepDiff
// ---------------------------------------------------------------------------
 
/**
 * Compute a flat diff between two plain objects.  Returns a Map of dotted paths
 * to `{prev, next}` for every leaf that changed (added, removed, or modified).
 * Nested objects are traversed recursively; circular references are not
 * supported (configs are never circular in practice).
 */
export function deepDiff(prev: unknown, next: unknown, path = ''): ConfigDiff {
    const result: ConfigDiff = new Map();
 
    function isPlain(v: unknown): v is Record<string, unknown> {
        return v !== null && typeof v === 'object' && !Array.isArray(v);
    }
 
    function visit(p: unknown, n: unknown, prefix: string): void {
        if (isPlain(p) && isPlain(n)) {
            const keys = new Set([...Object.keys(p), ...Object.keys(n)]);
            for (const key of keys) {
                visit(p[key], n[key], prefix ? `${prefix}.${key}` : key);
            }
        } else {
            const pStr = JSON.stringify(p);
            const nStr = JSON.stringify(n);
            if (pStr !== nStr) {
                result.set(prefix, {prev: p, next: n});
            }
        }
    }
 
    visit(prev, next, path);
    return result;
}
 
// ---------------------------------------------------------------------------
// ConfigRuntime
// ---------------------------------------------------------------------------
 
export default class ConfigRuntime implements IConfigRuntime {
    readonly #baseConfig: object;
    readonly #configs: object[];
    readonly #suite: string;
    readonly #subscribers: Set<ConfigSubscriber> = new Set();
 
    #rawSnapshot: object = {};
    #sources: IConfigSources | undefined;
    #validator?: (next: object) => void;
    #proxy: object;
    #updateProxy: (next: object) => void;
    #version = 0;
 
    readonly enterConfig: (mode?: FactoryPhaseMode) => void;
    readonly exitConfig: () => Error[];
 
    public constructor(baseConfig: object, configs: (object | boolean)[], suite: string) {
        this.#baseConfig = baseConfig;
        this.#configs = configs.filter(Boolean) as object[];
        this.#suite = suite;
        const {proxy, update, enterConfig, exitConfig} = createConfigProxy(this.#rawSnapshot);
        this.#proxy = proxy;
        this.#updateProxy = update;
        this.enterConfig = enterConfig;
        this.exitConfig = exitConfig;
    }

    // -----------------------------------------------------------------------
    // IConfigRuntime implementation
    // -----------------------------------------------------------------------

    public get snapshot(): object {
        return this.#proxy;
    }

    public get rawSnapshot(): object {
        return this.#rawSnapshot;
    }

    /** What the last load read (rc files, env names, argv keys). */
    public get sources(): IConfigSources | undefined {
        return this.#sources;
    }

    /** Bumped whenever the effective config is replaced; see `IConfigRuntime`. */
    public get version(): number {
        return this.#version;
    }

    private mergeConfigs(blongConfig: object): object {
        // The intents travel into `blong-config`, which reads them out of `env`. They decide which
        // rc files a process reads at all — the *trailing* one is the suffix both source names are
        // built from, the framework's existing convention — so a config step that cannot see them
        // leaves every process reading the `dev` file whatever it was asked to be (Phase 15 E).
        const intents = (this.#baseConfig as {configNames?: string[]}).configNames;
        const onSources = (sources: IConfigSources): void => {
            this.#sources = sources;
        };
        const loaded = loadBlong(
            intents?.length
                ? {env: intents.join(','), ...blongConfig, onSources}
                : {...blongConfig, onSources},
        ) as object;
        return merge({}, this.#baseConfig, ...this.#configs, loaded);
    }
 
    /**
     * Load configuration from all sources using blong-config.
     * Merges the result into the proxy backing store so existing references
     * automatically reflect the new values.
     */
    public async load(params: object = {}): Promise<object> {
        const loaded = this.mergeConfigs({config: {suite: this.#suite}, ...params});
        this.#rawSnapshot = loaded;
        this.#version += 1;
        this.#updateProxy(loaded);
        return this.#proxy;
    }
 
    /**
     * Reload config in-place:
     *  1. Load a fresh config snapshot
     *  2. Run the registered validator, if any — a rejection leaves the current
     *     configuration in place and the reload is not applied
     *  3. Compute the diff against the previous snapshot
     *  4. Update the proxy backing store
     *  5. Notify all subscribers
     */
    public async reload(): Promise<ConfigDiff> {
        const prev = this.#rawSnapshot;
        const next = this.mergeConfigs({config: {suite: this.#suite}});
        const diff = this.diff(prev, next);
 
        // Only do work when something actually changed
        if (diff.size > 0) {
            if (this.#validator) {
                try {
                    this.#validator(next);
                } catch (error) {
                    // A rejected reload keeps the previous snapshot and reports an
                    // empty diff, so the caller neither installs nor acts on the
                    // change. This module has no logger of its own — the same reason
                    // a subscriber error is reported here.
                    console.error('[ConfigRuntime] config reload rejected:', error);
                    return new Map();
                }
            }
            this.#rawSnapshot = next;
            this.#version += 1;
            this.#updateProxy(next);
            for (const subscriber of this.#subscribers) {
                try {
                    await subscriber(diff, next, prev);
                } catch (error) {
                    // Subscriber errors must not break the reload pipeline
                    console.error('[ConfigRuntime] subscriber error:', error);
                }
            }
        }
 
        return diff;
    }
 
    public diff(prev: object, next: object): ConfigDiff {
        return deepDiff(prev, next);
    }
 
    /**
     * Register a validator that every reload must pass before its snapshot is
     * installed. Throwing rejects the reload (@@D-548).
     */
    public setValidator(fn: (next: object) => void): void {
        this.#validator = fn;
    }
 
    /**
     * Register a subscriber.  Returns an unsubscribe function for clean tear-down.
     */
    public subscribe(fn: ConfigSubscriber): () => void {
        this.#subscribers.add(fn);
        return () => this.#subscribers.delete(fn);
    }
 
    // -----------------------------------------------------------------------
    // Centralized config merge methods
    //
    // These replace the scattered merge operations in loadRealm(), layerProxy,
    // and adapter.activeConfig().  Each method encapsulates a specific merge
    // scope so the merge order is documented and testable in one place.
    // -----------------------------------------------------------------------
 
    /**
     * Merge layer-scoped config for a handler closure.
     *
     * Previously done inline in `layerProxy.ts` / `createHandlerClosure()`:
     *   `merge({}, moduleConfig[name], port?.config?.[namespace])`
     *
     * @param moduleConfigSlice - config slice from the module (e.g. `moduleConfig[name]`)
     * @param portNamespaceConfig - namespace-specific config from the port (e.g. `port.config[namespace]`)
     */
    static mergeLayerConfig(
        moduleConfigSlice: unknown,
        portNamespaceConfig?: unknown,
    ): Record<string, unknown> {
        return merge({}, moduleConfigSlice, portNamespaceConfig) as Record<string, unknown>;
    }
 
    /**
     * A live view of one component's config slice, for a handler closure.
     *
     * `mergeLayerConfig` copies, so a handler that reads `config.timeout` inside
     * its function keeps whatever the value was when the layer was assembled,
     * however often the config is reloaded (T-159).  This hands the closure a
     * proxy over the merged slice instead: `mergeOnce` is called again when
     * `version()` reports a new runtime version, and the readers see the new
     * values — the handler's own `config` argument, and any intermediate node it
     * destructured at startup, because the nodes are the path proxies of a
     * `createConfigProxy` instance whose backing is replaced rather than a copy
     * of it.
     *
     * The merge runs at most once per runtime version, so a hot path that reads a
     * config leaf pays a property lookup and an integer compare, not a merge.
     */
    static liveLayerConfig(
        mergeOnce: () => Record<string, unknown>,
        version: () => number,
    ): Record<string, unknown> {
        let seen = version();
        const refresh = (): void => {
            const current = version();
            if (current === seen) return;
            seen = current;
            live.update(mergeOnce());
        };
        // The hook is passed to the proxy instance itself, so a node the closure
        // destructured at startup refreshes on its own reads — reading through
        // the root would leave it stale.
        //
        // This instance's factory-phase guard is never armed: layer assembly arms
        // the *runtime's* proxy, and a handler has always been free to destructure
        // a leaf from its `config` argument at factory time.
        const live = createConfigProxy(mergeOnce(), {beforeRead: refresh});
        return live.proxy as Record<string, unknown>;
    }
 
    /**
     * Merge activation-scoped config for an adapter.
     *
     * Previously done inline in `AdapterBase.ts` `activeConfig()`:
     *   Walk the prototype chain collecting `activation[envName]` from each
     *   level, then merge `['default', ...activationNames]` in order.
     *
     * @param target - the adapter instance (prototype chain is walked)
     * @param activationNames - active environment names (e.g. `['dev']`)
     */
    static mergeActivationConfig(
        target: {activation?: Record<string, unknown>},
        activationNames: string[] = [],
    ): object {
        return merge([
            {},
            ...['default', ...activationNames]
                .map(name => {
                    const result = [];
                    let current = target;
                    while (current) {
                        const config = current?.['activation']?.[name];
                        if (config) result.push(config);
                        current = Object.getPrototypeOf(current);
                    }
                    return result.reverse();
                })
                .flat(),
        ]);
    }
}