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

88.6% Statements 552/623
80.73% Branches 88/109
76.47% Functions 39/51
88.6% Lines 552/623

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 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 6241x 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 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 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 175x 8x 8x 189x 189x 189x 189x 189x 8x 8x 175x 175x 175x 175x 175x 175x 175x 175x 175x 14x 14x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 175x 8x 8x 8x 8x 175x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8691x 8691x 69x 69x 8691x 8691x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 629x 629x 627x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 629x 8x 8x 6528x 6528x 1x 1x 5751x 5751x                   5578x 5578x 5578x 5578x 5578x 1x 1x 42775x 42775x 42759x 42775x 42759x 42759x 1x 1x 6704x 6704x 6704x 6704x 6703x 6703x 6703x 6703x 6526x 6526x 6526x 6703x 6704x 6527x                               1x 1x 1x             521x 521x 521x 521x 521x 521x   1569x 17x 17x 17x 17x 17x 12x 17x 17x 17x 7x 7x 521x 521x 521x 521x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 36249x 36249x 36249x 1x 1x 3348x 3348x 1x 1x       1x 1x 173x 173x 1x 1x 173x       173x 173x 173x 213x 213x 213x 213x 213x 213x 213x 213x 213x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 16x 16x 16x 16x 16x 16x     3426x 3426x 3426x 3426x 3426x 3426x 3426x 3426x 3426x 3426x 3426x 2829x 2829x 2829x           6x           2512x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x         3426x 3426x 3426x 3426x 3426x 3426x 3426x 2829x 597x 3426x     3426x 1x 1x 174x 174x 174x 174x 174x 1x 1x 173x 173x 1x 1x 173x 173x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 171x 37x 173x 173x 171x 171x 171x 171x 171x 171x 171x 171x 171x 171x                 171x 171x 171x 171x 173x 173x 173x 173x  
import type {
    Adapter,
    CaptureSurface,
    Config,
    Errors,
    IApi,
    IContext,
    IErrorMap,
    IMeta,
    ITypedError,
    PortHandlerBound,
    VocabularyProxy,
} from '@feasibleone/blong/types';
import type net from 'node:net';
import PQueue from 'p-queue';
import type {TSchema} from 'typebox';
 
import ConfigRuntime from './ConfigRuntime.ts';
import {formatConfigIssues, validateConfigBlock} from './configValidation.ts';
import {isExpectedError, portLogCalls} from './lib.ts';
import loop from './loop.ts';
import {
    adoptInbound,
    attachProgress,
    beginProgress,
    inboundIdentities,
    isFlowId,
    takeProgress,
} from './responseContext.ts';
 
const errorMap: IErrorMap = {
    'adapter.configValidation': 'Adapter config validation:\r\n{message}',
    'adapter.missingParameters': 'Missing parameters',
    'adapter.missingMeta': 'Missing metadata',
    'adapter.notConnected': 'No connection',
    'adapter.disconnect': 'Adapter disconnected',
    'adapter.disconnectBeforeResponse': 'Disconnect before response received',
    'adapter.stream': 'Adapter stream error',
    'adapter.timeout': 'Timeout',
    'adapter.echoTimeout': 'Echo retries limit exceeded',
    'adapter.unhandled': 'Unhandled adapter error',
    'adapter.bufferOverflow': 'Message size of {size} exceeds the maximum of {max}',
    'adapter.socketTimeout': 'Socket timeout',
    'adapter.receiveTimeout': 'Receive timeout',
    'adapter.dispatchFailure': 'Cannot dispatch message to bus',
    'adapter.methodNotFound': 'Method {method} not found',
    'adapter.queueNotFound': 'Queue not found',
    'adapter.invalidPullStream': 'Invalid pull stream',
    'adapter.paramsValidation': 'Method {method} parameters failed validation for: {fields}',
    'adapter.resultValidation': 'Method {method} result failed validation for: {fields}',
    'adapter.deadlock':
        'Method {method} was recursively called, which may cause a deadlock!\nx-b3-traceid: {traceId}\nx-ut-stack: {sequence}',
    'adapter.noMeta': '$meta not passed',
    'adapter.noMetaForward': '$meta.forward not passed to method {method}',
    'adapter.noTraceId': "$meta.forward['x-b3-traceid'] not passed to method {method}",
};
 
