No description
Find a file
flemming-it 2131193f1f fix: come back quickly after a hub restart, and pin the dependencies
Two things helloeco ran into while wiring the gateway.

grpc-js waits a second before its second reconnect attempt and backs
off towards two minutes. That is right for a far-away service and
wrong for a hub on the same network: after a restart or a deploy a
gateway sits out the backoff with requests in hand. The client now
sets initial 200 ms and a 5 s ceiling, and a caller's own
channelOptions still win. The client exposes the options it ended up
with, which is the only way to tell a default that applies from one
that was silently replaced.

The dependencies are pinned exactly instead of by range. This package
is consumed by a handful of services, not by a library ecosystem, and
a surprise minor of grpc-js is what breaks a portal at three in the
morning. Raising one is a commit, with the skew job in front of it.

Guards: the defaults and the precedence are asserted (probed by
mutation), plus a case that a run works again once the hub is back.

Signed-off-by: flemming-it <sf@flemming.it>
2026-10-27 03:01:08 +01:00
.forgejo/workflows ci: hermetic tests on every push, and a skew job against a released hub 2026-10-27 02:19:50 +01:00
proto feat: idempotency key, the INTERRUPTED phase, and a real-hub skew suite 2026-10-27 01:32:58 +01:00
scripts feat: TypeScript client for Node, with a scriptable fake hub 2026-10-27 00:59:57 +01:00
src fix: come back quickly after a hub restart, and pin the dependencies 2026-10-27 03:01:08 +01:00
test fix: come back quickly after a hub restart, and pin the dependencies 2026-10-27 03:01:08 +01:00
.gitignore feat: TypeScript client for Node, with a scriptable fake hub 2026-10-27 00:59:57 +01:00
LICENSE feat: TypeScript client for Node, with a scriptable fake hub 2026-10-27 00:59:57 +01:00
package-lock.json feat: TypeScript client for Node, with a scriptable fake hub 2026-10-27 00:59:57 +01:00
package.json fix: come back quickly after a hub restart, and pin the dependencies 2026-10-27 03:01:08 +01:00
README.md fix: come back quickly after a hub restart, and pin the dependencies 2026-10-27 03:01:08 +01:00
tsconfig.json feat: TypeScript client for Node, with a scriptable fake hub 2026-10-27 00:59:57 +01:00
tsconfig.test.json feat: TypeScript client for Node, with a scriptable fake hub 2026-10-27 00:59:57 +01:00

chain-client-sdk-ts

TypeScript client for a Ch∆In hub, for Node 20 and newer. It covers what a service in front of a hub needs: start a flow, follow it, ask what became of a detached run, list and decide approvals.

The package ships the chain.v1 .proto files verbatim from the platform repo and loads them at runtime, so there is no generated code that can drift from the contract.

npm install chain-client-sdk-ts   # not published yet: use a path or git dependency

Running a flow

import { ChainClient, asText } from 'chain-client-sdk-ts';

const client = new ChainClient({
  address: '127.0.0.1:50051',
  token: process.env.CHAIN_TOKEN,
  project: 'helloeco',
});

const result = await client.submit({
  flowYaml: await readFile('flows/verbrauchsausweis.yaml', 'utf8'),
  inputs: { consumption: { json: { kwh: 15400 } } },
  idempotencyKey: stripeEvent.id,
});

console.log(asText(result.outputs.report));

Inputs: a string is text, an object tagged json, bytes or file is that kind, and any other object is sent as json. Outputs come back tagged, with asText, asJson and asBytes as readers.

idempotencyKey is the caller's word 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, which is what a payment webhook that retries needs.

Following a run

for await (const event of client.submitStream({ flowYaml, inputs })) {
  if (event.type === 'stepStarted') log.info({ step: event.step }, 'step started');
  if (event.type === 'result') deliver(event.result.outputs);
}

