Zig SDK

Native Zig SDK for Flo — zero-allocation wire protocol.

Installation

Add to build.zig.zon:

.dependencies = .{
    .flo = .{
        .url = "https://github.com/floruntime/flo-zig/archive/refs/tags/v0.1.0.tar.gz",
        .hash = "...",
    },
},

In build.zig:

const flo = b.dependency("flo", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("flo", flo.module("flo"));

Quick Start

const std = @import("std");
const flo = @import("flo");
 
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();
 
    var client = flo.Client.init(allocator, "localhost:9000", .{ .namespace = "myapp" });
    defer client.deinit();
    try client.connect();
 
    // KV
    var kv = flo.KV.init(&client);
    _ = try kv.put("key", "value", .{});
    if (try kv.get("key", .{})) |r_const| {
        var r = r_const;
        defer r.deinit(allocator);
        std.debug.print("Got: {s} @ v{d}\n", .{ r.value, r.version });
    }
 
    // Queue
    var queue = flo.Queue.init(&client);
    const seq = try queue.enqueue("tasks", "payload", .{ .priority = 5 });
    var result = try queue.dequeue("tasks", 10, .{});
    defer result.deinit();
    // Leased: complete them within the lease, or they're delivered again
    var done = try queue.complete("tasks", result.lease, result.messages, .{});
    defer done.deinit();
 
    // Stream
    var stream = flo.Stream.init(&client);
    _ = try stream.append("events", "data", .{});
    var records = try stream.read("events", .{});
    defer records.deinit();
}

KV Operations

var kv = flo.KV.init(&client);
 
// Get returns ?GetResult — carries both value and version
if (try kv.get("key", .{})) |r_const| {
    var r = r_const;
    defer r.deinit(allocator);
    std.debug.print("{s} @ v{d}\n", .{ r.value, r.version });
}
 
// Wait up to 5 s for the key to appear (.wait_for = .change waits for its next version)
_ = try kv.get("key", .{ .wait_ms = 5000 });
 
// Put returns PutResult { version: u64 }
const put_res = try kv.put("key", "value", .{
    .ttl_ms = 3_600_000,
    .condition = .if_absent,
    .namespace = "other-ns",
});
 
// CAS — use the version returned by Get/Put
if (try kv.get("key", .{})) |r_const| {
    var r = r_const;
    defer r.deinit(allocator);
    _ = try kv.put("key", "new", .{ .cas_version = r.version });
}
 
// Delete
const existed = try kv.delete("key", .{}); // a missing key isn't an error
 
// Multi-key get (single round trip, up to 256 keys, may span shards)
var mget_res = try kv.mget(&.{ "user:1", "user:2", "user:3" }, .{});
defer mget_res.deinit();
for (mget_res.entries) |e| {
    if (e.found) {
        std.debug.print("{s} = {s} (v{d})\n", .{ e.key, e.value, e.version });
    } else {
        std.debug.print("{s} missing\n", .{e.key});
    }
}
 
// Scan key names (not values); cursor is null on the last page
var page = try kv.scan("prefix:", .{ .limit = 100 });
defer page.deinit();
for (page.keys) |name| std.debug.print("{s}\n", .{name});
 
// History
const versions = try kv.history("key", .{ .limit = 10 }); // version, at_ms, value
defer {
    for (versions) |*v| v.deinit(allocator);
    allocator.free(versions);
}
 
// Atomic counter
const n = (try kv.incr("visits:home", .{})).value;
const m = try kv.incr("visits:home", .{ .delta = 10 });
 
// TTL lifecycle and existence
try kv.expire("lock:resource", 60_000, .{}); // extend TTL to 60 s
try kv.expire("lock:resource", 0, .{});      // clear TTL
const exists = try kv.exists("lock:resource", .{});
 