let _errors: Errors<typeof errorMap>;
 
const reserved: string[] = [
    'reducer',
    'start',
    'stop',
    'ready',
    'init',
    'namespace',
    'send',
    'requestSend',
    'responseSend',
    'errorSend',
    'receive',
    'requestReceive',
    'responseReceive',
    'errorReceive',
];
 
/**
 * AdapterBase — the runtime-provided base class for all adapters.
 *
 * This class replaces the plain-object literal that was previously defined
 * inline in `adapter()`.  It is exposed through the runtime injection
 * mechanism — realms and solutions never import it directly.  Custom
 * adapters extend it via prototype-chain inheritance
 * (`Object.setPrototypeOf(current, baseInstance)`), preserving the existing
 * hot-reload semantics.
 */
type AdapterHandlerContext = {
    importedMap?: Map<string, object>;
    imported: object;
    config: {namespace?: string | string[]};
};
 
/** Where a port keeps its resolved capture surface. */
const CAPTURE: unique symbol = Symbol('blong:capture');
 
export class AdapterBase<T, C extends IContext> implements AdapterHandlerContext {
    errors = _errors;
    exec: unknown = null;
    imported: Record<string, PortHandlerBound> = {};
    config: Config<T, C> = {} as Config<T, C>;
    configBase: string;
    log: unknown = null;
    /**
     * The process's declared vocabulary for this port, or nothing when it holds none.
     *
     * A port serves one namespace, and a namespace is one layer's handlers, so the vocabulary is
     * attached per port by the loader (`signals.ts`, `@@T-712`). Declared here because this class is
     * the runtime-provided base every adapter extends: without the member, `this.signal?.x?.()` in a
     * port's own code type-checks against nothing.
     */
    signal?: VocabularyProxy;
    importedMap?: Map<string, Record<string, (...args: unknown[]) => unknown>>;
    platform: IApi['platform'];
    registry: IApi['registry'];
 
    // These are prefixed with _ rather than using # private class fields.
    // The adapter uses Object.setPrototypeOf(current, base) to set the base as
    // the prototype of the plain handler-result object.  When prototype methods
    // are then called on `current`, `this` is `current` (not `base`), so
    // JavaScript's brand-checking on # private fields throws.  Regular
    // properties are found via normal prototype-chain lookup, which works.
    _register: IApi['register'];
    _subscribe: IApi['subscribe'];
    _dispatch: IApi['dispatch'];
    _methodId: IApi['methodId'];
    _getPath: IApi['getPath'];
    // _api is stored (not _attachHandlers directly) because Registry.ts sets
    // api.attachHandlers = ... only *after* the port factory returns.  Storing
    // the api object and reading api.attachHandlers lazily (at call time)
    // ensures we always see the real function rather than the initial undefined.
    _api: Pick<IApi, 'attachHandlers' | 'render' | 'attach' | 'captureFor'>;
    _createLog: IApi['createLog'];
    /**
     * The captures this port may take, by shape family (`@@T-730`).
     *
     * Handed over with the logger factory because a port's own body has no `this.signal` to reach: the
     * vocabulary arrives through the same seam, and the surface is resolved once here rather than on
     * every call.
     */
    _captureFor?: IApi['captureFor'];
    /** The resolved surface, remembered on the instance — a symbol rather than a private field so
     * it survives the port proxy the layer hands a handler. */
    [CAPTURE]?: CaptureSurface;
    _attachCheckpoint: IApi['attachCheckpoint'];
    _activationNames: string[];
    _queue?: PQueue;
    _portLoop: any; // eslint-disable-line @typescript-eslint/no-explicit-any
    _resolveConnected?: (value: boolean) => void;
    _connected: Promise<boolean>;
 
