chain-client-sdk-ts/test/real_hub.test.ts
flemming-it 0db793494d feat: idempotency key, the INTERRUPTED phase, and a real-hub skew suite
The hub now takes an idempotency key and reports INTERRUPTED for a run
its process did not survive, so the client exposes both. The real-hub
suite gained the cross-language half of the idempotency guard: a
repeated key has to answer with the first run's outputs, which only a
real hub can prove.

Signed-off-by: flemming-it <sf@flemming.it>
2026-10-27 01:32:58 +01:00

148 lines
5.4 KiB
TypeScript

// The client against a real hub binary.
//
// This is the skew gate for the TypeScript client: it proves that the
// shapes this client encodes are the shapes the hub decodes, which a
// fake can never prove. It needs a built `chain` binary and therefore
// skips when there is none; CI and release work set `CHAIN_BIN`.
//
// CHAIN_BIN=../fai_chain/target/debug/chain npm test
import assert from 'node:assert/strict';
import { spawn, type ChildProcess } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import { createServer } from 'node:net';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { after, before, describe, it } from 'node:test';
import { ChainClient, ChainError, asText, protoDir } from '../src/index.js';
// `protoDir` is found by searching, so it is the one path that holds
// whether this runs from `src`, `dist` or a test build.
const sdkRoot = resolve(protoDir, '..');
const platformRepo = resolve(
process.env.CHAIN_PLATFORM_REPO ?? join(sdkRoot, '..', 'fai_chain'),
);
const hubBinary = resolve(process.env.CHAIN_BIN ?? join(platformRepo, 'target', 'debug', 'chain'));
const modulesDir = join(platformRepo, 'modules');
const echoWasm = join(modulesDir, 'echo', 'target', 'wasm32-wasip2', 'release', 'echo.wasm');
const available = existsSync(hubBinary) && existsSync(echoWasm);
const HELLO = `name: hello
inputs:
name: text
steps:
- id: greet
use: debug.echo@^0
with:
message: "Hello, $inputs.name"
outputs:
greeting: $greet.echoed
`;
async function freePort(): Promise<number> {
return new Promise((resolvePort, reject) => {
const server = createServer();
server.on('error', reject);
server.listen(0, '127.0.0.1', () => {
const address = server.address();
const port = typeof address === 'object' && address ? address.port : 0;
server.close(() => resolvePort(port));
});
});
}
describe('client against a real hub', { skip: available ? false : `no hub binary at ${hubBinary}` }, () => {
let hub: ChildProcess | undefined;
let client: ChainClient;
let dataDir = '';
before(async () => {
const port = await freePort();
dataDir = mkdtempSync(join(tmpdir(), 'chain-ts-e2e-'));
hub = spawn(
hubBinary,
['serve', '--bind', `127.0.0.1:${port}`, '--modules-dir', modulesDir, '--data-dir', join(dataDir, 'chain.db')],
{ stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, CHAIN_DATA_DIR: dataDir } },
);
client = new ChainClient({ address: `127.0.0.1:${port}`, deadlineMs: 20_000 });
const until = Date.now() + 30_000;
for (;;) {
try {
const health = await client.health(2_000);
if (health.state === 'SERVING') break;
} catch {
// not up yet
}
if (Date.now() > until) throw new Error('the hub did not start');
await new Promise((r) => setTimeout(r, 200));
}
});
after(async () => {
client?.close();
hub?.kill('SIGTERM');
if (dataDir) rmSync(dataDir, { recursive: true, force: true });
});
it('runs the hello flow and reads the output', async () => {
const result = await client.submit({ flowYaml: HELLO, inputs: { name: 'Ch∆In' } });
assert.equal(asText(result.outputs.greeting), 'Hello, Ch∆In');
});
it('follows the same flow step by step', async () => {
const steps: string[] = [];
let greeting: string | undefined;
for await (const event of client.submitStream({ flowYaml: HELLO, inputs: { name: 'stream' } })) {
if (event.type === 'stepStarted') steps.push(event.step);
if (event.type === 'result') greeting = asText(event.result.outputs.greeting);
}
assert.deepEqual(steps, ['greet']);
assert.equal(greeting, 'Hello, stream');
});
it('gets the real error class out of a real refusal', async () => {
const err = (await client
.submit({ flowYaml: 'this is not a flow [' })
.catch((e: unknown) => e)) as ChainError;
assert.ok(err instanceof ChainError);
assert.equal(err.kind, 'flow_rejected');
assert.equal(err.reachedHub, true);
assert.equal(err.retryable, false);
});
it('answers a repeated idempotency key with the first run', async () => {
// The cross-language half of the idempotency guard: the field has
// to survive this client's encoding and the hub's decoding, which
// the fake hub cannot prove.
const key = `e2e-${Date.now()}`;
const first = await client.submit({
flowYaml: HELLO,
inputs: { name: 'first' },
idempotencyKey: key,
});
const again = await client.submit({
flowYaml: HELLO,
inputs: { name: 'second' },
idempotencyKey: key,
});
assert.equal(again.invocationId, first.invocationId);
// The replay answers with what the first run produced, not with
// the second request's input.
assert.equal(asText(again.outputs.greeting), 'Hello, first');
});
it('refuses a flow whose module is not installed, as not_found', async () => {
const err = (await client
.submit({
flowYaml: `name: nowhere\nsteps:\n - id: x\n use: nothing.at.all/missing@^1\noutputs:\n out: $x.text\n`,
})
.catch((e: unknown) => e)) as ChainError;
assert.ok(err instanceof ChainError);
assert.equal(err.reachedHub, true);
assert.ok(
err.kind === 'not_found' || err.kind === 'flow_rejected',
`an unknown capability reads as not_found or flow_rejected, got ${err.kind}`,
);
});
});