import { Readable } from 'node:stream' import { current, encode } from 'openspan' import { Connector } from './connector.ts' import { derive, newid } from './entities/newid.ts' import { RequestContractException, SafetyException, UnrepeatableException } from './exceptions.ts' import { abandoned, waiting } from './abandon.ts' import * as addressed from './instance.ts' import * as trail from './trail.ts' import type { Transmission } from './transmission.ts' import type { Request as Contract } from './contract/request.ts' import type { Terms } from './types/bindings.ts' import type { Envelope, Options, Reply, Request, Source } from './types/request.ts' export class Call extends Connector { readonly #transmitter: Transmission readonly #contract: Contract /** what this calls, as a hop is named, so that an identity derived here names it too */ readonly #target: string readonly #source: Source | undefined /** whether a call to it names the process it goes to */ readonly #stateful: boolean /** whether what it calls is incapable of changing the State; see `safety.ts` */ readonly #safe: boolean /** the input property a stream is carried in, where what it calls takes one */ readonly #streamed: string | undefined /** whether what it calls declares `once`; see `documentation/inbox.md` */ readonly #once: boolean // eslint-disable-next-line max-params public constructor( transmitter: Transmission, contract: Contract, target: string, source?: Source, stateful: boolean = false, safe: boolean = false, streamed?: string, once: boolean = false ) { super() this.#transmitter = transmitter this.#contract = contract this.#target = target this.#source = source this.#stateful = stateful this.#safe = safe this.#streamed = streamed this.#once = once this.depends(transmitter) } public async invoke(request: Request = {}, options: Options = {}): Promise { const invocation = trail.current() /* * The process a call goes to, which the transmission is handed beside what the call asks, and * what the caller said of reading, which is not the answer on its own. */ const { instance, readonly: stated, ...asked } = request /* * The disjunction is what makes it a guarantee rather than a convention: a caller under a * readonly invocation cannot clear it for a call of its own. */ const readonly = stated === true || invocation?.readonly === true /* * A retried transition makes this call again on every attempt, and under an identity of its * own each time, so what is made once would be made once per attempt. Refused on the first * as on any other. */ if (this.#once && invocation?.retried === true) throw new UnrepeatableException( `'${this.#target}' is made once, and a transition retried on a lost write would make it again` ) this.#refuse(request, options, readonly) /* * The envelope is built around what the caller asked for rather than written over it: one * request object is handed to several concurrent calls in more than one place, and those are * different calls — sharing one identity would have all but the first refused as duplicates * of it. */ const envelope: Envelope = { ...asked, // avoid validation on the recipient's side authentic: true, // an operation that takes no input still has to send an explicit null input: request.input ?? null, id: request.id ?? this.#identity(invocation), /* * What a receiver has already put on the request wins, and a service with no chain in * scope starts one under its own name. */ trail: request.trail ?? invocation?.hops ?? service(this.#source), // the caller may have attributed the call itself, as the node bridge does source: request.source ?? this.#source } // nothing carries a key it has no value for onto the wire if (envelope.source === undefined) delete envelope.source if (envelope.trail === undefined) delete envelope.trail if (readonly) envelope.readonly = true this.#contract.fit(envelope) const context = current() if (context !== undefined) envelope.telemetry = encode(context) const reply = await this.#transmit( envelope, this.#terms(instance, options.timeout, options.signal) ) if (reply === null) return null else if (reply instanceof Readable) return reply else { if (reply.exception !== undefined) throw reply.exception if (reply.error !== undefined) return new CodedError(reply.error) else return reply.output } } public explain(): any { return this.#contract.discovery } /** * Derived where this process is serving a call, so that the same call served twice makes the * same call here twice over and whatever it reaches refuses its own copy; minted where there * is nothing to derive from, which is an entry point, or a caller from before identities. */ #identity(invocation: trail.Invocation | undefined): string { if (invocation?.id === undefined) return newid() return derive(invocation.id, this.#target, trail.ordinal(invocation, this.#target)) } /** A call whose making contradicts what it calls is refused before anything is sent. */ #refuse(request: Request, options: Options, readonly: boolean): void { const { instance, task } = request const { timeout, signal } = options if (readonly && !this.#safe) throw new SafetyException( `'${this.#target}' may change state, and this call may only read` ) if (this.#stateful && instance === undefined) throw new RequestContractException( `'${this.#target}' is stateful, and a call to it names \`instance\`` ) if (!this.#stateful && instance !== undefined) throw new RequestContractException( `'${this.#target}' is stateless, and a call to it names no \`instance\`` ) // a task is taken by whichever process is free, and a stateful operation is served // under the name of one if (this.#stateful && task === true) throw new RequestContractException( `'${this.#target}' is stateful, and a call to it is no task` ) // nobody waits for a task, and it is made from wherever the queue is consumed if (task === true && (timeout !== undefined || signal !== undefined)) throw new RequestContractException('A task names no `timeout` and no `signal`') // an ordinary call is answered eventually, and what nobody could answer is parked with who // asked — which only means something to a caller still waiting if (!this.#stateful && (timeout !== undefined || signal !== undefined)) throw new RequestContractException( `'${this.#target}' is stateless, and a call to it names no \`timeout\` and no \`signal\`` ) if (this.#streamed !== undefined) { // a task is taken later, by a process whose caller is no longer holding a stream if (task === true) throw new RequestContractException( `'${this.#target}' takes a stream, and a task carries none` ) // the contract has the property, and only what is made here can say what is in it if (!carries(request.input, this.#streamed)) throw new RequestContractException( `'${this.#target}' takes a stream at '${this.#streamed}', which this call carries none of` ) } if (timeout !== undefined && !(Number.isFinite(timeout) && timeout > 0)) throw new RequestContractException('`timeout` is a positive number of milliseconds') } /** * What the transmission is handed beside the envelope. An addressed call always waits for a set * time — its caller's, or the context's — because nothing else ends a call to a process that has * gone; an ordinary call waits for as long as it takes, and is handed nothing. */ #terms(instance?: string, timeout?: number, signal?: AbortSignal): Terms | undefined { if (instance === undefined) return undefined const deadline = timeout ?? addressed.timeout() const expiry = AbortSignal.timeout(deadline) return { instance, timeout: deadline, signal: signal === undefined ? expiry : AbortSignal.any([signal, expiry]) } } /** The reply, or *abandoned* once the caller has stopped waiting, however the wait ended. */ async #transmit(envelope: Envelope, terms: Terms | undefined): Promise { const signal = terms?.signal // a call its caller stopped waiting for before it was made is handed to no binding if (signal?.aborted === true) throw abandoned(this.#target, signal) return await waiting(this.#transmitter.request(envelope, terms), signal, this.#target) } } /** * Whether the input carries a stream where the operation takes one: the property itself where its * caller said nothing about it, and the property's `stream` where a route filled one. */ function carries(input: unknown, property: string): boolean { if (input === null || typeof input !== 'object') return false const carried: unknown = (input as Record)[property] if (carried instanceof Readable) return true if (carried === null || typeof carried !== 'object') return false return (carried as { stream?: unknown }).stream instanceof Readable } /** Where a service calls from no invocation, the chain starts under the service's own name. */ function service(source: Source | undefined): string[] | undefined { return source !== undefined && 'service' in source ? [source.service] : undefined } /* * The error as a value. `code` and `cause` are its own enumerable properties, so whatever copies * or serialises it — a response body, an answer kept — yields the two and nothing else. */ class CodedError extends Error { public readonly code: string public constructor(error: NonNullable) { super(error.code) this.code = error.code if (error.cause !== undefined) this.cause = error.cause } }