    constructor(
        api: Pick<
            IApi,
            | 'register'
            | 'subscribe'
            | 'dispatch'
            | 'methodId'
            | 'getPath'
            | 'attachHandlers'
            | 'createLog'
            | 'attachCheckpoint'
            | 'captureFor'
            | 'render'
            | 'platform'
            | 'registry'
            | 'attach'
        >,
        configBase: string,
        activationNames: string[] = [],
    ) {
        this.configBase = configBase;
        this._register = api.register;
        this._subscribe = api.subscribe;
        this._dispatch = api.dispatch;
        this._methodId = api.methodId;
        this._getPath = api.getPath;
        this.platform = api.platform;
        this.registry = api.registry;
        this._api = api;
        this._createLog = api.createLog;
        this._captureFor = api.captureFor;
        this._attachCheckpoint = api.attachCheckpoint;
        this._activationNames = activationNames;
        this._connected = new Promise<boolean>(resolve => {
            this._resolveConnected = resolve;
        });
    }
 
    activeConfig(): object {
        return ConfigRuntime.mergeActivationConfig(
            this as {activation?: Record<string, unknown>},
            this._activationNames,
        );
    }
 
    async init(...configs: object[]): Promise<void> {
        // Validate the port's own config slice against the schema it declared
        // (`validation`), the counterpart of the realm-level check in `load.ts`.
        // Opt-in: the slice a port receives is its parent's declaration of it, so
        // a port with no schema cannot tell a parent-declared key (`backend` gets
        // `host`, `protocol`, `imports` from its realm) from an override. Only a
        // declared schema asserts which keys belong. Its activation keys and the
        // two the loader injects are added, because those are the port's own.
        const declared = (this as {validation?: TSchema}).validation;
        if (declared) {
            const allowed = ['id', 'pkg', ...Object.keys(this.activeConfig() as object)];
            for (const config of configs) {
                const issues = validateConfigBlock(config, declared, allowed);
                if (issues.length)
                    throw new Error(
                        formatConfigIssues(
                            String((config as {id?: unknown}).id ?? this.configBase),
                            issues,
                        ),
                    );
            }
        }
        this.config = this._api.render([this.activeConfig(), ...configs]) as Config<T, C>;
        // The port's own id — `<realm>.<layer>` — is the component the records belong to, and
        // `context` is the word both log implementations print: the terminal and the viewer show
        // it, `blong-dev log` filters on it, and a capture is enabled by it (`@@D-924`). It used to
        // be `name`, which lukaot only reads as a *fallback* for `context` — so passing both meant
        // the explicit `context: <type>` shadowed the id and no surface ever said which port a
        // record came from (`@@F-800`). The kind rides beside it as its own field, because every
        // adapter of a realm shares the layer id and only the pair tells two of them apart.
        const portType = this.config.type ?? 'dispatch';
        this.log = this._createLog?.(this.config.logLevel || 'info', {
            ...this.config.log,
            context: this.config.id,
            portType,
        });
        const id = this.config.id.replace(/\./g, '-');
        this._queue = new PQueue({concurrency: this.config.concurrency || 100});
        this._register(
            {
                [`${id}.start`]: this.start.bind(this),
                [`${id}.stop`]: this.stop.bind(this),
            },
            'ports',
            this.config.id,
            this.config.pkg,
        );
        this._subscribe(
            {
                [`${id}.drain`]: this.drain.bind(this),
            },
            'ports',
            this.config.id,
            this.config.pkg,
        );
    }
 
    /** The captures this port may take — `this.capture?.http?.({method}, () => exchange)`. */
    get capture(): CaptureSurface | undefined {
        const self = this as unknown as Record<symbol, CaptureSurface | undefined>;
        if (self[CAPTURE] === undefined) {
            self[CAPTURE] = this._captureFor?.(this.config.id, this.config.logLevel as never);
        }
        return self[CAPTURE];
    }
 
