feat: TypeScript client for Node, with a scriptable fake hub
A service in front of a hub needs four things: start a flow, follow it, read what a detached run produced, and decide approvals. This is that surface, plus the part a gateway cannot test without: a fake hub that speaks the same service from the same .proto files and can be scripted into every failure a real hub produces. Errors carry the hub's own class (chain-error-kind), a coarse family, and reachedHub, which separates a refused connection from a hub that reports a dependency as down. Both arrive as gRPC UNAVAILABLE, and a gateway that shows 'service not reachable' for the second one lies to its users. The .proto files are carried verbatim and loaded at runtime, so no generated code can drift from the contract; two guards hold the copies in place, and a skew suite runs the same client against a real hub binary. 32 hermetic tests plus 4 against a real hub. Signed-off-by: Dr. Stefan Flemming <sf@flemming.it>
This commit is contained in:
commit
b6c6cc8295
24 changed files with 5539 additions and 0 deletions
478
src/client.ts
Normal file
478
src/client.ts
Normal file
|
|
@ -0,0 +1,478 @@
|
|||
// The hub client.
|
||||
//
|
||||
// One method per thing a portal backend does: start a flow, follow
|
||||
// it, ask what became of it, decide an approval. Everything the
|
||||
// Ch∆In hub can do beyond that is reachable over the raw proto
|
||||
// surface (see `chainProto`), which this file does not try to mirror.
|
||||
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
|
||||
import { ChainError, asKind, chainErrorFrom, stepFromMessage } from './errors.js';
|
||||
import {
|
||||
type PayloadInput,
|
||||
type PayloadOutput,
|
||||
type WirePayload,
|
||||
payloadFromWire,
|
||||
payloadToWire,
|
||||
} from './payload.js';
|
||||
import { hubAdminServiceConstructor, hubServiceConstructor } from './proto.js';
|
||||
|
||||
/** Client certificates and roots, for a hub behind mTLS. */
|
||||
export interface TlsOptions {
|
||||
/** PEM of the CA that signed the hub's certificate. */
|
||||
rootCerts?: Buffer;
|
||||
/** PEM of this client's private key (mTLS). */
|
||||
privateKey?: Buffer;
|
||||
/** PEM of this client's certificate chain (mTLS). */
|
||||
certChain?: Buffer;
|
||||
}
|
||||
|
||||
/** How to reach the hub. */
|
||||
export interface ChainClientOptions {
|
||||
/** `host:port`, e.g. `127.0.0.1:50051`. */
|
||||
address: string;
|
||||
/** Bearer token, when the hub requires one. */
|
||||
token?: string;
|
||||
/** TLS. `true` uses the system roots; an object pins roots or adds a client certificate. */
|
||||
tls?: TlsOptions | true;
|
||||
/** Project every call belongs to unless a call overrides it. */
|
||||
project?: string;
|
||||
/** Deadline for a single call, in milliseconds. Default 30000. */
|
||||
deadlineMs?: number;
|
||||
/** Passed through to grpc-js, e.g. message size limits. */
|
||||
channelOptions?: grpc.ChannelOptions;
|
||||
}
|
||||
|
||||
/** Starting a flow. */
|
||||
export interface SubmitOptions {
|
||||
/** The flow definition as YAML. */
|
||||
flowYaml: string;
|
||||
/** Named flow inputs. */
|
||||
inputs?: Record<string, PayloadInput>;
|
||||
/** Project this run belongs to; defaults to the client's. */
|
||||
project?: string;
|
||||
/**
|
||||
* Return as soon as the run has an id and keep it running in the
|
||||
* background. Follow it with `getStatus` / `getResult`.
|
||||
*/
|
||||
detach?: boolean;
|
||||
/**
|
||||
* The caller's key for "this is the same request as before". A
|
||||
* second submit with a key the hub has already seen returns the
|
||||
* first run instead of starting a second one. Needed wherever the
|
||||
* caller may retry, for example a payment webhook.
|
||||
*/
|
||||
idempotencyKey?: string;
|
||||
/** Deadline for this call; defaults to the client's. */
|
||||
deadlineMs?: number;
|
||||
}
|
||||
|
||||
/** What a finished run produced. */
|
||||
export interface FlowResult {
|
||||
/** The hub's id for this run. */
|
||||
invocationId: string;
|
||||
/** The flow's declared outputs. */
|
||||
outputs: Record<string, PayloadOutput>;
|
||||
}
|
||||
|
||||
/** Where a detached run stands. */
|
||||
export interface InvocationStatus {
|
||||
phase: 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED' | 'PHASE_UNKNOWN';
|
||||
/** Step currently executing, empty unless running. */
|
||||
currentStep: string;
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
/** Error message when the phase is FAILED. */
|
||||
error: string;
|
||||
}
|
||||
|
||||
/** One thing that happened while a flow ran. */
|
||||
export type FlowEvent =
|
||||
| { type: 'stepStarted'; step: string; capability: string }
|
||||
| { type: 'stepFinished'; step: string; ok: boolean; durationMs: number }
|
||||
| { type: 'moduleEvent'; step: string; name: string; payload: PayloadOutput }
|
||||
| { type: 'result'; result: FlowResult };
|
||||
|
||||
/** A step waiting for a human decision. */
|
||||
export interface Approval {
|
||||
approvalId: string;
|
||||
flowExecution: string;
|
||||
flowName: string;
|
||||
stepId: string;
|
||||
/** What the reviewer is being asked, written by the flow. */
|
||||
prompt: string;
|
||||
payloadPreview: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
status: string;
|
||||
decidedAt: string;
|
||||
decidedBy: string;
|
||||
reason: string;
|
||||
project: string;
|
||||
}
|
||||
|
||||
/** Deciding an approval. */
|
||||
export interface DecideApprovalOptions {
|
||||
approvalId: string;
|
||||
/** True approves, false rejects. */
|
||||
approve: boolean;
|
||||
/**
|
||||
* Who decided. The hub overrides this with the identity behind the
|
||||
* token when it can verify one, so this is a fallback, not a claim
|
||||
* the hub trusts blindly.
|
||||
*/
|
||||
reviewer?: string;
|
||||
/** Why. Required when rejecting. */
|
||||
reason?: string;
|
||||
deadlineMs?: number;
|
||||
}
|
||||
|
||||
/** Health of the hub. */
|
||||
export interface HubHealth {
|
||||
state: 'SERVING' | 'NOT_SERVING' | 'UNKNOWN';
|
||||
detail: string;
|
||||
}
|
||||
|
||||
interface WireSubmitResponse {
|
||||
invocationId?: { value?: string };
|
||||
outputs?: Record<string, WirePayload>;
|
||||
}
|
||||
|
||||
type UnaryCallback<T> = (err: grpc.ServiceError | null, res?: T) => void;
|
||||
|
||||
const DEFAULT_DEADLINE_MS = 30_000;
|
||||
|
||||
/** A connection to one hub. */
|
||||
export class ChainClient {
|
||||
private readonly hub: grpc.Client;
|
||||
private readonly admin: grpc.Client;
|
||||
private readonly token: string | undefined;
|
||||
private readonly project: string;
|
||||
private readonly deadlineMs: number;
|
||||
|
||||
constructor(options: ChainClientOptions) {
|
||||
const credentials = options.tls
|
||||
? grpc.credentials.createSsl(
|
||||
options.tls === true ? undefined : options.tls.rootCerts,
|
||||
options.tls === true ? undefined : options.tls.privateKey,
|
||||
options.tls === true ? undefined : options.tls.certChain,
|
||||
)
|
||||
: grpc.credentials.createInsecure();
|
||||
const channelOptions = options.channelOptions ?? {};
|
||||
const Hub = hubServiceConstructor();
|
||||
const HubAdmin = hubAdminServiceConstructor();
|
||||
this.hub = new Hub(options.address, credentials, channelOptions);
|
||||
this.admin = new HubAdmin(options.address, credentials, channelOptions);
|
||||
this.token = options.token;
|
||||
this.project = options.project ?? '';
|
||||
this.deadlineMs = options.deadlineMs ?? DEFAULT_DEADLINE_MS;
|
||||
}
|
||||
|
||||
/** Close both channels. Pending calls fail with `cancelled`. */
|
||||
close(): void {
|
||||
this.hub.close();
|
||||
this.admin.close();
|
||||
}
|
||||
|
||||
private metadata(): grpc.Metadata {
|
||||
const md = new grpc.Metadata();
|
||||
if (this.token) md.set('authorization', `Bearer ${this.token}`);
|
||||
return md;
|
||||
}
|
||||
|
||||
private options(deadlineMs?: number): grpc.CallOptions {
|
||||
return { deadline: Date.now() + (deadlineMs ?? this.deadlineMs) };
|
||||
}
|
||||
|
||||
private unary<Req, Res>(
|
||||
client: grpc.Client,
|
||||
method: string,
|
||||
request: Req,
|
||||
deadlineMs?: number,
|
||||
): Promise<Res> {
|
||||
return new Promise<Res>((resolve, reject) => {
|
||||
const fn = (client as unknown as Record<string, unknown>)[method];
|
||||
if (typeof fn !== 'function') {
|
||||
reject(new Error(`grpc method ${method} not found on the client`));
|
||||
return;
|
||||
}
|
||||
const callback: UnaryCallback<Res> = (err, res) => {
|
||||
if (err) {
|
||||
reject(chainErrorFrom(err));
|
||||
return;
|
||||
}
|
||||
resolve((res ?? {}) as Res);
|
||||
};
|
||||
(fn as (...args: unknown[]) => unknown).call(
|
||||
client,
|
||||
request,
|
||||
this.metadata(),
|
||||
this.options(deadlineMs),
|
||||
callback,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** Is the hub serving? */
|
||||
async health(deadlineMs?: number): Promise<HubHealth> {
|
||||
const res = await this.unary<Record<string, never>, { state?: string; detail?: string }>(
|
||||
this.hub,
|
||||
'health',
|
||||
{},
|
||||
deadlineMs,
|
||||
);
|
||||
const state = res.state === 'SERVING' || res.state === 'NOT_SERVING' ? res.state : 'UNKNOWN';
|
||||
return { state, detail: res.detail ?? '' };
|
||||
}
|
||||
|
||||
private submitRequest(options: SubmitOptions): Record<string, unknown> {
|
||||
const inputs: Record<string, WirePayload> = {};
|
||||
for (const [name, value] of Object.entries(options.inputs ?? {})) {
|
||||
inputs[name] = payloadToWire(value);
|
||||
}
|
||||
return {
|
||||
flowYaml: Buffer.from(options.flowYaml, 'utf8'),
|
||||
inputs,
|
||||
detach: options.detach ?? false,
|
||||
project: options.project ?? this.project,
|
||||
idempotencyKey: options.idempotencyKey ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
private static resultFrom(res: WireSubmitResponse): FlowResult {
|
||||
const outputs: Record<string, PayloadOutput> = {};
|
||||
for (const [name, payload] of Object.entries(res.outputs ?? {})) {
|
||||
outputs[name] = payloadFromWire(payload);
|
||||
}
|
||||
return { invocationId: res.invocationId?.value ?? '', outputs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a flow and wait for it.
|
||||
*
|
||||
* With `detach: true` it returns once the run has an id; the
|
||||
* outputs are then empty and `getResult` fetches them later.
|
||||
*/
|
||||
async submit(options: SubmitOptions): Promise<FlowResult> {
|
||||
const res = await this.unary<Record<string, unknown>, WireSubmitResponse>(
|
||||
this.hub,
|
||||
'submit',
|
||||
this.submitRequest(options),
|
||||
options.deadlineMs,
|
||||
);
|
||||
return ChainClient.resultFrom(res);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a flow and follow it step by step.
|
||||
*
|
||||
* The iterator ends after the `result` event. A run that fails
|
||||
* throws a `ChainError` carrying the hub's error class, so the
|
||||
* events seen so far stay valid and the failure is not a silent
|
||||
* end of stream.
|
||||
*/
|
||||
async *submitStream(options: SubmitOptions): AsyncGenerator<FlowEvent, void, void> {
|
||||
const fn = (this.hub as unknown as Record<string, unknown>).submitStream;
|
||||
if (typeof fn !== 'function') throw new Error('grpc method submitStream not found');
|
||||
const call = (fn as (...args: unknown[]) => grpc.ClientReadableStream<unknown>).call(
|
||||
this.hub,
|
||||
this.submitRequest(options),
|
||||
this.metadata(),
|
||||
this.options(options.deadlineMs),
|
||||
);
|
||||
|
||||
const queue: FlowEvent[] = [];
|
||||
let failure: unknown;
|
||||
let done = false;
|
||||
let wake: (() => void) | undefined;
|
||||
const signal = () => {
|
||||
const w = wake;
|
||||
wake = undefined;
|
||||
w?.();
|
||||
};
|
||||
|
||||
call.on('data', (event: Record<string, unknown>) => {
|
||||
const translated = translateStreamEvent(event);
|
||||
if (translated instanceof ChainError) {
|
||||
failure = translated;
|
||||
done = true;
|
||||
} else if (translated) {
|
||||
queue.push(translated);
|
||||
}
|
||||
signal();
|
||||
});
|
||||
call.on('error', (err: unknown) => {
|
||||
failure = chainErrorFrom(err);
|
||||
done = true;
|
||||
signal();
|
||||
});
|
||||
call.on('end', () => {
|
||||
done = true;
|
||||
signal();
|
||||
});
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
while (queue.length > 0) {
|
||||
yield queue.shift() as FlowEvent;
|
||||
}
|
||||
if (failure) throw failure;
|
||||
if (done) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
wake = resolve;
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
call.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a detached run stands. */
|
||||
async getStatus(invocationId: string, deadlineMs?: number): Promise<InvocationStatus> {
|
||||
const res = await this.unary<
|
||||
{ value: string },
|
||||
Partial<InvocationStatus> & { phase?: string }
|
||||
>(this.hub, 'getInvocationStatus', { value: invocationId }, deadlineMs);
|
||||
return {
|
||||
phase: (res.phase as InvocationStatus['phase']) ?? 'PHASE_UNKNOWN',
|
||||
currentStep: res.currentStep ?? '',
|
||||
startedAt: res.startedAt ?? '',
|
||||
finishedAt: res.finishedAt ?? '',
|
||||
error: res.error ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/** The outputs of a finished detached run. */
|
||||
async getResult(invocationId: string, deadlineMs?: number): Promise<FlowResult> {
|
||||
const res = await this.unary<{ value: string }, WireSubmitResponse>(
|
||||
this.hub,
|
||||
'getInvocationResult',
|
||||
{ value: invocationId },
|
||||
deadlineMs,
|
||||
);
|
||||
return ChainClient.resultFrom(res);
|
||||
}
|
||||
|
||||
/** Stop a detached run. Returns false when it was already over. */
|
||||
async cancel(invocationId: string, deadlineMs?: number): Promise<boolean> {
|
||||
const res = await this.unary<{ value: string }, { cancelled?: boolean }>(
|
||||
this.hub,
|
||||
'cancelInvocation',
|
||||
{ value: invocationId },
|
||||
deadlineMs,
|
||||
);
|
||||
return res.cancelled ?? false;
|
||||
}
|
||||
|
||||
/** Steps waiting for a decision. */
|
||||
async listApprovals(
|
||||
options: { statuses?: string[]; limit?: number; project?: string; deadlineMs?: number } = {},
|
||||
): Promise<Approval[]> {
|
||||
const res = await this.unary<
|
||||
{ statuses: string[]; limit: number; project: string },
|
||||
{ entries?: Partial<Approval>[] }
|
||||
>(
|
||||
this.admin,
|
||||
'listApprovals',
|
||||
{
|
||||
statuses: options.statuses ?? ['PENDING'],
|
||||
limit: options.limit ?? 100,
|
||||
project: options.project ?? this.project,
|
||||
},
|
||||
options.deadlineMs,
|
||||
);
|
||||
return (res.entries ?? []).map((e) => ({
|
||||
approvalId: e.approvalId ?? '',
|
||||
flowExecution: e.flowExecution ?? '',
|
||||
flowName: e.flowName ?? '',
|
||||
stepId: e.stepId ?? '',
|
||||
prompt: e.prompt ?? '',
|
||||
payloadPreview: e.payloadPreview ?? '',
|
||||
createdAt: e.createdAt ?? '',
|
||||
expiresAt: e.expiresAt ?? '',
|
||||
status: e.status ?? '',
|
||||
decidedAt: e.decidedAt ?? '',
|
||||
decidedBy: e.decidedBy ?? '',
|
||||
reason: e.reason ?? '',
|
||||
project: e.project ?? '',
|
||||
}));
|
||||
}
|
||||
|
||||
/** Approve or reject a waiting step. */
|
||||
async decideApproval(
|
||||
options: DecideApprovalOptions,
|
||||
): Promise<{ approvalId: string; status: string }> {
|
||||
const res = await this.unary<Record<string, unknown>, { approvalId?: string; status?: string }>(
|
||||
this.admin,
|
||||
'decideApproval',
|
||||
{
|
||||
approvalId: options.approvalId,
|
||||
decision: options.approve ? 'APPROVE' : 'REJECT',
|
||||
reviewer: options.reviewer ?? '',
|
||||
reason: options.reason ?? '',
|
||||
},
|
||||
options.deadlineMs,
|
||||
);
|
||||
return { approvalId: res.approvalId ?? options.approvalId, status: res.status ?? '' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate one `SubmitStreamEvent`. A `StreamError` comes back as a
|
||||
* `ChainError` for the caller to throw; anything unknown (a newer
|
||||
* hub) comes back as `undefined` and is skipped.
|
||||
*/
|
||||
function translateStreamEvent(event: Record<string, unknown>): FlowEvent | ChainError | undefined {
|
||||
const started = event.stepStarted as { step?: string; capability?: string } | undefined;
|
||||
if (started) {
|
||||
return { type: 'stepStarted', step: started.step ?? '', capability: started.capability ?? '' };
|
||||
}
|
||||
const finished = event.stepFinished as
|
||||
| { step?: string; ok?: boolean; durationMs?: number }
|
||||
| undefined;
|
||||
if (finished) {
|
||||
return {
|
||||
type: 'stepFinished',
|
||||
step: finished.step ?? '',
|
||||
ok: finished.ok ?? false,
|
||||
durationMs: Number(finished.durationMs ?? 0),
|
||||
};
|
||||
}
|
||||
const moduleEvent = event.moduleEvent as
|
||||
| { step?: string; name?: string; payload?: WirePayload }
|
||||
| undefined;
|
||||
if (moduleEvent) {
|
||||
return {
|
||||
type: 'moduleEvent',
|
||||
step: moduleEvent.step ?? '',
|
||||
name: moduleEvent.name ?? '',
|
||||
payload: payloadFromWire(moduleEvent.payload),
|
||||
};
|
||||
}
|
||||
const final = event.finalResult as WireSubmitResponse | undefined;
|
||||
if (final) {
|
||||
const outputs: Record<string, PayloadOutput> = {};
|
||||
for (const [name, payload] of Object.entries(final.outputs ?? {})) {
|
||||
outputs[name] = payloadFromWire(payload);
|
||||
}
|
||||
return {
|
||||
type: 'result',
|
||||
result: { invocationId: final.invocationId?.value ?? '', outputs },
|
||||
};
|
||||
}
|
||||
const error = event.error as { message?: string; kind?: string } | undefined;
|
||||
if (error) {
|
||||
// The hub answered, so `reachedHub` is true whether or not this
|
||||
// hub is new enough to name the class. Without a class the error
|
||||
// reads as `internal` rather than claiming one it does not know.
|
||||
const kind = error.kind ? asKind(error.kind) : 'internal';
|
||||
const message = error.message ?? 'the run failed';
|
||||
return new ChainError(message, {
|
||||
kind,
|
||||
code: grpc.status.UNKNOWN,
|
||||
reachedHub: true,
|
||||
step: stepFromMessage(message),
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
234
src/errors.ts
Normal file
234
src/errors.ts
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
// Error classification for hub calls.
|
||||
//
|
||||
// Two facts are kept apart on purpose:
|
||||
//
|
||||
// * `kind` is the hub's own word for what went wrong. It travels in
|
||||
// the `chain-error-kind` trailer of every error response.
|
||||
// * `reachedHub` says whether the hub answered at all. A refused TCP
|
||||
// connection and a hub that answers "the model host is down" both
|
||||
// arrive as gRPC UNAVAILABLE; a gateway that shows "service not
|
||||
// reachable" for the second one is lying to its users.
|
||||
//
|
||||
// Callers that only want a coarse branch use `family`.
|
||||
|
||||
import { status as GrpcStatus } from '@grpc/grpc-js';
|
||||
import type { ServiceError } from '@grpc/grpc-js';
|
||||
|
||||
/** Metadata key under which the hub sends the error class. */
|
||||
export const ERROR_KIND_KEY = 'chain-error-kind';
|
||||
|
||||
/**
|
||||
* The hub's error classes. The vocabulary grows additively; an
|
||||
* unknown word from a newer hub shows up as `'unknown'`, never as a
|
||||
* crash.
|
||||
*/
|
||||
export type ChainErrorKind =
|
||||
| 'flow_rejected'
|
||||
| 'step_failed'
|
||||
| 'step_timeout'
|
||||
| 'approval_rejected'
|
||||
| 'approval_timeout'
|
||||
| 'unavailable'
|
||||
| 'overloaded'
|
||||
| 'precondition'
|
||||
| 'not_found'
|
||||
| 'conflict'
|
||||
| 'forbidden'
|
||||
| 'unauthenticated'
|
||||
| 'timeout'
|
||||
| 'cancelled'
|
||||
| 'internal'
|
||||
| 'unknown';
|
||||
|
||||
/** Coarse branch for callers that do not care about the detail. */
|
||||
export type ChainErrorFamily =
|
||||
| 'unreachable'
|
||||
| 'rejected'
|
||||
| 'failed'
|
||||
| 'overloaded'
|
||||
| 'auth'
|
||||
| 'timeout'
|
||||
| 'cancelled'
|
||||
| 'internal';
|
||||
|
||||
const KNOWN_KINDS: ReadonlySet<string> = new Set<ChainErrorKind>([
|
||||
'flow_rejected',
|
||||
'step_failed',
|
||||
'step_timeout',
|
||||
'approval_rejected',
|
||||
'approval_timeout',
|
||||
'unavailable',
|
||||
'overloaded',
|
||||
'precondition',
|
||||
'not_found',
|
||||
'conflict',
|
||||
'forbidden',
|
||||
'unauthenticated',
|
||||
'timeout',
|
||||
'cancelled',
|
||||
'internal',
|
||||
]);
|
||||
|
||||
const FAMILY_OF: Record<ChainErrorKind, ChainErrorFamily> = {
|
||||
flow_rejected: 'rejected',
|
||||
not_found: 'rejected',
|
||||
conflict: 'rejected',
|
||||
precondition: 'rejected',
|
||||
step_failed: 'failed',
|
||||
step_timeout: 'failed',
|
||||
approval_rejected: 'failed',
|
||||
approval_timeout: 'failed',
|
||||
unavailable: 'unreachable',
|
||||
overloaded: 'overloaded',
|
||||
forbidden: 'auth',
|
||||
unauthenticated: 'auth',
|
||||
timeout: 'timeout',
|
||||
cancelled: 'cancelled',
|
||||
internal: 'internal',
|
||||
unknown: 'internal',
|
||||
};
|
||||
|
||||
const RETRYABLE: ReadonlySet<ChainErrorFamily> = new Set<ChainErrorFamily>([
|
||||
'unreachable',
|
||||
'overloaded',
|
||||
'timeout',
|
||||
]);
|
||||
|
||||
/** Map a gRPC code to a class, for a hub that sent no class. */
|
||||
export function kindForCode(code: number): ChainErrorKind {
|
||||
switch (code) {
|
||||
case GrpcStatus.INVALID_ARGUMENT:
|
||||
case GrpcStatus.OUT_OF_RANGE:
|
||||
return 'flow_rejected';
|
||||
case GrpcStatus.NOT_FOUND:
|
||||
return 'not_found';
|
||||
case GrpcStatus.ALREADY_EXISTS:
|
||||
case GrpcStatus.ABORTED:
|
||||
return 'conflict';
|
||||
case GrpcStatus.FAILED_PRECONDITION:
|
||||
return 'precondition';
|
||||
case GrpcStatus.UNAVAILABLE:
|
||||
return 'unavailable';
|
||||
case GrpcStatus.RESOURCE_EXHAUSTED:
|
||||
return 'overloaded';
|
||||
case GrpcStatus.DEADLINE_EXCEEDED:
|
||||
return 'timeout';
|
||||
case GrpcStatus.PERMISSION_DENIED:
|
||||
return 'forbidden';
|
||||
case GrpcStatus.UNAUTHENTICATED:
|
||||
return 'unauthenticated';
|
||||
case GrpcStatus.CANCELLED:
|
||||
return 'cancelled';
|
||||
case GrpcStatus.INTERNAL:
|
||||
case GrpcStatus.DATA_LOSS:
|
||||
case GrpcStatus.UNIMPLEMENTED:
|
||||
case GrpcStatus.UNKNOWN:
|
||||
return 'internal';
|
||||
default:
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
/** Fields that `ChainError` carries beyond the message. */
|
||||
export interface ChainErrorInit {
|
||||
kind: ChainErrorKind;
|
||||
/** Numeric gRPC code, 2 (UNKNOWN) when the failure never got one. */
|
||||
code: number;
|
||||
/** True when the hub answered; false for a failure to reach it. */
|
||||
reachedHub: boolean;
|
||||
/** Flow step the hub blamed, when it named one. */
|
||||
step?: string;
|
||||
/** Invocation the failure belongs to, when one exists. */
|
||||
invocationId?: string;
|
||||
cause?: unknown;
|
||||
}
|
||||
|
||||
/** Every failure this client raises. */
|
||||
export class ChainError extends Error {
|
||||
readonly kind: ChainErrorKind;
|
||||
readonly family: ChainErrorFamily;
|
||||
readonly code: number;
|
||||
readonly reachedHub: boolean;
|
||||
readonly retryable: boolean;
|
||||
readonly step: string | undefined;
|
||||
readonly invocationId: string | undefined;
|
||||
|
||||
constructor(message: string, init: ChainErrorInit) {
|
||||
super(message, init.cause === undefined ? undefined : { cause: init.cause });
|
||||
this.name = 'ChainError';
|
||||
this.kind = init.kind;
|
||||
this.family = FAMILY_OF[init.kind];
|
||||
this.code = init.code;
|
||||
this.reachedHub = init.reachedHub;
|
||||
this.retryable = RETRYABLE.has(this.family);
|
||||
this.step = init.step;
|
||||
this.invocationId = init.invocationId;
|
||||
}
|
||||
|
||||
/** One line that is safe to log: no inputs, no payloads. */
|
||||
override toString(): string {
|
||||
const where = this.step ? ` step=${this.step}` : '';
|
||||
return `ChainError[${this.kind}/${this.family}] ${this.message}${where}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A word from the hub, as a class this version knows. */
|
||||
export function asKind(word: string): ChainErrorKind {
|
||||
return KNOWN_KINDS.has(word) ? (word as ChainErrorKind) : 'unknown';
|
||||
}
|
||||
|
||||
function kindFromMetadata(err: ServiceError): ChainErrorKind | undefined {
|
||||
const raw = err.metadata?.get(ERROR_KIND_KEY)?.[0];
|
||||
if (raw === undefined) return undefined;
|
||||
const word = typeof raw === 'string' ? raw : raw.toString('utf8');
|
||||
return asKind(word);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a grpc-js service error into a `ChainError`.
|
||||
*
|
||||
* The hub's own class wins. Without one, the gRPC code decides, and
|
||||
* the absence of the trailer is what tells us the hub never answered:
|
||||
* grpc-js produces UNAVAILABLE for a refused connection, and the hub
|
||||
* produces UNAVAILABLE for a dependency that is down. Only the second
|
||||
* one carries a class.
|
||||
*/
|
||||
export function chainErrorFrom(err: unknown, context?: { invocationId?: string }): ChainError {
|
||||
if (err instanceof ChainError) return err;
|
||||
const svc = err as ServiceError;
|
||||
const code = typeof svc?.code === 'number' ? svc.code : GrpcStatus.UNKNOWN;
|
||||
const fromHub = svc?.metadata ? kindFromMetadata(svc) : undefined;
|
||||
// A CANCELLED status without a class did not come from the hub: the
|
||||
// transport dropped the call, which happens when the hub goes down
|
||||
// mid-request. Reading it as "cancelled" would tell a gateway that
|
||||
// it cancelled its own run. This client never cancels a unary call,
|
||||
// so the only cancellation it can see is a lost connection.
|
||||
const kind =
|
||||
fromHub ??
|
||||
(code === GrpcStatus.CANCELLED ? 'unavailable' : kindForCode(code));
|
||||
const message = typeof svc?.details === 'string' && svc.details.length > 0
|
||||
? svc.details
|
||||
: (svc?.message ?? 'hub call failed');
|
||||
return new ChainError(message, {
|
||||
kind,
|
||||
code,
|
||||
reachedHub: fromHub !== undefined,
|
||||
step: stepFromMessage(message),
|
||||
invocationId: context?.invocationId,
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the step id out of a hub message when it names one.
|
||||
*
|
||||
* Exported because a stream error carries the same prose.
|
||||
*
|
||||
* The hub's prose starts with `step '<id>'` for step-level failures.
|
||||
* This is a convenience for logs and nothing branches on it, so a
|
||||
* wording change costs a `undefined`, not a wrong decision.
|
||||
*/
|
||||
export function stepFromMessage(message: string): string | undefined {
|
||||
const m = /step '([^']+)'/.exec(message);
|
||||
return m?.[1];
|
||||
}
|
||||
668
src/fake_hub.ts
Normal file
668
src/fake_hub.ts
Normal file
|
|
@ -0,0 +1,668 @@
|
|||
// A hub that answers like the real one, including when it says no.
|
||||
//
|
||||
// Point of this file: a gateway's tests must not need a real hub, a
|
||||
// real module or a real model. The fake speaks the same `chain.v1`
|
||||
// service from the same `.proto` files, so a test exercises the
|
||||
// client's own encoding and error classification, not a mock of it.
|
||||
//
|
||||
// What can be scripted: a run that succeeds, a run that fails with
|
||||
// any error class, an overloaded hub, a hub that is not listening at
|
||||
// all, a run that waits for an approval, and a restart that loses the
|
||||
// waiting run while keeping the approval, which is what today's hub
|
||||
// really does (see HANDOVER: run state is in memory, approvals are in
|
||||
// SQLite).
|
||||
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
|
||||
import type { ChainErrorKind } from './errors.js';
|
||||
import { type PayloadInput, type PayloadOutput, type WirePayload, payloadFromWire, payloadToWire } from './payload.js';
|
||||
import { hubAdminServiceDefinition, hubServiceDefinition } from './proto.js';
|
||||
|
||||
/** gRPC codes the fake uses for each class, mirroring the hub. */
|
||||
const CODE_FOR_KIND: Record<string, grpc.status> = {
|
||||
flow_rejected: grpc.status.INVALID_ARGUMENT,
|
||||
step_failed: grpc.status.INVALID_ARGUMENT,
|
||||
step_timeout: grpc.status.DEADLINE_EXCEEDED,
|
||||
approval_rejected: grpc.status.PERMISSION_DENIED,
|
||||
approval_timeout: grpc.status.DEADLINE_EXCEEDED,
|
||||
unavailable: grpc.status.UNAVAILABLE,
|
||||
overloaded: grpc.status.RESOURCE_EXHAUSTED,
|
||||
precondition: grpc.status.FAILED_PRECONDITION,
|
||||
not_found: grpc.status.NOT_FOUND,
|
||||
conflict: grpc.status.ALREADY_EXISTS,
|
||||
forbidden: grpc.status.PERMISSION_DENIED,
|
||||
unauthenticated: grpc.status.UNAUTHENTICATED,
|
||||
timeout: grpc.status.DEADLINE_EXCEEDED,
|
||||
cancelled: grpc.status.CANCELLED,
|
||||
internal: grpc.status.INTERNAL,
|
||||
};
|
||||
|
||||
/** A run that finishes. */
|
||||
export interface SucceedBehaviour {
|
||||
type: 'succeed';
|
||||
/** Flow outputs, in the same shapes a caller passes as inputs. */
|
||||
outputs?: Record<string, PayloadInput>;
|
||||
/** Steps to report while streaming. */
|
||||
steps?: string[];
|
||||
}
|
||||
|
||||
/** A run, or a request, that fails. */
|
||||
export interface FailBehaviour {
|
||||
type: 'fail';
|
||||
kind: ChainErrorKind;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** A run that stops at an approval and waits for a decision. */
|
||||
export interface AwaitApprovalBehaviour {
|
||||
type: 'awaitApproval';
|
||||
/** What the reviewer is asked. */
|
||||
prompt: string;
|
||||
/** Step id of the approval, for the approval row and the status. */
|
||||
stepId?: string;
|
||||
/** Outputs once it is approved. */
|
||||
outputs?: Record<string, PayloadInput>;
|
||||
/** Steps to report before the approval while streaming. */
|
||||
steps?: string[];
|
||||
}
|
||||
|
||||
/** One scripted answer. */
|
||||
export type Behaviour = SucceedBehaviour | FailBehaviour | AwaitApprovalBehaviour;
|
||||
|
||||
/** A submit the fake received. */
|
||||
export interface RecordedSubmit {
|
||||
flowYaml: string;
|
||||
inputs: Record<string, PayloadOutput>;
|
||||
project: string;
|
||||
detach: boolean;
|
||||
idempotencyKey: string;
|
||||
invocationId: string;
|
||||
}
|
||||
|
||||
/** A decision the fake received. */
|
||||
export interface RecordedDecision {
|
||||
approvalId: string;
|
||||
decision: string;
|
||||
reviewer: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
interface PendingApproval {
|
||||
approvalId: string;
|
||||
flowExecution: string;
|
||||
flowName: string;
|
||||
stepId: string;
|
||||
prompt: string;
|
||||
createdAt: string;
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED';
|
||||
decidedAt: string;
|
||||
decidedBy: string;
|
||||
reason: string;
|
||||
project: string;
|
||||
}
|
||||
|
||||
interface Waiter {
|
||||
approvalId: string;
|
||||
invocationId: string;
|
||||
outputs: Record<string, PayloadInput>;
|
||||
settle: (outcome: { ok: true; outputs: Record<string, PayloadInput> } | { ok: false; kind: ChainErrorKind; message: string }) => void;
|
||||
}
|
||||
|
||||
interface RunState {
|
||||
phase: 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED';
|
||||
currentStep: string;
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
error: string;
|
||||
outputs: Record<string, PayloadInput>;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
function nextId(prefix: string): string {
|
||||
counter += 1;
|
||||
return `${prefix}-${counter}`;
|
||||
}
|
||||
|
||||
function errorFor(kind: ChainErrorKind, message: string): grpc.ServiceError {
|
||||
const metadata = new grpc.Metadata();
|
||||
metadata.set('chain-error-kind', kind);
|
||||
const code = CODE_FOR_KIND[kind] ?? grpc.status.UNKNOWN;
|
||||
const err = new Error(message) as grpc.ServiceError;
|
||||
err.code = code;
|
||||
err.details = message;
|
||||
err.metadata = metadata;
|
||||
return err;
|
||||
}
|
||||
|
||||
function wireOutputs(outputs: Record<string, PayloadInput>): Record<string, WirePayload> {
|
||||
const out: Record<string, WirePayload> = {};
|
||||
for (const [name, value] of Object.entries(outputs)) {
|
||||
out[name] = payloadToWire(value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A scriptable stand-in for a hub. */
|
||||
export class FakeHub {
|
||||
private server: grpc.Server | undefined;
|
||||
private port = 0;
|
||||
|
||||
/** Answers for the next submits, in order. */
|
||||
private readonly script: Behaviour[] = [];
|
||||
|
||||
/** Answer used once the script is empty. */
|
||||
private fallback: Behaviour = { type: 'succeed', outputs: {} };
|
||||
|
||||
private health: 'SERVING' | 'NOT_SERVING' = 'SERVING';
|
||||
|
||||
/** Everything the fake was asked to run. */
|
||||
readonly submits: RecordedSubmit[] = [];
|
||||
|
||||
/** Every decision the fake was handed. */
|
||||
readonly decisions: RecordedDecision[] = [];
|
||||
|
||||
/**
|
||||
* Approvals. Kept across `restart()`, because the real hub keeps
|
||||
* them in SQLite.
|
||||
*/
|
||||
private approvals: PendingApproval[] = [];
|
||||
|
||||
/** Runs. Dropped by `restart()`, like the real hub drops them. */
|
||||
private runs = new Map<string, RunState>();
|
||||
|
||||
/** Submits blocked on an approval. Dropped by `restart()`. */
|
||||
private waiters = new Map<string, Waiter>();
|
||||
|
||||
/** Idempotency keys this fake has seen, per project. */
|
||||
private keys = new Map<string, string>();
|
||||
|
||||
/** Script the next submit. */
|
||||
push(behaviour: Behaviour): this {
|
||||
this.script.push(behaviour);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The next submit succeeds with these outputs. */
|
||||
succeeds(outputs: Record<string, PayloadInput> = {}, steps?: string[]): this {
|
||||
return this.push(steps ? { type: 'succeed', outputs, steps } : { type: 'succeed', outputs });
|
||||
}
|
||||
|
||||
/** The next submit fails with this class. */
|
||||
fails(kind: ChainErrorKind, message = 'scripted failure'): this {
|
||||
return this.push({ type: 'fail', kind, message });
|
||||
}
|
||||
|
||||
/** The next submit waits for an approval. */
|
||||
waitsForApproval(options: Omit<AwaitApprovalBehaviour, 'type'>): this {
|
||||
return this.push({ type: 'awaitApproval', ...options });
|
||||
}
|
||||
|
||||
/** Answer every further submit this way. */
|
||||
setFallback(behaviour: Behaviour): this {
|
||||
this.fallback = behaviour;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Report NOT_SERVING on Health while staying reachable. */
|
||||
setHealth(state: 'SERVING' | 'NOT_SERVING'): this {
|
||||
this.health = state;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The approvals the fake currently holds. */
|
||||
pendingApprovals(): PendingApproval[] {
|
||||
return this.approvals.filter((a) => a.status === 'PENDING');
|
||||
}
|
||||
|
||||
/** `host:port` of the running fake. */
|
||||
get address(): string {
|
||||
if (!this.port) throw new Error('fake hub is not listening');
|
||||
return `127.0.0.1:${this.port}`;
|
||||
}
|
||||
|
||||
/** Start listening. Keeps the port across a `restart()`. */
|
||||
async start(port = 0): Promise<string> {
|
||||
if (this.server) throw new Error('fake hub is already listening');
|
||||
const server = new grpc.Server();
|
||||
server.addService(hubServiceDefinition(), this.hubHandlers());
|
||||
server.addService(hubAdminServiceDefinition(), this.adminHandlers());
|
||||
const bound = await new Promise<number>((resolve, reject) => {
|
||||
server.bindAsync(
|
||||
`127.0.0.1:${port || this.port || 0}`,
|
||||
grpc.ServerCredentials.createInsecure(),
|
||||
(err, assigned) => (err ? reject(err) : resolve(assigned)),
|
||||
);
|
||||
});
|
||||
this.server = server;
|
||||
this.port = bound;
|
||||
return this.address;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop listening. A client now gets a refused connection, which is
|
||||
* the "hub not reachable" case: no error class, `reachedHub` false.
|
||||
*
|
||||
* The shutdown is forced on purpose. A graceful one waits for calls
|
||||
* in flight, and a run parked at an approval never finishes, so a
|
||||
* graceful stop would hang exactly where a crash is being modelled.
|
||||
*/
|
||||
async stop(): Promise<void> {
|
||||
const server = this.server;
|
||||
if (!server) return;
|
||||
this.server = undefined;
|
||||
this.dropWaiters('the hub went down while this run was waiting');
|
||||
// Let those answers leave before the socket does. Without the
|
||||
// tick, forceShutdown cancels the calls first and a caller learns
|
||||
// "cancelled" instead of "the hub is gone", which is the wrong
|
||||
// story for a gateway deciding whether to start the run again.
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
server.forceShutdown();
|
||||
}
|
||||
|
||||
/** Fail every run parked at an approval. */
|
||||
private dropWaiters(message: string): void {
|
||||
for (const waiter of [...this.waiters.values()]) {
|
||||
this.waiters.delete(waiter.approvalId);
|
||||
waiter.settle({ ok: false, kind: 'unavailable', message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and start again on the same port, losing what the real hub
|
||||
* loses: running and waiting runs. Approvals stay, so a test can
|
||||
* check that a decision after a restart no longer resumes anything.
|
||||
*/
|
||||
async restart(): Promise<string> {
|
||||
await this.stop();
|
||||
this.runs.clear();
|
||||
return this.start(this.port);
|
||||
}
|
||||
|
||||
/** Shut down for good. */
|
||||
async close(): Promise<void> {
|
||||
await this.stop();
|
||||
this.port = 0;
|
||||
}
|
||||
|
||||
private nextBehaviour(): Behaviour {
|
||||
return this.script.shift() ?? this.fallback;
|
||||
}
|
||||
|
||||
private recordSubmit(call: { request: Record<string, unknown> }, invocationId: string): RecordedSubmit {
|
||||
const request = call.request;
|
||||
const inputs: Record<string, PayloadOutput> = {};
|
||||
for (const [name, payload] of Object.entries(
|
||||
(request.inputs ?? {}) as Record<string, WirePayload>,
|
||||
)) {
|
||||
inputs[name] = payloadFromWire(payload);
|
||||
}
|
||||
const yaml = request.flowYaml;
|
||||
const recorded: RecordedSubmit = {
|
||||
flowYaml: Buffer.isBuffer(yaml) ? yaml.toString('utf8') : String(yaml ?? ''),
|
||||
inputs,
|
||||
project: String(request.project ?? ''),
|
||||
detach: Boolean(request.detach),
|
||||
idempotencyKey: String(request.idempotencyKey ?? ''),
|
||||
invocationId,
|
||||
};
|
||||
this.submits.push(recorded);
|
||||
return recorded;
|
||||
}
|
||||
|
||||
private flowNameOf(yaml: string): string {
|
||||
const m = /^\s*name:\s*(\S+)/m.exec(yaml);
|
||||
return m?.[1] ?? 'flow';
|
||||
}
|
||||
|
||||
private openApproval(
|
||||
behaviour: AwaitApprovalBehaviour,
|
||||
recorded: RecordedSubmit,
|
||||
): PendingApproval {
|
||||
const approval: PendingApproval = {
|
||||
approvalId: nextId('approval'),
|
||||
flowExecution: recorded.invocationId,
|
||||
flowName: this.flowNameOf(recorded.flowYaml),
|
||||
stepId: behaviour.stepId ?? 'approval',
|
||||
prompt: behaviour.prompt,
|
||||
createdAt: nowIso(),
|
||||
status: 'PENDING',
|
||||
decidedAt: '',
|
||||
decidedBy: '',
|
||||
reason: '',
|
||||
project: recorded.project,
|
||||
};
|
||||
this.approvals.push(approval);
|
||||
return approval;
|
||||
}
|
||||
|
||||
private hubHandlers(): grpc.UntypedServiceImplementation {
|
||||
return {
|
||||
health: (_call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
callback(null, { state: this.health, detail: 'fake hub' });
|
||||
},
|
||||
listModules: (_call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
callback(null, { modules: [] });
|
||||
},
|
||||
listInvocations: (_call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
callback(null, { invocations: [] });
|
||||
},
|
||||
submit: (call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
void this.handleSubmit(call as { request: Record<string, unknown> }, callback);
|
||||
},
|
||||
submitStream: (call: grpc.ServerWritableStream<Record<string, unknown>, unknown>) => {
|
||||
void this.handleSubmitStream(call);
|
||||
},
|
||||
getInvocationStatus: (call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
const id = String((call as { request: { value?: string } }).request.value ?? '');
|
||||
const run = this.runs.get(id);
|
||||
if (!run) {
|
||||
callback(errorFor('not_found', `unknown invocation '${id}'`));
|
||||
return;
|
||||
}
|
||||
callback(null, {
|
||||
phase: run.phase,
|
||||
currentStep: run.currentStep,
|
||||
startedAt: run.startedAt,
|
||||
finishedAt: run.finishedAt,
|
||||
error: run.error,
|
||||
});
|
||||
},
|
||||
getInvocationResult: (call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
const id = String((call as { request: { value?: string } }).request.value ?? '');
|
||||
const run = this.runs.get(id);
|
||||
if (!run) {
|
||||
callback(errorFor('not_found', `no retained result for '${id}'`));
|
||||
return;
|
||||
}
|
||||
if (run.phase === 'RUNNING' || run.phase === 'PENDING') {
|
||||
callback(errorFor('precondition', `invocation '${id}' is still running`));
|
||||
return;
|
||||
}
|
||||
if (run.phase === 'FAILED') {
|
||||
callback(errorFor('step_failed', run.error));
|
||||
return;
|
||||
}
|
||||
callback(null, {
|
||||
invocationId: { value: id },
|
||||
outputs: wireOutputs(run.outputs),
|
||||
});
|
||||
},
|
||||
cancelInvocation: (call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
const id = String((call as { request: { value?: string } }).request.value ?? '');
|
||||
const run = this.runs.get(id);
|
||||
const cancellable = run?.phase === 'RUNNING' || run?.phase === 'PENDING';
|
||||
if (run && cancellable) {
|
||||
run.phase = 'CANCELLED';
|
||||
run.finishedAt = nowIso();
|
||||
const waiter = [...this.waiters.values()].find((w) => w.invocationId === id);
|
||||
if (waiter) {
|
||||
this.waiters.delete(waiter.approvalId);
|
||||
waiter.settle({ ok: false, kind: 'cancelled', message: 'cancelled by the caller' });
|
||||
}
|
||||
}
|
||||
callback(null, { cancelled: Boolean(run && cancellable) });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async handleSubmit(
|
||||
call: { request: Record<string, unknown> },
|
||||
callback: grpc.sendUnaryData<unknown>,
|
||||
): Promise<void> {
|
||||
const key = String(call.request.idempotencyKey ?? '');
|
||||
const project = String(call.request.project ?? '');
|
||||
const scope = `${project}\u0000${key}`;
|
||||
if (key && this.keys.has(scope)) {
|
||||
const id = this.keys.get(scope) as string;
|
||||
const run = this.runs.get(id);
|
||||
this.recordSubmit(call, id);
|
||||
callback(null, {
|
||||
invocationId: { value: id },
|
||||
outputs: wireOutputs(run?.outputs ?? {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const invocationId = nextId('run');
|
||||
if (key) this.keys.set(scope, invocationId);
|
||||
const recorded = this.recordSubmit(call, invocationId);
|
||||
const behaviour = this.nextBehaviour();
|
||||
const detach = recorded.detach;
|
||||
|
||||
if (behaviour.type === 'fail') {
|
||||
if (detach) {
|
||||
this.runs.set(invocationId, {
|
||||
phase: 'FAILED',
|
||||
currentStep: '',
|
||||
startedAt: nowIso(),
|
||||
finishedAt: nowIso(),
|
||||
error: behaviour.message,
|
||||
outputs: {},
|
||||
});
|
||||
callback(null, { invocationId: { value: invocationId }, outputs: {} });
|
||||
return;
|
||||
}
|
||||
callback(errorFor(behaviour.kind, behaviour.message));
|
||||
return;
|
||||
}
|
||||
|
||||
if (behaviour.type === 'succeed') {
|
||||
const outputs = behaviour.outputs ?? {};
|
||||
this.runs.set(invocationId, {
|
||||
phase: 'SUCCEEDED',
|
||||
currentStep: '',
|
||||
startedAt: nowIso(),
|
||||
finishedAt: nowIso(),
|
||||
error: '',
|
||||
outputs,
|
||||
});
|
||||
callback(null, {
|
||||
invocationId: { value: invocationId },
|
||||
outputs: detach ? {} : wireOutputs(outputs),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// awaitApproval
|
||||
const approval = this.openApproval(behaviour, recorded);
|
||||
this.runs.set(invocationId, {
|
||||
phase: 'RUNNING',
|
||||
currentStep: approval.stepId,
|
||||
startedAt: nowIso(),
|
||||
finishedAt: '',
|
||||
error: '',
|
||||
outputs: {},
|
||||
});
|
||||
if (detach) {
|
||||
// A detached run returns its id and keeps waiting.
|
||||
callback(null, { invocationId: { value: invocationId }, outputs: {} });
|
||||
this.awaitDecision(approval, invocationId, behaviour.outputs ?? {}).catch(() => {});
|
||||
return;
|
||||
}
|
||||
const outcome = await this.awaitDecision(approval, invocationId, behaviour.outputs ?? {});
|
||||
if (outcome.ok) {
|
||||
callback(null, {
|
||||
invocationId: { value: invocationId },
|
||||
outputs: wireOutputs(outcome.outputs),
|
||||
});
|
||||
} else {
|
||||
callback(errorFor(outcome.kind, outcome.message));
|
||||
}
|
||||
}
|
||||
|
||||
private awaitDecision(
|
||||
approval: PendingApproval,
|
||||
invocationId: string,
|
||||
outputs: Record<string, PayloadInput>,
|
||||
): Promise<{ ok: true; outputs: Record<string, PayloadInput> } | { ok: false; kind: ChainErrorKind; message: string }> {
|
||||
return new Promise((resolve) => {
|
||||
this.waiters.set(approval.approvalId, {
|
||||
approvalId: approval.approvalId,
|
||||
invocationId,
|
||||
outputs,
|
||||
settle: (outcome) => {
|
||||
const run = this.runs.get(invocationId);
|
||||
if (run) {
|
||||
run.phase = outcome.ok ? 'SUCCEEDED' : 'FAILED';
|
||||
run.currentStep = '';
|
||||
run.finishedAt = nowIso();
|
||||
run.error = outcome.ok ? '' : outcome.message;
|
||||
run.outputs = outcome.ok ? outcome.outputs : {};
|
||||
}
|
||||
resolve(outcome);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async handleSubmitStream(
|
||||
call: grpc.ServerWritableStream<Record<string, unknown>, unknown>,
|
||||
): Promise<void> {
|
||||
const invocationId = nextId('run');
|
||||
const recorded = this.recordSubmit(call, invocationId);
|
||||
const behaviour = this.nextBehaviour();
|
||||
|
||||
const steps = behaviour.type === 'fail' ? [] : (behaviour.steps ?? []);
|
||||
for (const step of steps) {
|
||||
call.write({ stepStarted: { step, capability: 'fake/step@^1' } });
|
||||
call.write({ stepFinished: { step, ok: true, durationMs: 1 } });
|
||||
}
|
||||
|
||||
if (behaviour.type === 'fail') {
|
||||
call.write({ error: { message: behaviour.message, kind: behaviour.kind } });
|
||||
call.end();
|
||||
return;
|
||||
}
|
||||
if (behaviour.type === 'succeed') {
|
||||
call.write({
|
||||
finalResult: {
|
||||
invocationId: { value: invocationId },
|
||||
outputs: wireOutputs(behaviour.outputs ?? {}),
|
||||
},
|
||||
});
|
||||
call.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const approval = this.openApproval(behaviour, recorded);
|
||||
this.runs.set(invocationId, {
|
||||
phase: 'RUNNING',
|
||||
currentStep: approval.stepId,
|
||||
startedAt: nowIso(),
|
||||
finishedAt: '',
|
||||
error: '',
|
||||
outputs: {},
|
||||
});
|
||||
const outcome = await this.awaitDecision(approval, invocationId, behaviour.outputs ?? {});
|
||||
if (outcome.ok) {
|
||||
call.write({
|
||||
finalResult: {
|
||||
invocationId: { value: invocationId },
|
||||
outputs: wireOutputs(outcome.outputs),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
call.write({ error: { message: outcome.message, kind: outcome.kind } });
|
||||
}
|
||||
call.end();
|
||||
}
|
||||
|
||||
private adminHandlers(): grpc.UntypedServiceImplementation {
|
||||
const notImplemented = (_call: unknown, callback: grpc.sendUnaryData<unknown>) => {
|
||||
callback(errorFor('precondition', 'the fake hub does not implement this RPC'));
|
||||
};
|
||||
const handlers: grpc.UntypedServiceImplementation = {
|
||||
listApprovals: (call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
const request = (call as { request: { statuses?: string[]; project?: string; limit?: number } })
|
||||
.request;
|
||||
const wanted = (request.statuses ?? ['PENDING']).map((s) => s.toUpperCase());
|
||||
const project = request.project ?? '';
|
||||
const entries = this.approvals
|
||||
.filter((a) => wanted.length === 0 || wanted.includes(a.status))
|
||||
.filter((a) => !project || a.project === project)
|
||||
.slice(0, request.limit && request.limit > 0 ? request.limit : 100)
|
||||
.map((a) => ({
|
||||
approvalId: a.approvalId,
|
||||
flowExecution: a.flowExecution,
|
||||
flowName: a.flowName,
|
||||
stepId: a.stepId,
|
||||
prompt: a.prompt,
|
||||
payloadPreview: '',
|
||||
createdAt: a.createdAt,
|
||||
expiresAt: '',
|
||||
status: a.status,
|
||||
decidedAt: a.decidedAt,
|
||||
decidedBy: a.decidedBy,
|
||||
reason: a.reason,
|
||||
project: a.project,
|
||||
}));
|
||||
callback(null, { entries });
|
||||
},
|
||||
decideApproval: (call: grpc.ServerUnaryCall<Record<string, unknown>, unknown>, callback: grpc.sendUnaryData<unknown>) => {
|
||||
const request = (
|
||||
call as {
|
||||
request: { approvalId?: string; decision?: string; reviewer?: string; reason?: string };
|
||||
}
|
||||
).request;
|
||||
const approvalId = String(request.approvalId ?? '');
|
||||
const decision = String(request.decision ?? '').toUpperCase();
|
||||
const reviewer = String(request.reviewer ?? '');
|
||||
const reason = String(request.reason ?? '');
|
||||
this.decisions.push({ approvalId, decision, reviewer, reason });
|
||||
|
||||
const approval = this.approvals.find((a) => a.approvalId === approvalId);
|
||||
if (!approval) {
|
||||
callback(errorFor('not_found', `approval '${approvalId}' not found`));
|
||||
return;
|
||||
}
|
||||
if (approval.status !== 'PENDING') {
|
||||
callback(
|
||||
errorFor('precondition', `approval '${approvalId}' is already ${approval.status}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (decision === 'REJECT' && !reason) {
|
||||
callback(errorFor('flow_rejected', 'reason required for REJECT'));
|
||||
return;
|
||||
}
|
||||
approval.status = decision === 'APPROVE' ? 'APPROVED' : 'REJECTED';
|
||||
approval.decidedAt = nowIso();
|
||||
approval.decidedBy = reviewer;
|
||||
approval.reason = reason;
|
||||
|
||||
const waiter = this.waiters.get(approvalId);
|
||||
this.waiters.delete(approvalId);
|
||||
if (waiter) {
|
||||
if (approval.status === 'APPROVED') {
|
||||
waiter.settle({ ok: true, outputs: waiter.outputs });
|
||||
} else {
|
||||
waiter.settle({
|
||||
ok: false,
|
||||
kind: 'approval_rejected',
|
||||
message: `step '${approval.stepId}' was rejected by ${reviewer}: ${reason}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
callback(null, { approvalId, status: approval.status });
|
||||
},
|
||||
};
|
||||
// Every other HubAdmin RPC answers with a clear refusal rather
|
||||
// than hanging, so a test that strays finds out immediately.
|
||||
//
|
||||
// The definition keys the methods by their proto name
|
||||
// (`ListApprovals`) and carries the camelCase name as
|
||||
// `originalName`. grpc-js looks up the proto name first, so a
|
||||
// fallback registered under it would shadow a handler written in
|
||||
// camelCase. Both spellings are therefore checked.
|
||||
for (const [name, definition] of Object.entries(hubAdminServiceDefinition())) {
|
||||
const camel = (definition as { originalName?: string }).originalName;
|
||||
if (handlers[name] || (camel && handlers[camel])) continue;
|
||||
handlers[name] = notImplemented;
|
||||
}
|
||||
return handlers;
|
||||
}
|
||||
}
|
||||
44
src/index.ts
Normal file
44
src/index.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// Public surface of the TypeScript client.
|
||||
|
||||
export {
|
||||
ChainClient,
|
||||
type Approval,
|
||||
type ChainClientOptions,
|
||||
type DecideApprovalOptions,
|
||||
type FlowEvent,
|
||||
type FlowResult,
|
||||
type HubHealth,
|
||||
type InvocationStatus,
|
||||
type SubmitOptions,
|
||||
type TlsOptions,
|
||||
} from './client.js';
|
||||
export {
|
||||
ChainError,
|
||||
type ChainErrorFamily,
|
||||
type ChainErrorInit,
|
||||
type ChainErrorKind,
|
||||
ERROR_KIND_KEY,
|
||||
asKind,
|
||||
chainErrorFrom,
|
||||
kindForCode,
|
||||
} from './errors.js';
|
||||
export {
|
||||
asBytes,
|
||||
asJson,
|
||||
asText,
|
||||
type PayloadInput,
|
||||
type PayloadOutput,
|
||||
payloadFromWire,
|
||||
payloadToWire,
|
||||
structFromWire,
|
||||
structToWire,
|
||||
} from './payload.js';
|
||||
export {
|
||||
chainProto,
|
||||
hubAdminServiceConstructor,
|
||||
hubAdminServiceDefinition,
|
||||
hubServiceConstructor,
|
||||
hubServiceDefinition,
|
||||
protoDir,
|
||||
protoFiles,
|
||||
} from './proto.js';
|
||||
204
src/payload.ts
Normal file
204
src/payload.ts
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
// Payload conversion between plain JavaScript and `chain.v1.Payload`.
|
||||
//
|
||||
// `google.protobuf.Struct` is not plain JSON on the wire, so the
|
||||
// conversion is written out here rather than left to the proto
|
||||
// loader: both directions are covered by tests, and a `null` inside a
|
||||
// nested object stays a `null` instead of turning into an empty
|
||||
// object.
|
||||
|
||||
/** What a caller may pass as a flow input. */
|
||||
export type PayloadInput =
|
||||
| string
|
||||
| { text: string }
|
||||
| { json: unknown }
|
||||
| { bytes: Uint8Array; mimeType?: string }
|
||||
| { file: { uri: string; mimeType?: string; sizeBytes?: number; sha256?: string } }
|
||||
| Record<string, unknown>
|
||||
| unknown[];
|
||||
|
||||
/** What a flow output turns into. */
|
||||
export type PayloadOutput =
|
||||
| { kind: 'text'; text: string }
|
||||
| { kind: 'json'; json: unknown }
|
||||
| { kind: 'bytes'; mimeType: string; data: Buffer }
|
||||
| { kind: 'file'; uri: string; mimeType: string; sizeBytes: number; sha256: string }
|
||||
| { kind: 'empty' };
|
||||
|
||||
/** Wire shape of `google.protobuf.Value`. */
|
||||
interface WireValue {
|
||||
nullValue?: number | null;
|
||||
numberValue?: number;
|
||||
stringValue?: string;
|
||||
boolValue?: boolean;
|
||||
structValue?: WireStruct;
|
||||
listValue?: { values?: WireValue[] };
|
||||
kind?: string;
|
||||
}
|
||||
|
||||
/** Wire shape of `google.protobuf.Struct`. */
|
||||
interface WireStruct {
|
||||
fields?: Record<string, WireValue>;
|
||||
}
|
||||
|
||||
/** Wire shape of `chain.v1.Payload`. */
|
||||
export interface WirePayload {
|
||||
text?: string;
|
||||
json?: WireStruct;
|
||||
bytes?: { mimeType?: string; data?: Buffer | Uint8Array };
|
||||
file?: { uri?: string; mimeType?: string; sizeBytes?: number | string; sha256?: string };
|
||||
kind?: string;
|
||||
}
|
||||
|
||||
function valueToWire(value: unknown): WireValue {
|
||||
if (value === null || value === undefined) return { nullValue: 0 };
|
||||
switch (typeof value) {
|
||||
case 'string':
|
||||
return { stringValue: value };
|
||||
case 'number':
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new TypeError(`json inputs cannot carry ${String(value)}`);
|
||||
}
|
||||
return { numberValue: value };
|
||||
case 'boolean':
|
||||
return { boolValue: value };
|
||||
case 'bigint':
|
||||
return { numberValue: Number(value) };
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return { listValue: { values: value.map(valueToWire) } };
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return { stringValue: value.toISOString() };
|
||||
}
|
||||
return { structValue: structToWire(value as Record<string, unknown>) };
|
||||
}
|
||||
|
||||
/** Convert a plain object into a `google.protobuf.Struct`. */
|
||||
export function structToWire(obj: Record<string, unknown>): WireStruct {
|
||||
const fields: Record<string, WireValue> = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
if (value === undefined) continue;
|
||||
fields[key] = valueToWire(value);
|
||||
}
|
||||
return { fields };
|
||||
}
|
||||
|
||||
function valueFromWire(value: WireValue | undefined): unknown {
|
||||
if (!value) return null;
|
||||
if (value.stringValue !== undefined) return value.stringValue;
|
||||
if (value.numberValue !== undefined) return value.numberValue;
|
||||
if (value.boolValue !== undefined) return value.boolValue;
|
||||
if (value.structValue !== undefined) return structFromWire(value.structValue);
|
||||
if (value.listValue !== undefined) {
|
||||
return (value.listValue.values ?? []).map(valueFromWire);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Convert a `google.protobuf.Struct` into a plain object. */
|
||||
export function structFromWire(struct: WireStruct | undefined): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(struct?.fields ?? {})) {
|
||||
out[key] = valueFromWire(value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isTagged(value: object, key: string): boolean {
|
||||
return Object.prototype.hasOwnProperty.call(value, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a caller's input into a wire payload.
|
||||
*
|
||||
* A string is text. An object tagged `text`, `json`, `bytes` or
|
||||
* `file` is that kind. Any other object or array is sent as `json`,
|
||||
* because that is what a caller means by passing one.
|
||||
*/
|
||||
export function payloadToWire(input: PayloadInput): WirePayload {
|
||||
if (typeof input === 'string') return { text: input };
|
||||
if (typeof input === 'number' || typeof input === 'boolean') {
|
||||
return { text: String(input) };
|
||||
}
|
||||
if (input === null || input === undefined) return { text: '' };
|
||||
if (Array.isArray(input)) {
|
||||
throw new TypeError(
|
||||
'a bare array is not a payload: pass { json: [...] } so the kind is explicit',
|
||||
);
|
||||
}
|
||||
const obj = input as Record<string, unknown>;
|
||||
if (isTagged(obj, 'text')) return { text: String(obj.text ?? '') };
|
||||
if (isTagged(obj, 'json')) {
|
||||
const json = obj.json;
|
||||
if (json === null || typeof json !== 'object' || Array.isArray(json)) {
|
||||
throw new TypeError(
|
||||
'json payloads are objects: the hub carries google.protobuf.Struct, which has named fields',
|
||||
);
|
||||
}
|
||||
return { json: structToWire(json as Record<string, unknown>) };
|
||||
}
|
||||
if (isTagged(obj, 'bytes')) {
|
||||
const bytes = obj.bytes as Uint8Array;
|
||||
const mimeType = typeof obj.mimeType === 'string' ? obj.mimeType : 'application/octet-stream';
|
||||
return { bytes: { mimeType, data: Buffer.from(bytes) } };
|
||||
}
|
||||
if (isTagged(obj, 'file')) {
|
||||
const file = obj.file as { uri: string; mimeType?: string; sizeBytes?: number; sha256?: string };
|
||||
return {
|
||||
file: {
|
||||
uri: file.uri,
|
||||
mimeType: file.mimeType ?? '',
|
||||
sizeBytes: file.sizeBytes ?? 0,
|
||||
sha256: file.sha256 ?? '',
|
||||
},
|
||||
};
|
||||
}
|
||||
return { json: structToWire(obj) };
|
||||
}
|
||||
|
||||
/** Convert a wire payload into something a caller can read. */
|
||||
export function payloadFromWire(payload: WirePayload | undefined): PayloadOutput {
|
||||
if (!payload) return { kind: 'empty' };
|
||||
// The loader names the set member of the oneof in `kind`; trust it
|
||||
// over key presence, so a hub that starts sending defaults cannot
|
||||
// make a text payload look like json as well.
|
||||
if (payload.kind === 'text') return { kind: 'text', text: payload.text ?? '' };
|
||||
if (payload.text !== undefined) return { kind: 'text', text: payload.text };
|
||||
if (payload.json !== undefined) {
|
||||
return { kind: 'json', json: structFromWire(payload.json) };
|
||||
}
|
||||
if (payload.bytes !== undefined) {
|
||||
return {
|
||||
kind: 'bytes',
|
||||
mimeType: payload.bytes.mimeType ?? '',
|
||||
data: Buffer.from(payload.bytes.data ?? new Uint8Array()),
|
||||
};
|
||||
}
|
||||
if (payload.file !== undefined) {
|
||||
return {
|
||||
kind: 'file',
|
||||
uri: payload.file.uri ?? '',
|
||||
mimeType: payload.file.mimeType ?? '',
|
||||
sizeBytes: Number(payload.file.sizeBytes ?? 0),
|
||||
sha256: payload.file.sha256 ?? '',
|
||||
};
|
||||
}
|
||||
return { kind: 'empty' };
|
||||
}
|
||||
|
||||
/** The text of a payload, or `undefined` when it is another kind. */
|
||||
export function asText(payload: PayloadOutput | undefined): string | undefined {
|
||||
return payload?.kind === 'text' ? payload.text : undefined;
|
||||
}
|
||||
|
||||
/** The object of a json payload, or `undefined` when it is another kind. */
|
||||
export function asJson(payload: PayloadOutput | undefined): unknown | undefined {
|
||||
return payload?.kind === 'json' ? payload.json : undefined;
|
||||
}
|
||||
|
||||
/** The bytes of a payload, or `undefined` when it is another kind. */
|
||||
export function asBytes(payload: PayloadOutput | undefined): Buffer | undefined {
|
||||
return payload?.kind === 'bytes' ? payload.data : undefined;
|
||||
}
|
||||
111
src/proto.ts
Normal file
111
src/proto.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// Loading the `chain.v1` contract.
|
||||
//
|
||||
// The `.proto` files are carried verbatim from the platform repo and
|
||||
// loaded at runtime, so there is no generated code that can drift
|
||||
// from them. `scripts/sync-proto.mjs` refreshes the copies and
|
||||
// records their hashes; `test/proto_copy.test.ts` guards them.
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
import * as protoLoader from '@grpc/proto-loader';
|
||||
|
||||
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
/**
|
||||
* Find the `proto` directory by walking up from this file.
|
||||
*
|
||||
* The compiled module sits in `dist/`, a test build in
|
||||
* `build-test/src/`, and the sources in `src/`. Guessing a fixed
|
||||
* number of levels up breaks one of the three, so the directory is
|
||||
* searched for by what it contains.
|
||||
*/
|
||||
function findProtoDir(): string {
|
||||
let dir = moduleDir;
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
const candidate = path.join(dir, 'proto');
|
||||
if (fs.existsSync(path.join(candidate, 'chain', 'v1', 'common.proto'))) {
|
||||
return candidate;
|
||||
}
|
||||
const parent = path.dirname(dir);
|
||||
if (parent === dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
throw new Error(
|
||||
`proto/chain/v1 not found above ${moduleDir}: the package ships the .proto files, so this is a packaging fault`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Directory holding the verbatim `chain.v1` copies. */
|
||||
export const protoDir = findProtoDir();
|
||||
|
||||
/** The files that make up the contract. */
|
||||
export const protoFiles = [
|
||||
'chain/v1/common.proto',
|
||||
'chain/v1/hub.proto',
|
||||
'chain/v1/module.proto',
|
||||
'chain/v1/federation.proto',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Loader options, shared by the client and the fake hub so both speak
|
||||
* the same shapes.
|
||||
*
|
||||
* `defaults: false` matters: with defaults on, every member of a
|
||||
* `oneof` would come back present, and a payload would look like text
|
||||
* and json at once.
|
||||
*/
|
||||
const loaderOptions: protoLoader.Options = {
|
||||
keepCase: false,
|
||||
longs: Number,
|
||||
enums: String,
|
||||
defaults: false,
|
||||
oneofs: true,
|
||||
includeDirs: [protoDir],
|
||||
};
|
||||
|
||||
let cached: grpc.GrpcObject | undefined;
|
||||
|
||||
/** The loaded package, built once per process. */
|
||||
export function chainProto(): grpc.GrpcObject {
|
||||
if (cached) return cached;
|
||||
const definition = protoLoader.loadSync(
|
||||
protoFiles.map((f) => path.join(protoDir, f)),
|
||||
loaderOptions,
|
||||
);
|
||||
cached = grpc.loadPackageDefinition(definition);
|
||||
return cached;
|
||||
}
|
||||
|
||||
function serviceConstructor(name: 'Hub' | 'HubAdmin'): grpc.ServiceClientConstructor {
|
||||
const root = chainProto() as unknown as {
|
||||
chain: { v1: Record<string, grpc.ServiceClientConstructor> };
|
||||
};
|
||||
const ctor = root.chain?.v1?.[name];
|
||||
if (!ctor) {
|
||||
throw new Error(`chain.v1.${name} missing from the loaded proto files`);
|
||||
}
|
||||
return ctor;
|
||||
}
|
||||
|
||||
/** Constructor of the `chain.v1.Hub` client. */
|
||||
export function hubServiceConstructor(): grpc.ServiceClientConstructor {
|
||||
return serviceConstructor('Hub');
|
||||
}
|
||||
|
||||
/** Constructor of the `chain.v1.HubAdmin` client. */
|
||||
export function hubAdminServiceConstructor(): grpc.ServiceClientConstructor {
|
||||
return serviceConstructor('HubAdmin');
|
||||
}
|
||||
|
||||
/** Service definition of `chain.v1.Hub`, for building a server. */
|
||||
export function hubServiceDefinition(): grpc.ServiceDefinition {
|
||||
return hubServiceConstructor().service;
|
||||
}
|
||||
|
||||
/** Service definition of `chain.v1.HubAdmin`, for building a server. */
|
||||
export function hubAdminServiceDefinition(): grpc.ServiceDefinition {
|
||||
return hubAdminServiceConstructor().service;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue