# Go SDK (github.com/egeominotti/bunqueue/sdk/go)

Official Go 1.26.5+ SDK for bunqueue: goroutine Workers with panic recovery, atomic FlowProducer, native TLS, structured telemetry, and typed errors.

Canonical: https://bunqueue.dev/guide/sdks/go/

---

Official Go client speaking bunqueue TCP protocol v3 with concurrent workers, automatic panic recovery, verified TLS, and atomic flows.

**In 30 seconds**

- Install with go get github.com/egeominotti/bunqueue/sdk/go (v0.2.0+ required for protocol v3 and atomic PUSHF flows; Go 1.26.5+).
- Worker runs a bounded goroutine pool, recovers panics with full stack traces, and never crashes the worker loop.
- Heartbeats default to disabled in Go: set HeartbeatIntervalS (e.g. 10) for long-running jobs so leases stay alive.
- Inspect transport, timeout, auth, and command errors cleanly with errors.As.

*[Interactive doc iso diagram: Dispatch goroutine workers with panic recovery, atomic flows, and verified TLS - Idiomatic Go 1.26.5+: bounded goroutine pools, full panic recovery, typed errors.As handling, and optional HeartbeatIntervalS lock renewal - open the HTML page to view it.]*

## Install & connect

Add the Go module (Go 1.26.5+, `v0.2.0+` for protocol v3) and configure TCP/TLS options:

```bash
go get github.com/egeominotti/bunqueue/sdk/go
```

```go
import (
    "os"
    "time"
    bunqueue "github.com/egeominotti/bunqueue/sdk/go"
)

queue := bunqueue.NewQueue("emails", bunqueue.Options{
    Host: "queue.example.com", Port: 6789, Token: os.Getenv("BUNQUEUE_TOKEN"),
    TLS: &bunqueue.TLSOptions{CAFile: "./ca.pem"}, // or &bunqueue.TLSOptions{} for system CAs
    ConnectTimeout: 10 * time.Second, CommandTimeout: 30 * time.Second,
})
defer queue.Close()
```

## Produce jobs

Enqueue single jobs with `JobOptions` or send a batch in one TCP round-trip with `AddBulk`:

```go
_, err := queue.Add("charge", map[string]any{"orderId": "ord_42"}, bunqueue.JobOptions{
    "jobId": "order-ord_42", "priority": 10, "delay": 5000, "attempts": 5, "durable": true,
})

entries := make([]bunqueue.BulkEntry, 0, len(orders))
for _, o := range orders {
    entries = append(entries, bunqueue.BulkEntry{
        Name: "ingest", Data: o, Opts: bunqueue.JobOptions{"jobId": "order-" + o.ID},
    })
}
ids, err := queue.AddBulk(entries)
```

## Process jobs

`Worker` runs a bounded goroutine pool with automatic panic recovery (converted to job failures with stack traces); set `HeartbeatIntervalS` (disabled by default) to renew leases on long jobs:

```go
worker := bunqueue.NewWorker("emails", func(job *bunqueue.Job) (any, error) {
    payload, ok := job.Data().(map[string]any)
    if !ok || payload["to"] == "" {
        return nil, bunqueue.NewUnrecoverableError("missing recipient") // skip retries -> DLQ
    }
    return sendEmail(payload["to"].(string))
}, bunqueue.WorkerOptions{
    Host:               "localhost",
    Port:               6789,
    Concurrency:        8,
    BatchSize:          10,
    PollTimeoutMs:      5000,
    LockTtlMs:          30000,
    HeartbeatIntervalS: 10, // enable lock & worker heartbeats for long jobs
})

worker.On("completed", func(args ...any) { log.Printf("done %s", args[0].(*bunqueue.Job).ID()) })
worker.On("error", func(args ...any) { log.Println("worker error:", args[0]) })

// Graceful shutdown: worker.Stop() (drain in-flight), then worker.Close() (unregister & disconnect)
worker.Run()
```

## Query, control, and flows

Query jobs, control queues/DLQ, and submit atomic `PUSHF` chains or parent/child trees with `FlowProducer`:

```go
job, _ := queue.GetJob(id)                 // nil when missing
state, _ := queue.GetState(id)             // "waiting" | "active" | ...
result, _ := queue.WaitForJob(id, 30000)
counts, _ := queue.GetJobCounts()

_ = queue.Pause()
dropped, _ := queue.Drain()
_, _ = queue.RetryDlq("", 0)
```

Atomic parent/child trees and sequential pipelines with `FlowProducer`:

```go
flow := bunqueue.NewFlowProducer(bunqueue.Options{})
defer flow.Close()

ids, err := flow.AddChain([]bunqueue.ChainStep{
    {Name: "extract", QueueName: "etl"},
    {Name: "transform", QueueName: "etl"},
    {Name: "load", QueueName: "etl"},
})

node, err := flow.Add(bunqueue.FlowJob{
    Name:      "assemble",
    QueueName: "orders",
    Children: []bunqueue.FlowJob{
        {Name: "reserve-stock", QueueName: "orders"},
        {Name: "charge-card", QueueName: "orders"},
    },
})
```

## Telemetry and error handling

Observe connection, auth, command latency, and retry events via `OnEvent` (tokens and job payloads are never emitted):

```go
queue := bunqueue.NewQueue("emails", bunqueue.Options{
    OnEvent: func(event bunqueue.TelemetryEvent) {
        metrics.Observe(event)
    },
})
```

Use `errors.As` to branch on typed connection, timeout, auth, command, or serialization errors. Pass 64-bit snowflake IDs as strings to stay within IEEE 754 `2^53` integer precision.

## See also

- [SDKs Overview](https://bunqueue.dev/guide/sdks/): cross-language wire guarantees and options table
- [Source & Changelog](https://github.com/egeominotti/bunqueue/tree/main/sdk/go)