    /**
     * Record one port failure, and answer the error so the caller can throw it — the port's only
     * writer.
     *
     * Every failure a port meets — a call it answered badly, a stream that errored, a socket event —
     * ends here, and it is written **once**: the error object goes in the logger's own error slot,
     * which is the only place its message and stack are rendered (`Error`'s members are not
     * enumerable, so handing the error as the fields bag wrote an empty message and lost the stack),
     * its method rides in the envelope so the header says which call failed (`@@F-764`), and the
     * record is counted under the declared identity `frameworkPortFailure` so an operator can find it
     * with `blong-dev log --signal` and the service counts it beside every other signal (`@@T-731`).
     *
     * `$meta` is optional because a socket event has no dispatch to describe: `tcp.ts` reports a
     * server or client `error` event through here too, rather than dropping a bare object on a level
     * where it lost its type and its expected/silent handling.
     */
    error(error: ITypedError, $meta?: IMeta): ITypedError {
        if ($meta) error.method = $meta.method;
        if (error.silent) return error;
        const expected = isExpectedError(error.type, $meta?.expect);
        const entry = {
            signal: 'frameworkPortFailure',
            $meta: {mtid: 'error', ...(error.method === undefined ? {} : {method: error.method})},
            err: error,
            type: error.type,
            ...(error.statusCode === undefined ? {} : {statusCode: error.statusCode}),
            ...(error.params === undefined ? {} : {params: error.params}),
            ...(error.validation === undefined ? {} : {validation: error.validation}),
        };
        const face = this.log as
            | {
                  debug?: (bag: object, message: string) => void;
                  error?: (bag: object, message: string) => void;
              }
            | undefined;
        (expected ? face?.debug : face?.error)?.call(face, entry, error.message);
        return error;
    }
 
    findValidation(): unknown {
        return null;
    }
 
    namespaces(): (string | RegExp)[] {
        const namespace = this.config.namespace;
        return ([] as (string | RegExp)[]).concat(
            namespace
                ? Array.isArray(namespace) || typeof namespace === 'string'
                    ? namespace
                    : Object.keys(namespace)
                : this.config.imports || this.config.id.replace(/\./g, '-'),
        );
    }

    handles(name: string): boolean {
        if (reserved.includes(name)) return true;
        return this.namespaces().some(namespace =>
            typeof namespace === 'string' ? name.startsWith(namespace) : namespace.test(name),
        );
    }
 
    methodPath(methodName: string): string {
        const afterSlash = methodName.split('/', 2)[1];
        if (afterSlash !== undefined) return afterSlash;
        const strip = this.config?.stripNamespace;
        if (strip) return methodName.split('.').slice(strip).join('.');
        return methodName;
    }
 
    getConversion($meta: IMeta | false, type: 'send' | 'receive'): {fn: unknown; name: string} {
        let fn;
        let name: string = '';
        if ($meta) {
            if ($meta.method) {
                const path = this._getPath($meta.method);
                name = [path, $meta.mtid, type].join('.');
                fn = this.findHandler(name);
                if (!fn) {
                    name = [this.methodPath(path), $meta.mtid, type].join('.');
                    fn = this.findHandler(name);
                }
            }
            if (!fn) {
                name = [$meta.opcode, $meta.mtid, type].join('.');
                fn = this.findHandler(name);
            }
            if (!fn) {
                name = [$meta.mtid, type].join('.');
                fn = this.findHandler(name);
            }
        }
        if (!fn && (!$meta || $meta.mtid !== 'event')) {
            name = type;
            fn = this.findHandler(name);
        }
        return {fn, name};
    }

    async dispatch(...args: unknown[]): Promise<unknown> {
        const result = this._dispatch(...args);
        if (!result)
            (this.log as {error?: (...args: unknown[]) => void})?.error?.(
                this.errors['adapter.dispatchFailure']({args}),
            );
        return result;
    }

    async event(event: string, data?: object, mapper?: string): Promise<unknown> {
        (this.log as {info?: (...args: unknown[]) => void})?.info?.({
            $meta: {mtid: 'event', method: `adapter.${event}`},
            ...data,
        });
        const eventHandlers: Array<(...args: unknown[]) => unknown> = [];
        this.importedMap?.forEach(
            imp =>
                Object.prototype.hasOwnProperty.call(imp, event) && eventHandlers.push(imp[event]),
        );
        let result: unknown = data;
        switch (mapper) {
            case 'asyncMap':
                result = await Promise.all(eventHandlers.map(handler => handler.call(this, data)));
                break;
            case 'reduce':
            default:
                for (const eventHandler of eventHandlers) {
                    result = await eventHandler.call(this, result);
                }
                break;
        }
        return result;
    }
 
