TypeScript SDK
Build workers and manage tasks with the TypeScript SDK.
Installation
npm install https://github.com/IWhitebird/Valka/releases/download/v0.2.0/valka-sdk-0.2.0.tgzThe package is not on npm yet: each GitHub release carries it as a tarball. To build it from a
checkout instead, run npm install && npm pack in sdks/typescript and install the .tgz it
writes. Node.js 18 or newer.
The TypeScript SDK provides:
- ValkaWorker: process tasks from queues
- ValkaClient: create, get, list, and cancel tasks
- Full TypeScript type definitions
Worker
import { ValkaWorker, type TaskContext } from "@valka/sdk";
async function handleTask(ctx: TaskContext): Promise<unknown> {
ctx.log(`Processing task '${ctx.taskName}' (attempt ${ctx.attemptNumber})`);
const input = ctx.input<{ to?: string; subject?: string }>();
const to = input.to ?? "unknown";
ctx.log(`Sending email to ${to}...`);
await sleep(1000);
ctx.log("Email sent successfully");
return { delivered_to: to, status: "sent" };
}
const worker = ValkaWorker.builder()
.name("email-worker")
.serverAddr("localhost:50051")
.queues(["emails"])
.concurrency(4)
.handler(handleTask)
.build();
await worker.run();Builder Options
| Method | Description |
|---|---|
.name(name) | Worker name |
.serverAddr(addr) | Valka server gRPC address |
.serverAddrs([...]) | Several nodes; the worker moves to the next when its connection drops |
.apiKey(key) | API key (default: VALKA_API_KEY) |
.queues([...]) | Queues to listen on |
.concurrency(n) | Max concurrent tasks |
.handler(fn) | Async function to process tasks |
Task Context
async function handleTask(ctx: TaskContext): Promise<unknown> {
// Access metadata
const name = ctx.taskName;
const attempt = ctx.attemptNumber;
const taskId = ctx.taskId;
// Typed input parsing
const input = ctx.input<{ to: string; amount: number }>();
// Logging
ctx.log("Processing...");
ctx.debug("Debug info");
// Return output (any JSON-serializable value)
return { result: "done" };
}Step Checkpoints
ctx.step(name, fn) runs fn once per task: its result is checkpointed, and a retry of the
task returns the recorded result instead of running fn again.
async function handleTask(ctx: TaskContext) {
const rows = await ctx.step("fetch", () => fetchRows());
const report = await ctx.step("transform", () => buildReport(rows));
await ctx.step("upload", () => upload(report));
return { rows: rows.length };
}Step results must be JSON-serializable. ctx.checkpoint(step, value) and
ctx.checkpointValue(step) record and read checkpoints directly.
Client
The client uses the REST API (port 8989).
import { ValkaClient } from "@valka/sdk";
const client = new ValkaClient({
baseUrl: "http://valka-1:8989",
baseUrls: ["http://valka-2:8989", "http://valka-3:8989"], // optional: more nodes
apiKey: "...", // or VALKA_API_KEY
});
const task = await client.createTask({
queue_name: "emails",
task_name: "send-email",
input: { to: "user@example.com", subject: "Welcome!" },
max_retries: 3,
});
console.log(`created ${task.id}`);
const latest = await client.getTask(task.id);
console.log(`status ${latest.status}`);Several nodes, API keys and retries
- Give the client every node's URL. A call that fails because a node is unreachable or busy
(network errors,
429,502,503,504) is retried with backoff on the next node, up toattemptstimes (default 6); each attempt has atimeoutMs(default 10 s). - Every create carries an idempotency key: yours, or a generated
auto-…one. A retried create therefore returns the task the first attempt made instead of making a second. SetautoIdempotency: falseto turn this off. - Cancels and signals are sent once, since repeating them is not safe.
apiKey(default: theVALKA_API_KEYenvironment variable) is sent asAuthorization: Bearer <key>.
Signal Handling
const worker = ValkaWorker.builder()
.name("worker")
.serverAddr("localhost:50051")
.queues(["emails"])
.concurrency(4)
.handler(handleTask)
.onSignal(async (signal) => {
console.log(`Signal received: ${signal.signalType}`);
})
.build();Reconnects
The worker survives server restarts and node failures without losing work:
- When its stream breaks (or the server sends
ServerShutdown), the worker reconnects with exponential backoff, from 100 ms up to 30 s, to its node (the next one in its list when it has several). Running handlers keep going meanwhile. - On the new connection it resends every result not yet acknowledged (
APPLIEDorSTALE), and keeps heartbeating those tasks until then. - Its hello lists the runs it is still executing. The task's owner reattaches each one to the new connection instead of running the task again, or records a dispatch that was lost in a crash. A run that ended meanwhile (cancelled, expired) gets a cancellation.
In a cluster, give the worker every node with .serverAddrs([...]) (it moves to the next on each
reconnect), or point it at a load balancer or DNS name that covers several nodes, so it lands
on a live node when its own dies. See
Clustering.