// JSON paths
_ = try kv.jsonSet("order:42", "$", "{\"items\":3,\"status\":\"new\"}", .{});
const set_res = try kv.jsonSet("order:42", "$.status", "\"shipped\"", .{}); // atomic sub-field
std.debug.print("doc now at v{d}\n", .{set_res.version});
if (try kv.jsonGet("order:42", "$.status", .{})) |status_const| {
    var status = status_const;
    defer status.deinit(allocator);
    std.debug.print("{s} @ v{d}\n", .{ status.value, status.version });
}
_ = try 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.
var txn = try kv.begin("{user:42}:name", .{});
defer txn.deinit();
_ = try txn.put("{user:42}:name", "Jane", .{});
try txn.incr("{user:42}:visits", 1);
const result = try txn.commit();
std.debug.print("committed {d} ops at index {d}\n", .{ result.op_count, result.commit_index });
// On error, call `txn.rollback()` instead — idempotent.

scan, mget, jsonGet, jsonSet, jsonDel, and history are not supported inside a transaction and return FloError.TxnUnsupportedOp. 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

var queue = flo.Queue.init(&client);
 
// Enqueue with options
const seq = try queue.enqueue("tasks", "payload", .{
    .priority = 5,
});
 
// Dequeue with long polling: the messages are leased until completed
var result = try queue.dequeue("tasks", 10, .{
    .block_ms = 5000,
});
defer result.deinit();
 
// Complete them within the lease (queue.fail hands them back)
var report = try queue.complete("tasks", result.lease, result.messages, .{});
defer report.deinit();
// Dead letters: up to 100, oldest first; pass .after = page.last_seq for the next page
var page = try queue.dlqList("tasks", .{ .limit = 100 });
defer page.deinit();

Stream Operations

var stream = flo.Stream.init(&client);
 
// Append
const result = try stream.append("events", "payload", .{});
 
// Append with headers
const result = try stream.append("events", "payload", .{
    .headers = "content-type=application/json\nsource=web",
});
 
// Read from beginning
var records = try stream.read("events", .{});
defer records.deinit();
 
// Read from a specific position
var records = try stream.read("events", .{
    .start = flo.StreamID.fromSequence(100), .count = 50,
});
defer records.deinit();
 
// Read from tail with long polling
var records = try stream.read("events", .{
    .tail = true, .block_ms = 5000,
});
defer records.deinit();
 
// Access record fields
for (records.records) |rec| {
    std.debug.print("Stream: {s}\n", .{rec.stream});   // stream name
    std.debug.print("Payload: {s}\n", .{rec.payload});  // raw bytes
    // rec.headers = ?[]const u8 (raw wire bytes, null if no headers)
}
 
// Consumer groups: a read leases its records to the consumer
var got = try stream.groupRead("events", "my-group", "worker-1", .{
    .count = 10, .block_ms = 5000,
});
defer got.deinit();
var acked = try stream.groupAck("events", "my-group", got.lease, done_records, .{ .consumer = "worker-1" });
defer acked.deinit();
 
// Nack a failure with why (at most 1024 bytes): ready again, or dead once
// the group's attempts are spent
var nacked = try stream.groupNack("events", "my-group", got.lease, failed_records, .{
    .consumer = "worker-1", .error_message = "payment service timed out",
});
defer nacked.deinit();
 
// 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.
var handed_back = try stream.groupNack("events", "my-group", got.lease, unstarted_records, .{
    .consumer = "worker-1", .abandon = true,
});
defer handed_back.deinit();
 
// Info and trim
const info = try stream.info("events", .{});
const trimmed = try stream.trim("events", .{ .max_len = 1000 }); // trimmed.removed records

StreamWorker (high-level)

The recommended way to consume streams is the StreamWorker. It handles consumer group join, polling, concurrency, ack/nack, and reconnection automatically:

fn processEvent(ctx: *flo.StreamContext) !void {
    const data = try ctx.json(Event);
    defer data.deinit();
 
    std.debug.print("Stream: {s}, ID: {d}\n", .{ ctx.stream(), ctx.streamID().sequence });
    if (ctx.headers()) |hdrs| {
        // iterate parsed headers
        _ = hdrs;
    }
}
 
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();
 
    var worker = try flo.StreamWorker.init(allocator, .{
        .endpoint = "localhost:9000",
        .namespace = "myapp",
        .stream = "events",
        .group = "processors",
        .concurrency = 5,
        .batch_size = 10,
        .block_ms = 30_000,
    }, processEvent);
    defer worker.deinit();
 
    try worker.start();
}