A run that fails throws a ChainError out of the loop, so the events seen so far stay valid and a failure is never a silent end of stream.

Detached runs (detach: true) return once they have an id; getStatus, getResult and cancel take it from there.

Approvals

const waiting = await client.listApprovals({ project: 'helloeco' });
await client.decideApproval({
  approvalId: waiting[0].approvalId,
  approve: true,
  reviewer: 'aussteller@example.org',
});

The hub records who decided and why. Where it can verify an identity behind the token, that identity wins over the reviewer field, so the field is a fallback and not a claim the hub trusts blindly.

Errors

Every failure is a ChainError with four fields worth branching on:

Field What it says
kind the hub's own class: flow_rejected, step_failed, step_timeout, approval_rejected, approval_timeout, unavailable, overloaded, precondition, not_found, conflict, forbidden, unauthenticated, timeout, cancelled, internal, or unknown from a newer hub
family the coarse branch: unreachable, rejected, failed, overloaded, auth, timeout, cancelled, internal
reachedHub whether the hub answered at all
retryable true for unreachable, overloaded and timeout

reachedHub is the field that keeps a gateway honest. A refused connection and a hub reporting "the model host is down" both arrive as gRPC UNAVAILABLE; only the second one carries a class, so only the second one is the hub's own answer. The class travels in the chain-error-kind trailer of every error response (hub 0.25 and newer) and in StreamError.kind inside a stream.

Testing against a fake hub

The package carries a scriptable hub that speaks the same service from the same .proto files, so a gateway's tests need no hub binary, no module and no model.

import { FakeHub } from 'chain-client-sdk-ts/fake-hub';

const hub = new FakeHub();
const address = await hub.start();

hub.succeeds({ report: 'zugestellt' });          // the next run finishes
hub.fails('overloaded', 'too many runs');        // the next run is refused
hub.waitsForApproval({ prompt: 'Zustellen?' });  // the next run waits
await hub.stop();                                // the hub is gone
await hub.restart();                             // it comes back, without the running runs

hub.submits and hub.decisions record what arrived, so a test can assert on what the gateway sent, not only on what it got back. restart() models what today's hub really does: run state lives in memory and is lost, while approvals live in SQLite and survive. A gateway has to treat "approval still pending after a restart" as a run it must start again.

Versions and the channel

The dependencies are pinned exactly, not by range. This package is consumed by a handful of services rather than by a library ecosystem, and a surprise minor of grpc-js is the kind of thing that breaks a portal at three in the morning. Raising one is a commit, and the skew job runs against a released hub before it lands.

The client sets two channel options by default: grpc.initial_reconnect_backoff_ms: 200 and grpc.max_reconnect_backoff_ms: 5000. grpc-js otherwise waits a second before its second reconnect attempt and backs off towards two minutes, which is right for a far-away service and wrong for a hub on the same network: after a restart or a deploy, a gateway would sit out that backoff with requests in hand. Anything in channelOptions wins over these, and client.channelOptions says what the client ended up with.

Development

npm install
npm test              # type-check, then the hermetic suites
npm run build         # dist/

# the skew gate: the same client against a real hub binary
CHAIN_BIN=../fai_chain/target/debug/chain npm test

# refresh the contract after a platform change
node scripts/sync-proto.mjs ../fai_chain

npm test runs the fake-hub suite, the payload and error-class unit tests, and the guard that the .proto copies still match both their recorded hashes and the platform repo. The real-hub suite skips itself when no binary is there.

.forgejo/workflows/ci.yml runs the same two things in CI: the hermetic suite on every push, and a skew job that downloads a released hub and runs this client against it, because a client has to keep working against the hub operators actually run. The skew job needs the repository secret CHAIN_RELEASE_READ_TOKEN (a Forgejo job token cannot read release assets) and fails with that message rather than passing quietly when the secret is missing.

License

Apache 2.0. Copyright Dr. Stefan Flemming, Flemming.AI.