    async drain(): Promise<void> {}
 
    /**
     * Every handler registered for a method, in load order.
     *
     * `findHandler` answers with the one function the proxy will call: the newest
     * group shadows the earlier ones, which is deliberate — it is how a handler
     * reaches its super. The shadowed implementations stay in `importedMap`, and
     * this walks them. It exists for an entry point whose answer is a *composition*
     * of what every provider says rather than a choice between them (the portal
     * configuration is the first), where shadowing is the wrong default.
     */
    findHandlers(methodName: string): unknown[] {
        const method = this.methodPath(this._methodId(methodName));
        const handlers: unknown[] = [];
        this.importedMap?.forEach(imported => {
            if (Object.prototype.hasOwnProperty.call(imported, method))
                handlers.push(imported[method]);
        });
        return handlers;
    }
 
    findHandler(methodName: string): unknown {
        methodName = this.methodPath(this._methodId(methodName));
        return this.imported[methodName];
    }
 
    async request(...params: unknown[]): Promise<unknown> {
        return this._queue!.add(this._portLoop(params, true));
    }
 
    async publish(...params: unknown[]): Promise<unknown> {
        await this._queue!.add(this._portLoop(params, false));
        return [true, params[params.length - 1]];
    }
 
    async ready(): Promise<unknown> {
        return this.event('ready');
    }
 
    forNamespaces<R>(reducer: (prev: R, current: unknown) => R, initial: R): R {
        return this.namespaces().reduce(reducer.bind(this), initial);
    }

    async start(): Promise<unknown> {
        await this._api.attachHandlers(this, this.config.imports, true);
        const {req, pub} = this.forNamespaces(
            (
                prev: {
                    req: Record<string, (...args: unknown[]) => Promise<unknown>>;
                    pub: Record<string, (...args: unknown[]) => Promise<unknown>>;
                },
                next,
            ) => {
                if (typeof next === 'string') {
                    prev.req[`${next}.request`] = this.request.bind(this);
                    prev.pub[`${next}.publish`] = this.publish.bind(this);
                }
                return prev;
            },
            {req: {}, pub: {}},
        );
        this._register(req, 'ports', this.config.id, this.config.pkg);
        this._subscribe(pub, 'ports', this.config.id, this.config.pkg);
        const {context: _, ...config} = this.config;
        return this.event('start', {configBase: this.configBase, config});
    }
 
    async attach(
        patterns: (string | RegExp)[] | string | RegExp,
        target: object = {},
    ): Promise<object> {
        await this._api.attach(target, patterns);
        return target;
    }

