Go SDK

Go client SDK for Flo — KV, Streams, Queues, Actions, and Workers.

Installation

go get github.com/floruntime/flo-go

Quick Start

package main
 
import (
    "fmt"
    "log"
    flo "github.com/floruntime/flo-go"
)
 
func main() {
    client := flo.NewClient("localhost:9000",
        flo.WithNamespace("myapp"),
    )
    if err := client.Connect(); err != nil {
        log.Fatal(err)
    }
    defer client.Close()
 
    // KV
    client.KV.Put("user:123", []byte("John Doe"), nil)
    value, _ := client.KV.Get("user:123", nil)
    fmt.Printf("Got: %s\n", value)
 
    // Queue
    client.Queue.Enqueue("tasks", []byte(`{"task":"process"}`), nil)
    result, _ := client.Queue.Dequeue("tasks", 10, nil)
    for _, msg := range result.Messages {
        fmt.Printf("Task: %s\n", msg.Payload)
    }
    client.Queue.Complete("tasks", result.Lease, result.Items(), nil)
 
    // Stream
    client.Stream.Append("events", []byte(`{"event":"login"}`), nil)
    records, _ := client.Stream.Read("events", nil)
    for _, rec := range records.Records {
        fmt.Printf("Event: %s\n", rec.Payload)
    }
}

Client Options

client := flo.NewClient("localhost:9000",
    flo.WithNamespace("default"),     // Default namespace
    flo.WithTimeout(5 * time.Second), // Connection/operation timeout
    flo.WithDebug(true),              // Enable debug logging
)

KV Operations

Get

// Returns *flo.GetResult (nil if not found) — carries both value and version
result, err := client.KV.Get("key", nil)
if result != nil {
    fmt.Printf("%s @ v%d\n", result.Value, result.Version)
}
 
// Wait up to 5 s for the key to appear (WaitFor: flo.WaitForChange waits for its next version)
result, _ = client.KV.Get("key", &flo.GetOptions{WaitMs: 5000})

Put

// Simple put — returns flo.PutResult with the committed version
res, err := client.KV.Put("key", []byte("value"), nil)
fmt.Println("committed at version", res.Version)
 
// With TTL
ttl := uint64(3_600_000) // one hour, in milliseconds
res, _ = client.KV.Put("key", []byte("value"), &flo.PutOptions{TTLMs: &ttl})
 
// With CAS — use the version returned by Get or a previous Put
cur, _ := client.KV.Get("key", nil)
res, err = client.KV.Put("key", []byte("new"), &flo.PutOptions{CASVersion: &cur.Version})
if flo.IsConflict(err) {
    // Version mismatch — re-read and retry
}
 
// CAS create-if-absent (version 0 means "must not exist")
zero := uint64(0)
res, err = client.KV.Put("key", []byte("first"), &flo.PutOptions{CASVersion: &zero})
 
// Conditional
res, err = client.KV.Put("key", []byte("value"), &flo.PutOptions{Condition: flo.ConditionIfAbsent})

Delete

existed, err := client.KV.Delete("key", nil) // a missing key isn't an error

Multi-key get

Fetch up to 256 keys in one call — keys may live on different shards; when the answers don't fit one response, MGet asks again from where the server stopped. Each entry has a Found flag.

entries, err := client.KV.MGet([]string{"user:1", "user:2", "user:3"}, nil)
if err != nil { return err }
for _, e := range entries {
    if e.Found {
        fmt.Printf("%s = %s (v%d)\n", e.Key, e.Value, e.Version)
    } else {
        fmt.Printf("%s missing\n", e.Key)
    }
}

Atomic counters

n, err := client.KV.Incr("visits:home", nil)            // +1; n.Value, n.Version
n, err = client.KV.Incr("visits:home", &flo.KVIncrOptions{Delta: flo.Int64Ptr(10)})

TTL lifecycle and existence

client.KV.Expire("lock:resource", 60_000, nil) // extend TTL to 60 s
client.KV.Expire("lock:resource", 0, nil)      // clear TTL
ok, _ := client.KV.Exists("lock:resource", nil)

JSON paths

// Whole-document set (creates the key)
client.KV.JsonSet("order:42", "$", []byte(`{"items":3,"status":"new"}`), nil)
 
// Atomic sub-field update — single Raft entry, returns new version
res, _ := client.KV.JsonSet("order:42", "$.status", []byte(`"shipped"`), nil)
fmt.Println("doc now at v", res.Version)
 
// Read a sub-field — returns *GetResult{Value, Version}
status, _ := client.KV.JsonGet("order:42", "$.status", nil)
fmt.Printf("%s @ v%d\n", status.Value, status.Version)
 
// Remove a sub-field
client.KV.JsonDel("order:42", "$.status", nil)

Per-shard transactions

Buffer multiple writes on one shard and commit them atomically as one Raft entry. A transaction is pinned to the {tag} of the key it begins with (the text between the first { and the next }), or the whole key if it has none. Give every key in it the same {tag}: one that routes elsewhere is refused bad_request with ReasonKeysNotColocated, and doesn't run.

txn, err := client.KV.Begin("{user:42}:name", nil)
if err != nil {
    return err
}
 
