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

86.25% Statements 477/553
79.45% Branches 116/146
63.79% Functions 37/58
86.25% Lines 477/553

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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 5541x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 1x 1x 1x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 6x 6x 6x 6x     6x 6x 331x 331x 331x 199x 199x 199x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 264x 6x 6x 6x 6x 6x           6x 264x 264x 264x 264x 264x 6x           6x 184x 184x 6x 6x 6x 132x   132x 132x 132x 132x 132x 132x 42x 42x 42x 42x 42x 42x 42x 42x 42x 118x 118x 118x 118x 118x 118x 10x 10x 10x 118x 118x 2896x 2896x 2896x 2896x 2896x 3646x 2896x 2896x 339x 84x 84x 84x 84x       84x 84x 84x 84x               316x           42x 42x 14x 332x   14x 42x 42x 4x 13x 275x 275x 275x   42x 42x 42x 42x 275x 275x 275x 275x 24x 24x 24x   24x 24x 504x 504x 504x 504x 504x 504x 6x 10x 6x 6x 6x 504x 504x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 132x 108x 108x 316x 316x 316x 151x 316x 316x 316x 316x 316x 14x   316x 316x 316x 6x 126x 12x 12x 126x 6x 1x 1x                                           369x 369x 369x 369x 369x 369x 369x 369x   369x 369x 369x 369x 369x         42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 24x 24x 42x 24x 24x 24x 23x 42x 42x 42x 42x 42x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 331x 331x 331x 14x 14x 14x 14x 14x 14x 204x 204x 204x 14x 132x 132x 132x 14x 14x               14x 76x 65x 65x 3x                       54x 54x 54x 54x 3x 3x 3x 3x 3x 3x 3x 3x 54x 54x 3x 3x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 3x 3x 3x 3x 3x 3x 3x 70x 70x 70x 3x 3x 3x 3x 3x 54x 54x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 24x 24x 24x 3x 3x 6x 6x 6x 6x 6x 3x 3x 3x 3x 6x 132x 132x 132x 132x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import type {
    Adapter,
    GatewaySchema,
    Handlers,
    IAdapterFactory,
    IAdapterRegistry,
    IApiSchema,
    IErrorFactory,
    IGateway,
    ILocal,
    ILog,
    IManifest,
    IMeta,
    IObjectSchema,
    IPlatformApi,
    IRegistry,
    IRegistryDescription,
    IRemote,
    IRpcServer,
} from '@feasibleone/blong/types';
import {Internal} from '@feasibleone/blong/types';
import nodeAssert from 'node:assert';
import PQueue from 'p-queue';
import merge from 'ut-function.merge';
 
import * as blongLib from '@feasibleone/blong-lib';
import {renderAll} from '@feasibleone/blong-template';
import {createAttachCheckpoint} from './checkpoint.ts';
import {methodId, methodParts} from './lib.ts';
import type {IResolution} from './Resolution.ts';
import type {IWatch} from './Watch.ts';
 
type MatchMethodsCallback = (
    name: string,
    local: {config?: object; namespace?: string | string[]},
    literals: object[],
) => void;
const API: RegExp = /\.validation$|\.api$|^validation$|^api$/;
const SCHEMA: RegExp = /\.type$/;
 
interface IConfig {
    api?: Record<string, {source: string; def: {namespace: Record<string, string | string[]>}}>;
    checkpointMode?: 'test' | 'debug' | 'production';
    /**
     * Map of namespace → true for methods that should be registered in
     * `Local` only (in-process dispatch) and skipped in `RpcServer`
     * (inter-process dispatch).  When running as a monolith with
     * `canSkipSocket: true`, local-only methods avoid unnecessary RPC
     * registration overhead.
     */
    localOnly?: Record<string, boolean>;
}
 
