TypeScript SDK
Record and replay Node handlers with @kavachlabs/kavach. Node 22 or later, ESM, no runtime dependencies.
cd sdk/typescript && npm install && npm run build # from a checkout of the Kavach repositoryimport { Recorder, maybeHost, Panic, HandlerError, GatewayError, type Handler } from "@kavachlabs/kavach";Node 22 or later. ESM. No runtime dependencies. Works for JavaScript and TypeScript services.
Handler#
const handler: Handler = {
async handle(env, input) {
const at = env.now(); // sync, recorded
const id = env.random(8); // sync, recorded
const flag = env.config("flag.beta"); // sync, Uint8Array | undefined
const rate = await env.query("fx-rates", req); // async, rejects with GatewayError
env.emit("postgres:balances", bytes); // delivered after the step succeeds
},
snapshot() { return bytes; }, // optional
restore(data) {}, // optional
invariants() { // optional
return [{ name: "non_negative", check() { if (balance < 0) throw new Error(`balance ${balance}`); } }];
},
};Use env instead of Date.now, Math.random or crypto, fetch, and process.env for anything that can change what the handler does. env is invalid after its step ends.
Async and ordering#
now,nowNanos,random,configandemitare synchronous.queryreturns a promise, but its place in the journal is reserved whenquery()is called, not when it resolves.Promise.all([env.query(a), env.query(b)])recordsathenbhowever the responses arrive.- The order of reads must not depend on timing.
- Steps are serialised.
Failures#
| The handler | Marker | Message |
|---|---|---|
throws an Error |
panic |
`${err.name}: ${err.message}`, stack as data |
throws a non-Error x |
panic |
String(x) |
throws new Panic(msg) |
panic |
exactly msg |
throws new HandlerError(msg) |
error |
exactly msg |
| ends ok but an invariant fails | invariant |
the invariant's name |
Recording#
const rec = await Recorder.start({
service: "ledger",
handler,
gateways: { "fx-rates": { call: (req) => fx.get(req), scope: "remote" } },
deliver: async (outputs) => { for (const o of outputs) await sinks.write(o.sink, o.data); },
});
const result = await rec.step({ source: "kafka:wallet-events", position: "3:1042", data });
// never throws for handler failures; check result
await rec.flush({ durable: true });
await rec.close();Options: recorderCommand (argv; else KAVACH_RECORDER; else kavach-recorder on PATH), required, gateways, config, flags, deliver, log, snapshot (start from a snapshot), journal settings (dir, compression, …), and clock / random overrides.
If the recorder cannot start, dies or reports a fatal error, the SDK logs loudly and keeps running steps. required: true makes Recorder.start reject instead.
Replay host#
await maybeHost(() => handler, { gateways }); // first thing in mainWhen the last argument is kavach-host, the process serves the CLI and exits. In host mode, console.log, console.info, console.debug and process.stdout.write go to stderr.
kavach replay incident.kavach --bin "node dist/main.js"
kavach diff incident.kavach --old "node /tmp/old/dist/main.js" --new "node dist/main.js"Example#
From sdk/typescript, after the build above:
node dist/examples/ledger/main.js --in ../../examples/ledger/testdata/events.jsonl # buggy
node dist/examples/ledger/main.js --in ../../examples/ledger/testdata/events.jsonl --fixed # fixedSomething wrong or missing on this page? Report it on GitHub, or write to hello@thekavachlabs.com.