if _, err := txn.Put("{user:42}:name", []byte("Jane"), nil); err != nil {
    _ = txn.Rollback()
    return err
}
if err := txn.Incr("{user:42}:visits", 1); err != nil {
    _ = txn.Rollback()
    return err
}
 
result, err := txn.Commit()
if err != nil {
    _ = txn.Rollback() // idempotent
    return err
}
fmt.Printf("committed %d ops at index %d\n", result.OpCount, result.CommitIndex)

scan, mget, JsonGet, JsonSet, JsonDel, and History are not supported inside a transaction and return ErrTxnUnsupportedOp. 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).

Scan

// Names only; read values with Get or MGet. Pages of up to 1024 (the default).
result, _ := client.KV.Scan("user:", nil)
for {
    for _, key := range result.Keys {
        fmt.Println(key)
    }
    if result.Cursor == nil {
        break // last page
    }
    result, _ = client.KV.Scan("user:", &flo.ScanOptions{Cursor: result.Cursor})
}

History

entries, _ := client.KV.History("key", nil)
for _, e := range entries {
    fmt.Printf("v%d at %d ms: %s\n", e.Version, e.AtMs, e.Value)
}

Queue Operations

Enqueue

seq, _ := client.Queue.Enqueue("tasks", payload, &flo.EnqueueOptions{
    Priority: 10, // lower is taken first
})

Dequeue

blockMS := uint32(30000)
result, _ := client.Queue.Dequeue("tasks", 10, &flo.DequeueOptions{
    BlockMS: &blockMS,
})
for _, msg := range result.Messages {
    fmt.Printf("seq=%d: %s\n", msg.Seq, msg.Payload)
}

A dequeue leases its messages: complete each one within its lease, or it is delivered again. Failing one hands it back, and after its last attempt it moves to the dead-letter queue.

DLQ

// Up to 100 dead letters, oldest first; pass After: &page.LastSeq for the next page
page, _ := client.Queue.DLQList("tasks", &flo.DLQListOptions{Limit: 100})

Requeueing dead letters isn't served yet: the server refuses DLQRequeue.

Peek

result, _ := client.Queue.Peek("tasks", 10, nil) // the next ready messages, without taking them

Stream Operations

// Append
client.Stream.Append("events", []byte(`{"event":"click"}`), nil)
 
// Append with headers
client.Stream.Append("events", []byte(`{"event":"click"}`), &flo.StreamAppendOptions{
    Headers: map[string]string{"content-type": "application/json", "source": "web"},
})
 
// Read
records, _ := client.Stream.Read("events", nil)
 
// Access record fields
for _, rec := range records.Records {
    fmt.Println(rec.Stream)   // stream name (e.g. "events")
    fmt.Println(rec.Payload)  // raw bytes
    fmt.Println(rec.Headers)  // map[string]string or nil
    fmt.Println(rec.ID)       // StreamID{TimestampMS, Sequence}
}
 
// Consumer groups: a read leases its records to the consumer
count := uint32(10)
got, _ := client.Stream.GroupRead("events", "processors", "worker-1",
    &flo.StreamGroupReadOptions{Count: &count},
)
var done, failed []flo.StreamGroupItem
for _, rec := range got.Records {
    if err := process(rec.Payload); err != nil {
        failed = append(failed, rec.Item())
    } else {
        done = append(done, rec.Item())
    }
}
client.Stream.GroupAck("events", "processors", got.Lease, done, nil)
 