StreamWorkerConfig

OptionTypeDefaultDescription
stream[]const u8""Single stream name
streams?[]const []const u8nullMultiple streams
group[]const u8"default"Consumer group name
consumer?[]const u8autoConsumer ID
concurrencyu3210Max concurrent handlers
batch_sizeu3210Records per poll
block_msu3230_000Long-poll timeout (ms)
heartbeat_interval_msu6430_000Heartbeat interval (ms)

StreamContext

The handler receives a *StreamContext with convenience accessors:

fn handler(ctx: *flo.StreamContext) !void {
    ctx.payload();    // []const u8
    ctx.streamID();   // StreamID
    ctx.stream();     // stream name
    ctx.headers();    // ?std.StringHashMap([]const u8)
    ctx.json(T);      // parsed JSON
}

Records are auto-acked on handler success and auto-nacked on error. When the worker stops, records it read but hasn't started are abandoned: ready for another consumer at once, with no attempt spent. The worker can't interrupt a running handler; a long one checks ctx.stopping() and returns an error to cut itself short, and that record is abandoned too, not nacked. Connection errors trigger automatic reconnect.

abandon can't be given with dead, delay_ms or error_message (FloError.BadRequest, before sending). A report to a group that doesn't exist is FloError.NotFound.

ActionWorker

The ActionWorker is a high-level worker that manages connection, registration, polling, heartbeats, and graceful shutdown:

const flo = @import("flo");
 
fn processOrder(ctx: *flo.ActionContext) anyerror!flo.ActionHandlerResult {
    const input = try ctx.json(OrderRequest);
    defer input.deinit();
 
    // For long tasks, keep the lease: touch at least every half lease
    _ = try ctx.touch();
 
    return .{ .bytes = try ctx.toBytes(.{ .status = "completed" }) };
}
 
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();
 
    var worker = try flo.ActionWorker.init(allocator, .{
        .endpoint = "localhost:9000",
        .namespace = "myapp",
        .concurrency = 10,
    });
    defer worker.deinit();
 
    // The last argument is the action's options: .{} is a 30 s lease and 3 attempts.
    try worker.registerAction("process-order", processOrder, .{});
    try worker.start();
}

For low-level action operations (register, invoke, status), use flo.Actions:

var actions = flo.Actions.init(&client);
 
// Register an action type
try actions.registerAction("send-email", .user, .{
    .timeout_ms = 30000, .max_retries = 3, // max_retries counts attempts in all
});
 
// Invoke an action; .labels routes it to workers registered with those labels
var invoked = try actions.invoke("send-email", "{\"to\":\"user@example.com\"}", .{
    .labels = "{\"region\":\"eu\"}",
});
defer invoked.deinit();
 
// Check status
var status = try actions.getStatus(invoked.run_id, .{});
defer status.deinit();

Error Handling

All operations return flo.FloError:

ErrorDescription
NotConnectedClient not connected
ConnectionFailedTCP connection failed
NotFoundKey/queue not found
BadRequestInvalid request
ConflictCAS conflict
ServerErrorInternal server error
TableMismatchThe server is from another release; client.foreign_server names it. Upgrade the SDK and the server together

After a refusal, client.lastError() gives its status code, reason, ran (whether the request took effect) and message.

Memory Management

  • All results that allocate memory have a .deinit() method — always defer result.deinit()
  • The client requires an allocator at init time
  • String values returned from get() must be freed by the caller

Errors

A refusal is a FloError; client.lastError() has the server's status, reason, ran and message.

ErrorWhen
FloError.Overloaded with reason queue_fullAn enqueue found the queue, or the shard's queues and groups together, at their caps. The client retries it with backoff, since it drains as messages are completed, and returns it once its retries run out.
FloError.GroupHeldFullA group read took nothing new: the 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. Never retried: reading again won't help. The stream worker logs it and backs off.
FloError.LimitStatus limit: the node is at a limit built into the server. Only too many actions, counted per shard, is returned today; it is never retried, and no setting raises it.