All files / blong-gogo/src ConfigRuntime.ts

72.97% Statements 297/407
87.69% Branches 57/65
63.15% Functions 24/38
72.97% Lines 297/407

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 4081x 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 25x 25x 25x 25x 25x 25x 25x 25x 25x                                                               170x 170x 170x 170x                 170x 170x 170x 170x 170x     547x 547x 547x 757x           547x 547x     3158x 3158x 3878x 3878x 3878x 3158x 3158x     547x 547x 522x 522x 522x 250x 250x 250x 1712x 1712x 1712x 1712x 1151x 1151x 546x 1712x 1190x 1190x 5x 4x 4x 1190x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 1188x 1188x 522x 522x 250x 22x 22x 22x 22x 250x 162x 162x 162x 162x 250x 328x 328x 328x 328x 250x 309x 309x 309x 309x 250x 625x 625x 625x 625x 250x         250x 250x 547x 225x 225x 250x 250x 250x 25x 25x 25x 25x 25x 16x 16x 16x 16x 25x 25x 25x 25x 25x 25x 25x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x         26x 12x 12x 19x 19x 26x 14x 14x 14x 7x                   1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x     11x 11x 11x 11x                                       11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x             8x 8x                         1x 1x   5x 5x 5x 5x 5x 5x       100x 100x 100x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 83x 83x 83x 83x 83x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 45x 45x 45x 45x 45x 45x 45x 149x 149x 149x 742x 742x 742x 742x 149x 149x 45x 45x 45x 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,
} 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,
): {
    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) {
                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) {
                const container = getNode(path);
                if (container == null) return false;
                return Reflect.has(container as object, prop);
            },
            ownKeys() {
                const container = getNode(path);
                if (container == null) return [];
                return Reflect.ownKeys(container as object);
            },
            getOwnPropertyDescriptor(_target, prop) {
                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 = {};
    #proxy: object;
    #updateProxy: (next: object) => void;
 
    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;
    }

    private mergeConfigs(blongConfig: object): object {
        const loaded = loadBlong(blongConfig);
        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.#updateProxy(loaded);
        return this.#proxy;
    }
 
    /**
     * Reload config in-place:
     *  1. Load a fresh config snapshot
     *  2. Compute the diff against the previous snapshot
     *  3. Update the proxy backing store
     *  4. 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) {
            this.#rawSnapshot = next;
            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 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>;
    }
 
    /**
     * 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(),
        ]);
    }
}