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 | 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 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 1x 1x 1x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5608x 5608x 5608x 5608x 5608x 5608x 5608x 1612x 5608x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5710x 5710x 5710x 5710x 5710x 5710x 5710x 5710x 5710x 5710x 5710x 5710x 1612x 1612x 1612x 1612x 1612x 1612x 1612x 1612x 1612x 1612x 911x 911x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1168x 1168x 1168x 1168x 1168x 1168x 1168x 1168x 1168x 1167x 1167x 1168x 1168x 3691x 3691x 1612x 1612x 2090x 2090x 2090x 5x 11x 2x 2x 2x 2x 11x 1x 1x 1x 1x 2090x 2079x 2079x 2079x 2079x 2078x 2078x 3885x 212x 212x 212x 212x 212x 212x 212x 212x 1x 1x 41x 41x 1x 25x 25x 1x | import type {
Errors,
HRTime,
IErrorFactory,
IErrorMap,
ILocal,
ILog,
IMeta,
IPlatformApi,
IRemote,
ITypedError,
RemoteMethod,
} from '@feasibleone/blong/types';
import { Internal } from '@feasibleone/blong/types';
const errorMap: IErrorMap = {
'remote.bindingFailed': 'Method binding failed for {typeName} {methodType} {methodName}',
'remote.cacheFailed': 'Method cache failed for {typeName} {methodType} {methodName}',
'remote.cacheOperationMissing':
'Cache before and after operations missing for {typeName} {methodType} {methodName}',
'remote.noMeta': '$meta not passed to method: {method}',
'remote.timeout': 'Method {method} timed out',
};
export default class Remote extends Internal implements IRemote {
#config: {
/**
* Whether a call may be answered in this process instead of through the transport: `true` for
* every method, `false` for none, or a regular-expression *source* matched against the method
* name for the ones that belong here ({@link canAnswerLocally}).
*
* A configured gateway still wins, and deliberately: a method a gateway is declared for is not
* this process's to answer, and a deployment that wants an exception says so on the other side
* — `GatewayCodec`'s `skipGateway` keeps the method out of the gateway, and this is what the
* fallback then resolves by. Asking the same question in two places would make the two settings
* disagreeable; asking it here only when nothing else claims the call keeps them composable.
*/
canSkipSocket: boolean | string;
requireMeta: 'trace' | 'debug' | 'warn' | 'error' | 'fatal' | 'info' | true;
} = {
canSkipSocket: false,
requireMeta: true,
};
#importCache: Record<string, unknown> = {};
#requireMeta: ((method: string) => void) | null;
#errors: Errors<typeof errorMap>;
#local: ILocal;
#platform: IPlatformApi;
/**
* The compiled pattern of each `canSkipSocket` source seen, `null` for one that does not compile.
*
* Per source rather than one slot, because a reload replaces the config and a process may see more
* than one value in its life; the map is small enough that keeping the earlier ones costs nothing.
*/
#skipPatterns = new Map<string, RegExp | null>();
#brokerRequest: RemoteMethod;
#brokerPublish: RemoteMethod;
public constructor(
// Declared rather than read off the caller's own interface, because a type that names only
// `logLevel` refuses the value the loader actually passes — `canSkipSocket` among them.
config: {logLevel?: Parameters<ILog['logger']>[0]; canSkipSocket?: boolean | string},
{
log,
error,
local,
platform,
}: {log: ILog; error: IErrorFactory; local: ILocal; platform: IPlatformApi},
) {
super({log});
config = this.merge(this.#config, config);
this.#local = local;
this.#platform = platform;
this.#errors = error.register(errorMap);
switch (this.#config.requireMeta) {
case 'trace':
case 'debug':
case 'info':
case 'warn': {
this.#requireMeta = method => {
this.log?.[this.#config.requireMeta as 'trace' | 'debug' | 'info' | 'warn']?.(
this.#errors['remote.noMeta']({params: {method}}),
);
};
break;
}
case 'error':
case 'fatal':
case true: {
const logLevel =
this.#config.requireMeta === true ? 'error' : this.#config.requireMeta;
this.#requireMeta = method => {
const error = this.#errors['remote.noMeta']({params: {method}});
this.log?.[logLevel]?.(error);
throw error;
};
break;
}
default:
this.#requireMeta = null;
break;
}
this.#brokerRequest = this._getMethod('req', 'request', undefined, {returnMeta: true});
this.#brokerPublish = this._getMethod('pub', 'publish', undefined, {returnMeta: true});
}
protected gateway(..._args: unknown[]): object | void {}
protected spare(time: HRTime, latency?: number): number {
return this.#platform.timing.spare(time, latency);
}
protected sender(methodType: 'request' | 'publish', typeName: 'req' | 'pub'): RemoteMethod {
return async (...rest: unknown[]) => {
const $meta = rest.pop() as IMeta;
throw this.#errors['remote.bindingFailed']({
params: {
methodName: $meta.method,
methodType,
typeName,
},
});
};
}
public remote(methodName: string, options?: {method?: string; timeout?: number}): RemoteMethod {
methodName = options?.method || methodName;
let result; // = !options && this.#importCache[methodName];
const startRetry = (
fn: () => Promise<unknown>,
{timeout, retry}: {timeout?: number; retry?: number},
): Promise<unknown> => {
return new Promise((resolve, reject) => {
const attempt = (): void => {
fn()
.then(resolve)
.catch((error: {params?: {method: string}}) => {
// todo maybe log these errors
if (timeout && Date.now() > timeout) {
if (error) error.params = {method: 'methodName'};
reject(this.#errors['remote.timeout'](error));
} else {
setTimeout(attempt, retry);
}
});
};
attempt();
});
};
if (!result) {
const method = this._getMethod(
'req',
'request',
methodName,
(options ?? {}) as {fallback?: boolean; returnMeta?: boolean; timeout?: number},
);
result = Object.assign(function (...params: unknown[]) {
const $meta = params.length > 1 && (params[params.length - 1] as IMeta);
if ($meta && $meta.timeout && $meta.retry) {
return startRetry(
() => method(...params),
$meta as unknown as {timeout?: number; retry?: number},
);
} else {
return method(...params);
}
}, method);
if (!options) this.#importCache[methodName!] = result;
Object.defineProperty(result, 'name', {
value: methodName,
configurable: true,
enumerable: false,
});
}
return result;
}
private _getMethod(
typeName: 'req' | 'pub',
methodType: 'request' | 'publish',
methodName: string | undefined,
options: {
fallback?: boolean;
returnMeta?: boolean;
timeout?: number;
cache?: IMeta['cache'];
},
): RemoteMethod {
let fn: RemoteMethod | null = null;
let unpack = true;
const fallback = options && options.fallback;
const timeoutSec = (options && options.timeout && Math.floor(options.timeout / 1000)) || 0;
const timeoutNSec = (options && options.timeout && (options.timeout % 1000) * 1000000) || 0;
let fnCache: RemoteMethod | null = null;
const cache = options && options.cache;
const busMethod: RemoteMethod = async (...params) => {
const $meta = (params.length > 1 && params[params.length - 1]) as IMeta;
let $applyMeta: IMeta;
if (!$meta) {
this.#requireMeta?.(methodName!);
params.push(($applyMeta = {method: methodName}));
} else {
$applyMeta = params[params.length - 1] = {
...$meta,
...($meta.forward && {forward: {...$meta.forward}}),
};
}
if (options && options.timeout && !$applyMeta.timeout) {
$applyMeta.timeout = this.#platform.timing.now();
$applyMeta.timeout[1] += timeoutNSec;
$applyMeta.timeout[0] += timeoutSec;
if ($applyMeta.timeout[1] >= 1000000000) {
$applyMeta.timeout[0]++;
$applyMeta.timeout[1] -= 1000000000;
}
}
if (!fn) {
// don't try skipping socket if there is a gateway configured
if (methodName && !this.gateway?.($applyMeta, methodName)) {
if (this.canAnswerLocally(methodName))
fn = this._findMethod(methodName, methodType);
if (fn) unpack = true;
else if (this.canAnswerLocally(methodName)) {
// Visibility: under canSkipSocket every call is expected
// to resolve locally. A missing method (e.g. a derived
// handler name that doesn't match a registered file —
// `$subject$objectModel` vs `$subject$ObjectModel`) would
// otherwise fail or hang silently. Name it so the typo /
// case / placeholder mismatch is obvious.
this.signal?.frameworkRemoteMethodNotFound?.({method: methodName});
}
}
if (!fn) {
fn = this.sender(methodType, typeName);
}
}
if (cache && !fnCache) {
fnCache = this._findMethod(`${cache.port || 'cache'}`, methodType);
// todo || bus.rpc.brokerMethod(typeName, methodType);
if (!fnCache && !cache.optional) {
return Promise.reject(
this.#errors['remote.cacheFailed']({
params: {
typeName,
methodType,
methodName,
},
}),
);
}
}
if (fn) {
let $metaBefore, $metaAfter;
if (methodName) {
$applyMeta.opcode = this._getOpcode(methodName);
if (!['request', 'notification'].includes($applyMeta.mtid ?? ''))
$applyMeta.mtid = 'request';
$applyMeta.method = methodName!;
if (cache) {
const before =
cache.instead ||
cache.before ||
{
get: 'get',
fetch: 'get',
add: false,
create: false,
edit: 'drop',
update: 'drop',
delete: 'drop',
remove: 'drop',
}[$applyMeta.opcode];
$metaBefore = before && {
method: methodName,
timeout: $applyMeta.timeout,
auth: $applyMeta.auth,
cache: {
key: cache.key,
ttl: cache.ttl,
operation: before,
},
};
const after =
cache.after ||
{
get: 'set',
fetch: 'set',
add: 'set',
create: 'set',
edit: 'set',
update: 'set',
delete: false,
remove: false,
}[$applyMeta.opcode];
$metaAfter = after && {
method: methodName,
timeout: $applyMeta.timeout,
auth: $applyMeta.auth,
cache: {
key: cache.key,
ttl: cache.ttl,
operation: after,
},
};
if (!$metaBefore && !$metaAfter) {
return Promise.reject(
this.#errors['remote.cacheOperationMissing']({
params: {
typeName,
methodType,
methodName,
},
}),
);
}
if (typeof cache.key === 'function') {
const key = await cache.key(params[0]);
if ($metaBefore) $metaBefore.cache.key = key;
if ($metaAfter) $metaAfter.cache.key = key;
}
}
}
let applyFn;
try {
const cached = (fnCache &&
$metaBefore &&
$metaBefore.cache.key &&
(await fnCache.call(this, params[0], $metaBefore))) as unknown[];
if (cached && cached[0] !== null) return cached[0];
if (cache && cache.instead) return cached && cached[0];
applyFn = fn;
const result = (await fn.apply(this, params)) as unknown[];
if (
fnCache &&
$metaAfter &&
$metaAfter.cache.key &&
typeof result[0] !== 'undefined'
)
await fnCache.call(this, result[0], $metaAfter);
if ($meta.timer) {
const $resultMeta = result.length > 1 && result[result.length - 1];
if ($resultMeta && ($resultMeta as {calls?: string}).calls)
$meta.timer(($resultMeta as {calls?: string}).calls);
}
if (!unpack || (options && options.returnMeta)) {
return result;
}
return result[0];
} catch (error) {
if (
typeof fallback === 'function' &&
fallback !== applyFn &&
(error as {type?: string}).type === 'bus.methodNotFound'
) {
if (fn) fn = fallback as unknown as RemoteMethod;
unpack = false;
return fn!.apply(this, params);
}
return Promise.reject(this._processError(error as ITypedError, $applyMeta));
}
} else {
return Promise.reject(
this.#errors['remote.bindingFailed']({
params: {
typeName,
methodType,
methodName,
},
}),
);
}
};
return busMethod;
}
public dispatch(...params: unknown[]): boolean | Promise<unknown> {
const $meta = (params.length > 1 && params[params.length - 1]) as IMeta;
let mtid;
if ($meta) {
mtid = $meta.mtid;
if (mtid === 'discard') return true;
const handler =
this.canAnswerLocally($meta.method) &&
this._findMethod($meta.method!, mtid === 'request' ? 'request' : 'publish');
if (handler) {
return Promise.resolve(handler(...params));
} else {
if (mtid === 'request') {
return this.#brokerRequest(...params);
} else {
return this.#brokerPublish(...params);
}
}
} else {
return false;
}
}
private _getPath(method: string): string {
return method.match(/^[^[#?]*/)?.[0] || method;
}
private _getOpcode(name: string): string {
return this._getPath(name).split('.').pop()!;
}
/**
* Whether a method may be answered in this process rather than through the transport.
*
* `true` and `false` are the two ends — a process that carries everything answers everything, one
* that carries only its own realm answers nothing — and the string is the middle: a
* regular-expression *source*, read against the method name, for a process that serves some of what
* it can reach and has to send the rest out. The pattern is compiled once per value, because a
* reload replaces the config.
*
* A source that does not compile is not a reason to refuse every call: it is reported once and
* treated as nothing matching, which leaves the process dialling as it would have with `false`.
*
* The caller decides *when* to ask ({@link _getMethod} asks only where no gateway claims the call),
* so nothing here knows about gateways: this is the local half of the question and the routing half
* lives in the codec that actually routes.
*/
protected canAnswerLocally(methodName: string | undefined): boolean {
const {canSkipSocket} = this.#config;
if (canSkipSocket === true) return true;
if (typeof canSkipSocket !== 'string' || !methodName) return false;
const cached = this.#skipPatterns.get(canSkipSocket);
if (cached !== undefined) return cached ? cached.test(methodName) : false;
try {
const pattern = new RegExp(canSkipSocket);
this.#skipPatterns.set(canSkipSocket, pattern);
return pattern.test(methodName);
} catch (error) {
this.#skipPatterns.set(canSkipSocket, null);
this.signal?.frameworkRemoteSkipPatternInvalid?.({pattern: canSkipSocket, error});
return false;
}
}
private _findMethod(methodName: string, type: 'request' | 'publish'): RemoteMethod {
methodName = this._getPath(methodName);
const key = ['ports', methodName, type].join('.');
let result = this.#local.get(key) || this.#local.get(methodName);
if (!result) {
const names = methodName.split('/')[0].split('.');
while (!result && names.length) {
result = this.#local.get(['ports', names.join('.'), type].join('.'));
names.pop();
}
}
return result && result.method;
}
private _processError(obj: ITypedError, $meta: IMeta): object {
if (obj && $meta && $meta.method) {
if (Array.isArray(obj.method)) {
obj.method.push($meta.method);
} else if (obj.method) {
obj.method = [obj.method, $meta.method];
} else {
obj.method = $meta.method;
}
}
return obj;
}
protected sanitize(
params: unknown,
{httpRequest, mtid, method, forward, language, cache}: IMeta,
): {params: unknown; meta: object} {
if (Array.isArray(params) && params.length) {
const paramsArray = [...params];
paramsArray[paramsArray.length - 1] = 'meta&';
params = paramsArray;
}
return {
params,
meta: {mtid, method, url: httpRequest?.url, language, forward, cache},
};
}
public async stop(): Promise<IRemote> {
return this as unknown as IRemote;
}
public async start(): Promise<IRemote> {
return this as unknown as IRemote;
}
}
|