// Nack a failure with why (at most 1024 bytes): ready again, or dead once
// the group's attempts are spent
client.Stream.GroupNack("events", "processors", got.Lease, failed,
    &flo.StreamGroupNackOptions{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.
unstarted := got.Items()[reached:]
client.Stream.GroupNack("events", "processors", got.Lease, unstarted,
    &flo.StreamGroupNackOptions{Abandon: true})

Abandon can't be given with Dead, DelayMS or Error. A report to a group that doesn't exist is ErrNotFound.

StreamWorker (high-level)

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

worker, _ := client.NewStreamWorker(flo.StreamWorkerOptions{
    Stream:      "events",
    Group:       "processors",
    Concurrency: 5,
    BatchSize:   10,
    BlockMS:     30000,
}, func(sctx *flo.StreamContext) error {
    var data map[string]interface{}
    sctx.Into(&data)
    fmt.Printf("Stream: %s, ID: %v\n", sctx.Stream(), sctx.StreamID())
    fmt.Printf("Headers: %v\n", sctx.Headers())
    return process(data)
})
defer worker.Close()
 
worker.Start(ctx)

StreamWorkerOptions

OptionTypeDefaultDescription
StreamstringSingle stream name (shorthand)
Streams[]stringMultiple streams (merged with Stream)
Groupstring"default"Consumer group name
ConsumerstringautoConsumer ID within the group
Concurrencyint10Max concurrent handlers
BatchSizeuint3210Records per poll
BlockMSuint3230000Long-poll timeout (ms)
MessageTimeouttime.Duration5mMax handler duration

StreamContext

The handler receives a *StreamContext with convenience accessors:

func handler(sctx *flo.StreamContext) error {
    sctx.Payload()    // []byte
    sctx.StreamID()   // StreamID
    sctx.Stream()     // stream name
    sctx.Headers()    // map[string]string
    sctx.Namespace()  // namespace
    sctx.Group()      // consumer group
    sctx.Consumer()   // consumer ID
    sctx.Record()     // full StreamRecord
    sctx.Into(&v)     // JSON unmarshal
    return nil
}

Records are auto-acked on handler success and auto-nacked on error. When the worker stops, records it read but hasn't started, and any whose handler the stop cut short (the handler's context is cancelled), are abandoned: ready for another consumer at once, with no attempt spent. Connection errors trigger automatic reconnect.

ActionWorker

w, _ := client.NewActionWorker(flo.ActionWorkerOptions{Concurrency: 10})
defer w.Close()
 
// The last argument is the action's options (*flo.ActionRegisterOptions); nil
// takes the server's defaults.
w.MustRegisterAction("process-order", func(actx *flo.ActionContext) (interface{}, error) {
    var input map[string]interface{}
    if err := actx.Into(&input); err != nil {
        return nil, err
    }
    actx.Touch() // keeps the lease in a long handler
    return map[string]string{"status": "done"}, nil
}, nil)
 
w.Start(ctx)

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:

r, err := client.Workflow.SyncBytes([]byte(yamlString), nil)
// r.Name, r.Version, r.Action → "created" | "updated" | "unchanged"

Start and Monitor Runs

import "encoding/json"
 
// Start a run
input, _ := json.Marshal(map[string]interface{}{
    "orderId": "ORD-123",
    "amount":  99.99,
})
runID, err := client.Workflow.Start("process-order", input, nil)
 
// Get status
s, err := client.Workflow.Status(runID, nil)
fmt.Println(s.RunID)        // string
fmt.Println(s.Workflow)     // workflow name
fmt.Println(s.Version)      // version string
fmt.Println(s.Status)       // "pending"|"running"|"waiting"|"completed"|"failed"|...
fmt.Println(s.CurrentStep)  // current or last step name
// s.Input        []byte  — raw input bytes
// s.CreatedAt    int64   — epoch ms
// s.StartedAt    *int64  — nil if not yet started
// s.CompletedAt  *int64  — nil if not yet completed
// s.WaitSignal   *string — signal type being waited for, or nil
 
// Cancel a run
err = client.Workflow.Cancel(runID, nil)

Signals

Deliver external events to a waiting workflow:

sigData, _ := json.Marshal(map[string]interface{}{
    "approved": true,
    "approver": "manager@corp.com",
})
err = client.Workflow.Signal(runID, "approval_decision", sigData, nil)

History and Listings

History, ListRuns, and ListDefinitions return raw binary and are parsed with helper functions (see the full example for reference parsers):

// Run event history (binary response)
data, err := client.Workflow.History(runID, nil)
events := parseHistory(data) // []HistoryEvent{Type, Detail, Timestamp}
 
// List runs for a workflow
limit := 50
data, err = client.Workflow.ListRuns("process-order", &flo.WorkflowListRunsOptions{Limit: limit})
runs := parseListRuns(data) // []RunEntry{RunID, Workflow, Status, CreatedAt}
 
// List all registered definitions
data, err = client.Workflow.ListDefinitions(nil)
defs := parseListDefinitions(data) // []DefinitionEntry{Name, Version, CreatedAt}
 
// Download a definition's YAML
yamlBytes, err := client.Workflow.GetDefinition("process-order", nil)

Disable / Enable

// Pause new runs (existing runs continue)
err = client.Workflow.Disable("process-order", nil)
 
// Resume
err = client.Workflow.Enable("process-order", nil)

Full Example

See examples/workflows/main.go and examples/action_worker/main.go for a complete walkthrough covering sync, signals, signal timeouts, outcome-based routing, history, and cancellation.

Error Handling

if flo.IsNotFound(err) { /* Key not found */ }
if flo.IsConflict(err) { /* CAS conflict */ }
if flo.IsBadRequest(err) { /* Invalid params */ }
if flo.IsOverloaded(err) { /* Retry later */ }
if flo.IsQueueFull(err) { /* Enqueue refused at the queue's or shard's caps, after the client's retries */ }
if flo.IsGroupHeldFull(err) { /* Group read took nothing new: ack what you hold; not retried */ }
if flo.IsLimit(err) { /* At a limit built into the server; not retried */ }
if errors.Is(err, flo.ErrTableMismatch) { /* Server from another release: upgrade together */ }
 
var se *flo.ServerError
if errors.As(err, &se) && se.Ran == flo.RanYes { /* It took effect: don't resend */ }

ErrQueueFull and ErrGroupHeldFull are also ErrOverloaded. The client retries a full queue with backoff, as any overloaded refusal that didn't run: it drains as messages are completed. It doesn't retry ErrGroupHeldFull: 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, so reading again won't help. ErrLimit (status limit) is returned only for too many actions today, counted per shard; no setting raises it.

Thread Safety

The Go client is thread-safe. Multiple goroutines can use the same client instance.