export default class Registry extends Internal implements IRegistry {
    public modules: Map<string | symbol, IRegistry[]> = new Map();
    public ports: Map<string, IAdapterRegistry> = new Map();
    public methods: Map<string, Handlers> = new Map();
    public objectSchema: IObjectSchema = {};
    #stopped = false;
    #logger:
        | {info?: (...args: unknown[]) => void; warn?: (...args: unknown[]) => void}
        | undefined = undefined;
    #reload: PQueue = new PQueue({concurrency: 1});
    #ports: Map<string, Adapter> = new Map();
    #error: IErrorFactory;
    #portAttachments: Map<
        string,
        [
            {
                port: object;
                target: {importedMap?: Map<string, object>};
                parent: object;
                pointer: object;
            },
        ]
    > = new Map();
    #validations: Record<string, GatewaySchema> = {};
 
    #resolution: IResolution;
    #rpcServer: IRpcServer;
    #remote: IRemote;
    #gateway: IGateway;
    #local: ILocal;
    #watch: IWatch;
    #log: ILog;
    #apiSchema: IApiSchema;
    #platform: IPlatformApi;
    #config: IConfig = {};
    #attachCheckpoint?: (meta: IMeta) => void;
 
    #manifest: IManifest | undefined;
 
    public constructor(
        config: object,
        {
            log,
            error,
            rpcServer,
            remote,
            gateway,
            local,
            resolution,
            watch,
            apiSchema,
            platform,
            manifest,
        }: {
            log?: ILog;
            error?: IErrorFactory;
            rpcServer?: IRpcServer;
            remote?: IRemote;
            gateway?: IGateway;
            local?: ILocal;
            resolution?: IResolution;
            watch?: IWatch;
            apiSchema?: IApiSchema;
            platform?: IPlatformApi;
            manifest?: IManifest;
        },
    ) {
        super({log});
        this.merge(this.#config, config);
        this.#resolution = resolution!;
        this.#rpcServer = rpcServer!;
        this.#error = error!;
        this.#remote = remote!;
        this.#gateway = gateway!;
        this.#local = local!;
        this.#log = log!;
        this.#watch = watch!;
        this.#apiSchema = apiSchema!;
        this.#platform = platform!;
        this.#manifest = manifest;
        this.#attachCheckpoint = createAttachCheckpoint(
            this.#config.checkpointMode ?? 'production',
        );
        this.#rpcServer?.setAttachCheckpoint?.(this.#attachCheckpoint);
        watch?.setObjectSchema?.(this.objectSchema);
    }
 
    public getPort(id: string): Adapter | undefined {
        return this.#ports.get(id);
    }
 