    async handle(...params: unknown[]): Promise<unknown> {
        const $meta = params && params.length > 1 && (params[params.length - 1] as IMeta);
        if ($meta && typeof $meta === 'object') this._attachCheckpoint?.($meta);
        const method = ($meta && $meta.method) || 'exec';
        const handler = this.findHandler(method) || this.imported['exec'];
        if (handler instanceof Function) {
            const run = () => handler.apply(this, params);
            // A call the caller declared is answered by writing one record here, inside the
            // leg that arrived: that is what turns the caller's declaration into a receipt
            // the ledger can match, and it happens only when a flow was traced at all, so an
            // untraced request still pays nothing.
            const answered = async (): Promise<unknown> => {
                const inbound = inboundIdentities($meta as IMeta);
                const traced = isFlowId(inbound.flow) && inbound.leg !== undefined;
                if (traced) {
                    // The receipt is the receiver's record for the leg it was handed. It carries
                    // no declared target - the caller named the ends - so the ledger can tell a
                    // receipt from a declaration by the leg alone, in one process or many.
                    portLogCalls(this)?.received(inbound.leg as string);
                    // And the collection starts *before* the handler runs, because the boxes it will
                    // read are installed with `enterWith`: one created after the handler's first wait
                    // never reaches the frame that answers for the call (T-136).
                    beginProgress();
                }
                const result = await run();
                // What the handler announced while it ran (`$meta.checkpoint`, `$meta.decide`) is
                // staged in the scope around it and written on no record of its own: the records
                // of a call are the framework's, written before the handler starts and after it
                // returns. Reading the progress here — inside that scope, once the handler is
                // done — is what lets the call answer with its own work: a point becomes a note
                // beside this hop, and a branch becomes the alternative that was taken
                // (PRD R26/R27). Nothing is written when a handler announced nothing, so an
                // uninstrumented call still costs one scope read.
                if (traced) {
                    const progress = takeProgress();
                    if (progress !== undefined) {
                        attachProgress(progress);
                        portLogCalls(this)?.answered(inbound.leg as string);
                    }
                }
                return result;
            };
            // The callee adopts the identity its caller declared, so the records its
            // handler writes belong to the caller's execution and its own calls are
            // declared against the same one. Only adopt, never mint: the two places
            // that mint a flow are the external request and the cross-process call,
            // and a port that invented one would fill the ledger with runs nobody
            // asked for.
            //
            // Measured (T-115): the identity *is* on `$meta` here — the gateway route
            // publishes it before it makes the local call — while the callee's handler
            // otherwise runs in whatever context its transport scheduled it in, where
            // `declareCall` finds no flow. What this does *not* do is make a quiet call
            // visible: a recorded call is a record written inside it, and the ports that
            // make calls in a served request log nothing at that moment. The leg is
            // bound correctly; whether it can be seen depends on the callee logging.
            return isFlowId(inboundIdentities($meta as IMeta).flow)
                ? adoptInbound($meta as IMeta, method, answered)
                : run();
        } else {
            throw this.errors['adapter.methodNotFound']({params: {method}});
        }
    }
 
    connect(what?: net.Socket | (() => void), context?: C): void {
        what ??= this.handle.bind(this);
        context ??= this.config.context;
        this._portLoop = loop(what, this as any, context); // eslint-disable-line @typescript-eslint/no-explicit-any
        this._resolveConnected?.(true);
    }
 
    async connected(): Promise<boolean> {
        return this._connected;
    }
 
    async stop(): Promise<unknown> {
        return this.event('stop');
    }
}
 
/**
 * Create an adapter instance from the API and handler definitions.
 *
 * The `AdapterBase` class is instantiated here (not imported by realms) and
 * placed at the end of the handler prototype chain.  This preserves the
 * constraint that realms/solutions never depend on blong-gogo.
 */
export default async function adapter<T, C extends IContext>(
    api: IApi,
    configBase: string,
    activationNames: string[] = [],
): Promise<Adapter<T, C>> {
    const {
        adapter: adapterFactory,
        utError,
        handlers,
        remote,
        rpc,
        local,
        registry,
        type,
        schema,
    } = api;
    _errors ||= utError.register(errorMap);
 
    const base = new AdapterBase<T, C>(api, configBase, activationNames);
 
    const result = handlers!({
        utError,
        remote,
        type,
        schema: registry.objectSchema,
        manifest: api.manifest,
    });
    /**
     * The base an instance names, from the process or from the realm that ships it.
     *
     * A port this process runs answers from `ports`, which is where the loader puts a child it
     * imported. A prototype a realm ships with `thunk` is not a port — nothing serves it, so nothing
     * starts it — and it answers from that realm's resolver instead, which is the one place the
     * module is imported (`@@T-593`).
     */
    type BaseFactory = (api: unknown) => object;
    const resolveBase = async (id: string): Promise<BaseFactory | undefined> =>
        (adapterFactory(id) as unknown as BaseFactory | undefined) ??
        ((await registry.thunks?.get(id)?.()) as BaseFactory | undefined);
    let current = result;
    while (current.extends) {
        const parent = await (typeof current.extends === 'string'
            ? (await resolveBase(current.extends))!({
                  utError,
                  remote,
                  rpc,
                  local,
                  registry,
                  schema,
                  manifest: api.manifest,
              })
            : current.extends({
                  utError,
                  remote,
                  rpc,
                  local,
                  registry,
                  schema,
                  manifest: api.manifest,
              }));
        Object.setPrototypeOf(current, parent);
        current = parent;
    }
    Object.setPrototypeOf(current, base);
 
    return result as Adapter<T, C>;
}