# Python SDK (bunqueue-client)

Official Python 3.10+ SDK for bunqueue: threaded Workers, ACK batching, atomic FlowProducer, Simple Mode, native TLS, and structured telemetry.

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

---

Official Python 3.10+ client over native binary MessagePack TCP. Ideal for ML inference, data pipelines, and async backend workers paired with any frontend runtime.

**In 30 seconds**

- Install with pip install bunqueue-client (0.2.0+ required for protocol v3 and atomic PUSHF flows).
- Includes concurrent Worker with automatic heartbeats, opt-in ack_batch coalescing, FlowProducer (trees, chains, fan-in), and Simple Mode.
- All job and worker options use Python snake_case (job_id, remove_on_complete, lock_ttl_ms, heartbeat_interval_s).
- Pass tls=True, {"ca_file": ...}, or a custom ssl.SSLContext; certificate verification is enabled by default.

*[Interactive doc iso diagram: Run threaded Workers, ACK batching, atomic flows, and Simple Mode over TCP - Built for Python AI & backend teams: install bunqueue-client (Python 3.10+) with concurrent workers, automatic heartbeats, and verified TLS - open the HTML page to view it.]*

## Install & connect

Install `bunqueue-client` and connect over MessagePack TCP (pass an explicit `Connection` when customizing `connect_timeout`):

```bash
pip install bunqueue-client
```

```python
import os
from bunqueue import Connection, Queue

queue = Queue(
    "emails", host="queue.example.com", port=6789,
    token=os.environ["BUNQUEUE_TOKEN"], tls=True, command_timeout=10.0,
)
# tls also accepts {"ca_file": "./ca.pem"} or ssl.SSLContext; share a Connection for connect_timeout:
conn = Connection(host="queue.example.com", port=6789, connect_timeout=5.0, tls=True)
custom_queue = Queue("emails", connection=conn)
```

## Produce jobs

Enqueue single jobs with Python `snake_case` options or send a batch in one TCP round-trip via `add_bulk`:

```python
queue.add(
    "charge", {"order_id": "ord_42", "amount": 1999},
    job_id="order-ord_42", priority=10, delay=5000, attempts=5, durable=True,
)
queue.add_bulk([{"name": "ingest", "data": o, "job_id": f"order-{o['id']}"} for o in orders])
```

## Process jobs

`Worker` runs a bounded thread pool with automatic lease heartbeats, optional `ack_batch` coalescing, and `UnrecoverableError` to bypass retries into the DLQ:

```python
from bunqueue import UnrecoverableError, Worker

def process(job):
    if not job.data.get("to"):
        raise UnrecoverableError("missing recipient")  # skip retries -> DLQ
    send_email(job.data["to"])
    return {"sent": True}

worker = Worker(
    "emails", process, host="localhost", port=6789,
    concurrency=10, batch_size=10, poll_timeout_ms=5000, lock_ttl_ms=30000, heartbeat_interval_s=10,
    ack_batch={"max_size": 50, "max_delay_ms": 5},  # opt-in high-volume ACK batching
)
worker.on("completed", lambda job, res: print(f"done {job.id}: {res}"))
worker.on("failed", lambda job, err: print(f"failed {job.id}: {err}"))
worker.on("error", lambda err: print(f"worker error: {err}"))
worker.run()
# Graceful shutdown: worker.close() (flush ACKs & wait) or worker.close(timeout=5) (bound wait)
```

Permanent refusals (bad auth token or validation error) raise out of `run()` unless an `error` listener is attached.

## Query, control, and webhooks

Inspect job state, wait for completion, control queues/DLQ, and manage webhooks directly on `Queue`:

```python
job = queue.get_job(job_id)                 # None when missing
state = queue.get_state(job_id)             # "waiting" | "active" | ...
result = queue.wait_for_job(job_id, timeout_ms=30000)
counts = queue.get_job_counts()

queue.pause()
dropped = queue.drain()
queue.retry_dlq()

# Webhook helpers
wh_id = queue.add_webhook("https://api.example.com/hooks", ["job.completed"], secret="s3cr3t")
queue.set_webhook_enabled(wh_id, False)
queue.remove_webhook(wh_id)
```

## Flows (`FlowProducer`)

`FlowProducer` validates the entire graph locally and submits one atomic `PUSHF` command:

```python
from bunqueue import FlowProducer

flow = FlowProducer()

# Sequential pipeline
flow.add_chain([
    {"name": "extract", "queueName": "etl"},
    {"name": "transform", "queueName": "etl"},
    {"name": "load", "queueName": "etl"},
])

# Parent waits for children
node = flow.add({
    "name": "assemble",
    "queueName": "orders",
    "children": [
        {"name": "reserve-stock", "queueName": "orders"},
        {"name": "charge-card", "queueName": "orders"},
    ],
})

# Fan-in: N parallel jobs converge into one
flow.add_bulk_then(parts, {"name": "merge", "queueName": "orders"})
```

## Simple Mode (`Bunqueue`)

Combine queue, worker, named routes, middleware, retries, circuit breaker, and crons in one object:

```python
from bunqueue import Bunqueue

app = Bunqueue(
    "notifications",
    routes={
        "send-email": lambda job: {"sent": True},
        "send-sms": lambda job: {"sent": True},
    },
    concurrency=10,
    retry={"max_attempts": 5, "strategy": "jitter"},
    circuit_breaker={"threshold": 5, "reset_timeout": 30000},
)

def timing(job, next_fn):
    result = next_fn()
    print(f"{job.name} done")
    return result

app.use(timing)
app.add("send-email", {"to": "alice@example.com"})
app.cron("daily-digest", "0 9 * * *", {"to": "all"})
```

## Structured telemetry & errors

Attach `on_telemetry` to emit connection, auth, command latency, and retry events without exposing tokens or payloads:

```python
queue = Queue("emails", on_telemetry=lambda event: metrics.observe(event))
```

Typed exceptions distinguish connection drops, command timeouts, server rejections, auth failures, and serialization errors. Large integers outside int32 travel as float64 (pass 64-bit snowflake IDs as strings).

## See also

- [SDKs Overview](https://bunqueue.dev/guide/sdks/): cross-language wire guarantees and options table
- [PyPI Package](https://pypi.org/project/bunqueue-client/) · [Source & Changelog](https://github.com/egeominotti/bunqueue/tree/main/sdk/python)
