JavaScript / TypeScript SDK
TypeScript SDK for Node.js over TCP.
The JavaScript SDK is a monorepo with two packages:
| Package | Environment | Transport |
|---|---|---|
@floruntime/core | Shared | Wire protocol, types |
@floruntime/node | Node.js | TCP |
Installation
npm install @floruntime/node
Quick Start
import { FloClient } from "@floruntime/node";
const client = new FloClient("localhost:9000", {
namespace: "myapp",
timeoutMs: 5000,
});
await client.connect();
const encoder = new TextEncoder();
const decoder = new TextDecoder();
// KV
await client.kv.put("greeting", encoder.encode("Hello, Flo!"));
const value = await client.kv.get("greeting");
console.log(decoder.decode(value!.value));
// Queue
await client.queue.enqueue("tasks", encoder.encode('{"task":"process"}'));
const result = await client.queue.dequeue("tasks", 10);
for (const msg of result.messages) {
console.log(decoder.decode(msg.payload));
}
await client.queue.complete("tasks", result); // within the lease, or they're delivered again
await client.close();
Retries
When the server refuses a request as overloaded or unavailable and says it didn't run it (err.ran === Ran.No), the client sends it again itself, as a new request, after a jittered wait. The server never ran it, so this is safe for writes too. Any other refusal, or one that may have run, is thrown at once.
retry field | Default | |
|---|---|---|
maxAttempts | 4 | Tries in all, the first included; 1 turns retrying off |
initialBackoffMs | 50 | Ceiling of the first wait; it doubles each retry |
maxBackoffMs | 1000 | Largest ceiling |
Each wait is uniform between 0 and its ceiling, so with the defaults a refused request is thrown after at most about 350 ms of waiting. Unset fields take the defaults.
const client = new FloClient("localhost:9000", {
retry: { maxAttempts: 8, initialBackoffMs: 100, maxBackoffMs: 2000 },
});
KV Operations
// Get returns GetResult | null \u2014 carries both value and version
const r = await client.kv.get("key");
if (r) console.log(r.value, "@", r.version); // r.version is bigint
// Put returns PutResult { version: bigint }
const res = await client.kv.put("key", encode("value"), {
ttlMs: 3_600_000n,
casVersion: r?.version, // optimistic locking against the latest read
});
// Only if the key doesn't exist
await client.kv.put("key", encode("value"), { condition: Condition.IfAbsent });
// Wait up to 5 s for the key to appear (waitFor: WaitFor.Change waits for its next version)
const waited = await client.kv.get("key", { waitMs: 5000 });
console.log("committed at v", res.version);
// Delete
const existed = await client.kv.delete("key"); // a missing key isn't an error
// Multi-key get (single round trip, up to 256 keys, may span shards)
const entries = await client.kv.mget(["user:1", "user:2", "user:3"]);
const decoder = new TextDecoder();
for (const e of entries) {
if (e.found) {
console.log(`${e.key} = ${decoder.decode(e.value)} (v${e.version})`);
} else {
console.log(`${e.key} missing`);
}
}
// Scan key names (not values); cursor is null on the last page
let page = await client.kv.scan("user:", { limit: 100 });
while (page.cursor) page = await client.kv.scan("user:", { cursor: page.cursor });
// History
const versions = await client.kv.history("key"); // { version, atMs, value }[]
// Atomic counter
const { value: n } = await client.kv.incr("visits:home"); // +1
const m = await client.kv.incr("visits:home", { delta: 10n });
// TTL lifecycle and existence
await client.kv.expire("lock:resource", 60_000n); // extend TTL to 60 s
await client.kv.expire("lock:resource", 0n); // clear TTL
const exists = await client.kv.exists("lock:resource");
// JSON paths
await client.kv.jsonSet("order:42", "$", encode('{"items":3,"status":"new"}'));
const setRes = await client.kv.jsonSet("order:42", "$.status", encode('"shipped"'));
console.log("doc now at v", setRes.version);
const status = await client.kv.jsonGet("order:42", "$.status"); // GetResult | null
if (status) console.log(`${decode(status.value)} @ v${status.version}`);
await client.kv.jsonDel("order:42", "$.status");
// Per-shard transaction — atomic multi-key writes on one shard. It is pinned
// to the {tag} of the key it begins with: give every key in it the same one.
const txn = await client.kv.begin("{user:42}:name");
try {
await txn.put("{user:42}:name", encode("Jane"));
await txn.incr("{user:42}:visits", 1n);
const result = await txn.commit();
console.log(`committed ${result.opCount} ops at index ${result.commitIndex}`);
} catch (err) {
await txn.rollback(); // idempotent
throw err;
}
scan, mget, jsonGet, jsonSet, jsonDel, and history are not supported inside a transaction and throw TxnUnsupportedOpError. Server caps: 64 ops and 256 KiB of keys and values per transaction, unless the operator sets them higher or lower (at most 256 ops and 1 MiB).
Queue Operations
// Enqueue
const seq = await client.queue.enqueue("tasks", payload, {
priority: 10,
});
// Dequeue with long polling: the messages are leased until completed
const result = await client.queue.dequeue("tasks", 10, {
blockMs: 30000,
});
await client.queue.complete("tasks", result);
// Dead letters: up to 100, oldest first; pass after: page.lastSeq for the next page
const page = await client.queue.dlqList("tasks", { limit: 100 });
// Peek: the next ready messages, without taking them
const peeked = await client.queue.peek("tasks", 5);
Stream Operations
// Append takes the payload as bytes
const encoder = new TextEncoder();
const result = await client.stream.append(
"events",
encoder.encode(JSON.stringify({ event: "signup", userId: "user-123" })),
{ partitionKey: "user-123" },
);
await client.stream.append("events", encoder.encode("user signed in"));
// Read
const records = await client.stream.read("events", {
limit: 10, // from the start; `start: id` resumes after a record, `tail: true` reads the end
});
// Access record fields
for (const rec of records.records) {
console.log(rec.stream); // stream name (e.g. "events")
console.log(rec.payload); // Uint8Array
console.log(rec.headers); // Record<string, string> | null
console.log(rec.id); // StreamID { timestampMs, sequence }
}
// Consumer groups: a read leases its records to the consumer
const got = await client.stream.groupRead("events", {
group: "processors",
consumer: "consumer-1",
limit: 10,
});
const done = [], failed = [];
for (const r of got.records) {
try { await handle(r); done.push(r); } catch { failed.push(r); }
}
await client.stream.groupAck("events", { ...got, records: done }, { group: "processors" });
// Nack a failure with why (at most 1024 bytes): ready again, or dead once
// the group's attempts are spent
await client.stream.groupNack("events", { ...got, records: failed },
{ group: "processors", error: "payment service timed out" });
// Stopping before reaching some records? Abandon them: ready at once, no
// failure counted. Abandon never dead-letters, so never use it for a
// record that failed, or a poison record goes round for ever.
await client.stream.groupNack("events", { ...got, records: unstarted },
{ group: "processors", abandon: true });
abandon can't be given with dead, delayMs or error. A report to a group that doesn't exist throws NotFoundError.
append() takes a Uint8Array: encode strings with TextEncoder, and objects with JSON.stringify first.
StreamWorker (high-level)
The recommended way to consume streams is the StreamWorker, available in @floruntime/node. It handles consumer group join, polling, concurrency, ack/nack, and reconnection:
import { StreamWorker } from "@floruntime/node";
const worker = new StreamWorker("localhost:9000", {
stream: "events",
group: "processors",
concurrency: 5,
batchSize: 10,
blockMs: 30000,
}, async (ctx) => {
const data = ctx.json<{ event: string }>();
console.log(`Stream: ${ctx.stream}, ID: ${ctx.streamId}`);
console.log(`Headers:`, ctx.headers);
await process(data);
});
await worker.start();
StreamWorkerConfig
| Option | Type | Default | Description |
|---|---|---|---|
stream | string | required | Stream name to consume |
group | string | "default" | Consumer group name |
consumer | string | auto | Consumer ID within the group |
concurrency | number | 10 | Max concurrent handlers |
batchSize | number | 10 | Records per poll |
blockMs | number | 30000 | Long-poll timeout (ms) |
messageTimeoutMs | number | 300000 | Max handler duration (ms) |
retry | Partial<RetryPolicy> | client default | Retries for the client the worker creates when given an endpoint; a worker given a client uses that client's |
StreamContext
The handler receives a StreamContext with convenience accessors:
async (ctx) => {
ctx.payload; // Uint8Array
ctx.text(); // string (UTF-8 decoded)
ctx.json<T>(); // parsed JSON
ctx.streamId; // StreamID
ctx.stream; // stream name
ctx.headers; // Record<string, string> (empty object if none)
ctx.record; // full StreamRecord
}
Records are auto-acked on handler success and auto-nacked on exception. When the worker stops, records it read but hasn't started are abandoned: ready for another consumer at once, with no attempt spent. ctx.signal aborts on a stop; a handler that throws once it has aborted abandons its record too, rather than nacking it. If the connection drops, the worker redials (waiting as after a failed poll: jittered, from 100 ms up to 5 s, until stop()), rejoins the group and re-registers, then polls again. An ActionWorker does the same and registers its actions again.
Action & Worker Operations
import { ActionType } from "@floruntime/node";
// Register and invoke
await client.action.register("process-image", ActionType.User, {
timeoutMs: 60000, maxRetries: 3, // the lease, and attempts in all
});
const result = await client.action.invoke("process-image", payload);
ActionWorker (high-level)
The recommended approach for executing actions is the ActionWorker class, which handles connection management, concurrency, heartbeats, and graceful shutdown:
import { ActionWorker } from "@floruntime/node";
const worker = new ActionWorker({
endpoint: "localhost:9000",
namespace: "myapp",
concurrency: 10,
});
worker.action("process-image", async (ctx) => {
const input = ctx.json<{ url: string }>();
const output = await processImage(input.url);
return ctx.toBytes({ status: "done", result: output });
});
await worker.start();
ActionWorker takes retry too, for the client it creates.
Workflow Operations
client.workflow manages the full lifecycle of workflow definitions and runs.
Declarative Sync
Deploy or update a workflow definition safely — calling this on every app boot is idiomatic:
// Sync from a YAML string
const result = await client.workflow.sync(yamlString);
console.log(`${result.name} v${result.version}: ${result.action}`);
// result.action → "created" | "updated" | "unchanged"
// Sync from raw bytes
const result2 = await client.workflow.syncBytes(
new TextEncoder().encode(yamlString)
);
Start and Monitor Runs
// Start a run
const runId = await client.workflow.start(
"process-order",
JSON.stringify({ orderId: "ORD-123", amount: 99.99 })
);
// Poll status
const status = await client.workflow.status(runId);
console.log(status.run_id); // string
console.log(status.workflow); // workflow name
console.log(status.version); // version string
console.log(status.status); // "pending"|"running"|"waiting"|"completed"|"failed"|...
console.log(status.current_step); // current or last step name
// status.input → Uint8Array (raw input bytes)
// status.created_at → bigint (epoch ms)
// status.started_at? → bigint | undefined
// status.completed_at? → bigint | undefined
// status.wait_signal? → string | undefined (signal type being waited for)
// Cancel a run
await client.workflow.cancel(runId, "User requested cancellation");
Signals
Deliver external events to a waiting workflow:
// The workflow must have a wait_for_signal step expecting "approval_decision"
await client.workflow.signal(
runId,
"approval_decision",
JSON.stringify({ approved: true, approver: "manager@corp.com" })
);
History and Listings
// Run event history
const events = await client.workflow.history(runId, { limit: 20 });
for (const event of events) {
console.log(`[${event.timestamp}] ${event.type}: ${event.detail}`);
}
// List runs for a workflow
const runs = await client.workflow.listRuns({
workflowName: "process-order",
limit: 50,
});
for (const run of runs) {
console.log(`${run.run_id} — ${run.status} (${run.created_at})`);
}
// List all registered definitions
const defs = await client.workflow.listDefinitions();
for (const def of defs) {
console.log(`${def.name} v${def.version}`);
}
// Download a definition's YAML
const yaml = await client.workflow.getDefinition("process-order");
// yaml → Uint8Array | null
Disable / Enable
// Pause new runs (existing runs continue)
await client.workflow.disable("process-order");
// Resume
await client.workflow.enable("process-order");
Full Example
See examples/workflow.ts for a complete walkthrough covering sync, signals, signal timeouts, outcome-based routing, history, and cancellation.
API Reference Tables
KV Methods
| Method | Signature | Description |
|---|---|---|
get | get(key, opts?) → Promise<GetResult | null> | Get value and version |
put | put(key, value, opts?) → Promise<PutResult> | Set value; returns the new version |
delete | delete(key, opts?) → Promise<void> | Delete key |
scan | scan(prefix, opts?) → Promise<ScanResult> | Prefix scan |
history | history(key, opts?) → Promise<VersionEntry[]> | Version history |
Queue Methods
| Method | Signature | Description |
|---|---|---|
enqueue | enqueue(queue, payload, opts?) → Promise<bigint> | Add message |
dequeue | dequeue(queue, count, opts?) → Promise<DequeueResult> | Fetch messages |
complete | complete(queue, delivery, opts?) → Promise<QueueReportResult> | Complete a dequeue's messages (pass its result) |
fail | fail(queue, delivery, opts?) → Promise<QueueReportResult> | Hand them back: ready again, or dead once their attempts are spent |
touch | touch(queue, delivery, opts?) → Promise<QueueTouchResult> | Keep their lease |
peek | peek(queue, limit?, opts?) → Promise<PeekResult> | The next ready messages, without taking them (limit 1 to 100, default 20) |
dlqList | dlqList(queue, { limit?, after? }?) → Promise<DLQListResult> | A page of dead letters, oldest first: { messages, total, hasMore, lastSeq } |
Stream Methods
| Method | Signature | Description |
|---|---|---|
append | append(stream, payload, opts?) → Promise<AppendResult> | Append record (with optional headers) |
read | read(stream, opts?) → Promise<ReadResult> | Read records |
groupRead | groupRead(stream, opts) → Promise<StreamGroupReadResult> | Lease up to limit of a group's records |
groupAck | groupAck(stream, delivery, opts) → Promise<StreamGroupReportResult> | Ack a read's records |
groupNack | groupNack(stream, delivery, opts) → Promise<StreamGroupReportResult> | Nack them (error, delayMs, dead), or hand them back unstarted (abandon) |
groupTouch | groupTouch(stream, delivery, opts) → Promise<StreamGroupTouchResult> | Keep their lease |
Workflow Methods
| Method | Signature | Description |
|---|---|---|
sync | sync(yaml) → Promise<SyncResult> | Deploy/update definition from YAML string |
syncBytes | syncBytes(bytes) → Promise<SyncResult> | Deploy/update from raw bytes |
start | start(name, input?) → Promise<string> | Start a run, returns run ID |
status | status(runId) → Promise<WorkflowStatusResult> | Get run status |
signal | signal(runId, type, data?) → Promise<void> | Deliver a signal to a waiting run |
cancel | cancel(runId, reason?) → Promise<void> | Cancel a run |
history | history(runId, opts?) → Promise<HistoryEvent[]> | Run event history |
listRuns | listRuns(opts?) → Promise<RunEntry[]> | List runs for a workflow |
listDefinitions | listDefinitions() → Promise<DefinitionEntry[]> | List registered definitions |
getDefinition | getDefinition(name) → Promise<Uint8Array | null> | Download definition YAML |
disable | disable(name) → Promise<void> | Pause new runs |
enable | enable(name) → Promise<void> | Resume new runs |
Errors
Refusals are ServerError subclasses carrying status, reason and ran.
import { isQueueFull, isGroupHeldFull, isLimit } from "@floruntime/node";
try {
await client.queue.enqueue("tasks", payload);
} catch (err) {
if (isQueueFull(err)) { /* the queue's or the shard's caps: back off and send again */ }
else if (isGroupHeldFull(err)) { /* a group read took nothing new: ack what you hold */ }
else if (isLimit(err)) { /* a LimitError: at a limit built into the server */ }
else throw err;
}
A full queue and a full group are OverloadedErrors with reason QueueFull or GroupHeldFull. The client retries a full queue with backoff, as any overloaded refusal that didn't run, since it drains as messages are completed. It doesn't retry GroupHeldFull: a group's cap counts its leased, ready and dead records, and dead ones leave only when the group is deleted or a stream trim passes them. LimitError (status limit) is thrown only for too many actions today, counted per shard; it is never retried, and no setting raises it.