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 | 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 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 1x 1x 55x 55x 55x 55x 55x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 1x 1x 12x 12x 8x 8x 8x 4x 12x 12x 1x 1x 343x 343x 1x 1x 290x 290x 290x 290x 290x 290x 290x 290x 1x 1x 339x 339x 339x 339x 339x 339x 1x 1x 347x 347x 347x 347x 347x 347x 347x 347x 339x 339x 339x 347x 347x 339x 339x 339x 347x 339x 339x 339x 347x 347x 334x 334x 334x 347x 347x 1x 1x 1x 1x 165x 162x 162x 162x 165x 165x 165x 228x 165x 165x 165x 165x 165x 165x 165x 2x 2x 165x 165x 165x 165x 1x 1x 1x 1x 1867x 1867x 1867x 1x 1x 170x 170x 1x 1x 1x 1x 55x 55x 1x 1x 55x 55x 55x 55x 55x 1x 1x 55x 55x 55x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 55x 55x 55x 55x 55x 55x 55x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 164x 164x 164x 164x 164x 164x 164x 164x 1x 1x 55x 55x 55x 55x 55x 1x 1x 55x 55x 1x 1x 55x 55x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 44x 44x 44x 44x 44x 44x 55x 55x 55x 55x | import type {
Adapter,
Config,
Errors,
IApi,
IContext,
IErrorMap,
IMeta,
ITypedError,
PortHandlerBound,
} from '@feasibleone/blong/types';
import type net from 'node:net';
import PQueue from 'p-queue';
import merge from 'ut-function.merge';
import ConfigRuntime from './ConfigRuntime.ts';
import {isExpectedError} from './lib.ts';
import loop from './loop.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[]};
};
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;
importedMap?: Map<string, Record<string, (...args: unknown[]) => unknown>>;
// 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'>;
_createLog: IApi['createLog'];
_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'
>,
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._api = api;
this._createLog = api.createLog;
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> {
this.config = merge(this.activeConfig(), ...configs) as Config<T, C>;
this.log = this._createLog?.(this.config.logLevel || 'info', {
...this.config.log,
name: this.config.id,
context: this.config.type ?? 'dispatch',
});
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,
);
}
error(error: ITypedError, $meta: IMeta): ITypedError {
if ($meta) error.method = $meta.method;
if (isExpectedError(error.type, $meta?.expect)) {
(this.log as {debug?: (...args: unknown[]) => void})?.debug?.(error);
return error;
}
(this.log as {error?: (...args: unknown[]) => void})?.error?.(error);
return error;
}
findValidation(): unknown {
return null;
}
handles(name: string): boolean {
if (reserved.includes(name)) return true;
const id = this.config.id.replace(/\./g, '-');
return ([] as (string | RegExp)[])
.concat(this.config.namespace || this.config.imports || id)
.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> {}
findHandler(methodName: string): unknown {
methodName = 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 {
const id = this.config.id.replace(/\./g, '-');
return ([] as (string | RegExp)[])
.concat(this.config.namespace || this.config.imports || id)
.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 link(
patterns: (string | RegExp)[] | string | RegExp,
target: AdapterHandlerContext = {} as unknown as AdapterHandlerContext,
): Promise<object> {
await this._api.attachHandlers(target, patterns);
return target.imported;
}
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) {
return handler.apply(this, params);
} 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} = api;
_errors ||= utError.register(errorMap);
const base = new AdapterBase<T, C>(api, configBase, activationNames);
const result = handlers!({utError, remote, type});
let current = result;
while (current.extends) {
const parent = await (typeof current.extends === 'string'
? adapterFactory(current.extends)!({utError, remote, rpc, local, registry})
: current.extends({utError, remote, rpc, local, registry}));
Object.setPrototypeOf(current, parent);
current = parent;
}
Object.setPrototypeOf(current, base);
return result as Adapter<T, C>;
}
|