    public async createPort(id: string): Promise<Adapter | undefined> {
        const port = this.ports.get(id);
        await this.#ports.get(id)?.stop();
        if (port!.config === false) {
            this.#ports.delete(id);
            return;
        }
        const api: Parameters<IAdapterFactory>[0] = {
            id,
            type: blongLib.type,
            schema: this.objectSchema,
            adapter: id => this.ports.get(id),
            utError: {
                register: this.#error.register.bind(this.#error),
                defineError: this.#error.define.bind(this.#error),
                getError: this.#error.get.bind(this.#error),
                fetchErrors: this.#error.fetch.bind(this.#error),
            },
            errors: this.#error,
            gateway: this.#gateway,
            remote: this.#remote,
            rpc: this.#rpcServer,
            local: this.#local,
            registry: this,
            register: (methods, namespace, port, pkg) => {
                if (!this.#config.localOnly?.[namespace]) {
                    this.#rpcServer?.register(methods, namespace, true, pkg);
                }
                this.#local?.register(methods, namespace, true, pkg);
            },
            unregister: (methods, namespace) => {
                if (!this.#config.localOnly?.[namespace]) {
                    this.#rpcServer?.unregister(methods, namespace, true);
                }
                this.#local?.unregister(methods, namespace);
            },
            subscribe: (methods, namespace, port, pkg) => {
                if (!this.#config.localOnly?.[namespace]) {
                    this.#rpcServer?.register(methods, namespace, false, pkg);
                }
                this.#local?.register(methods, namespace, false, pkg);
            },
            unsubscribe: (methods, namespace) => {
                if (!this.#config.localOnly?.[namespace]) {
                    this.#rpcServer?.unregister(methods, namespace, false);
                }
                this.#local?.unregister(methods, namespace);
            },
            getPath(method: string) {
                return method.match(/^[^[#?]*/)?.[0] || method;
            },
            methodId,
            importMethod: (methodName, options) => this.#remote.remote(methodName, options),
            dispatch: (...params) => this.#remote.dispatch(...params),
            attachHandlers: undefined!,
            attach: undefined!,
            createLog: (level, bindings) => this.#log?.logger(level, bindings) || {},
            attachCheckpoint: this.#attachCheckpoint,
            manifest: this.#manifest,
            render: (what: object[] | object) =>
                renderAll(Array.isArray(what) ? merge(...what) : what, this.#platform.context),
            platform: this.#platform,
        };
        const result = (await port!(api)) as unknown as Adapter;
        this.#ports.set(id, result);
        api.attach = this._attach.bind(this);
        api.attachHandlers = this._attachHandlers(result);
        return result as Adapter;
    }
 
    private async _matchMethods(
        mode: 'extend' | 'merge',
        patterns: (string | RegExp)[] | string | RegExp,
        port: object | MatchMethodsCallback | undefined,
        callback?: MatchMethodsCallback,
    ): Promise<void> {
        if (typeof port === 'function' && !callback) {
            callback = port as MatchMethodsCallback;
            port = undefined;
        }
        const log = this.#log.logger('info', {name: 'registry'});
        for (const [name, value] of this.methods.entries()) {
            if (
                ([] as (string | RegExp)[])
                    .concat(patterns)
                    .some(
                        pattern =>
                            (pattern instanceof RegExp && pattern.test(name)) || pattern === name,
                    )
            ) {
                if (mode === 'merge') {
                    for (const item of value) {
                        const started = Date.now();
                        const {local, literals} = await this._createHandlers([item], port);
                        // Visibility: a handler factory that hangs (e.g. a
                        // `subject.validation` resolving a model handler whose
                        // derived name doesn't match a registered file) would
                        // otherwise stall startup silently. Warn after a slow
                        // threshold so the stuck method is identified.
                        const elapsed = Date.now() - started;
                        if (elapsed > 3_000) {
                            log.warn?.(
                                `registry handler factory for '${name}' took ${elapsed}ms — ` +
                                    'a hanging dependency (e.g. an unresolvable remote method) is likely',
                            );
                        }
                        callback!(name, local, literals);
                    }
                } else {
                    const {local, literals} = await this._createHandlers(value, port);
                    callback!(name, local, literals);
                }
            }
        }
    }
 
    private async _collectObjectSchema(): Promise<void> {
        for (const [name, handlers] of this.methods) {
            if (SCHEMA.test(name)) await this._createHandlers(handlers, undefined);
        }
    }
 
    private async _validations(): Promise<Record<string, GatewaySchema>> {
        await this._matchMethods('merge', API, (name, local) => {
            Object.entries(local).forEach(([name, validation]) => {
                const schema =
                    typeof validation === 'function'
                        ? (validation as () => GatewaySchema)()
                        : typeof validation === 'object'
                          ? validation
                          : {};
                if (typeof validation === 'function') name = validation.name;
                // A later-registered validation REPLACES an earlier one for the
                // same methodParts key instead of merging. `subject.validation`
                // (blong-server, `srv`) registers first and auto-generates the
                // CRUD validations for every `public: true` model; an explicit
                // realm gateway file (`gateway/<subject>/<method>.ts`) registers
                // later and must reliably WIN for the operation it overrides.
                // Merging TypeBox schemas with ut-function.merge also corrupts
                // symbol-keyed Kind markers on nested schemas (e.g. a `details`
                // array) and lets auto-required fields leak into the override,
                // so replace instead. Unrelated keys still merge normally.
                this.#validations[methodParts(name)] = schema as GatewaySchema;
            });
        });
        return this.#validations;
    }
 
    private async _attach(target: object, patterns: (string | RegExp)[] | string | RegExp) {
        await this._matchMethods('merge', patterns, (name, local) =>
            Array.isArray(target) ? target.push(local) : merge(target, local),
        );
        return target;
    }
 
    private _attachHandlers(port: object): (
        target: {
            importedMap?: Map<string, object>;
            imported: object;
            config: {namespace?: string | string[]};
        },
        patterns: (string | RegExp)[] | string | RegExp,
        adapter?: boolean,
    ) => unknown {
        return (
            target: {
                importedMap?: Map<string, object>;
                imported: object;
                config: {
                    namespace?: string | string[];
                };
            },
            patterns: (string | RegExp)[] | string | RegExp,
            adapter?: boolean,
        ) => {
            target.imported = {};
            Object.setPrototypeOf(target.imported, target);
            if (patterns && (!Array.isArray(patterns) || patterns.length)) {
                target.importedMap = new Map(); // preserve patterns order
                return this._matchMethods('extend', patterns, port, (name, local, literals) => {
                    const ports = this.#portAttachments.get(name);
                    const info = {port, target, parent: target.imported, pointer: {}};
                    if (ports) ports.push(info);
                    else this.#portAttachments.set(name, [info]);
                    target.importedMap!.set(name, local);
                    if (adapter) {
                        if (local.config) merge(target.config, local.config);
                        if (local.namespace)
                            target.config.namespace = target.config.namespace
                                ? ([] as string[]).concat(target.config.namespace, local.namespace)
                                : ([] as string[]).concat(local.namespace);
                    }
                    literals.forEach(literal => Object.setPrototypeOf(literal, target.imported));
                    Object.setPrototypeOf(local, info.parent);
                    Object.setPrototypeOf(info.pointer, local);
                    target.imported = info.pointer;
                });
            }
        };
    }
 
    public async replaceHandlers(id: string, handlers: Handlers): Promise<void> {
        const attachments = this.#portAttachments.get(id);
        if (attachments) {
            for (const {port, target, parent, pointer} of attachments) {
                const {local, literals} = await this._createHandlers(handlers, port);
                target.importedMap!.set(id, local);
                literals.forEach(literal => Object.setPrototypeOf(literal, parent));
                Object.setPrototypeOf(local, parent);
                Object.setPrototypeOf(pointer, local);
            }
        }
        if (API.test(id)) {
            await this.#reload.add(async () => {
                this.methods.set(id, handlers);
                this.#validations = {};
                this.#gateway?.route(await this._validations(), {name: '', version: ''});
                await this.#gateway?.start();
            });
        }
    }

    private async _createHandlers(
        handlers: Handlers,
        port: object | undefined,
    ): Promise<{local: object; literals: object[]}> {
        const attachCheckpoint = this.#attachCheckpoint;
        const lib = {
            error: this.#error.register.bind(this.#error),
            assert: attachCheckpoint ? nodeAssert : undefined,
            render: (what: object[] | object) =>
                renderAll(Array.isArray(what) ? merge(...what) : what, this.#platform.context),
            timing: this.#platform.timing,
            ...blongLib,
            // The runtime services a `library()` function needs, mirroring the
            // port API (`registry: this`, `platform: …`).
            //
            // A `library()` *factory* is not given the platform: `layerApi`
            // carries only config/handler/errors/schema/gateway/apiSchema. And
            // the lib proxy returns an attached function **raw**, so `this`
            // inside it is this object — not the port, which is only bound in the
            // proxy's not-yet-attached fallback path. Without these keys a
            // library function therefore cannot reach the platform or registry at
            // all, which is what a library needs to be reusable outside a
            // request.
            platform: this.#platform,
            registry: this,
        };
        const local = {};
        const literals: object[] = [];
        for (const fn of handlers) {
            await fn({
                lib,
                local,
                literals,
                gateway: this.#gateway,
                remote: (name: string) => this.#remote.remote(methodParts(name)),
                port,
                attachCheckpoint,
                apiSchema: this.#apiSchema,
            });
        }
        return {local, literals};
    }
 
    public async init(): Promise<IRegistry> {
        for (const [id, {source, def}] of Object.entries(this.#config.api || {}))
            await this.loadApi(id, def, source);
        return this;
    }
 
    public async start(configOverride: object): Promise<IRegistry> {
        this.#stopped = false;
 
        await this._collectObjectSchema();
        this.#logger = this.#log.logger('info', {name: 'registry'});
        let created = 0;
        const portIds = Array.from(this.ports.keys());
        await blongLib.withProgress(
            this.#logger,
            'create ports',
            (async () => {
                for (const id of portIds) {
                    await this.createPort(id);
                    created += 1;
                }
            })(),
            {getProgress: () => ({done: created, total: portIds.length})},
        );
        let started = 0;
        const startPorts = Array.from(this.#ports.values());
        await blongLib.withProgress(
            this.#logger,
            'start ports',
            (async () => {
                for (const port of startPorts) {
                    await port.start(configOverride);
                    started += 1;
                }
            })(),
            {getProgress: () => ({done: started, total: startPorts.length})},
        );
        let ready = 0;
        const readyPorts = Array.from(this.#ports.values());
        await blongLib.withProgress(
            this.#logger,
            'ready ports',
            (async () => {
                for (const port of readyPorts) {
                    await port.ready();
                    ready += 1;
                }
            })(),
            {getProgress: () => ({done: ready, total: readyPorts.length})},
        );
        this.#gateway?.route(await this._validations(), {name: '', version: ''});
        await this.#resolution?.start();
        await this.#rpcServer?.start();
        await this.#remote?.start();
        await this.#gateway?.start();
        await this.#watch?.start(this, this.#remote, configOverride);
        return this;
        // console.dir(this.ports.entries());
        // console.dir(this.#validations);
        // console.dir(created);
    }
 
    public async connected(): Promise<boolean> {
        return (
            await Promise.all(
                Array.from(this.#ports.values())
                    .reverse()
                    .map(port => port.connected?.() ?? port.isConnected),
            )
        ).every(item => item);
    }
 
    public async test(framework: unknown): Promise<void> {
        return await this.#watch.test(framework);
    }
 
    /**
     * Structural snapshot of the loaded realm graph.
     *
     * Combines the live registry (realms, ports, registered method groups) with
     * the on-disk view owned by `Watch` (handler folders and files). This is the
     * runtime source of truth that tooling and agents should query instead of
     * re-deriving layout from conventions.
     */
    public describe(): IRegistryDescription {
        const disk = this.#watch?.describe?.();
        return {
            realms: Array.from(this.modules.keys()).filter(
                (key): key is string => typeof key === 'string',
            ),
            ports: Array.from(this.ports.keys()),
            groups: Array.from(this.methods.entries()).map(([name, handlers]) => ({
                name,
                handlerCount: handlers.length,
            })),
            folders: disk?.folders ?? [],
            files: disk?.files ?? [],
            layerFiles: disk?.layerFiles ?? [],
        };
    }
 
    public async stop(): Promise<IRegistry> {
        if (this.#stopped) return this;
        await this.#watch?.stop();
        await this.#gateway?.stop();
        await this.#remote?.stop();
        await this.#rpcServer?.stop();
        await this.#resolution?.stop();
        let stopped = 0;
        const ports = Array.from(this.#ports.values());
        await blongLib.withProgress(
            this.#logger,
            'stop ports',
            (async () => {
                for (const port of ports) {
                    await port.stop();
                    stopped += 1;
                }
            })(),
            {getProgress: () => ({done: stopped, total: ports.length})},
        );
        this.#stopped = true;
        this.#logger = undefined;
        // The log implementation can hold something the process will not exit without: the
        // semantic log's in-process cluster service listens on a socket (9455 by default), and
        // a run that closes every other server still hangs on it — a tap suite that passed
        // every test then reports "timeout!" against a live server. Stopping it here is what
        // makes `stop()` mean "nothing of this platform is still running". Optional because
        // the plain log implementation has nothing to stop.
        await (this.#log as {stop?: () => Promise<void>})?.stop?.();
        return this;
    }
 
    public async loadApi(
        id: string,
        def: {
            namespace: Record<string, string | string[]>;
        },
        source: string,
    ): Promise<void> {
        const api = await this.#apiSchema.schema(def, source);
        this.methods.set(id, [({local}) => merge(local, api)]);
    }
}