broker

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 54 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fastworker Broker (pre-v1)

An experimental message broker for Go with embedded, single-node, and distributed prototypes. Correctness, durability, protocol conformance, and security hardening are still in progress.

What This Is

Capability Status
Embedded broker (in-process) Pre-v1; functional, hardening in progress
Standalone broker (HTTP/native server) Pre-v1; functional, hardening in progress
Distributed broker (multi-node) Pre-v1 etcd/raft implementation; release gates remain
Encryption at rest (AES-GCM) Optional, configurable
Encryption in transit (TLS/mTLS) Listener-dependent; conformance in progress

Release status: No current mode has a stable production-support contract. See the release gates and pre-v1 migration notes.

The enhancement plan covers durable messaging, low-latency delivery, client interoperability, and the measurements required to validate improvements.

For publishing atomically with an application database update, see the transactional SQLite outbox and its runnable example.

Atomic stream transactions commit a consumer offset and output messages together through the embedded API, HTTP, or Go client.


Table of Contents


Quick Start

# Install
go get github.com/oarkflow/broker

# Run tests
go test ./...
go test -race ./broker
go vet ./...
Embedded (in-process)
package main

import (
    "context"
    "fmt"
    "time"
    "github.com/oarkflow/broker"
)

func main() {
    ctx := context.Background()
    b := broker.MustNew(broker.Config{
        DefaultQueue: "jobs",
        DefaultVisibility: 30 * time.Second,
    })
    b.Start(ctx)
    defer b.Stop(context.Background())

    b.Subscribe(ctx, broker.ConsumerConfig{
        Name: "worker", Queue: "email.send", AckMode: broker.AckAuto,
    }, func(ctx context.Context, d broker.Delivery) error {
        fmt.Println("received:", string(d.Message.Payload))
        return nil
    })

    b.Publisher().Publish(ctx, "email.created", map[string]string{
        "to": "user@example.com",
    }, broker.WithQueue("email.send"))
}
Standalone (HTTP server)
# Start broker
export BROKER_TOKEN='your-secret-token'
go run ./cmd/brokerd -addr :8090 -wal ./.broker-data -token "$BROKER_TOKEN"

# Publish a message
curl -X POST -H "Authorization: Bearer $BROKER_TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/publish \
  -d '{"topic":"events","queue":"jobs","payload":{"task":"send-email"}}'

# Pull a message
curl -X POST -H "Authorization: Bearer $BROKER_TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/queues/jobs/pull \
  -d '{"consumer_id":"worker-1","limit":1}'

Running the Broker

This is the complete operating guide: build, start, publish, consume, run tasks, and inspect everything. Every command here has been run against a real broker.

Build the binaries

All binaries live in the cmd module and build from its own go.mod:

cd cmd
go build -o /tmp/brokerd    ./brokerd        # broker + admin API + console
go build -o /tmp/brokerctl  ./brokerctl      # CLI / TUI operator client
go build -o /tmp/broker-worker ./broker-worker # remote worker process
cd ..
Start the broker

Two modes. Pick one.

Local development — plain HTTP, no authentication:

/tmp/brokerd --insecure-dev -addr 127.0.0.1:8090 -wal /tmp/broker-data -store wal

--insecure-dev disables authentication entirely: every request is treated as an admin with full permissions. Local use only. Anything reachable from a network must not use it.

Production-shaped — TLS and a bearer token:

/tmp/brokerd \
  -addr 127.0.0.1:8090 \
  -token "$BROKER_TOKEN" \
  -tls-cert cert.pem -tls-key key.pem \
  -wal /var/lib/oarkflow -store wal

brokerd refuses to start unless one of these is true:

  • --insecure-dev is set, or
  • -token is set, and
  • TLS is configured via -tls-cert and -tls-key

Both must be supplied together. Skipping TLS without --insecure-dev is a deliberate startup failure, not a warning.

Useful flags:

Flag Default Meaning
-addr :8090 admin API, data plane and console listen address
-wal (empty) WAL directory. Empty uses an in-memory store
-store auto memory, wal, wal2 (segmented), or sqlite
-wal-shards 1 independent binary WAL shards
-profile durable durable, latency, throughput, lightweight
-queue default default queue name
-token (empty) admin bearer token
-read-token (empty) additional read-only token
-worker-token (empty) token for remote workers
-publisher-token (empty) publish-only token
-quiet false suppress live broker event logs
-max-body 1MiB maximum HTTP request body

Every flag also has an environment variable equivalent (BROKER_ADDR, BROKER_TOKEN, BROKER_WAL, and so on).

With durable, latency or throughput profiles, brokerd refuses to run on the in-memory store. Use -store=wal, -store=wal2, -store=sqlite, or -profile=lightweight.

Open the console

With the broker running, open:

http://127.0.0.1:8090/console/
  • The bare host http://127.0.0.1:8090 redirects there automatically.
  • /console (no trailing slash) redirects to /console/.
  • Paste the admin token and press Connect. The token is kept in sessionStorage for that tab only and sent as an Authorization: Bearer header — never in a URL.
  • Under --insecure-dev there is no token; press Connect to proceed.

The console has no build step and needs no Node tooling. It is a static app served from the binary and reads nothing server-side: every value it shows is fetched by the browser from the same endpoints you would call with curl, using your own credentials.

Views: Overview, Queues, Topics, Streams, Publish, Consumers, Tasks, Dead letters, Routes, Cluster, Audit. It polls every 5 seconds while the auto box is ticked.

You can create and control from the UI: declare queues, topics and streams, register consumers, add routes, publish messages, submit and cancel tasks, replay dead letters, and pause or resume the broker and individual queues.

Publish a message
curl -s -X POST http://127.0.0.1:8090/publish \
  -H 'Content-Type: application/json' \
  -d '{"queue":"orders","payload":{"id":"order-1","amount":100}}'

Target a topic, a stream, or a queue — or set several at once:

# Topic with retention
curl -s -X POST http://127.0.0.1:8090/publish \
  -d '{"topic":"orders.created","payload":{"id":"order-1"}}'

# Stream, for ordered replay
curl -s -X POST http://127.0.0.1:8090/publish \
  -d '{"stream":"audit","payload":{"action":"login"}}'

# Fan out to a topic and a queue in one call
curl -s -X POST http://127.0.0.1:8090/publish \
  -d '{"topic":"orders.created","queue":"orders.process","payload":{"id":"order-1"}}'

Batch publishing takes a bare JSON array, not an object with a messages key. A {"messages":[...]} body is rejected with 400:

curl -s -X POST http://127.0.0.1:8090/publish/batch \
  -d '[{"queue":"orders","payload":{"n":1}},
       {"queue":"orders","payload":{"n":2}}]'

With a token, add -H "Authorization: Bearer $BROKER_TOKEN". Note that a published payload is returned base64-encoded, because Message.Payload is []byte:

curl -s "$BROKER/v1/topics/events?limit=1" \
  | python3 -c 'import sys,json,base64;print(base64.b64decode(json.load(sys.stdin)[0]["payload"]).decode())'
Create queues, topics, streams and consumers

Everything the console can create is also a plain HTTP call. These are the exact bodies its dialogs send.

# Queue. Durations are nanoseconds.
curl -s -X POST $BROKER/queues -d '{
  "name": "orders",
  "max_inflight": 10,
  "max_depth": 500,
  "visibility_timeout": 30000000000,
  "ack_mode": "manual",
  "dlq": "orders.dlq"
}'

# Topic, with retention
curl -s -X POST $BROKER/topics -d '{"name":"orders.created","partitions":1,"retention":86400000000000}'

# Stream, optionally compacted
curl -s -X POST $BROKER/streams -d '{"name":"audit","partitions":1,"compact":true}'

# Consumer. The id is optional; the broker assigns one when it is blank.
curl -s -X POST $BROKER/v1/consumers/register -d '{
  "consumer_id": "worker-1",
  "group": "workers",
  "queues": ["orders","invoices"],
  "concurrency": 2,
  "max_inflight": 8,
  "ack_mode": "manual"
}'

# Route: forward matching topics to queues
curl -s -X POST $BROKER/routes -d '{
  "name": "orders-to-queue",
  "match": "orders.*",
  "mode": "publish",
  "to": [{"type":"queue","name":"orders"}],
  "enabled": true
}'

GET /routes lists routes. There is no delete route over HTTP — disable one by re-adding it with "enabled": false. Route creation is refused on a tenant-scoped broker, because routes are global.

The console exposes all of the above: New queue, New topic, New stream, Register consumer, Add route, and a Publish view that accepts any JSON payload and shows the resulting message id. The Dead letters view has a Replay all action per queue.

Durations in the console accept 30s, 5m, 1h and are converted to nanoseconds before sending. The HTTP API itself takes nanoseconds.

Read a topic

Topics keep a retained copy of what was published:

curl -s "$BROKER/v1/topics/orders.created?limit=20"

# Resume after a known message id, for scrolling
curl -s "$BROKER/v1/topics/orders.created?limit=20&after=msg-42-ab12cd34"

Pages never repeat or skip messages. An unknown topic returns 404 with topic_not_found.

Run a consumer

In-process, which is the usual embedded shape:

b.Subscribe(ctx, broker.ConsumerConfig{
    Name: "email-worker", Queue: "email.send", AckMode: broker.AckAuto,
}, func(ctx context.Context, d broker.Delivery) error {
    log.Println("got", d.Message.ID, string(d.Message.Payload))
    return nil // non-nil error triggers retry, then the DLQ
})

As a separate process against a running broker:

/tmp/broker-worker \
  -broker http://127.0.0.1:8090 \
  -token "$BROKER_TOKEN" \
  -id worker-1 -group workers \
  -queue orders \
  -task invoice.send

broker-worker needs at least one of -queue, -pattern, -task, -request or -command, and logs every message it handles. Once it connects you will see it register:

curl -s $BROKER/v1/consumers \
  | python3 -c 'import sys,json;[print(c["consumer_id"],c["state"],c.get("queues")) for c in json.load(sys.stdin)]'
# worker-1 ready ['orders']

End-to-end check — publish three messages with no worker attached, then start one:

for i in 1 2 3; do curl -s -X POST $BROKER/publish -d '{"queue":"orders","payload":{"n":1}}' -o /dev/null; done
curl -s $BROKER/queues          # {"orders":3,...}
# start broker-worker, then:
curl -s $BROKER/queues          # {"orders":0,...}

Controlling a remote consumer:

CID=$(curl -s -X POST $BROKER/v1/consumers/register \
      -d '{"consumer_id":"c1","queues":["orders"],"group":"g1"}' \
      | python3 -c 'import sys,json;print(json.load(sys.stdin)["consumer_id"])')

curl -s -X POST $BROKER/v1/consumers/$CID/pause
curl -s -X POST $BROKER/v1/consumers/$CID/drain
curl -s -X POST $BROKER/v1/consumers/$CID/resume
curl -s -X POST $BROKER/v1/consumers/$CID/ban  -d '{"reason":"misbehaving"}'
curl -s -X POST $BROKER/v1/consumers/$CID/unban
curl -s -X POST $BROKER/v1/consumers/$CID/unregister

The identifier is generated by the broker. A consumer_id you send is honoured if you supply one; otherwise the server assigns its own and returns it. Always use the returned value.

Run a task

A task is a message with a registered handler, tracked by id, with status, progress, result and logs. Submit one to a queue a task handler is watching:

TID=$(curl -s -X POST $BROKER/v1/tasks/submit \
      -d '{"name":"invoice.send","queue":"tasks.invoice.send","payload":{"amount":42}}' \
      | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')

curl -s $BROKER/v1/tasks/$TID
curl -s $BROKER/v1/tasks/$TID/result
curl -s $BROKER/v1/tasks/$TID/logs
curl -s "$BROKER/v1/tasks?limit=50"

A completed task looks like this:

{
  "id": "task-4-1635d05f1d36",
  "name": "invoice.send",
  "status": "succeeded",
  "progress": { "percent": 50, "message": "working" },
  "result": "eyJtZXNzYWdlX2lkIjoi..."
}

result is base64, like any payload.

Task control:

curl -s -X POST $BROKER/v1/tasks/$TID/cancel   # stop a running task
curl -s -X POST $BROKER/v1/tasks/$TID/retry    # re-queue its message

cancel interrupts a running handler through its context, and the task stays cancelled — a late completion cannot overwrite it.

retry re-queues the underlying message with attempts and error reset. It does not change the status of the task you asked about; that record stays terminal, and the replayed message runs as a new task when a worker picks it up.

Registering a task handler in Go:

b.RegisterTask(ctx, "invoice.send", func(ctx context.Context, d broker.TaskDelivery) (any, error) {
    _ = d.Progress(ctx, broker.Progress{Percent: 50, Message: "charging"})
    return map[string]any{"ok": true}, nil // the returned value is the task result
}, broker.ConsumerConfig{Name: "billing", Queue: "tasks.invoice.send"})
Retries and the dead-letter queue

A message is retried on nack, then dead-lettered once attempts are exhausted. The default is 3 attempts. To watch it happen, run a worker that always fails:

/tmp/broker-worker -broker $BROKER -id w2 -group g2 -queue risky -fail
for i in 1 2 3 4 5; do curl -s -X POST $BROKER/publish -d '{"queue":"risky","payload":{"n":1}}' -o /dev/null; done
sleep 5

curl -s $BROKER/queues
# {"risky":0,"risky.dlq":5,...}

curl -s "$BROKER/dlq/risky.dlq/messages?limit=5"
# each message shows attempts=3 and last_error="forced failure"

Replay a dead letter back to its queue:

curl -s -X POST $BROKER/dlq/risky.dlq/replay-all
curl -s $BROKER/queues     # {"risky":5,"risky.dlq":0,...}

If the worker is still failing, messages will simply dead-letter again — stop the worker before replaying if you want to see the queue refill.

Pause, resume and queue control
# Broker-wide
curl -s $BROKER/v1/broker                                    # {"state":"running"}
curl -s -X POST $BROKER/v1/broker -d '{"action":"pause"}'
curl -s -X POST $BROKER/v1/broker -d '{"action":"resume"}'

Know what broker pause actually does:

  • Publishing is rejected with 409 and {"error":{"code":"paused"}}.
  • In-process pool workers stop.
  • Remote consumers are not stopped. A broker-worker or HTTP poller will keep draining whatever is already queued.

For a hard stop, pause the queues themselves:

curl -s -X POST $BROKER/queues/orders/pause
curl -s -X POST $BROKER/queues/orders/resume
curl -s -X POST $BROKER/queues/orders/purge    # deletes every message; irreversible
curl -s "$BROKER/queues/orders/messages?limit=20"
Inspect broker state
curl -s $BROKER/stats

Note the shape — everything is nested under store, and queues, topics and dlq are name → count maps, not objects:

{
  "broker_state": "running",
  "error": "",
  "store": {
    "queues": { "orders": 3, "orders.dlq": 0 },
    "topics": { "events": 5 },
    "streams": {},
    "dlq":    { "orders.dlq": 0 },
    "messages": 8, "leased": 0, "dead_letter": 0
  }
}

Extract a count with:

curl -s $BROKER/stats | python3 -c 'import sys,json;print(json.load(sys.stdin)["store"]["queues"]["orders"])'

Other endpoints:

curl -s $BROKER/healthz      # unauthenticated probe, always allowed
curl -s $BROKER/readyz       # unauthenticated probe, always allowed
curl -s $BROKER/queues
curl -s $BROKER/topics
curl -s $BROKER/streams
curl -s $BROKER/dlq
curl -s $BROKER/cluster/status
curl -s "$BROKER/audit?limit=20"
curl -s "$BROKER/lag?stream=audit"   # the stream name is required; bare /lag returns 400
                                      # and an unknown stream returns 404

There is no /queues/{name} detail route — queue counters come from /stats, and queued messages from /queues/{name}/messages.

/audit returns an empty list unless the broker was given an audit logger; brokerd does not set one.

Use the CLI

brokerctl talks to a running broker. Global flags come before the subcommand; subcommand flags come after.

export BROKER_ADDR=http://127.0.0.1:8090
export BROKER_TOKEN=your-secret-token     # omit under --insecure-dev

/tmp/brokerctl stats
/tmp/brokerctl queues
/tmp/brokerctl topics
/tmp/brokerctl consumers

/tmp/brokerctl publish -queue orders -payload '{"id":"order-1"}'
/tmp/brokerctl publish -topic orders.created -payload '{"id":"order-1"}'

/tmp/brokerctl pull email.send -consumer cli -group cli -limit 1
/tmp/brokerctl ack <message-id> -queue email.send -lease <lease-token> -consumer cli

/tmp/brokerctl pause  orders
/tmp/brokerctl resume orders

/tmp/brokerctl dlq                       # dead-letter summary
/tmp/brokerctl dlq-dashboard
/tmp/brokerctl dlq-replay -queue orders.dlq

/tmp/brokerctl cluster
/tmp/brokerctl tui                       # interactive terminal UI

Point it at a different broker with -addr and -token, again before the subcommand:

/tmp/brokerctl -addr https://broker.internal:8090 -token "$BROKER_TOKEN" stats

brokerctl has no flag to skip TLS verification or to supply a private CA, so it cannot connect to a broker using a certificate your machine does not already trust. Trust the CA at the OS level, or use plain HTTP for local work.

Verify an installation

A script that starts a broker and exercises every management surface:

bash scripts/manual_verify.sh          # 70 checks over HTTP
bash scripts/manual_verify.sh --tls    # 75 checks, also proves auth is enforced

It builds brokerd, runs it against a temporary WAL, and asserts the responses, including that the console enforces CSP, that topic cursor paging does not repeat messages, and that unauthenticated requests get 401.

Load and benchmark
cd cmd
go build -o /tmp/loadgen ./loadgen
go build -o /tmp/native-bench ./native-bench

loadgen drives publishers and consumers against a running broker; native-bench measures the native stream protocol. See PERFORMANCE.md for published numbers and the method behind them.

End-to-end smoke test

Copy-paste this to confirm a working install in under a minute:

BROKER=http://127.0.0.1:8090

# 1. broker up?
curl -s $BROKER/healthz

# 2. declare a queue and publish
curl -s -X POST $BROKER/queues -d '{"name":"orders"}'
for i in 1 2 3; do curl -s -X POST $BROKER/publish -d '{"queue":"orders","payload":{"n":1}}' -o /dev/null; done
curl -s $BROKER/queues

# 3. topic retention
for i in 1 2 3; do curl -s -X POST $BROKER/publish -d '{"topic":"events","payload":{"n":1}}' -o /dev/null; done
curl -s "$BROKER/v1/topics/events?limit=3"

# 4. task with no worker attached: submit, then cancel
TID=$(curl -s -X POST $BROKER/v1/tasks/submit -d '{"name":"demo","queue":"orders"}' \
      | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')
curl -s $BROKER/v1/tasks/$TID
curl -s -X POST $BROKER/v1/tasks/$TID/cancel
curl -s $BROKER/v1/tasks/$TID     # status: cancelled

# 5. console
open $BROKER/console/

To see a consumer and a task actually run, start a worker first:

/tmp/broker-worker -broker $BROKER -id w1 -group g1 -queue orders -task invoice.send &

curl -s $BROKER/v1/consumers
for i in 1 2 3; do curl -s -X POST $BROKER/publish -d '{"queue":"orders","payload":{"n":1}}' -o /dev/null; done
curl -s $BROKER/queues            # orders drains to 0

TID=$(curl -s -X POST $BROKER/v1/tasks/submit \
      -d '{"name":"invoice.send","queue":"tasks.invoice.send"}' \
      | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')
sleep 2 && curl -s $BROKER/v1/tasks/$TID   # status: succeeded

Installation

go get github.com/oarkflow/broker
Build binaries
go build -o brokerd ./cmd/brokerd/
go build -o brokerctl ./cmd/brokerctl/
go build -o broker-worker ./cmd/broker-worker/

Broker Modes

Mode Description Use Case
Embedded Runs in your Go process as a library High-performance in-process messaging
Standalone HTTP server with auth/TLS/ACL Microservices, API gateway
Distributed Durable etcd/raft replication, snapshots, membership, and leader-gated reads Pre-v1 clustered evaluation

Complete Examples

The example index maps every recent enhancement to a runnable scenario. Run all nine, including failure handling and durable-store restart:

cd examples
go run ./enhancements -scenario all

Runnable, fail-fast examples for embedded workflows, durable WAL restart, and a real three-node etcd/Raft cluster are in examples/complete. From the examples module:

go run ./complete embedded
go run ./complete durable
go run ./complete distributed
./complete/check.sh

Features

Messaging
Feature Description
Queues Point-to-point with FIFO/priority leasing
Topics Pub-sub with wildcard routing (*, #)
Streams Append-only logs with consumer offsets
Request/Response Sync, async futures, streaming
Commands RPC-style request/response
Tasks Managed submission with progress tracking
Saga Multi-step workflow orchestration
Reliability
Feature Description
WAL durability JSONL or native packed BWL1 records with CRC32C
Crash recovery Replay WAL, in-flight requeue
Retry policy Exponential backoff with jitter
DLQ Dead-letter queue with replay
Idempotency Publisher and consumer dedup
Delivery semantics At-least-once queues with bounded idempotency helpers
Circuit breaker Automatic failure detection and recovery
Rate limiting Per-queue and per-topic token bucket
Backpressure Block, reject, drop-oldest, drop-newest, DLQ
Operations
Feature Description
Prometheus metrics /metrics endpoint with histograms
Distributed tracing OpenTelemetry-compatible spans
Audit logging Structured audit trail with sinks
Webhooks Event callbacks with retry
SSE streaming Real-time event stream
Schema evolution Versioned schema registry
Stream lag monitoring Consumer lag per stream
WAL compaction Experimental detached JSON-WAL utility; not active-store compaction
Consumer priority Weighted routing based on consumer capacity
Consumer group rebalancing Weighted, graceful drain
Partitioning Hash, round-robin, key-based routing
Multi-tenancy Tenant-scoped core data paths; full control-plane isolation is pending
Federation Inter-broker message forwarding
Shovel Queue-to-queue message movement
Graceful shutdown HTTP connection draining

Protocols

Protocol Transport Port Status
HTTP/JSON TCP 8090 Pre-v1; daemon-integrated
Native stream TCP/TLS configurable Pre-v1; authenticated (token/mTLS) handshake, see below
AMQP 0-9-1 TCP/TLS configurable Experimental; conformance not established
MQTT 3.1.1 TCP/TLS configurable Experimental; persistent sessions remain incomplete
Native RPC TCP/TLS configurable Experimental JSON/TCP; not gRPC
SSE HTTP(S) configurable Experimental event stream, separate from WebSocket
WebSocket RFC 6455 configurable Pre-v1; protobuf-independent JSON data plane
gRPC protobuf/HTTP2 configurable Pre-v1 versioned broker.v1 API

brokerd supervises every enabled listener. Protocol listeners are opt-in by address; production mode requires TLS and authentication on every listener, including the native BST1 stream, which enforces a token or mTLS handshake unless --insecure-dev is set.


Encryption

At Rest
Component Encryption How to Enable
JSONL WAL AES-256-GCM -frame-encryption-key <hex-key>
Binary WAL (BWL1) AES-256-GCM + optional HMAC-SHA256 -frame-encryption-key, -frame-signing-key
FWB1/FWB2 network codecs AES-GCM + HMAC-SHA256 WithFrameEncryptionKey(), WithFrameSigningKey()
SQLite AES-256-GCM NewEncryptedMessageStore(db, key)
In Transit
Transport TLS mTLS How to Enable
HTTP Admin ✅ ✅ -tls-cert, -tls-key, -client-ca, -require-client-cert
MQTT ✅ ✅ MQTTConfig.TLSCertFile, etc.
Native JSON/TCP RPC ✅ ✅ NativeRPCConfig.TLSCertFile, etc.; this is not gRPC
AMQP ✅ ✅ ListenTLS(), EXTERNAL auth
gRPC v1 ✅ ✅ GRPCV1Config.TLSConfig
RFC 6455 WebSocket ✅ via HTTPS client identity RFC6455Config behind a TLS HTTP server
Client SDK ✅ ✅ Config.TLSCertFile, etc.

At-rest encryption remains opt-in. brokerd rejects plaintext production mode; plaintext listeners require the explicit --insecure-dev flag.


Security

Authentication
Method Protocol How
Bearer token HTTP Authorization: Bearer <token>
ACL tokens HTTP Named tokens with 28+ permissions
MQTT password MQTT BrokerToken in MQTTConfig
AMQP PLAIN AMQP Username/password
AMQP EXTERNAL AMQP Client certificate (mTLS)
Authorization (HTTP)
Permission Description
admin:* All admin/API actions
broker:read health/ready/stats
message:publish publish messages
message:ack/nack ack/nack messages
message:move move/copy/replay
queue:read/write/control/purge queue management
topic:read/write topic management
stream:read/write/commit stream management
dlq:read/replay DLQ management
route:read/write route management
consumer:register/read/control/poll consumer management
task:read/write task management
notification:read notification/SSE access
TLS/mTLS
# TLS
brokerd -addr :8443 -tls-cert server.crt -tls-key server.key

# mTLS
brokerd -addr :8443 -tls-cert server.crt -tls-key server.key \
  -client-ca ca.crt -require-client-cert

Configuration

Environment Variables
Variable Default Description
BROKER_ADDR :8090 Listen address
BROKER_WAL - WAL directory (empty = memory)
BROKER_WAL_FORMAT binary binary or json
BROKER_TOKEN - Admin token (required unless --insecure-dev)
BROKER_READ_TOKEN - Read-only token
BROKER_WORKER_TOKEN - Worker token
BROKER_PUBLISHER_TOKEN - Publisher token
BROKER_TLS_CERT - TLS certificate
BROKER_TLS_KEY - TLS key
BROKER_CLIENT_CA - Client CA for mTLS
BROKER_REQUIRE_CLIENT_CERT false Require mTLS
BROKER_MAX_BODY 1048576 Max request body (bytes)
BROKER_FRAME_SIGNING_KEY - HMAC signing key
BROKER_FRAME_ENCRYPTION_KEY - AES encryption key (hex)
BROKER_INSECURE_DEV false Disable auth (dev only)
CLI Flags
brokerd \
  -addr :8090 \
  -wal ./.broker-data \
  -wal-format binary \
  -token "your-secret-token" \
  -tls-cert server.crt \
  -tls-key server.key \
  -client-ca ca.crt \
  -require-client-cert \
  -max-body 1048576 \
  -frame-signing-key "hex-signing-key" \
  -frame-encryption-key "hex-encryption-key" \
  -frame-compress-threshold 1024

CLI Usage

export BROKER_TOKEN='your-secret-token'
export BROKER_ADDR='http://127.0.0.1:8090'

# Stats
brokerctl stats

# List queues
brokerctl queues

# Publish
brokerctl publish -topic orders.created -queue orders.process \
  -type order -payload '{"id":"order-1","amount":100}'

# Pull
brokerctl pull email.send -consumer cli -group cli -limit 1

# Ack
brokerctl ack <message-id> -queue email.send -lease <lease-token> -consumer cli

# Move (DLQ replay)
brokerctl move -from-type queue -from email.send.dlq \
  -to-type queue -to email.send -mode replay

HTTP API

Health and Stats
curl http://localhost:8090/healthz           # Health check
curl http://localhost:8090/readyz            # Readiness check
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:8090/stats                # Broker stats
curl http://localhost:8090/metrics           # Prometheus metrics
curl http://localhost:8090/lag?stream=audit  # Stream lag
Publish
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/publish \
  -d '{
    "topic": "orders.created",
    "queue": "orders.process",
    "type": "order",
    "payload": {"id": "order-1", "amount": 100}
  }'
Queue Operations
# Create queue
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/queues \
  -d '{"name":"orders","visibility_timeout":30000000000,"max_depth":100000}'

# Pull messages
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/queues/orders/pull \
  -d '{"consumer_id":"worker-1","consumer_group":"workers","limit":1}'

# Pause/Resume/Purge
curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:8090/queues/orders/pause
curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:8090/queues/orders/resume
curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:8090/queues/orders/purge
Message Operations
# Ack
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/messages/<id>/ack \
  -d '{"queue":"orders","consumer_id":"worker-1","lease_token":"<token>"}'

# Nack with retry
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/messages/<id>/nack \
  -d '{"queue":"orders","consumer_id":"worker-1","lease_token":"<token>","action":"retry","delay":5000000000}'
Movement
# Replay DLQ
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/move \
  -d '{
    "source_type":"queue","source":"orders.dlq",
    "destination_type":"queue","destination":"orders",
    "mode":"replay","reset_attempts":true,"reset_error":true
  }'
SSE Events

The standalone SSE listener is secure by default: configure its ACL (or call SetToken for the pre-v1 compatibility path), or explicitly set InsecureDev for isolated development. Tenant-scoped connections receive only tenant-tagged broadcasts for an allowed tenant; unowned global events are not forwarded.

curl -N -H "Authorization: Bearer $TOKEN" http://localhost:8090/events

Publisher

pub := b.Publisher()

// Fire-and-forget
pub.Publish(ctx, "orders.created", payload, broker.WithQueue("orders"))

// Confirmed publish
pub.PublishConfirm(ctx, "orders.created", payload, broker.WithQueue("orders"))

// Async publish
future := pub.PublishAsync(ctx, "events.raw", payload, broker.WithQueue("events"))
res, _ := future.Wait(ctx)

// Batch publish
pub.PublishBatch(ctx, "events.raw", []any{e1, e2, e3}, broker.WithQueue("events"))

// Transactional publish
tx, _ := pub.BeginTx(ctx)
tx.Publish("order.created", order, broker.WithQueue("orders"))
tx.Publish("audit.event", audit, broker.WithStream("audit"))
tx.Commit(ctx)

// Delayed publish
pub.PublishAfter(ctx, "email.reminder", payload, 30*time.Minute, broker.WithQueue("email"))

// Scheduled publish
pub.PublishAt(ctx, "billing.renew", payload, renewAt, broker.WithQueue("billing"))

Consumer

// Auto-ack
b.Subscribe(ctx, broker.ConsumerConfig{
    Name: "worker", Queue: "jobs", AckMode: broker.AckAuto, Concurrency: 32,
}, func(ctx context.Context, d broker.Delivery) error {
    // process
    return nil
})

// Manual ack
b.Subscribe(ctx, broker.ConsumerConfig{
    Name: "worker", Queue: "jobs", AckMode: broker.AckManual,
}, func(ctx context.Context, d broker.Delivery) error {
    if err := process(d); err != nil {
        return d.Nack(ctx, broker.WithNackAction(broker.NackRetry), broker.WithNackDelay(5*time.Second))
    }
    return d.Ack(ctx)
})

// Batch consumer
b.SubscribeBatch(ctx, broker.ConsumerConfig{
    Name: "batcher", Queue: "events", BatchSize: 500, BatchWait: 50*time.Millisecond,
}, func(ctx context.Context, ds []broker.Delivery) error {
    // process batch
    return nil
})

// Idempotent consumer (deduplicates messages)
b.Subscribe(ctx, broker.ConsumerConfig{
    Name: "idempotent-worker", Queue: "orders",
    Idempotent: true, DeduplicationWindow: 5*time.Minute,
}, func(ctx context.Context, d broker.Delivery) error {
    // automatically deduplicates by idempotency_key
    return nil
})

Routing

// Wildcard routes
b.AddRoute(broker.Route{
    Name: "tenant-invoices", Match: "tenant.*.invoice.created",
    To: []broker.Destination{{Kind: broker.DestinationQueue, Name: "invoice.process"}},
})

// Fanout
b.AddRoute(broker.Route{
    Name: "all-events", Match: "events.*", Mode: broker.RouteFanout,
    To: []broker.Destination{
        {Kind: broker.DestinationQueue, Name: "analytics"},
        {Kind: broker.DestinationQueue, Name: "audit"},
    },
})

// Add route via HTTP
curl -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  http://localhost:8090/routes \
  -d '{"name":"my-route","match":"orders.*","to":[{"kind":"queue","name":"orders.process"}]}'

Queues

b.DeclareQueue(ctx, broker.QueueConfig{
    Name: "orders", VisibilityTimeout: 30*time.Second, MaxDepth: 100000,
    RetryPolicy: broker.DefaultRetryPolicy(), DLQ: "orders.dlq",
})

Features: FIFO/priority leasing, delayed availability, TTL, manual/auto ack, visibility timeout, lease extension, redelivery, pause/resume/purge, max-depth backpressure.


Streams

b.DeclareStream(ctx, broker.StreamConfig{Name: "audit.events"})

// Publish to stream
pub.Publish(ctx, "audit.login", event, broker.WithStream("audit.events"))

// Read from stream
msgs, _ := b.ReadStream(ctx, broker.StreamReadRequest{Stream: "audit.events", ConsumerGroup: "analytics", Limit: 100})

// Commit offset
b.CommitOffset(ctx, broker.OffsetCommit{Stream: "audit.events", ConsumerGroup: "analytics", Offset: msgs[len(msgs)-1].Offset})

// Check lag
lag, _ := b.StreamLag(ctx, "audit.events", "analytics")

Retries and DLQ

// Retry on error
return fmt.Errorf("temporary failure")

// Permanent error (skip retry, go to DLQ)
return broker.Permanent(fmt.Errorf("invalid payload"))

// Manual retry
return d.Nack(ctx, broker.WithNackAction(broker.NackRetry), broker.WithNackDelay(10*time.Second))

// Reject to DLQ
return d.Reject(ctx, "invalid customer id")

// Replay DLQ
curl -X POST -H "Authorization: Bearer $TOKEN" \
  http://localhost:8090/dlq/orders.dlq/replay?queue=orders

Tasks

// Register task handler
b.RegisterTask(ctx, "image.resize", func(ctx context.Context, d broker.TaskDelivery) (any, error) {
    d.Progress(ctx, broker.Progress{Current: 1, Total: 2, Percent: 50})
    return resize(d.Message.Payload)
})

// Submit task
h, _ := pub.SubmitTask(ctx, "image.resize", req, broker.WithTaskQueue("image.jobs"))
result, _ := h.Wait(ctx)

Multi-Tenancy

b := broker.MustNew(broker.Config{
    Tenancy: &broker.TenancyConfig{
        Enabled: true, IsolationLevel: broker.IsolationQueuePrefix, QueuePrefix: "t.",
    },
})

tenantMgr := b.TenantManager()
tenantMgr.EnsureTenant("tenant-a")

// Tenant-isolated publish
tenantMgr.TenantAwarePublish(ctx, "tenant-a", "orders.created", payload)

// Tenant-isolated subscribe
tenantMgr.TenantAwareSubscribe(ctx, "tenant-a", broker.ConsumerConfig{Queue: "orders"}, handler)

Federation and Shovel

// Shovel: move messages from queue A to queue B
b.ShovelManager().StartShovel(broker.ShovelConfig{
    Source: "source-queue", Destination: "dest-queue", BatchSize: 100,
})

// Federation: link to upstream broker
b.FederationManager().AddLink(broker.FederationConfig{
    Upstream: "http://upstream:8090", Queues: []string{"orders"},
})

Partitioning

b := broker.MustNew(broker.Config{
    Partition: &broker.PartitionConfig{Partitions: 4, Strategy: broker.PartitionHash},
})

router := broker.NewPartitionRouter(broker.PartitionConfig{Partitions: 4, Strategy: broker.PartitionHash})
partition := router.SelectPartition(broker.Message{Key: "user-123"})
queue := fmt.Sprintf("events.p%d", partition)
pub.Publish(ctx, "events.user", payload, broker.WithQueue(queue))

Schema Evolution

registry := broker.NewMemorySchemaRegistry(
    broker.SchemaDefinition{Name: "invoice", Version: "v1", Required: []string{"id", "amount"}},
    broker.SchemaDefinition{Name: "invoice", Version: "v2", Required: []string{"id", "amount", "currency"}, CompatibleWith: "v1"},
)
b := broker.MustNew(broker.Config{SchemaRegistry: registry})

pub.Publish(ctx, "invoice.created", payload, broker.WithSchema("invoice", "v2"))

Observability

Prometheus Metrics
curl http://localhost:8090/metrics

Metrics: broker_messages_published_total, broker_messages_delivered_total, broker_messages_acked_total, broker_queue_depth{queue}, broker_topic_published_total{topic}, latency histograms.

Tracing
b := broker.MustNew(broker.Config{
    EnableTracing: true,
    TracerConfig: &broker.TracerConfig{ServiceName: "my-service"},
})
Audit Logging
curl -H "Authorization: Bearer $TOKEN" http://localhost:8090/audit

Production Checklist

  • Set BROKER_TOKEN or -token; never use --insecure-dev
  • Enable TLS; use mTLS for sensitive environments
  • Use named ACL tokens with least-privilege permissions
  • Set -max-body to a sane value
  • Put WAL on reliable storage and back it up
  • Enable encryption at rest if storing sensitive data
  • Run behind a private network or authenticated ingress
  • Monitor /stats, /metrics, /lag, queue depth, DLQ count
  • Alert on DLQ growth and callback failure
  • Use idempotency keys for unsafe operations
  • Use manual ack for operations requiring confirmation
  • Keep visibility timeout longer than handler time or extend leases
  • Run scripts/release_gate.sh and archive its artifacts for the exact commit
  • Complete DURATION=72h scripts/soak.sh on production-like hardware
  • Perform the backup, restore, upgrade, rollback, and alert drills in Operations
  • Review the threat model and close deployment-specific risks
  • Verify required third-party clients against the protocol compatibility scope
  • Obtain independent security review and explicit release sign-off

Package Layout

broker/
  broker.go              Core broker runtime
  publisher.go           Publisher/request/task APIs
  consumer.go            Consumers, delivery, ack/nack
  router.go              Routes and wildcard matching
  store.go               Store interface, memory store, WAL stores
  task.go                Task state/result/wait/progress
  saga.go                Saga orchestration
  notification.go        Notification bus and webhooks
  security.go            Auth, ACL, audit
  hooks.go               Lifecycle hooks
  types.go               Types and config
  health.go              Health checks, metrics
  admin.go               HTTP admin/API server
  dataplane.go           /v1/* data-plane endpoints
  remote.go              Remote consumer registry
  distributed.go         Distributed broker and replicated store adapter
  rebalance.go           Consumer group rebalancing
  strategy.go            14 routing strategies
  schema.go              Schema registry
  errors.go              Error types
  mqtt.go                MQTT 3.1.1 server
  grpc_transport.go      Experimental native JSON/TCP RPC transport
  websocket.go           Server-Sent Events (SSE) transport
  federation.go          Federation and shovel
  tenancy.go             Multi-tenancy
  exactly_once.go        Legacy in-memory publish retry buffer and replay helpers
  partition_ordering.go  Partition routing
  wal_compaction.go      WAL segment management
  metrics.go             Prometheus metrics
  tracing.go             Distributed tracing
  ratelimit.go           Rate limiting
  circuit_breaker.go     Circuit breaker
  audit.go               Audit logging
  frame_codec.go         FWB1 network message codec
  compact_codec.go       FWB2 compact network codec
  wal_record_codec.go    BWL1 packed mutation codec
  binary_wal_store.go    Native BWL1 WAL store

  amqp/                  AMQP 0-9-1 protocol server
  cluster/               Durable etcd/raft consensus and transports
  contrib/sqlitestore/   SQLite state + message stores
  cmd/brokerd/           Standalone broker server
  cmd/brokerctl/         CLI client
  cmd/broker-worker/     Remote worker process
  pkg/client/            Client SDK
  pkg/pool/              Worker pool (execution engine)
  examples/              BCL-driven examples

License

Apache License 2.0. See LICENSE for the full text.

High-throughput BST1 stream mode

For Kafka-equivalent append/fetch workloads use the native stream listener rather than queue leasing:

brokerd -wal .broker-data/queue -native-addr :8091 \
  -native-dir .broker-data/native-stream -native-partitions 8 \
  -native-sync=true -insecure-dev

The native stream listener supports an authenticated handshake (bearer token or mTLS, enforced via the same ACL used by the HTTP admin API). Outside --insecure-dev, brokerd requires -token or -require-client-cert to be set before it will start the listener. --insecure-dev disables that enforcement (anonymous/auto-admin access) and must only be used for local development.

The native-bench command uses persistent TCP clients, compact record batches, partition offsets and restart-safe segmented logs. See NATIVE_STREAM_PERFORMANCE.md and scripts/benchmark_native_vs_kafka.sh.

Documentation

Index

Constants

View Source
const (
	FWB2Magic        = "FWB2"
	FWB2Version byte = 2
)
View Source
const (
	FrameMagic        = "FWB1"
	FrameVersion byte = 1
)
View Source
const (
	GRPCMethodPublish       = "broker.Publish"
	GRPCMethodSubscribe     = "broker.Subscribe"
	GRPCMethodAck           = "broker.Ack"
	GRPCMethodNack          = "broker.Nack"
	GRPCMethodPoll          = "broker.Poll"
	GRPCMethodRequest       = "broker.Request"
	GRPCMethodStats         = "broker.Stats"
	GRPCMethodHealth        = "broker.Health"
	GRPCMethodDeclareQueue  = "broker.DeclareQueue"
	GRPCMethodDeclareTopic  = "broker.DeclareTopic"
	GRPCMethodDeclareStream = "broker.DeclareStream"
	GRPCMethodReadStream    = "broker.ReadStream"
	GRPCMethodCommitOffset  = "broker.CommitOffset"
	GRPCMethodMove          = "broker.Move"
	GRPCMethodPauseQueue    = "broker.PauseQueue"
	GRPCMethodResumeQueue   = "broker.ResumeQueue"
	GRPCMethodPurgeQueue    = "broker.PurgeQueue"
)
View Source
const (
	MQTTConnect     byte = 0x10
	MQTTConnack     byte = 0x20
	MQTTPublish     byte = 0x30
	MQTTPuback      byte = 0x40
	MQTTPubrec      byte = 0x50
	MQTTPubrel      byte = 0x60
	MQTTPubcomp     byte = 0x70
	MQTTSubscribe   byte = 0x82
	MQTTSuback      byte = 0x90
	MQTTUnsubscribe byte = 0xA2
	MQTTUnsuback    byte = 0xB0
	MQTTPingreq     byte = 0xC0
	MQTTPingresp    byte = 0xD0
	MQTTDisconnect  byte = 0xE0
)

MQTT 3.1.1 packet types.

View Source
const (
	NativeStreamMagic uint32 = 0x42535431 // BST1

	NativeAuthAnonymous byte = 0x00
	NativeAuthToken     byte = 0x01
	NativeAuthMTLS      byte = 0x02

	NativeStatusSuccess      byte = 0x00
	NativeStatusUnauthorized byte = 0x01
	NativeStatusForbidden    byte = 0x02
	NativeStatusThrottled    byte = 0x03
	NativeStatusErrProtocol  byte = 0x04
)
View Source
const (
	PermissionConsumerRegister = "consumer:register"
	PermissionConsumerRead     = "consumer:read"
	PermissionConsumerControl  = "consumer:control"
	PermissionConsumerPoll     = "consumer:poll"
	PermissionTaskRead         = "task:read"
	PermissionTaskWrite        = "task:write"
)
View Source
const (
	PermissionAdminAll      = "admin:*"
	PermissionBrokerRead    = "broker:read"
	PermissionPublish       = "message:publish"
	PermissionMessageRead   = "message:read"
	PermissionMessageAck    = "message:ack"
	PermissionMessageNack   = "message:nack"
	PermissionMessageMove   = "message:move"
	PermissionQueueRead     = "queue:read"
	PermissionQueueWrite    = "queue:write"
	PermissionQueueControl  = "queue:control"
	PermissionQueuePurge    = "queue:purge"
	PermissionTopicRead     = "topic:read"
	PermissionTopicWrite    = "topic:write"
	PermissionStreamRead    = "stream:read"
	PermissionStreamWrite   = "stream:write"
	PermissionStreamCommit  = "stream:commit"
	PermissionDLQRead       = "dlq:read"
	PermissionDLQReplay     = "dlq:replay"
	PermissionRouteRead     = "route:read"
	PermissionRouteWrite    = "route:write"
	PermissionNotification  = "notification:read"
	PermissionConsumerBan   = "consumer:ban"
	PermissionConsumerUnban = "consumer:unban"
)
View Source
const (
	SegmentMagic          uint32 = 0x42574C32 // "BWL2"
	SegmentVersion        byte   = 2
	SegmentTrailerMagic   uint32 = 0x434C4F53 // "CLOS"
	DefaultMaxSegmentSize        = 64 << 20   // 64 MiB
	DefaultMaxSegments           = 10
	DefaultCompactionInt         = 5 * time.Minute
)
View Source
const Version = "0.1.0-dev"

Version remains pre-v1 until the documented production release gates pass.

Variables

View Source
var (
	ErrClosed           = errors.New("broker: closed")
	ErrStopped          = errors.New("broker: stopped")
	ErrPaused           = errors.New("broker: paused")
	ErrQueueNotFound    = errors.New("broker: queue not found")
	ErrTopicNotFound    = errors.New("broker: topic not found")
	ErrStreamNotFound   = errors.New("broker: stream not found")
	ErrMessageNotFound  = errors.New("broker: message not found")
	ErrInvalidMessage   = errors.New("broker: invalid message")
	ErrMessageTooLarge  = errors.New("broker: message too large")
	ErrNoDestination    = errors.New("broker: no route destination")
	ErrNoSubscribers    = errors.New("broker: no subscribers")
	ErrDuplicateMessage = errors.New("broker: duplicate message")
	ErrBackpressure     = errors.New("broker: backpressure limit reached")
	ErrPublishTimeout   = errors.New("broker: publish timeout")
	ErrRequestTimeout   = errors.New("broker: request timeout")
	ErrNoHandler        = errors.New("broker: no handler")
	ErrUnauthorized     = errors.New("broker: unauthorized")
	// ErrUnauthenticated is a missing or invalid credential, as distinct from
	// ErrUnauthorized which is an authenticated principal lacking permission.
	// The two need separating so a client can tell "authenticate again" from
	// "you are not allowed", which is also how the HTTP status differs.
	ErrUnauthenticated    = errors.New("broker: unauthenticated")
	ErrLeaseLost          = errors.New("broker: lease lost")
	ErrPermanent          = errors.New("broker: permanent error")
	ErrTransactionClosed  = errors.New("broker: transaction closed")
	ErrOffsetConflict     = errors.New("broker: committed stream offset changed")
	ErrUnsupportedMode    = errors.New("broker: unsupported mode")
	ErrBrokerUnavailable  = errors.New("broker: unavailable")
	ErrCallbackFailed     = errors.New("broker: callback failed")
	ErrCancelled          = errors.New("broker: cancelled")
	ErrConsumerBanned     = errors.New("broker: consumer banned")
	ErrRateLimited        = errors.New("broker: rate limited")
	ErrNotLeader          = errors.New("broker: not leader")
	ErrStaleEpoch         = errors.New("broker: stale leader epoch")
	ErrQuorumUnavailable  = errors.New("broker: quorum unavailable")
	ErrThrottled          = errors.New("broker: throttled")
	ErrTransactionAborted = errors.New("broker: transaction aborted")
	ErrStorageUnavailable = errors.New("broker: storage unavailable")
)
View Source
var (
	// ErrProducerFenced is returned when a publish has an epoch strictly less than the registered epoch.
	ErrProducerFenced = errors.New("producer fenced: epoch is older than current epoch")
	// ErrOutOfOrderSequence is returned when a sequence gap is detected.
	ErrOutOfOrderSequence = errors.New("out of order sequence: sequence number gap detected")
)
View Source
var (
	ErrCircuitOpen = errors.New("cluster: circuit breaker open, write rejected")
)
View Source
var ErrFrameEncrypted = errors.New("broker: frame encrypted")
View Source
var (
	ErrInvalidConfig = errors.New("invalid configuration")
)
View Source
var (
	ErrInvalidRange = errors.New("zerocopy: invalid segment range")
)

Functions

func CompressPayload

func CompressPayload(codec CompressionCodec, data []byte) ([]byte, error)

CompressPayload compresses the provided byte slice using the requested codec. If CompressionNone is requested, data is returned unchanged.

func DecompressPayload

func DecompressPayload(codec CompressionCodec, data []byte) ([]byte, error)

DecompressPayload decompresses the provided byte slice according to the specified codec.

func EncodeAckFrameBatch

func EncodeAckFrameBatch(dst []byte, requests []AckRequest) []byte

func EncodeMessageFrameBatch

func EncodeMessageFrameBatch(dst []byte, codec FrameCodec, messages []Message) ([]byte, error)

func ErrorCode

func ErrorCode(err error) string

ErrorCode returns the stable wire code for err, or "internal" when err does not wrap a known sentinel.

func FrameFingerprint

func FrameFingerprint(b []byte) string

func HTTPStatusForError

func HTTPStatusForError(err error) int

HTTPStatusForError maps a broker error onto a status code. Everything the data plane previously reported as 409 is separated here so a client can tell an authorization failure from a conflict, a missing resource from a bad request, and a retryable condition from a permanent one.

func IntPtr

func IntPtr(v int) *int

IntPtr returns a pointer to v, for the optional numeric Config fields where an explicit zero has to be distinguishable from "not set".

func IsBinaryFrame

func IsBinaryFrame(b []byte) bool

func IsPermanent

func IsPermanent(err error) bool

func LogNotifications

func LogNotifications(bus *NotificationBus, id string, includeDebug bool)

LogNotifications writes broker notifications as structured log entries. Debug heartbeat events are intentionally skipped unless includeDebug is true.

func NotLeaderError

func NotLeaderError(leader string, epoch uint64) error

NotLeaderError reports that this node cannot serve the request because another node leads, and names that node so a client can retry there instead of parsing the message text.

The distributed layer used to wrap cluster.ErrNotLeader with fmt.Errorf and append the leader to the message string. errors.Is still matched, so ClassifyRetry returned not_leader, but RetryError.Leader was never populated and the leader address existed only as prose in an HTTP 409 body. A follower aware client had no way to extract it.

func PartitionedTopicName

func PartitionedTopicName(topic string, partition int) string

PartitionedTopicName returns the partitioned topic name.

func Permanent

func Permanent(err error) error

func RecoverFromAllSegments

func RecoverFromAllSegments(dir string, store *MemoryStore) error

RecoverFromAllSegments recovers from all WAL segments in a directory.

func ReplaySegment

func ReplaySegment(path string, store *MemoryStore) error

ReplaySegment replays a specific WAL segment into a MemoryStore.

func SendSegmentRange

func SendSegmentRange(conn net.Conn, file *os.File, offset, count int64) (int64, error)

SendSegmentRange transfers count bytes from file starting at offset directly to conn. If conn supports io.ReaderFrom (such as *net.TCPConn), it will utilize kernel zero-copy mechanisms (sendfile(2) / splice(2)) automatically.

func SentinelForCode

func SentinelForCode(code string) (error, bool)

SentinelForCode returns the broker sentinel a wire code refers to.

func SpanIDFromContext

func SpanIDFromContext(ctx context.Context) string

SpanIDFromContext extracts the span ID from context.

func StaleEpochError

func StaleEpochError(current uint64) error

StaleEpochError reports that the caller's leader epoch is behind the cluster's.

func TopicMatch

func TopicMatch(pattern, subject string) bool

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext extracts the trace ID from context.

func VisitFetchRaw

func VisitFetchRaw(raw []byte, fn func([]byte) error) error

VisitFetchRaw visits payload slices backed by raw without copying them.

func WithAdminPrincipal

func WithAdminPrincipal(ctx context.Context, p AdminPrincipal) context.Context

WithAdminPrincipal attaches an authenticated principal to a context so that in-process code runs under the same tenant scoping a listener would apply.

This is the supported way for an embedder to apply per-tenant rules to its own calls. Without it, in-process calls are unscoped, which is the documented trust boundary rather than an oversight: see Config.ACL.

A listener that authenticates a request must use this (or an equivalent internal helper) rather than trusting callers to set the value themselves.

func WriteBrokerError

func WriteBrokerError(w http.ResponseWriter, err error)

WriteBrokerError writes err as a JSON envelope with a meaningful status code.

The body is additive: a client that does not understand it still sees a non-empty message, and WriteBrokerError keeps the message text identical to err.Error() so existing string-matching clients keep working.

Types

type ACL

type ACL struct {
	Tokens []AdminToken
	// contains filtered or unexported fields
}

func NewACL

func NewACL(tokens ...AdminToken) *ACL

func (*ACL) AddToken

func (a *ACL) AddToken(token AdminToken)

func (*ACL) Admit

func (a *ACL) Admit(principal AdminPrincipal) (func(), error)

Admit applies the authenticated principal's shared request-rate and concurrency limits. The returned release function must be called exactly once after the request or connection finishes.

func (*ACL) AdmitConnection

func (a *ACL) AdmitConnection(principal AdminPrincipal) (func(), error)

AdmitConnection admits a long-lived protocol connection (MQTT, AMQP, gRPC, WebSocket, BST1) enforcing per-principal MaxConcurrent connection limits across all protocols. The returned release function must be called once the connection terminates.

func (*ACL) Authenticate

func (a *ACL) Authenticate(raw string) (AdminPrincipal, bool)

func (*ACL) AuthenticateCertificate

func (a *ACL) AuthenticateCertificate(cert *x509.Certificate) (AdminPrincipal, bool)

AuthenticateCertificate maps a verified TLS client certificate to a named ACL principal. Identity entries use cn:, dns:, uri:, email:, or ip: prefixes.

func (*ACL) Authorize

func (a *ACL) Authorize(p AdminPrincipal, permission string) bool

func (*ACL) Revoke

func (a *ACL) Revoke(name string) bool

Revoke invalidates every credential with the supplied logical name.

type AckMode

type AckMode string
const (
	AckAuto   AckMode = "auto"
	AckManual AckMode = "manual"
)

type AckPolicy

type AckPolicy string

AckPolicy is the acknowledgement requested by a publisher.

const (
	AckNone      AckPolicy = "none"
	AckLeader    AckPolicy = "leader"
	AckQuorum    AckPolicy = "quorum"
	AckAll       AckPolicy = "all"
	AckProcessed AckPolicy = "processed"
)

type AckRequest

type AckRequest struct {
	MessageID  string `json:"message_id,omitempty"`
	Queue      string `json:"queue,omitempty"`
	LeaseToken string `json:"lease_token,omitempty"`
	ConsumerID string `json:"consumer_id,omitempty"`
}

type AdminAuditEvent

type AdminAuditEvent struct {
	Time       time.Time `json:"time"`
	Principal  string    `json:"principal"`
	RemoteAddr string    `json:"remote_addr,omitempty"`
	Method     string    `json:"method"`
	Path       string    `json:"path"`
	Action     string    `json:"action"`
	Allowed    bool      `json:"allowed"`
	Status     int       `json:"status"`
	Reason     string    `json:"reason,omitempty"`
}

type AdminAuditLogger

type AdminAuditLogger interface {
	LogAdmin(context.Context, AdminAuditEvent)
}

type AdminPrincipal

type AdminPrincipal struct {
	Name              string
	Token             string
	Permissions       []string
	Tenants           []string
	RequestsPerSecond int
	Burst             int
	MaxConcurrent     int
}

func AdminPrincipalFromContext

func AdminPrincipalFromContext(ctx context.Context) (AdminPrincipal, bool)

AdminPrincipalFromContext returns the principal attached to ctx, if any.

func (AdminPrincipal) HasPermission

func (p AdminPrincipal) HasPermission(perm string) bool

HasPermission reports whether the principal has the specified permission.

type AdminServer

type AdminServer struct {
	Broker *Broker

	// Token is a convenience single-token credential with admin:* access.
	// For production, prefer ACL with named tokens and narrow permissions.
	Token string
	ACL   *ACL

	// InsecureDev explicitly disables authentication. It is intended only for
	// local tests and examples. Production brokerd refuses to start this way
	// unless --insecure-dev is provided.
	InsecureDev bool

	// MaxBodyBytes limits JSON request bodies. Defaults to 1 MiB.
	MaxBodyBytes int64

	ReadTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	TLSCertFile       string
	TLSKeyFile        string
	ClientCAFile      string
	RequireClientCert bool

	// AllowedOrigins is the list of allowed CORS origins.
	// Default: same-origin only (""). Set to ["*"] for public APIs.
	AllowedOrigins []string

	Audit AdminAuditLogger
}

func (AdminServer) GracefulShutdown

func (a AdminServer) GracefulShutdown(ctx context.Context, srv *http.Server, drainTimeout time.Duration) error

GracefulShutdown performs a graceful shutdown of the HTTP server, waiting for in-flight requests to complete within the given timeout.

func (AdminServer) HTTPServer

func (a AdminServer) HTTPServer(addr string) *http.Server

func (AdminServer) Handler

func (a AdminServer) Handler() http.Handler

func (AdminServer) ListenAndServe

func (a AdminServer) ListenAndServe(addr string) *http.Server

func (AdminServer) Shutdown

func (a AdminServer) Shutdown(ctx context.Context, srv *http.Server) error

type AdminToken

type AdminToken struct {
	Name                  string    `json:"name,omitempty"`
	Token                 string    `json:"-"`
	Permissions           []string  `json:"permissions,omitempty"`
	Tenants               []string  `json:"tenants,omitempty"`
	CertificateIdentities []string  `json:"certificate_identities,omitempty"`
	RequestsPerSecond     int       `json:"requests_per_second,omitempty"`
	Burst                 int       `json:"burst,omitempty"`
	MaxConcurrent         int       `json:"max_concurrent,omitempty"`
	ExpiresAt             time.Time `json:"expires_at,omitempty"`
	Revoked               bool      `json:"revoked,omitempty"`
	// contains filtered or unexported fields
}

AdminToken describes one API credential. Token values are intentionally not emitted through JSON. Use Permissions with exact strings or the admin:* wildcard for full access.

type AppendEntry

type AppendEntry struct {
	Message      Message       `json:"message"`
	Destinations []Destination `json:"destinations"`
}

type AtomicStore

type AtomicStore interface {
	AppendAtomic(context.Context, []AppendEntry) ([]Message, error)
}

type AuditEvent

type AuditEvent struct {
	ID        string         `json:"id"`
	Timestamp time.Time      `json:"timestamp"`
	Principal string         `json:"principal"`
	TenantID  string         `json:"tenant_id,omitempty"`
	Action    string         `json:"action"`
	Resource  string         `json:"resource"`
	Status    string         `json:"status"`
	Detail    string         `json:"detail,omitempty"`
	Error     string         `json:"error,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

AuditEvent represents a structured audit log entry.

type AuditLogger

type AuditLogger struct {
	// contains filtered or unexported fields
}

AuditLogger provides structured audit logging for the broker.

func NewAuditLogger

func NewAuditLogger(capacity int) *AuditLogger

NewAuditLogger creates a new audit logger with the given capacity.

func (*AuditLogger) AddSink

func (a *AuditLogger) AddSink(sink AuditSink)

AddSink adds an audit sink for writing events.

func (*AuditLogger) History

func (a *AuditLogger) History(limit int) []AuditEvent

History returns recent audit events.

func (*AuditLogger) Log

func (a *AuditLogger) Log(ctx context.Context, event AuditEvent)

Log records an audit event and writes it to all sinks.

func (*AuditLogger) LogAck

func (a *AuditLogger) LogAck(ctx context.Context, principal, messageID, queue string, success bool)

LogAck records an ack audit event.

func (*AuditLogger) LogAuth

func (a *AuditLogger) LogAuth(ctx context.Context, principal, action, resource string, allowed bool, detail string)

LogAuth records an authentication/authorization audit event.

func (*AuditLogger) LogDLQ

func (a *AuditLogger) LogDLQ(ctx context.Context, principal, action, queue string, count int, success bool)

LogDLQ records a DLQ operation audit event.

func (*AuditLogger) LogMove

func (a *AuditLogger) LogMove(ctx context.Context, principal string, req MoveRequest, result MoveResult, success bool)

LogMove records a message movement audit event.

func (*AuditLogger) LogNack

func (a *AuditLogger) LogNack(ctx context.Context, principal, messageID, queue, action string, success bool)

LogNack records a nack audit event.

func (*AuditLogger) LogPublish

func (a *AuditLogger) LogPublish(ctx context.Context, principal, messageID, topic, queue string, success bool)

LogPublish records a publish audit event.

func (*AuditLogger) LogQueue

func (a *AuditLogger) LogQueue(ctx context.Context, principal, action, queue string, success bool)

LogQueue records a queue operation audit event.

func (*AuditLogger) LogSchema

func (a *AuditLogger) LogSchema(ctx context.Context, principal, schema, version string, valid bool, detail string)

LogSchema records a schema validation audit event.

func (*AuditLogger) LogStream

func (a *AuditLogger) LogStream(ctx context.Context, principal, action, stream string, success bool)

LogStream records a stream operation audit event.

type AuditSeverity

type AuditSeverity string

AuditSeverity represents the severity of an audit event.

const (
	AuditInfo     AuditSeverity = "info"
	AuditWarn     AuditSeverity = "warn"
	AuditCritical AuditSeverity = "critical"
)

type AuditSink

type AuditSink interface {
	Write(ctx context.Context, event AuditEvent) error
}

AuditSink is the interface for writing audit events.

type BCLAction

type BCLAction struct {
	Strategy  string   `json:"strategy,omitempty"`
	Consumers []string `json:"consumers,omitempty"`
	Queue     string   `json:"queue,omitempty"`
	Weight    int      `json:"weight,omitempty"`
}

type BCLCondition

type BCLCondition struct {
	Field    string `json:"field"`
	Operator string `json:"operator"`
	Value    string `json:"value"`
}

type BCLPlanDefinition

type BCLPlanDefinition struct {
	Name     string   `json:"name"`
	Queue    string   `json:"queue,omitempty"`
	Topic    string   `json:"topic,omitempty"`
	Strategy string   `json:"strategy"`
	Fallback string   `json:"fallback,omitempty"`
	Rules    []string `json:"rules,omitempty"`
}

type BCLPolicyDefinition

type BCLPolicyDefinition struct {
	Name   string         `json:"name"`
	Type   string         `json:"type"`
	Config map[string]any `json:"config,omitempty"`
}

type BCLRoutingConfig

type BCLRoutingConfig struct {
	Version     string                  `json:"version"`
	Description string                  `json:"description,omitempty"`
	Strategies  []BCLStrategyDefinition `json:"strategies"`
	Rules       []BCLRuleDefinition     `json:"rules"`
	Plans       []BCLPlanDefinition     `json:"plans"`
	Policies    []BCLPolicyDefinition   `json:"policies,omitempty"`
}

BCLRoutingConfig holds BCL-compatible routing configuration. This struct can be populated from BCL decision tables or from standard JSON/YAML config files.

type BCLRuleDefinition

type BCLRuleDefinition struct {
	Name     string         `json:"name"`
	Priority int            `json:"priority"`
	When     []BCLCondition `json:"when"`
	Then     BCLAction      `json:"then"`
	Enabled  bool           `json:"enabled"`
}

type BCLStrategyDefinition

type BCLStrategyDefinition struct {
	Name       string         `json:"name"`
	Type       StrategyType   `json:"type"`
	Params     map[string]any `json:"params,omitempty"`
	Conditions []BCLCondition `json:"conditions,omitempty"`
}

type BackpressurePolicy

type BackpressurePolicy string
const (
	BackpressureBlock      BackpressurePolicy = "block"
	BackpressureReject     BackpressurePolicy = "reject"
	BackpressureDropOldest BackpressurePolicy = "drop_oldest"
	BackpressureDropNewest BackpressurePolicy = "drop_newest"
	BackpressureSpillDisk  BackpressurePolicy = "spill_disk"
	BackpressureDLQ        BackpressurePolicy = "dlq"
)

type BatchAckStore

type BatchAckStore interface {
	AckBatch(context.Context, []AckRequest) []error
}

type BatchHandler

type BatchHandler func(context.Context, []Delivery) error

type BatchPublishFuture

type BatchPublishFuture interface {
	Done() <-chan struct{}
	Wait(context.Context) (BatchPublishResult, error)
	Cancel(context.Context) error
}

type BatchPublishResult

type BatchPublishResult struct {
	Results []PublishResult `json:"results"`
	Errors  []string        `json:"errors,omitempty"`
}

type BatchUpdateStore

type BatchUpdateStore interface {
	UpdateBatch(context.Context, []Message) []error
}

type BinaryFileWALStore

type BinaryFileWALStore struct {
	*MemoryStore
	// contains filtered or unexported fields
}

BinaryFileWALStore is a durable single-node store backed by the native BWL1 operation codec. BWL1 writes packed mutation records directly—without JSON or a generic Message wrapper—and protects them with CRC32C plus optional HMAC-SHA256 and AES-GCM.

WAL-first ordering guarantee: every durable mutation (Lease, Ack, Nack, Move, Update, PauseQueue, ResumeQueue, PurgeQueue, CommitOffset) encodes and group-commits the WAL record BEFORE applying the change to the in-memory index. A crash between WAL write and memory application is safe: on recovery the WAL record is replayed and the in-memory state is rebuilt correctly.

func NewBinaryFileWALStore

func NewBinaryFileWALStore(dir string, opts ...BinaryMessageCodecOption) (*BinaryFileWALStore, error)

func NewBinaryFileWALStoreWithCodec

func NewBinaryFileWALStoreWithCodec(dir string, codec FrameCodec) (*BinaryFileWALStore, error)

NewBinaryFileWALStoreWithCodec creates a BinaryFileWALStore with a specific codec (FWB1 or FWB2).

func NewBinaryFileWALStoreWithWALCodec

func NewBinaryFileWALStoreWithWALCodec(dir string, legacyCodec FrameCodec, walCodec *WALRecordCodec) (*BinaryFileWALStore, error)

NewBinaryFileWALStoreWithWALCodec allows applications using a custom network FrameCodec to configure the native BWL1 durability codec explicitly. The frame codec is retained only to recover pre-BWL1 FWB1/FWB2 JSON records.

func (*BinaryFileWALStore) Ack

Ack implements WAL-first ordering: validate (read-only), WAL, then apply.

func (*BinaryFileWALStore) AckBatch

func (s *BinaryFileWALStore) AckBatch(ctx context.Context, reqs []AckRequest) []error

AckBatch implements WAL-first ordering: validate all, WAL the valid subset, then apply.

func (*BinaryFileWALStore) Append

func (s *BinaryFileWALStore) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

func (*BinaryFileWALStore) AppendAtomic

func (s *BinaryFileWALStore) AppendAtomic(ctx context.Context, entries []AppendEntry) ([]Message, error)

func (*BinaryFileWALStore) AppendAtomicMinimal

func (s *BinaryFileWALStore) AppendAtomicMinimal(ctx context.Context, entries []AppendEntry) error

func (*BinaryFileWALStore) AppendAtomicOwned

func (s *BinaryFileWALStore) AppendAtomicOwned(ctx context.Context, entries []AppendEntry) error

func (*BinaryFileWALStore) Close

func (s *BinaryFileWALStore) Close() error

func (*BinaryFileWALStore) CommitOffset

func (s *BinaryFileWALStore) CommitOffset(ctx context.Context, commit OffsetCommit) error

CommitOffset implements WAL-first ordering.

func (*BinaryFileWALStore) CommitStreamTransaction

func (s *BinaryFileWALStore) CommitStreamTransaction(ctx context.Context, tx StreamTransaction) ([]Message, error)

func (*BinaryFileWALStore) ConfirmationLevel

func (*BinaryFileWALStore) ConfirmationLevel() ConfirmLevel

func (*BinaryFileWALStore) DeclareQueue

func (s *BinaryFileWALStore) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*BinaryFileWALStore) DeclareStream

func (s *BinaryFileWALStore) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*BinaryFileWALStore) DeclareTopic

func (s *BinaryFileWALStore) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*BinaryFileWALStore) ExtendLease

func (s *BinaryFileWALStore) ExtendLease(ctx context.Context, req LeaseRequest) error

ExtendLease implements WAL-first ordering: validate, snapshot the updated lease-until timestamp, WAL, then apply.

func (*BinaryFileWALStore) Lease

func (s *BinaryFileWALStore) Lease(ctx context.Context, req LeaseRequest) ([]Message, error)

Lease implements WAL-first ordering: prepare the lease state (no mutation), fsync the WAL record, then apply the mutation to the in-memory index.

func (*BinaryFileWALStore) Move

Move implements WAL-first ordering.

func (*BinaryFileWALStore) Nack

Nack implements WAL-first ordering: validate (read-only), WAL, then apply.

func (*BinaryFileWALStore) PauseQueue

func (s *BinaryFileWALStore) PauseQueue(ctx context.Context, name string) error

func (*BinaryFileWALStore) PurgeQueue

func (s *BinaryFileWALStore) PurgeQueue(ctx context.Context, name string) (int, error)

PurgeQueue implements WAL-first ordering.

func (*BinaryFileWALStore) ResumeQueue

func (s *BinaryFileWALStore) ResumeQueue(ctx context.Context, name string) error

ResumeQueue implements WAL-first ordering.

func (*BinaryFileWALStore) SetHealthCallback

func (s *BinaryFileWALStore) SetHealthCallback(fn func(error))

func (*BinaryFileWALStore) StoreHealth

func (s *BinaryFileWALStore) StoreHealth() error

func (*BinaryFileWALStore) SweepLeases

func (s *BinaryFileWALStore) SweepLeases(ctx context.Context, now time.Time) (int, error)

SweepLeases implements WAL-first ordering: prepare the deterministic expiry set, persist it, then apply it. The promoted MemoryStore.SweepLeases mutates memory only, so without this override lease expirations are not durable.

func (*BinaryFileWALStore) Update

func (s *BinaryFileWALStore) Update(ctx context.Context, msg Message) error

Update implements WAL-first ordering. The target must already exist; validating first avoids appending a WAL record that the apply step would reject, which would leave a spurious record for replay to trip over.

func (*BinaryFileWALStore) UpdateBatch

func (s *BinaryFileWALStore) UpdateBatch(ctx context.Context, messages []Message) []error

UpdateBatch implements WAL-first ordering: validate the batch, WAL the valid subset, then apply. WALing entries whose targets are missing would append records the apply step rejects.

type BinaryMessageCodec

type BinaryMessageCodec struct {
	CompressThreshold int
	MaxFrameSize      int
	EncryptionKey     []byte
	SigningKey        []byte
}

func NewBinaryMessageCodec

func NewBinaryMessageCodec(opts ...BinaryMessageCodecOption) *BinaryMessageCodec

func (*BinaryMessageCodec) DecodeFrame

func (c *BinaryMessageCodec) DecodeFrame(frame []byte, msg *Message) error

func (*BinaryMessageCodec) DecodeMessage

func (c *BinaryMessageCodec) DecodeMessage(frame []byte, msg *Message) error

func (*BinaryMessageCodec) DecodeMessageBase64

func (c *BinaryMessageCodec) DecodeMessageBase64(s string, msg *Message) error

func (*BinaryMessageCodec) EncodeFrame

func (c *BinaryMessageCodec) EncodeFrame(dst []byte, typ FrameType, msg Message) ([]byte, error)

func (*BinaryMessageCodec) EncodeMessage

func (c *BinaryMessageCodec) EncodeMessage(dst []byte, msg Message) ([]byte, error)

func (*BinaryMessageCodec) EncodeMessageBase64

func (c *BinaryMessageCodec) EncodeMessageBase64(msg Message) (string, error)

func (*BinaryMessageCodec) PeekHeader

func (c *BinaryMessageCodec) PeekHeader(frame []byte, msg *Message) error

func (*BinaryMessageCodec) WALCodecConfig

func (c *BinaryMessageCodec) WALCodecConfig() WALCodecConfig

WALCodecConfig exposes equivalent durability protection settings to the dedicated BWL1 write-ahead-log codec.

type BinaryMessageCodecOption

type BinaryMessageCodecOption func(*BinaryMessageCodec)

func WithFrameCompressionThreshold

func WithFrameCompressionThreshold(n int) BinaryMessageCodecOption

func WithFrameEncryptionKey

func WithFrameEncryptionKey(key []byte) BinaryMessageCodecOption

func WithFrameMaxSize

func WithFrameMaxSize(n int) BinaryMessageCodecOption

func WithFrameSigningKey

func WithFrameSigningKey(key []byte) BinaryMessageCodecOption

type Broker

type Broker struct {
	// contains filtered or unexported fields
}

func MustNew

func MustNew(cfg Config) *Broker

func New

func New(cfg Config) (*Broker, error)

func (*Broker) ACL

func (b *Broker) ACL() *ACL

ACL returns the configured ACL manager for the broker.

func (*Broker) AddRoute

func (b *Broker) AddRoute(route Route)

func (*Broker) AddRoutingPlan

func (b *Broker) AddRoutingPlan(plan RoutingPlan)

func (*Broker) AuditLogger

func (b *Broker) AuditLogger() *AuditLogger

func (*Broker) BanRemoteConsumer

func (b *Broker) BanRemoteConsumer(ctx context.Context, id string, reason string) (ConsumerInfo, error)

func (*Broker) CancelTask

func (b *Broker) CancelTask(ctx context.Context, id, reason string) error

CancelTask cancels a task by id. It reports whether the task was known.

func (*Broker) Cluster

func (b *Broker) Cluster() *Cluster

func (*Broker) CommitOffset

func (b *Broker) CommitOffset(ctx context.Context, commit OffsetCommit) error

func (*Broker) ConfigLoader

func (b *Broker) ConfigLoader() *RoutingConfigLoader

func (*Broker) ConsumerJoinGroup

func (b *Broker) ConsumerJoinGroup(ctx context.Context, consumerID, group string) *GroupState

func (*Broker) ConsumerLeaveGroup

func (b *Broker) ConsumerLeaveGroup(ctx context.Context, consumerID, group string)

func (*Broker) ConsumerOffset

func (b *Broker) ConsumerOffset(ctx context.Context, commit OffsetCommit) (uint64, error)

func (*Broker) ConsumerOffsetManager

func (b *Broker) ConsumerOffsetManager() *ConsumerOffsetManager

ConsumerOffsetManagerAccessor on Broker.

func (*Broker) Consumers

func (b *Broker) Consumers() *ConsumerRegistry

func (*Broker) DeclareQueue

func (b *Broker) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*Broker) DeclareStream

func (b *Broker) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*Broker) DeclareTopic

func (b *Broker) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*Broker) DefaultStrategy

func (b *Broker) DefaultStrategy() StrategyType

DefaultStrategy returns the default routing strategy type.

func (*Broker) FederationManager

func (b *Broker) FederationManager() *FederationManager

FederationManager accessor on Broker.

func (*Broker) FrameCodec

func (b *Broker) FrameCodec() FrameCodec

func (*Broker) GetTask

func (b *Broker) GetTask(ctx context.Context, id string) (TaskInfo, bool)

GetTask returns the current state of a task, and whether it is known.

func (*Broker) GroupRebalancer

func (b *Broker) GroupRebalancer() *GroupRebalancer

func (*Broker) Health

func (b *Broker) Health() HealthStatus

func (*Broker) HealthMonitor

func (b *Broker) HealthMonitor() *StoreHealthMonitor

func (*Broker) IsStoreFenced

func (b *Broker) IsStoreFenced() bool

func (*Broker) ListTasks

func (b *Broker) ListTasks(ctx context.Context) []TaskInfo

func (*Broker) ListTopic

func (b *Broker) ListTopic(ctx context.Context, name string, limit int) ([]Message, error)

ListTopic returns the retained messages of a topic, oldest first.

Topics had no read path before this: a message published to a topic could not be read back, replayed or backfilled, so topic retention grew with nothing able to consume it.

func (*Broker) LoadRoutingConfig

func (b *Broker) LoadRoutingConfig(data []byte) error

func (*Broker) MessageReplay

func (b *Broker) MessageReplay() *MessageReplay

MessageReplayAccessor on Broker.

func (*Broker) Metrics

func (b *Broker) Metrics() BrokerMetrics

func (*Broker) Notifications

func (b *Broker) Notifications() *NotificationBus

func (*Broker) OTLPExporter

func (b *Broker) OTLPExporter() *OTLPExporter

func (*Broker) PartitionOrdering

func (b *Broker) PartitionOrdering() *PartitionOrdering

PartitionOrderingAccessor on Broker.

func (*Broker) PartitionReassignment

func (b *Broker) PartitionReassignment() *PartitionReassignment

PartitionReassignmentAccessor on Broker.

func (*Broker) Pause

func (b *Broker) Pause(ctx context.Context) error

func (*Broker) PauseQueue

func (b *Broker) PauseQueue(ctx context.Context, name string) error

func (*Broker) ProducerRegistry

func (b *Broker) ProducerRegistry() *ProducerRegistry

EnsureProducerRegistry makes sure the broker has an initialized ProducerRegistry.

func (*Broker) PrometheusMetrics

func (b *Broker) PrometheusMetrics() *PrometheusMetrics

func (*Broker) PublishRetryBuffer

func (b *Broker) PublishRetryBuffer() *PublishRetryBuffer

func (*Broker) Publisher

func (b *Broker) Publisher() *Publisher

func (*Broker) PurgeQueue

func (b *Broker) PurgeQueue(ctx context.Context, name string) (int, error)

func (*Broker) QueueCandidates

func (b *Broker) QueueCandidates(queue, group string) []ConsumerCandidate

func (*Broker) QueueMaxDepth

func (b *Broker) QueueMaxDepth(name string) int

QueueMaxDepth reports the configured depth limit for a queue, or 0 when the queue is unlimited or undeclared.

func (*Broker) ReadStream

func (b *Broker) ReadStream(ctx context.Context, req StreamReadRequest) ([]Message, error)

func (*Broker) ReadTopic

func (b *Broker) ReadTopic(ctx context.Context, name, afterID string, limit int) ([]Message, error)

ReadTopic returns retained topic messages published after afterID, so a reader can resume from where it stopped instead of restarting from the oldest message.

func (*Broker) RegisterRemoteConsumer

func (b *Broker) RegisterRemoteConsumer(ctx context.Context, reg ConsumerRegistration) (ConsumerInfo, error)

func (*Broker) RegisterTask

func (b *Broker) RegisterTask(ctx context.Context, name string, handler TaskHandler, cfg ...ConsumerConfig) (*Subscription, error)

func (*Broker) RemoteConsumerHeartbeat

func (b *Broker) RemoteConsumerHeartbeat(ctx context.Context, id string) (ConsumerInfo, error)

func (*Broker) RemoteConsumerSubscribe

func (b *Broker) RemoteConsumerSubscribe(ctx context.Context, id string, sub RemoteSubscription) (ConsumerInfo, error)

func (*Broker) RemoveRoute

func (b *Broker) RemoveRoute(name string) bool

RemoveRoute deletes a route by name, reporting whether one was found.

func (*Broker) RemoveRoutingPlan

func (b *Broker) RemoveRoutingPlan(name string)

func (*Broker) Resume

func (b *Broker) Resume(ctx context.Context) error

func (*Broker) ResumeQueue

func (b *Broker) ResumeQueue(ctx context.Context, name string) error

func (*Broker) RetryTask

func (b *Broker) RetryTask(ctx context.Context, id string) error

RetryTask returns a failed task to its queue by id.

func (*Broker) Router

func (b *Broker) Router() *Router

func (*Broker) SagaEngine

func (b *Broker) SagaEngine() *SagaEngine

func (*Broker) SelectConsumers

func (b *Broker) SelectConsumers(ctx context.Context, msg Message, candidates []ConsumerCandidate) ([]ConsumerCandidate, error)

SelectConsumers selects consumers for a message using the configured routing strategy.

func (*Broker) SetACL

func (b *Broker) SetACL(a *ACL)

SetACL sets or updates the ACL manager for the broker.

func (*Broker) SetDefaultStrategy

func (b *Broker) SetDefaultStrategy(st StrategyType)

SetDefaultStrategy sets the default routing strategy type.

func (*Broker) SetRemoteConsumerState

func (b *Broker) SetRemoteConsumerState(ctx context.Context, id string, st ConsumerState, reason string) (ConsumerInfo, error)

func (*Broker) ShovelManager

func (b *Broker) ShovelManager() *ShovelManager

ShovelManager accessor on Broker.

func (*Broker) Start

func (b *Broker) Start(ctx context.Context) error

func (*Broker) StartTime

func (b *Broker) StartTime() time.Time

func (*Broker) State

func (b *Broker) State() BrokerState

func (*Broker) StateStore

func (b *Broker) StateStore() StateStore

func (*Broker) Stop

func (b *Broker) Stop(ctx context.Context) error

func (*Broker) Store

func (b *Broker) Store() Store

func (*Broker) StreamHeadOffset

func (b *Broker) StreamHeadOffset(ctx context.Context, stream string) (uint64, error)

StreamHeadOffset returns the latest offset for a stream.

func (*Broker) StreamLag

func (b *Broker) StreamLag(ctx context.Context, stream, consumerGroup string) (uint64, error)

StreamLag returns the consumer lag (messages behind) for a given stream and consumer group.

func (*Broker) StreamLagAll

func (b *Broker) StreamLagAll(ctx context.Context, stream string) (map[string]uint64, error)

StreamLagAll returns consumer lag for all consumer groups on a stream.

func (*Broker) StreamLagReport

func (b *Broker) StreamLagReport(ctx context.Context, stream string) (StreamConsumerLag, error)

StreamLagReport returns a full lag report for a stream.

func (*Broker) StreamLogCompaction

func (b *Broker) StreamLogCompaction() *StreamLogCompaction

StreamLogCompactionAccessor on Broker.

func (*Broker) Subscribe

func (b *Broker) Subscribe(ctx context.Context, cfg ConsumerConfig, handler Handler) (*Subscription, error)

func (*Broker) SubscribeBatch

func (b *Broker) SubscribeBatch(ctx context.Context, cfg ConsumerConfig, handler BatchHandler) (*Subscription, error)

func (*Broker) Task

func (b *Broker) Task(id string) TaskHandle

Task returns a handle for a task by id, or nil when no such task is known.

Cancel, Retry, Status and Wait were reachable only through the handle returned by SubmitTask, which lives in memory and is lost on restart. Operator tooling that holds a task id from a log, a database or a previous process therefore had no way to cancel or inspect it: there was no Broker.GetTask, and GetTask existed only on the internal StateStore.

The returned handle reads through to the StateStore, so a task submitted before a restart is still addressable.

func (*Broker) TaskRouter

func (b *Broker) TaskRouter() *TaskRouter

func (*Broker) TenantManager

func (b *Broker) TenantManager() *TenantManager

TenantAccessor on Broker.

func (*Broker) TopicPartitionStats

func (b *Broker) TopicPartitionStats(ctx context.Context, topic string, partitions int) (*TopicPartitionStats, error)

TopicPartitionStats returns partition statistics for a topic.

func (*Broker) Tracer

func (b *Broker) Tracer() *Tracer

func (*Broker) TransactionalOutbox

func (b *Broker) TransactionalOutbox() *TransactionalOutbox

TransactionalOutbox returns the legacy in-memory publish retry buffer. Deprecated: use PublishRetryBuffer.

func (*Broker) UnbanRemoteConsumer

func (b *Broker) UnbanRemoteConsumer(ctx context.Context, id string) (ConsumerInfo, error)

func (*Broker) UnregisterRemoteConsumer

func (b *Broker) UnregisterRemoteConsumer(ctx context.Context, id string) error

type BrokerError

type BrokerError struct {
	Code      string            `json:"code"`
	Message   string            `json:"message"`
	Temporary bool              `json:"temporary,omitempty"`
	Retryable bool              `json:"retryable,omitempty"`
	Details   map[string]string `json:"details,omitempty"`
}

func (BrokerError) Error

func (e BrokerError) Error() string

type BrokerEvent

type BrokerEvent struct {
	Broker string
	State  BrokerState
	Error  error
	Time   time.Time
}

type BrokerMetrics

type BrokerMetrics struct {
	MessagesPublished    uint64        `json:"messages_published"`
	MessagesDelivered    uint64        `json:"messages_delivered"`
	MessagesAcked        uint64        `json:"messages_acked"`
	MessagesNacked       uint64        `json:"messages_nacked"`
	MessagesDeadLettered uint64        `json:"messages_dead_lettered"`
	ActiveConsumers      int           `json:"active_consumers"`
	ActiveSubscriptions  int           `json:"active_subscriptions"`
	QueueCount           int           `json:"queue_count"`
	TopicCount           int           `json:"topic_count"`
	StreamCount          int           `json:"stream_count"`
	StoreStats           StoreStats    `json:"store_stats"`
	Uptime               time.Duration `json:"uptime"`
	RaftState            string        `json:"raft_state"`
	RaftTerm             uint64        `json:"raft_term"`
	RaftCommitIndex      uint64        `json:"raft_commit_index"`
	RaftAppliedIndex     uint64        `json:"raft_applied_index"`
	IsLeader             bool          `json:"is_leader"`
}

type BrokerState

type BrokerState string
const (
	BrokerConfigured   BrokerState = "configured"
	BrokerInitializing BrokerState = "initializing"
	BrokerRecovering   BrokerState = "recovering"
	BrokerStarting     BrokerState = "starting"
	BrokerReady        BrokerState = "ready"
	BrokerRunning      BrokerState = "running"
	BrokerDegraded     BrokerState = "degraded"
	BrokerPaused       BrokerState = "paused"
	BrokerDraining     BrokerState = "draining"
	BrokerStopping     BrokerState = "stopping"
	BrokerStopped      BrokerState = "stopped"
	BrokerFailed       BrokerState = "failed"
)

type BrokerStateRecord

type BrokerStateRecord struct {
	Name      string            `json:"name"`
	NodeID    string            `json:"node_id,omitempty"`
	Mode      Mode              `json:"mode"`
	State     BrokerState       `json:"state"`
	UpdatedAt time.Time         `json:"updated_at"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

BrokerStateRecord is durable broker/runtime state independent from the hot message queue store. It is intentionally compact so it can be persisted by memory, SQLite, Postgres, etc.

type BrokerStateStore

type BrokerStateStore interface {
	PutBrokerState(context.Context, BrokerStateRecord) error
	GetBrokerState(context.Context, string) (BrokerStateRecord, bool, error)
}

type Callback

type Callback interface {
	HandleNotification(context.Context, Notification) error
}

type CallbackFunc

type CallbackFunc func(context.Context, Notification) error

func (CallbackFunc) HandleNotification

func (f CallbackFunc) HandleNotification(ctx context.Context, n Notification) error

type CircuitBreaker

type CircuitBreaker struct {
	// contains filtered or unexported fields
}

CircuitBreaker provides automatic failure detection and recovery.

func NewCircuitBreaker

func NewCircuitBreaker(cfg CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker with the given config.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow checks if a request is allowed through the circuit breaker.

func (*CircuitBreaker) IsOpen

func (cb *CircuitBreaker) IsOpen() bool

IsOpen returns true if the circuit is open (rejecting requests).

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed operation.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful operation.

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset manually resets the circuit breaker to closed state.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current circuit breaker state.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// Threshold is the number of consecutive failures before opening the circuit.
	// Default: 5.
	Threshold int

	// Timeout is how long the circuit stays open before transitioning to half-open.
	// Default: 30 seconds.
	Timeout time.Duration

	// HalfOpenMax is the number of test requests allowed in half-open state.
	// Default: 3.
	HalfOpenMax int

	// SuccessThreshold is the number of consecutive successes in half-open state
	// before closing the circuit. Default: 2.
	SuccessThreshold int
}

CircuitBreakerConfig configures the circuit breaker.

type CircuitState

type CircuitState string

CircuitState represents the state of a circuit breaker.

const (
	CircuitClosed   CircuitState = "closed"    // normal operation
	CircuitOpen     CircuitState = "open"      // rejecting requests
	CircuitHalfOpen CircuitState = "half_open" // testing recovery
)

type Cluster

type Cluster struct {
	// contains filtered or unexported fields
}

func NewCluster

func NewCluster(self string) *Cluster

func (*Cluster) ActiveNodes

func (c *Cluster) ActiveNodes() []ClusterNode

func (*Cluster) Assign

func (c *Cluster) Assign(topic string, partitions, replicas int) ([]PartitionAssignment, error)

func (*Cluster) Assignment

func (c *Cluster) Assignment(topic string, partition int) (PartitionAssignment, bool)

func (*Cluster) Assignments

func (c *Cluster) Assignments() []PartitionAssignment

func (*Cluster) Drain

func (c *Cluster) Drain(ctx context.Context, id string) error

func (*Cluster) IsLeader

func (c *Cluster) IsLeader() bool

func (*Cluster) Join

func (c *Cluster) Join(ctx context.Context, node ClusterNode) error

func (*Cluster) Leader

func (c *Cluster) Leader() string

func (*Cluster) Leave

func (c *Cluster) Leave(ctx context.Context, id string) error

func (*Cluster) MarkFailed

func (c *Cluster) MarkFailed(ctx context.Context, id string) error

func (*Cluster) Nodes

func (c *Cluster) Nodes() []ClusterNode

func (*Cluster) Self

func (c *Cluster) Self() string

type ClusterConfig

type ClusterConfig struct {
	Enabled           bool     `json:"enabled"`
	ClusterID         string   `json:"cluster_id,omitempty"`
	Peers             []string `json:"peers,omitempty"`
	ReplicationFactor int      `json:"replication_factor,omitempty"`
	MinInSyncReplicas int      `json:"min_in_sync_replicas,omitempty"`
}

ClusterConfig defines replicated broker behavior. ReplicationFactor defaults to three and MinInSyncReplicas defaults to a majority.

type ClusterNode

type ClusterNode struct {
	ID        string            `json:"id"`
	Address   string            `json:"address,omitempty"`
	Zone      string            `json:"zone,omitempty"`
	State     NodeState         `json:"state"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	JoinedAt  time.Time         `json:"joined_at"`
	UpdatedAt time.Time         `json:"updated_at"`
}

type Codec

type Codec interface {
	Marshal(any) ([]byte, error)
	Unmarshal([]byte, any) error
	ContentType() string
}

type CodecType

type CodecType string

CodecType identifies the binary frame format.

const (
	CodecFWB1 CodecType = "fwb1" // Original format with string keys
	CodecFWB2 CodecType = "fwb2" // Compact format with numeric tags
)

type CompactCodecOption

type CompactCodecOption func(*CompactMessageCodec)

func WithCompactCompressThreshold

func WithCompactCompressThreshold(n int) CompactCodecOption

func WithCompactEncryptionKey

func WithCompactEncryptionKey(key []byte) CompactCodecOption

func WithCompactMaxFrameSize

func WithCompactMaxFrameSize(n int) CompactCodecOption

func WithCompactSigningKey

func WithCompactSigningKey(key []byte) CompactCodecOption

type CompactMessageCodec

type CompactMessageCodec struct {
	CompressThreshold int
	MaxFrameSize      int
	EncryptionKey     []byte
	SigningKey        []byte
}

CompactMessageCodec is a lightweight binary codec optimized for minimal frame size. Uses 1-byte numeric tags instead of string keys, packed integers, and delta timestamps.

func NewCompactMessageCodec

func NewCompactMessageCodec(opts ...CompactCodecOption) *CompactMessageCodec

func (*CompactMessageCodec) DecodeMessage

func (c *CompactMessageCodec) DecodeMessage(frame []byte, msg *Message) error

DecodeMessage decodes a FWB2 frame into a Message.

func (*CompactMessageCodec) EncodeMessage

func (c *CompactMessageCodec) EncodeMessage(dst []byte, msg Message) ([]byte, error)

EncodeMessage encodes a Message into a compact FWB2 frame.

func (*CompactMessageCodec) WALCodecConfig

func (c *CompactMessageCodec) WALCodecConfig() WALCodecConfig

WALCodecConfig exposes equivalent durability protection settings to the dedicated BWL1 write-ahead-log codec.

type CompactableStore

type CompactableStore interface {
	Store
	// CompactableMessages returns all message IDs that can be safely removed.
	// Typically acked/completed messages that won't be needed.
	CompactableMessages(ctx context.Context) ([]string, error)
	// RemoveMessages removes the specified messages from the store.
	RemoveMessages(ctx context.Context, ids []string) error
}

CompactableStore is a store that supports compaction operations.

type CompressionCodec

type CompressionCodec byte

CompressionCodec represents the algorithm used to compress record batches or stream segments.

const (
	CompressionNone CompressionCodec = 0
	CompressionLZ4  CompressionCodec = 1
	CompressionZstd CompressionCodec = 2
)

func ParseCompressionCodec

func ParseCompressionCodec(s string) (CompressionCodec, error)

ParseCompressionCodec parses a string representation into a CompressionCodec.

func (CompressionCodec) String

func (c CompressionCodec) String() string

type Config

type Config struct {
	Name                        string             `json:"name"`
	PerformanceProfile          PerformanceProfile `json:"performance_profile,omitempty"`
	Mode                        Mode               `json:"mode"`
	NodeID                      string             `json:"node_id"`
	Store                       Store              `json:"-"`
	StateStore                  StateStore         `json:"-"`
	Pool                        *pool.Pool         `json:"-"`
	OwnPool                     bool               `json:"own_pool"`
	Codec                       Codec              `json:"-"`
	FrameCodec                  FrameCodec         `json:"-"`
	FrameCodecType              CodecType          `json:"-"`
	SchemaRegistry              SchemaRegistry     `json:"-"`
	DefaultQueue                string             `json:"default_queue"`
	DefaultVisibility           time.Duration      `json:"default_visibility"`
	DefaultRetry                RetryPolicy        `json:"default_retry"`
	DefaultDLQ                  string             `json:"default_dlq"`
	MaxMessageSize              int                `json:"max_message_size"`
	Backpressure                BackpressurePolicy `json:"backpressure"`
	EnableNotifications         bool               `json:"enable_notifications"`
	NotificationHistoryCapacity int                `json:"notification_history_capacity,omitempty"`
	MessageHistory              *int               `json:"message_history,omitempty"`
	EnablePublisherTracking     bool               `json:"enable_publisher_tracking,omitempty"`
	EnableConsumerEventTracking bool               `json:"enable_consumer_event_tracking,omitempty"`
	EnableRequestResponse       bool               `json:"enable_request_response"`
	EnableTaskTracking          bool               `json:"enable_task_tracking"`
	DrainTimeout                time.Duration      `json:"drain_timeout"`
	PollInterval                time.Duration      `json:"poll_interval"`
	LeaseSweepInterval          time.Duration      `json:"lease_sweep_interval"`
	RemoteConsumerTimeout       time.Duration      `json:"remote_consumer_timeout"`
	Hooks                       Hooks              `json:"-"`
	EnablePrometheus            bool               `json:"enable_prometheus,omitempty"`
	EnableTracing               bool               `json:"enable_tracing,omitempty"`
	TracerConfig                *TracerConfig      `json:"-"`
	AuditEnabled                bool               `json:"audit_enabled,omitempty"`
	RateLimit                   *RateLimitConfig   `json:"rate_limit,omitempty"`
	Tenancy                     *TenancyConfig     `json:"tenancy,omitempty"`
	// ACL authorizes requests arriving on a listener: the HTTP admin and data
	// plane, gRPC, the native RPC transport, WebSocket and the BST1 native stream.
	//
	// It is deliberately not a boundary for in-process calls. Code holding a
	// *Broker has already run inside the process, so Publisher, Store, Consumers
	// and the consumer registry are reachable directly and there is no credential
	// to present. Treating those calls as untrusted would mean every embedder had
	// to manufacture a principal for ordinary use, so instead the trust boundary
	// is stated here: configure the ACL for network surfaces, and do not hand a
	// *Broker to code you would not trust with full access.
	//
	// Tenant scoping is separate and does apply wherever a principal is present.
	// resolveTenant and tenantAllowed restrict a tenant-scoped principal even
	// inside the process; only an unscoped principal, which no listener ever
	// produces, is unrestricted.
	ACL          *ACL               `json:"-"`
	OTLPEndpoint string             `json:"otlp_endpoint,omitempty"`
	OTLPInterval time.Duration      `json:"otlp_interval,omitempty"`
	OTLPHeaders  map[string]string  `json:"otlp_headers,omitempty"`
	Partition    *PartitionConfig   `json:"partition,omitempty"`
	WebSocket    *WebSocketConfig   `json:"websocket,omitempty"`
	ExactlyOnce  *ExactlyOnceConfig `json:"exactly_once,omitempty"`
	// SigningKey is the HMAC signing key for frame authentication.
	SigningKey []byte `json:"-"`
	// EncryptionKey is the AES encryption key for frame encryption at rest.
	EncryptionKey []byte `json:"-"`
}

type ConfigWatcher

type ConfigWatcher struct {
	// contains filtered or unexported fields
}

ConfigWatcher monitors a configuration file and reloads broker state when changed.

func NewConfigWatcher

func NewConfigWatcher(b *Broker, filePath string, pollInterval time.Duration) *ConfigWatcher

NewConfigWatcher creates a hot-reload config watcher.

func (*ConfigWatcher) ApplyConfig

func (cw *ConfigWatcher) ApplyConfig(ctx context.Context, dc DynamicConfig) error

ApplyConfig validates and atomically applies dynamic configuration to the broker.

func (*ConfigWatcher) Reload

func (cw *ConfigWatcher) Reload(ctx context.Context) error

Reload reads, validates, and atomically applies the configuration file.

func (*ConfigWatcher) Start

func (cw *ConfigWatcher) Start(ctx context.Context)

Start runs the hot reload monitoring loop.

func (*ConfigWatcher) Stop

func (cw *ConfigWatcher) Stop()

Stop stops the config watcher.

type ConfirmLevel

type ConfirmLevel string
const (
	ConfirmAccepted   ConfirmLevel = "accepted"
	ConfirmValidated  ConfirmLevel = "validated"
	ConfirmRouted     ConfirmLevel = "routed"
	ConfirmEnqueued   ConfirmLevel = "enqueued"
	ConfirmPersisted  ConfirmLevel = "persisted"
	ConfirmReplicated ConfirmLevel = "replicated"
	ConfirmCommitted  ConfirmLevel = "committed"
	ConfirmDelivered  ConfirmLevel = "delivered"
	ConfirmProcessed  ConfirmLevel = "processed"
)

type ConfirmationStore

type ConfirmationStore interface {
	ConfirmationLevel() ConfirmLevel
}

ConfirmationStore reports the strongest confirmation its completed writes actually provide. It is intentionally separate from Store for compatibility with third-party stores; unannotated stores are treated as memory-only.

type ConsoleAuditSink

type ConsoleAuditSink struct{}

ConsoleAuditSink writes audit events to stdout.

func (ConsoleAuditSink) Write

func (s ConsoleAuditSink) Write(_ context.Context, event AuditEvent) error

type ConsoleExporter

type ConsoleExporter struct {
	// Prefix is prepended to each line. Default: "[TRACE] ".
	Prefix string
}

ConsoleExporter writes trace spans to an io.Writer for debugging.

func NewConsoleExporter

func NewConsoleExporter() *ConsoleExporter

func (*ConsoleExporter) ExportSpan

func (e *ConsoleExporter) ExportSpan(_ context.Context, span TraceSpan) error

func (*ConsoleExporter) Flush

func (e *ConsoleExporter) Flush(_ context.Context) error

type ConsumerCandidate

type ConsumerCandidate struct {
	ConsumerID   string            `json:"consumer_id"`
	Group        string            `json:"group"`
	TenantID     string            `json:"tenant_id,omitempty"`
	Weight       int               `json:"weight"`
	Capabilities []string          `json:"capabilities,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	InFlight     int               `json:"in_flight"`
	MaxInFlight  int               `json:"max_in_flight"`
	Acked        int64             `json:"acked"`
	Failed       int64             `json:"failed"`
	Leased       int64             `json:"leased"`
	Healthy      bool              `json:"healthy"`
	LastLatency  time.Duration     `json:"last_latency"`
	AvgLatency   time.Duration     `json:"avg_latency"`
}

ConsumerCandidate represents a consumer that can receive a routed message.

func (*ConsumerCandidate) LoadScore

func (c *ConsumerCandidate) LoadScore() float64

LoadScore returns a 0.0 (fully loaded) to 1.0 (idle) score for a consumer.

func (*ConsumerCandidate) SuccessRate

func (c *ConsumerCandidate) SuccessRate() float64

SuccessRate returns 0.0 to 1.0 success ratio.

type ConsumerCommitMode

type ConsumerCommitMode string

ConsumerCommitMode determines when consumer offsets are committed.

const (
	// CommitAuto commits after each message (at-least-once).
	CommitAuto ConsumerCommitMode = "auto"
	// CommitManual commits only on explicit request.
	CommitManual ConsumerCommitMode = "manual"
	// CommitBatched commits in batches for throughput.
	CommitBatched ConsumerCommitMode = "batched"
)

type ConsumerConfig

type ConsumerConfig struct {
	Name                string            `json:"name"`
	Group               string            `json:"group"`
	Queue               string            `json:"queue"`
	Topic               string            `json:"topic"`
	Pattern             string            `json:"pattern"`
	Concurrency         int               `json:"concurrency"`
	MaxInFlight         int               `json:"max_inflight"`
	BatchSize           int               `json:"batch_size"`
	BatchWait           time.Duration     `json:"batch_wait"`
	VisibilityTimeout   time.Duration     `json:"visibility_timeout"`
	AckMode             AckMode           `json:"ack_mode"`
	RetryPolicy         RetryPolicy       `json:"retry_policy"`
	DLQ                 string            `json:"dlq"`
	Ordered             bool              `json:"ordered"`
	OrderBy             OrderMode         `json:"order_by"`
	Timeout             time.Duration     `json:"timeout"`
	HeartbeatInterval   time.Duration     `json:"heartbeat_interval"`
	Strategy            StrategyType      `json:"strategy,omitempty"`
	StrategyConfig      *StrategyConfig   `json:"-"`
	Priority            int               `json:"priority,omitempty"`
	Idempotent          bool              `json:"idempotent,omitempty"`
	DeduplicationWindow time.Duration     `json:"deduplication_window,omitempty"`
	FilterExpression    string            `json:"filter_expression,omitempty"`
	FilterHeaders       map[string]string `json:"filter_headers,omitempty"`
}

type ConsumerDedup

type ConsumerDedup struct {
	// contains filtered or unexported fields
}

ConsumerDedup provides idempotent consumer processing by deduplicating messages based on idempotency key or deduplication ID.

func NewConsumerDedup

func NewConsumerDedup(window time.Duration) *ConsumerDedup

NewConsumerDedup creates a new consumer deduplication tracker.

func (*ConsumerDedup) Cleanup

func (d *ConsumerDedup) Cleanup()

Cleanup removes expired entries from the dedup tracker.

func (*ConsumerDedup) IsDuplicate

func (d *ConsumerDedup) IsDuplicate(msg Message) bool

IsDuplicate returns true if the message has already been processed within the dedup window.

type ConsumerEvent

type ConsumerEvent struct {
	Consumer string
	Group    string
	Queue    string
	State    ConsumerState
	Error    error
	Time     time.Time
}

type ConsumerFilter

type ConsumerFilter interface {
	Match(msg Message) bool
}

ConsumerFilter evaluates whether a message matches a consumer filter.

func NewConsumerFilter

func NewConsumerFilter(cfg ConsumerConfig) (ConsumerFilter, error)

NewConsumerFilter creates a ConsumerFilter from a ConsumerConfig.

type ConsumerInfo

type ConsumerInfo struct {
	ConsumerRegistration
	State         ConsumerState        `json:"state"`
	RegisteredAt  time.Time            `json:"registered_at"`
	LastHeartbeat time.Time            `json:"last_heartbeat"`
	Paused        bool                 `json:"paused"`
	Draining      bool                 `json:"draining"`
	Banned        bool                 `json:"banned"`
	BannedReason  string               `json:"banned_reason,omitempty"`
	InFlight      int                  `json:"inflight"`
	Leased        int64                `json:"leased"`
	Acked         int64                `json:"acked"`
	Nacked        int64                `json:"nacked"`
	Failed        int64                `json:"failed"`
	LastError     string               `json:"last_error,omitempty"`
	Subscriptions []RemoteSubscription `json:"subscriptions,omitempty"`
}

type ConsumerOffsetManager

type ConsumerOffsetManager struct {
	// contains filtered or unexported fields
}

ConsumerOffsetManager provides external consumer offset management.

func NewConsumerOffsetManager

func NewConsumerOffsetManager(b *Broker) *ConsumerOffsetManager

NewConsumerOffsetManager creates a new offset manager.

func (*ConsumerOffsetManager) CommitOffset

func (om *ConsumerOffsetManager) CommitOffset(ctx context.Context, stream, group string, offset uint64) error

CommitOffset commits a consumer offset for a stream.

func (*ConsumerOffsetManager) GetAllOffsets

func (om *ConsumerOffsetManager) GetAllOffsets(stream string) map[string]uint64

GetAllOffsets returns all committed offsets for a stream.

func (*ConsumerOffsetManager) GetOffset

func (om *ConsumerOffsetManager) GetOffset(stream, group string) (uint64, bool)

GetOffset returns the committed offset for a stream and group.

func (*ConsumerOffsetManager) Lag

func (om *ConsumerOffsetManager) Lag(ctx context.Context, stream, group string) (uint64, error)

Lag returns the consumer lag for a stream and group.

type ConsumerRegistration

type ConsumerRegistration struct {
	ConsumerID        string            `json:"consumer_id"`
	Group             string            `json:"group"`
	Name              string            `json:"name,omitempty"`
	TenantID          string            `json:"tenant_id,omitempty"`
	Hostname          string            `json:"hostname,omitempty"`
	Version           string            `json:"version,omitempty"`
	Capabilities      []string          `json:"capabilities,omitempty"`
	Topics            []string          `json:"topics,omitempty"`
	Queues            []string          `json:"queues,omitempty"`
	Patterns          []string          `json:"patterns,omitempty"`
	TaskTypes         []string          `json:"task_types,omitempty"`
	CommandTypes      []string          `json:"command_types,omitempty"`
	RequestSubjects   []string          `json:"request_subjects,omitempty"`
	MaxInFlight       int               `json:"max_inflight,omitempty"`
	Concurrency       int               `json:"concurrency,omitempty"`
	AckMode           AckMode           `json:"ack_mode,omitempty"`
	HeartbeatEveryNS  int64             `json:"heartbeat_every_ns,omitempty"`
	VisibilityTimeout int64             `json:"visibility_timeout_ns,omitempty"`
	Metadata          map[string]string `json:"metadata,omitempty"`
}

type ConsumerRegistry

type ConsumerRegistry struct {
	// contains filtered or unexported fields
}

func NewConsumerRegistry

func NewConsumerRegistry(capacity int) *ConsumerRegistry

func (*ConsumerRegistry) AddEvent

func (r *ConsumerRegistry) AddEvent(id string, n Notification)

func (*ConsumerRegistry) AddStats

func (r *ConsumerRegistry) AddStats(id string, leased, acked, nacked, failed int64, lastErr string)

func (*ConsumerRegistry) Ban

func (r *ConsumerRegistry) Ban(id string, reason string) (ConsumerInfo, bool)

func (*ConsumerRegistry) Events

func (r *ConsumerRegistry) Events(id, after string, limit int) []Notification

func (*ConsumerRegistry) Get

func (r *ConsumerRegistry) Get(id string) (ConsumerInfo, bool)

func (*ConsumerRegistry) Heartbeat

func (r *ConsumerRegistry) Heartbeat(id string) (ConsumerInfo, bool)

func (*ConsumerRegistry) List

func (r *ConsumerRegistry) List() []ConsumerInfo

func (*ConsumerRegistry) ListContext

func (r *ConsumerRegistry) ListContext(ctx context.Context) []ConsumerInfo

func (*ConsumerRegistry) Register

func (*ConsumerRegistry) SetState

func (r *ConsumerRegistry) SetState(id string, st ConsumerState, reason string) (ConsumerInfo, bool)

func (*ConsumerRegistry) Subscribe

func (r *ConsumerRegistry) Subscribe(id string, sub RemoteSubscription) (ConsumerInfo, bool)

func (*ConsumerRegistry) Unban

func (r *ConsumerRegistry) Unban(id string) (ConsumerInfo, bool)

func (*ConsumerRegistry) Unregister

func (r *ConsumerRegistry) Unregister(id string) (ConsumerInfo, bool)

type ConsumerState

type ConsumerState string
const (
	ConsumerRegistered    ConsumerState = "registered"
	ConsumerJoining       ConsumerState = "joining"
	ConsumerAssigned      ConsumerState = "assigned"
	ConsumerReady         ConsumerState = "ready"
	ConsumerPolling       ConsumerState = "polling"
	ConsumerIdle          ConsumerState = "idle"
	ConsumerProcessing    ConsumerState = "processing"
	ConsumerBackpressured ConsumerState = "backpressured"
	ConsumerPaused        ConsumerState = "paused"
	ConsumerDraining      ConsumerState = "draining"
	ConsumerLeaving       ConsumerState = "leaving"
	ConsumerDisconnected  ConsumerState = "disconnected"
	ConsumerFailed        ConsumerState = "failed"
	ConsumerBanned        ConsumerState = "banned"
	ConsumerStopped       ConsumerState = "stopped"
)

type ConsumerStateStore

type ConsumerStateStore interface {
	PutConsumer(context.Context, ConsumerInfo) error
	GetConsumer(context.Context, string) (ConsumerInfo, bool, error)
	ListConsumers(context.Context) ([]ConsumerInfo, error)
	DeleteConsumer(context.Context, string) error
	AddConsumerEvent(context.Context, string, Notification) error
	ConsumerEvents(context.Context, string, string, int) ([]Notification, error)
}

type ConsumerStrategy

type ConsumerStrategy interface {
	// Select returns the best consumer for the given message from the candidates.
	Select(ctx context.Context, msg Message, candidates []ConsumerCandidate) ([]ConsumerCandidate, error)
	// Name returns the strategy type identifier.
	Name() StrategyType
}

ConsumerStrategy defines how messages are routed to consumers.

func NewAdaptiveLoadBalanceStrategy

func NewAdaptiveLoadBalanceStrategy() ConsumerStrategy

func NewCapabilityBasedStrategy

func NewCapabilityBasedStrategy(requiredCaps []string) ConsumerStrategy

func NewConsistentHashStrategy

func NewConsistentHashStrategy(hashKey string) ConsumerStrategy

func NewFanOutStrategy

func NewFanOutStrategy() ConsumerStrategy

func NewHealthBasedStrategy

func NewHealthBasedStrategy() ConsumerStrategy

func NewLeastLoadedStrategy

func NewLeastLoadedStrategy() ConsumerStrategy

func NewPowerOfTwoChoicesStrategy

func NewPowerOfTwoChoicesStrategy() ConsumerStrategy

func NewPriorityAwareStrategy

func NewPriorityAwareStrategy(threshold int) ConsumerStrategy

func NewRandomStrategy

func NewRandomStrategy() ConsumerStrategy

func NewRoundRobinStrategy

func NewRoundRobinStrategy() ConsumerStrategy

func NewRuleBasedStrategy

func NewRuleBasedStrategy(rules []RoutingRule) ConsumerStrategy

func NewShardedStrategy

func NewShardedStrategy(hashKey string) ConsumerStrategy

func NewStickySessionStrategy

func NewStickySessionStrategy(stickyKey string) ConsumerStrategy

NewStickySessionStrategy keeps up to 65,536 session bindings. New sessions evict the oldest inserted binding at that limit. Use StrategyConfig with MaxStickyBindings to choose a different bound.

func NewStrategy

func NewStrategy(cfg StrategyConfig) ConsumerStrategy

NewStrategy creates a ConsumerStrategy from a StrategyConfig.

func NewWeightedRoundRobinStrategy

func NewWeightedRoundRobinStrategy() ConsumerStrategy

type DLQArchiveRequest

type DLQArchiveRequest struct {
	Destination string `json:"destination"`
	Limit       int    `json:"limit"`
	DryRun      bool   `json:"dry_run"`
}

DLQArchiveRequest configures archiving DLQ messages.

type DLQArchiveResponse

type DLQArchiveResponse struct {
	Source      string   `json:"source"`
	Destination string   `json:"destination"`
	Archived    int      `json:"archived"`
	DryRun      bool     `json:"dry_run"`
	MessageIDs  []string `json:"message_ids,omitempty"`
}

DLQArchiveResponse summarizes archiving results.

type DLQDashboardResponse

type DLQDashboardResponse struct {
	TotalDepth int               `json:"total_depth"`
	QueueCount int               `json:"queue_count"`
	Queues     []DLQQueueSummary `json:"queues"`
}

DLQDashboardResponse contains an aggregated overview of all dead-letter queues.

type DLQErrorCount

type DLQErrorCount struct {
	Error string `json:"error"`
	Count int    `json:"count"`
}

DLQErrorCount aggregates error frequencies.

type DLQErrorInfo

type DLQErrorInfo struct {
	Error            string     `json:"error"`
	Count            int        `json:"count"`
	FirstSeenAt      *time.Time `json:"first_seen_at,omitempty"`
	LastSeenAt       *time.Time `json:"last_seen_at,omitempty"`
	SampleMessageIDs []string   `json:"sample_message_ids"`
}

DLQErrorInfo details a single error pattern.

type DLQErrorsResponse

type DLQErrorsResponse struct {
	Queue         string         `json:"queue"`
	TotalErrors   int            `json:"total_errors"`
	TotalMessages int            `json:"total_messages"`
	Page          int            `json:"page"`
	Limit         int            `json:"limit"`
	TotalPages    int            `json:"total_pages"`
	Errors        []DLQErrorInfo `json:"errors"`
}

DLQErrorsResponse returns paginated error report for a queue.

type DLQEvent

type DLQEvent struct {
	Message Message
	Queue   string
	Reason  string
	Error   error
	Time    time.Time
}

type DLQQueueSummary

type DLQQueueSummary struct {
	Name            string          `json:"name"`
	Depth           int             `json:"depth"`
	TopErrors       []DLQErrorCount `json:"top_errors"`
	LastError       string          `json:"last_error,omitempty"`
	LastErrorAt     *time.Time      `json:"last_error_at,omitempty"`
	OldestMessageAt *time.Time      `json:"oldest_message_at,omitempty"`
}

DLQQueueSummary contains depth, error distribution, and recency for a specific DLQ.

type DLQReplayAllRequest

type DLQReplayAllRequest struct {
	BatchSize   int      `json:"batch_size"`
	Destination string   `json:"destination"`
	DryRun      bool     `json:"dry_run"`
	Mode        MoveMode `json:"mode,omitempty"`
}

DLQReplayAllRequest configures bulk replay of DLQ messages.

type DLQReplayAllResponse

type DLQReplayAllResponse struct {
	Source      string   `json:"source"`
	Destination string   `json:"destination"`
	Replayed    int      `json:"replayed"`
	Batches     int      `json:"batches"`
	DryRun      bool     `json:"dry_run"`
	MessageIDs  []string `json:"message_ids,omitempty"`
}

DLQReplayAllResponse summarizes bulk replay results.

type Delivery

type Delivery struct {
	Message Message
	// contains filtered or unexported fields
}

func (Delivery) Ack

func (d Delivery) Ack(ctx context.Context) error

func (Delivery) Decode

func (d Delivery) Decode(out any) error

func (Delivery) Extend

func (d Delivery) Extend(ctx context.Context, v time.Duration) error

func (Delivery) Nack

func (d Delivery) Nack(ctx context.Context, opts ...NackOption) error

func (Delivery) Progress

func (d Delivery) Progress(ctx context.Context, p Progress) error

func (Delivery) Reject

func (d Delivery) Reject(ctx context.Context, reason string) error

func (Delivery) Respond

func (d Delivery) Respond(ctx context.Context, response any, opts ...ResponseOption) error

func (Delivery) RespondError

func (d Delivery) RespondError(ctx context.Context, err error, opts ...ResponseOption) error

type Destination

type Destination struct {
	Kind DestinationKind `json:"kind"`
	Name string          `json:"name"`
}

type DestinationKind

type DestinationKind string
const (
	DestinationTopic   DestinationKind = "topic"
	DestinationQueue   DestinationKind = "queue"
	DestinationStream  DestinationKind = "stream"
	DestinationDLQ     DestinationKind = "dlq"
	DestinationArchive DestinationKind = "archive"
)

type DistributedBroker

type DistributedBroker struct {
	*Broker
	// contains filtered or unexported fields
}

func NewDistributed

func NewDistributed(cfg Config, distCfg DistributedConfig) (*DistributedBroker, error)

func (*DistributedBroker) AddNode

func (db *DistributedBroker) AddNode(addr string) error

func (*DistributedBroker) AddRaftNode

func (db *DistributedBroker) AddRaftNode(ctx context.Context, addr string) (uint64, error)

AddRaftNode commits a voting-member addition and returns the ID that the joining process must use with JoinExisting enabled.

func (*DistributedBroker) CanServeReads

func (db *DistributedBroker) CanServeReads() bool

func (*DistributedBroker) ClusterStats

func (db *DistributedBroker) ClusterStats() map[string]any

func (*DistributedBroker) DegradedMode

func (db *DistributedBroker) DegradedMode() bool

func (*DistributedBroker) HealthCheck

func (db *DistributedBroker) HealthCheck() map[string]any

func (*DistributedBroker) IsLeader

func (db *DistributedBroker) IsLeader() bool

func (*DistributedBroker) Leader

func (db *DistributedBroker) Leader() string

func (*DistributedBroker) RaftState

func (db *DistributedBroker) RaftState() string

func (*DistributedBroker) RemoveNode

func (db *DistributedBroker) RemoveNode(id string) error

func (*DistributedBroker) Start

func (db *DistributedBroker) Start(ctx context.Context) error

func (*DistributedBroker) Stop

func (db *DistributedBroker) Stop(ctx context.Context) error

func (*DistributedBroker) SubmitToRaft

func (db *DistributedBroker) SubmitToRaft(command []byte) (uint64, error)

type DistributedConfig

type DistributedConfig struct {
	Peers      []string
	ListenAddr string
	WALDir     string
	TLSConfig  *tls.Config
	Cluster    *cluster.Cluster
	// AllowExperimentalCustomRaft explicitly enables the legacy custom
	// consensus path. It is unsafe for production and will be removed when the
	// etcd/raft controller and partition groups replace it.
	AllowExperimentalCustomRaft bool

	// UseEtcdRaft enables the audited production etcd/raft consensus engine.
	UseEtcdRaft            bool
	RaftNodeID             uint64
	RaftPeers              map[uint64]string
	ReplicationFactor      int
	ControllerAddrs        []string
	SnapshotEntries        uint64
	SnapshotCatchUpEntries uint64
	// AllowStaleReads permits follower-local reads. It is false by default;
	// callers requiring linearizable reads must use the leader.
	AllowStaleReads bool
	// JoinExisting starts a fresh node without bootstrapping a separate Raft
	// cluster. Add the node through AddRaftNode first and use its returned ID.
	JoinExisting bool

	SubmitTimeout  time.Duration
	ForwardTimeout time.Duration

	OnLeaderChange func(leader string)
	OnStateChange  func(state string)
	OnNodeJoin     func(nodeID string)
	OnNodeLeave    func(nodeID string)
}

type DistributedOpsServer

type DistributedOpsServer struct {
	OpsServer
	// contains filtered or unexported fields
}

func NewDistributedOpsServer

func NewDistributedOpsServer(cfg OpsConfig, dist *DistributedBroker) *DistributedOpsServer

func (*DistributedOpsServer) Start

func (s *DistributedOpsServer) Start() error

type DuplicateProducerSequenceError

type DuplicateProducerSequenceError struct {
	ProducerID string
	Epoch      int32
	Sequence   uint64
	MessageID  string
}

DuplicateProducerSequenceError identifies the message already committed for the producer's current sequence. Stores return this typed error so publisher retries can be acknowledged without performing a second append.

func (*DuplicateProducerSequenceError) Error

func (*DuplicateProducerSequenceError) Unwrap

type DurabilityScope

type DurabilityScope string

DurabilityScope states where an acknowledged record was made durable.

const (
	DurabilityMemory      DurabilityScope = "memory"
	DurabilityLocalFsync  DurabilityScope = "local_fsync"
	DurabilityQuorumFsync DurabilityScope = "quorum_fsync"
)

type DurableOutbox

type DurableOutbox struct {
	// contains filtered or unexported fields
}

DurableOutbox is a legacy in-memory dispatch worker. Its entries do not survive process restart and are not atomic with an application database transaction. Deprecated: use contrib/sqlitestore.NewOutbox for a transactional SQL outbox.

func NewDurableOutbox

func NewDurableOutbox(cfg DurableOutboxConfig) (*DurableOutbox, error)

NewDurableOutbox initializes the legacy in-memory dispatch worker.

func (*DurableOutbox) Enqueue

func (o *DurableOutbox) Enqueue(ctx context.Context, msg Message, dests []Destination) (string, error)

Enqueue stores a message in memory for background dispatch.

func (*DurableOutbox) Flush

func (o *DurableOutbox) Flush(ctx context.Context) error

Flush synchronously dispatches up to BatchSize entries and returns failures.

func (*DurableOutbox) GetEntry

func (o *DurableOutbox) GetEntry(id string) (*DurableOutboxEntry, bool)

GetEntry returns a copy of an outbox entry by ID.

func (*DurableOutbox) PendingCount

func (o *DurableOutbox) PendingCount() int

PendingCount returns the number of outbox entries currently waiting to be published.

func (*DurableOutbox) Start

func (o *DurableOutbox) Start() error

Start launches the background dispatch worker loop.

func (*DurableOutbox) Stop

func (o *DurableOutbox) Stop() error

Stop cleanly terminates the outbox worker.

type DurableOutboxConfig

type DurableOutboxConfig struct {
	Broker          *Broker
	PollInterval    time.Duration
	BatchSize       int
	MaxRetries      int
	DeadLetterQueue string
	DispatchTimeout time.Duration
}

DurableOutboxConfig configures the legacy in-memory dispatch worker.

type DurableOutboxEntry

type DurableOutboxEntry struct {
	ID           string              `json:"id"`
	Message      Message             `json:"message"`
	Destinations []Destination       `json:"destinations"`
	Status       DurableOutboxStatus `json:"status"`
	Attempts     int                 `json:"attempts"`
	MaxAttempts  int                 `json:"max_attempts"`
	LastError    string              `json:"last_error,omitempty"`
	CreatedAt    time.Time           `json:"created_at"`
	UpdatedAt    time.Time           `json:"updated_at"`
	PublishedAt  *time.Time          `json:"published_at,omitempty"`
}

DurableOutboxEntry represents a durable message pending or completed dispatch.

type DurableOutboxStatus

type DurableOutboxStatus string

DurableOutboxStatus tracks the dispatch lifecycle of an outbox message.

const (
	OutboxPending    DurableOutboxStatus = "pending"
	OutboxInFlight   DurableOutboxStatus = "in_flight"
	OutboxPublished  DurableOutboxStatus = "published"
	OutboxFailed     DurableOutboxStatus = "failed"
	OutboxDeadLetter DurableOutboxStatus = "dead_lettered"
)

type DynamicConfig

type DynamicConfig struct {
	Routes     []Route             `json:"routes,omitempty"`
	RateLimits map[string]int      `json:"rate_limits,omitempty"`
	ACLTokens  map[string][]string `json:"acl_tokens,omitempty"`
	Metadata   map[string]string   `json:"metadata,omitempty"`
}

DynamicConfig represents runtime reloadable configuration properties.

func (*DynamicConfig) Validate

func (dc *DynamicConfig) Validate() error

Validate verifies that the dynamic configuration is valid before applying.

type ExactlyOnceConfig

type ExactlyOnceConfig struct {
	// Enabled activates the legacy helpers. Default: false.
	Enabled bool `json:"enabled"`
	// TransactionalOutbox enables an in-memory publish retry buffer. It is not
	// atomic with an application database and is not durable.
	TransactionalOutbox bool `json:"transactional_outbox,omitempty"`
	// DeduplicationWindow is the window for deduplicating messages. Default: 5m.
	DeduplicationWindow time.Duration `json:"deduplication_window,omitempty"`
	// ConsumerCommitMode determines how consumer offsets are committed.
	ConsumerCommitMode ConsumerCommitMode `json:"consumer_commit_mode,omitempty"`
}

ExactlyOnceConfig configures legacy deduplication and offset behavior. Deprecated: this does not provide universal exactly-once delivery. Use explicit deduplication windows and durable stream transactions when those APIs become available.

type ExpressionFilter

type ExpressionFilter struct {
	// contains filtered or unexported fields
}

ExpressionFilter evaluates a parsed filter expression.

func ParseFilterExpression

func ParseFilterExpression(raw string) (*ExpressionFilter, error)

ParseFilterExpression parses a filter expression into a MessageFilter. Supported syntax:

  • headers["key"] == "val" / headers["key"] != "val"
  • headers.has("key")
  • type == "val" / type != "val"
  • topic == "val" / topic != "val"
  • priority > N / priority >= N / priority < N / priority <= N / priority == N
  • Conjunctions: &&, AND, ||, OR

func (*ExpressionFilter) Match

func (ef *ExpressionFilter) Match(msg Message) bool

Match evaluates the expression against the message.

type FederationConfig

type FederationConfig struct {
	// Upstream is the URL of the upstream broker to pull messages from.
	Upstream string `json:"upstream"`
	// Downstream is the URL to push messages to (for shovel).
	Downstream string `json:"downstream,omitempty"`
	// Queues is the list of queue names to federate.
	Queues []string `json:"queues,omitempty"`
	// Topics is the list of topic patterns to federate.
	Topics []string `json:"topics,omitempty"`
	// PollInterval is how often to poll upstream. Default: 1s.
	PollInterval time.Duration `json:"poll_interval,omitempty"`
	// BatchSize is the number of messages to pull per poll. Default: 100.
	BatchSize int `json:"batch_size,omitempty"`
	// MaxInFlight limits concurrent unacked federated messages. Default: 1000.
	MaxInFlight int `json:"max_inflight,omitempty"`
	// ReconnectDelay is the delay between reconnection attempts. Default: 5s.
	ReconnectDelay time.Duration `json:"reconnect_delay,omitempty"`
	// Filter is an optional message filter.
	Filter *FederationFilter `json:"filter,omitempty"`
	// Transform is an optional message transform.
	Transform *FederationTransform `json:"transform,omitempty"`
}

FederationConfig configures federation between broker instances.

type FederationFilter

type FederationFilter struct {
	Types       []string          `json:"types,omitempty"`
	Tenants     []string          `json:"tenants,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
	MinPriority int               `json:"min_priority,omitempty"`
}

FederationFilter filters messages during federation.

type FederationLink struct {
	ID        string           `json:"id"`
	Config    FederationConfig `json:"config"`
	State     string           `json:"state"`
	Messages  uint64           `json:"messages"`
	Errors    uint64           `json:"errors"`
	StartedAt time.Time        `json:"started_at"`
	// contains filtered or unexported fields
}

FederationLink represents a single federation link.

type FederationManager

type FederationManager struct {
	// contains filtered or unexported fields
}

FederationManager manages federation links.

func NewFederationManager

func NewFederationManager(b *Broker) *FederationManager

NewFederationManager creates a new federation manager.

AddLink adds a federation link.

func (fm *FederationManager) ListLinks() []*FederationLink

ListLinks returns all federation links.

func (fm *FederationManager) RemoveLink(id string)

RemoveLink stops and removes a federation link.

func (*FederationManager) Stop

func (fm *FederationManager) Stop()

Stop halts all federation links.

type FederationTransform

type FederationTransform struct {
	// AddHeaders adds headers to federated messages.
	AddHeaders map[string]string `json:"add_headers,omitempty"`
	// RemoveHeaders removes headers from federated messages.
	RemoveHeaders []string `json:"remove_headers,omitempty"`
	// PrefixTopic adds a prefix to the topic.
	PrefixTopic string `json:"prefix_topic,omitempty"`
	// RewriteQueue rewrites the target queue.
	RewriteQueue string `json:"rewrite_queue,omitempty"`
}

FederationTransform transforms messages during federation.

type FileWALStore

type FileWALStore struct {
	*MemoryStore
	// contains filtered or unexported fields
}

FileWALStore is a durable local store that appends every mutation to JSONL and rebuilds the in-memory indexes on startup. It is intended for embedded and single-node standalone deployments. Encryption is optional — set EncryptionKey in the config to enable AES-GCM encryption of all WAL records at rest.

func NewFileWALStore

func NewFileWALStore(dir string) (*FileWALStore, error)

func NewFileWALStoreWithConfig

func NewFileWALStoreWithConfig(cfg FileWALStoreConfig) (*FileWALStore, error)

NewFileWALStoreWithConfig creates a FileWALStore with optional encryption. If EncryptionKey is nil or empty, WAL records are stored in plaintext. If EncryptionKey is provided (16, 24, or 32 bytes), all records are AES-GCM encrypted.

func (*FileWALStore) Ack

func (s *FileWALStore) Ack(ctx context.Context, req AckRequest) error

func (*FileWALStore) AckBatch

func (s *FileWALStore) AckBatch(ctx context.Context, reqs []AckRequest) []error

func (*FileWALStore) Append

func (s *FileWALStore) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

func (*FileWALStore) AppendAtomic

func (s *FileWALStore) AppendAtomic(ctx context.Context, entries []AppendEntry) ([]Message, error)

func (*FileWALStore) AppendAtomicMinimal

func (s *FileWALStore) AppendAtomicMinimal(ctx context.Context, entries []AppendEntry) error

func (*FileWALStore) AppendAtomicOwned

func (s *FileWALStore) AppendAtomicOwned(ctx context.Context, entries []AppendEntry) error

func (*FileWALStore) Close

func (s *FileWALStore) Close() error

func (*FileWALStore) CommitOffset

func (s *FileWALStore) CommitOffset(ctx context.Context, commit OffsetCommit) error

func (*FileWALStore) CommitStreamTransaction

func (s *FileWALStore) CommitStreamTransaction(ctx context.Context, tx StreamTransaction) ([]Message, error)

func (*FileWALStore) ConfirmationLevel

func (*FileWALStore) ConfirmationLevel() ConfirmLevel

func (*FileWALStore) DeclareQueue

func (s *FileWALStore) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*FileWALStore) DeclareStream

func (s *FileWALStore) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*FileWALStore) DeclareTopic

func (s *FileWALStore) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*FileWALStore) ExtendLease

func (s *FileWALStore) ExtendLease(ctx context.Context, req LeaseRequest) error

func (*FileWALStore) Lease

func (s *FileWALStore) Lease(ctx context.Context, req LeaseRequest) ([]Message, error)

func (*FileWALStore) Move

func (s *FileWALStore) Move(ctx context.Context, req MoveRequest) (MoveResult, error)

func (*FileWALStore) Nack

func (s *FileWALStore) Nack(ctx context.Context, req NackRequest) error

func (*FileWALStore) PauseQueue

func (s *FileWALStore) PauseQueue(ctx context.Context, name string) error

func (*FileWALStore) PurgeQueue

func (s *FileWALStore) PurgeQueue(ctx context.Context, name string) (int, error)

func (*FileWALStore) ResumeQueue

func (s *FileWALStore) ResumeQueue(ctx context.Context, name string) error

func (*FileWALStore) StoreHealth

func (s *FileWALStore) StoreHealth() error

func (*FileWALStore) SweepLeases

func (s *FileWALStore) SweepLeases(ctx context.Context, now time.Time) (int, error)

SweepLeases implements WAL-first ordering: compute the deterministic expiry set without mutating, persist it, then apply it. Without this override the promoted MemoryStore.SweepLeases would mutate memory only and every un-lease would be lost on crash.

func (*FileWALStore) Update

func (s *FileWALStore) Update(ctx context.Context, msg Message) error

func (*FileWALStore) UpdateBatch

func (s *FileWALStore) UpdateBatch(ctx context.Context, messages []Message) []error

type FileWALStoreConfig

type FileWALStoreConfig struct {
	Dir           string
	EncryptionKey []byte
	KeyName       string
}

FileWALStoreConfig configures the FileWALStore.

type FrameCodec

type FrameCodec interface {
	EncodeMessage(dst []byte, msg Message) ([]byte, error)
	DecodeMessage(frame []byte, msg *Message) error
}

FrameCodec is the unified interface for encoding/decoding messages to binary frames. Both BinaryMessageCodec (FWB1) and CompactMessageCodec (FWB2) implement this interface.

func NewFrameCodec

func NewFrameCodec(cfg FrameCodecConfig) FrameCodec

NewFrameCodec creates a FrameCodec based on the config.

type FrameCodecConfig

type FrameCodecConfig struct {
	Type              CodecType
	CompressThreshold int
	MaxFrameSize      int
	SigningKey        []byte
	EncryptionKey     []byte
}

FrameCodecConfig holds configuration for creating a FrameCodec.

type FrameFlags

type FrameFlags uint16
const (
	FrameFlagCompressed FrameFlags = 1 << iota
	FrameFlagEncrypted
	FrameFlagSigned
	FrameFlagHasHeaders
	FrameFlagHasMetadata
	FrameFlagTask
	FrameFlagRequest
	FrameFlagResponse
	FrameFlagStreamEnd
)

type FrameHeader

type FrameHeader struct {
	Version    byte
	Type       FrameType
	Flags      FrameFlags
	HeaderLen  uint64
	PayloadLen uint64
	CRC32C     uint32
	HMACLen    uint64
}

func (FrameHeader) String

func (h FrameHeader) String() string

type FrameType

type FrameType byte
const (
	FrameMessageAppend FrameType = 1
	FrameMessageAck    FrameType = 2
	FrameMessageNack   FrameType = 3
	FrameMessageLease  FrameType = 4
	FrameMessageExtend FrameType = 5
	FrameMessageMove   FrameType = 6
	FrameMessageCopy   FrameType = 7
	FrameMessageDLQ    FrameType = 8
	FrameOffsetCommit  FrameType = 9
	FrameTaskProgress  FrameType = 10
	FrameTaskResult    FrameType = 11
	FrameConsumerEvent FrameType = 12
	FrameHeartbeat     FrameType = 13
	FrameMessage       FrameType = 100
)

type GRPCConfig

type GRPCConfig struct {
	// ListenAddr is the TCP address. Default: ":50051".
	ListenAddr string
	// MaxConnections limits concurrent connections. Default: 1000.
	MaxConnections int
	// MaxMessageSize limits incoming message size. Default: 4MB.
	MaxMessageSize int
	// KeepAlive is the keep-alive interval. Default: 60s.
	KeepAlive time.Duration
	// TLSCertFile is the path to the TLS certificate file.
	TLSCertFile string
	// TLSKeyFile is the path to the TLS private key file.
	TLSKeyFile string
	// ClientCAFile is the path to the CA certificate for client verification (mTLS).
	ClientCAFile string
	// RequireClientCert requires client certificate verification (mTLS).
	RequireClientCert bool
	// BrokerToken is the bearer token for authentication.
	// If set, every request must include this token.
	BrokerToken string
}

GRPCConfig configures the legacy native JSON/TCP RPC server. Deprecated: use NativeRPCConfig. This transport is not gRPC. Uses a custom protocol over TCP for environments without gRPC dependencies.

type GRPCServer

type GRPCServer struct {
	// contains filtered or unexported fields
}

GRPCServer provides the legacy native JSON/TCP transport. Deprecated: use NativeRPCServer. This transport is not gRPC. Uses length-prefixed JSON frames over TCP.

func NewGRPCServer

func NewGRPCServer(b *Broker, cfg GRPCConfig) *GRPCServer

NewGRPCServer creates the legacy native JSON/TCP server.

func (*GRPCServer) ListenAndServe

func (gs *GRPCServer) ListenAndServe() error

ListenAndServe starts the legacy native JSON/TCP server.

func (*GRPCServer) Stop

func (gs *GRPCServer) Stop()

Stop shuts down the server.

type GRPCV1Config

type GRPCV1Config struct {
	ListenAddr     string
	TLSConfig      *tls.Config
	ACL            *ACL
	InsecureDev    bool
	MaxMessageSize int
}

type GRPCV1Server

type GRPCV1Server struct {
	brokerv1.UnimplementedBrokerServiceServer
	// contains filtered or unexported fields
}

GRPCV1Server is the protobuf/HTTP2 gRPC data plane.

func NewGRPCV1Server

func NewGRPCV1Server(b *Broker, cfg GRPCV1Config) (*GRPCV1Server, error)

func (*GRPCV1Server) Ack

func (*GRPCV1Server) CommitOffset

func (*GRPCV1Server) Health

func (*GRPCV1Server) ListenAndServe

func (s *GRPCV1Server) ListenAndServe() error

func (*GRPCV1Server) Nack

func (*GRPCV1Server) Poll

func (*GRPCV1Server) Publish

func (*GRPCV1Server) ReadStream

func (*GRPCV1Server) Serve

func (s *GRPCV1Server) Serve(ln net.Listener) error

func (*GRPCV1Server) Stop

func (s *GRPCV1Server) Stop(ctx context.Context) error

type GroupAssignment

type GroupAssignment struct {
	ConsumerID string `json:"consumer_id"`
	Group      string `json:"group"`
	Partitions []int  `json:"partitions,omitempty"`
	HashSlot   uint32 `json:"hash_slot,omitempty"`
	TotalSlots int    `json:"total_slots,omitempty"`
	Weight     int    `json:"weight,omitempty"`
}

type GroupRebalancer

type GroupRebalancer struct {
	// contains filtered or unexported fields
}

func NewGroupRebalancer

func NewGroupRebalancer() *GroupRebalancer

func NewGroupRebalancerWithHooks

func NewGroupRebalancerWithHooks(hooks *RebalanceHooks) *GroupRebalancer

func (*GroupRebalancer) ConsumerAssignment

func (r *GroupRebalancer) ConsumerAssignment(consumerID, group string) *GroupAssignment

func (*GroupRebalancer) GetGroup

func (r *GroupRebalancer) GetGroup(group string) *GroupState

func (*GroupRebalancer) JoinGroup

func (r *GroupRebalancer) JoinGroup(consumerID, group string) *GroupState

func (*GroupRebalancer) JoinGroupWithWeight

func (r *GroupRebalancer) JoinGroupWithWeight(consumerID, group string, weight int) *GroupState

func (*GroupRebalancer) LeaveGroup

func (r *GroupRebalancer) LeaveGroup(consumerID, group string) *GroupState

func (*GroupRebalancer) ListGroups

func (r *GroupRebalancer) ListGroups() []*GroupState

func (*GroupRebalancer) ShouldLeaseForConsumer

func (r *GroupRebalancer) ShouldLeaseForConsumer(consumerID, group string, messageKey string) bool

type GroupState

type GroupState struct {
	Name        string            `json:"name"`
	Members     []string          `json:"members"`
	Weights     map[string]int    `json:"weights,omitempty"`
	Assignments []GroupAssignment `json:"assignments"`
	Version     int               `json:"version"`
	UpdatedAt   time.Time         `json:"updated_at"`
}

type Handler

type Handler func(context.Context, Delivery) error

type HeaderMatchFilter

type HeaderMatchFilter struct {
	Required map[string]string
}

HeaderMatchFilter matches when all specified key/value pairs match message headers.

func (*HeaderMatchFilter) Match

func (f *HeaderMatchFilter) Match(msg Message) bool

Match evaluates whether the message contains all required headers.

type HealthCheck

type HealthCheck struct {
	Name   string `json:"name"`
	Status string `json:"status"` // "ok", "warn", "fail"
	Detail string `json:"detail,omitempty"`
}

type HealthStatus

type HealthStatus struct {
	Status  string        `json:"status"` // "healthy", "degraded", "unhealthy"
	State   BrokerState   `json:"state"`
	Mode    Mode          `json:"mode"`
	NodeID  string        `json:"node_id"`
	Leader  string        `json:"leader,omitempty"`
	Uptime  time.Duration `json:"uptime"`
	Store   StoreStats    `json:"store"`
	Version string        `json:"version"`
	Checks  []HealthCheck `json:"checks"`
}

type Hooks

type Hooks struct {
	OnInitializing func(context.Context, BrokerEvent)
	OnRecovering   func(context.Context, BrokerEvent)
	OnStarted      func(context.Context, BrokerEvent)
	OnReady        func(context.Context, BrokerEvent)
	OnDegraded     func(context.Context, BrokerEvent)
	OnPaused       func(context.Context, BrokerEvent)
	OnResumed      func(context.Context, BrokerEvent)
	OnDraining     func(context.Context, BrokerEvent)
	OnStopped      func(context.Context, BrokerEvent)
	OnFailed       func(context.Context, BrokerEvent)

	BeforePublish      func(context.Context, PublishEvent) error
	AfterPublish       func(context.Context, PublishEvent)
	OnPublishRejected  func(context.Context, PublishEvent)
	OnPublishConfirmed func(context.Context, PublishEvent)
	OnPublishFailed    func(context.Context, PublishEvent)

	BeforeRoute       func(context.Context, RoutingEvent) error
	AfterRoute        func(context.Context, RoutingEvent)
	OnRouteMiss       func(context.Context, RoutingEvent)
	OnRouteConflict   func(context.Context, RoutingEvent)
	OnMessageMoved    func(context.Context, MovementEvent)
	OnMessageCopied   func(context.Context, MovementEvent)
	OnMessageRerouted func(context.Context, MovementEvent)

	OnConsumerRegistered func(context.Context, ConsumerEvent)
	OnConsumerAssigned   func(context.Context, ConsumerEvent)
	OnConsumerRevoked    func(context.Context, ConsumerEvent)
	BeforeHandle         func(context.Context, MessageEvent) error
	AfterHandle          func(context.Context, MessageEvent)
	OnHandlerError       func(context.Context, MessageEvent)
	OnPanic              func(context.Context, MessageEvent)
	OnAck                func(context.Context, MessageEvent)
	OnNack               func(context.Context, MessageEvent)
	OnLeaseExtended      func(context.Context, MessageEvent)
	OnConsumerPaused     func(context.Context, ConsumerEvent)
	OnConsumerResumed    func(context.Context, ConsumerEvent)
	OnConsumerDraining   func(context.Context, ConsumerEvent)
	OnConsumerBanned     func(context.Context, ConsumerEvent)
	OnConsumerUnbanned   func(context.Context, ConsumerEvent)
	OnConsumerStopped    func(context.Context, ConsumerEvent)

	OnTaskCreated      func(context.Context, TaskEvent)
	OnTaskScheduled    func(context.Context, TaskEvent)
	OnTaskQueued       func(context.Context, TaskEvent)
	OnTaskStarted      func(context.Context, TaskEvent)
	OnTaskProgress     func(context.Context, TaskEvent)
	OnTaskSucceeded    func(context.Context, TaskEvent)
	OnTaskFailed       func(context.Context, TaskEvent)
	OnTaskRetrying     func(context.Context, TaskEvent)
	OnTaskCancelled    func(context.Context, TaskEvent)
	OnTaskTimedOut     func(context.Context, TaskEvent)
	OnTaskCompensating func(context.Context, TaskEvent)
	OnTaskCompensated  func(context.Context, TaskEvent)
	OnTaskArchived     func(context.Context, TaskEvent)

	BeforeAppend    func(context.Context, StorageEvent) error
	AfterAppend     func(context.Context, StorageEvent)
	OnCommit        func(context.Context, StorageEvent)
	OnRollback      func(context.Context, StorageEvent)
	OnFsyncSlow     func(context.Context, StorageEvent)
	OnCorruption    func(context.Context, StorageEvent)
	OnRecoveryStart func(context.Context, StorageEvent)
	OnRecoveryDone  func(context.Context, StorageEvent)

	OnRetryDecision  func(context.Context, RetryEvent)
	OnRetryScheduled func(context.Context, RetryEvent)
	OnRetryExhausted func(context.Context, RetryEvent)
	OnDeadLettered   func(context.Context, DLQEvent)
	OnDLQReplay      func(context.Context, DLQEvent)
	OnDLQPurge       func(context.Context, DLQEvent)
	OnDLQArchive     func(context.Context, DLQEvent)

	OnMaxRedeliveryExceeded func(context.Context, DLQEvent)
	OnRateLimited           func(context.Context, MessageEvent)
	OnCircuitOpen           func(context.Context, BrokerEvent)
	OnCircuitClosed         func(context.Context, BrokerEvent)
}

type InMemoryExporter

type InMemoryExporter struct {
	// contains filtered or unexported fields
}

InMemoryExporter stores trace spans in memory for debugging/testing.

func NewInMemoryExporter

func NewInMemoryExporter() *InMemoryExporter

func (*InMemoryExporter) ExportSpan

func (e *InMemoryExporter) ExportSpan(_ context.Context, span TraceSpan) error

func (*InMemoryExporter) Flush

func (e *InMemoryExporter) Flush(_ context.Context) error

func (*InMemoryExporter) Spans

func (e *InMemoryExporter) Spans() []TraceSpan

type IndexEntry

type IndexEntry struct {
	Seq    uint64 `json:"seq"`
	Offset int64  `json:"offset"`
	Time   int64  `json:"time"`
}

IndexEntry represents one sparse index checkpoint.

type IsolationLevel

type IsolationLevel string

IsolationLevel determines tenant isolation strategy.

const (
	// IsolationQueuePrefix isolates tenants by prefixing queue names.
	IsolationQueuePrefix IsolationLevel = "queue_prefix"
	// IsolationVHost isolates tenants like AMQP vhosts (logical namespace).
	IsolationVHost IsolationLevel = "vhost"
	// IsolationShared uses shared queues but filters by tenant header.
	IsolationShared IsolationLevel = "shared"
)

type JSONCodec

type JSONCodec struct{}

func (JSONCodec) ContentType

func (JSONCodec) ContentType() string

func (JSONCodec) Marshal

func (JSONCodec) Marshal(v any) ([]byte, error)

func (JSONCodec) Unmarshal

func (JSONCodec) Unmarshal(b []byte, v any) error

type LagAlert

type LagAlert struct {
	Target        string        `json:"target"` // Stream or Queue name
	ConsumerGroup string        `json:"consumer_group,omitempty"`
	CurrentLag    uint64        `json:"current_lag"`
	Threshold     uint64        `json:"threshold"`
	Level         LagAlertLevel `json:"level"`
	Timestamp     time.Time     `json:"timestamp"`
}

LagAlert represents an alert fired when consumer lag exceeds a threshold.

type LagAlertConfig

type LagAlertConfig struct {
	DefaultWarning   uint64
	DefaultCritical  uint64
	StreamThresholds map[string]LagThreshold
	QueueThresholds  map[string]LagThreshold
	CheckInterval    time.Duration
	OnAlert          func(alert LagAlert)
}

LagAlertConfig configures the LagMonitor.

type LagAlertLevel

type LagAlertLevel string
const (
	LagAlertWarning  LagAlertLevel = "warning"
	LagAlertCritical LagAlertLevel = "critical"
)

type LagMonitor

type LagMonitor struct {
	// contains filtered or unexported fields
}

LagMonitor inspects consumer offsets and queue depths and fires alerts on threshold violations.

func NewLagMonitor

func NewLagMonitor(b *Broker, cfg LagAlertConfig) *LagMonitor

NewLagMonitor creates a new consumer lag monitor.

func (*LagMonitor) ActiveAlerts

func (lm *LagMonitor) ActiveAlerts() []LagAlert

ActiveAlerts returns the latest set of active alerts.

func (*LagMonitor) CheckLag

func (lm *LagMonitor) CheckLag(ctx context.Context) ([]LagAlert, error)

CheckLag inspects the current broker state and evaluates all configured lag thresholds.

func (*LagMonitor) Start

func (lm *LagMonitor) Start(ctx context.Context)

Start launches the background monitoring loop.

func (*LagMonitor) Stop

func (lm *LagMonitor) Stop()

Stop halts the lag monitor.

type LagThreshold

type LagThreshold struct {
	Warning  uint64 `json:"warning"`
	Critical uint64 `json:"critical"`
}

LagThreshold defines warning and critical thresholds for a target.

type LeaseRequest

type LeaseRequest struct {
	Queue             string
	ConsumerID        string
	ConsumerGroup     string
	Limit             int
	VisibilityTimeout time.Duration
	LeaseToken        string
	MessageID         string
	TenantID          string `json:"tenant_id,omitempty"`
	// Accept is evaluated before a message is leased. It is process-local and
	// intentionally excluded from wire/WAL encoding; embedded dispatch uses it
	// to ensure a consumer never leases work assigned to another consumer.
	Accept func(Message) bool `json:"-"`
}

type ListenerConfig

type ListenerConfig struct {
	HTTP      string `json:"http,omitempty"`
	NativeRPC string `json:"native_rpc,omitempty"`
	Native    string `json:"native_stream,omitempty"`
	AMQP      string `json:"amqp,omitempty"`
	MQTT      string `json:"mqtt,omitempty"`
	GRPC      string `json:"grpc,omitempty"`
	WebSocket string `json:"websocket,omitempty"`
	SSE       string `json:"sse,omitempty"`
}

ListenerConfig names all supported listener addresses. Empty addresses disable the corresponding listener.

type MQTTConfig

type MQTTConfig struct {
	// ListenAddr is the TCP address to listen on. Default: ":1883".
	// For TLS, use ":8883" or set TLSCertFile/TLSKeyFile.
	ListenAddr string
	// MaxConnections limits concurrent MQTT connections. Default: 1000.
	MaxConnections int
	// MaxInflight limits in-flight QoS 1/2 messages per client. Default: 20.
	MaxInflight int
	// KeepAlive is the max keep-alive seconds. Default: 60.
	KeepAlive uint16
	// MaxPacketSize is the max MQTT packet size. Default: 1MB.
	MaxPacketSize int
	// RequireAuth requires username/password authentication. Default: false.
	RequireAuth bool
	// Username/Password for basic auth.
	Username string
	Password string
	// TLSCertFile is the path to the TLS certificate file.
	TLSCertFile string
	// TLSKeyFile is the path to the TLS private key file.
	TLSKeyFile string
	// ClientCAFile is the path to the CA certificate for client verification (mTLS).
	ClientCAFile string
	// RequireClientCert requires client certificate verification (mTLS).
	RequireClientCert bool
	// BrokerToken is the bearer token for MQTT CONNECT authentication.
	// If set, the MQTT password field is validated against this token.
	BrokerToken string
	// ACL provides shared authentication and admission control across protocols.
	ACL *ACL
}

MQTTConfig configures the MQTT protocol server.

type MQTTServer

type MQTTServer struct {
	// contains filtered or unexported fields
}

func NewMQTTServer

func NewMQTTServer(b *Broker, cfg MQTTConfig) *MQTTServer

NewMQTTServer creates a new MQTT server.

func (*MQTTServer) ListenAndServe

func (ms *MQTTServer) ListenAndServe() error

ListenAndServe starts the MQTT server.

func (*MQTTServer) Stop

func (ms *MQTTServer) Stop()

Stop shuts down the MQTT server.

type MQTTSession

type MQTTSession struct {
	ClientID      string
	Subscriptions map[string]uint8
	UpdatedAt     time.Time
}

MQTTServer is a lightweight MQTT 3.1.1 server backed by the broker.

type MemoryQueueSnapshot

type MemoryQueueSnapshot struct {
	Config      QueueConfig `json:"config"`
	IDs         []string    `json:"ids"`
	State       QueueState  `json:"state"`
	Head        int         `json:"head,omitempty"`
	Depth       int         `json:"depth,omitempty"`
	HasPriority bool        `json:"has_priority,omitempty"`
}

MemoryQueueSnapshot captures queue configuration, state, and ordered IDs for durable snapshot stores. It is intentionally exported so contrib stores can persist/recover the default in-memory data-plane without reaching into MemoryStore internals.

type MemorySchemaRegistry

type MemorySchemaRegistry struct {
	// contains filtered or unexported fields
}

func NewMemorySchemaRegistry

func NewMemorySchemaRegistry(defs ...SchemaDefinition) *MemorySchemaRegistry

func (*MemorySchemaRegistry) CheckCompatibility

func (r *MemorySchemaRegistry) CheckCompatibility(name, newVersion, existingVersion string) SchemaCompatibility

CheckCompatibility checks if a new schema version is compatible with an existing version.

func (*MemorySchemaRegistry) DeprecateSchema

func (r *MemorySchemaRegistry) DeprecateSchema(name, version string) error

DeprecateSchema marks a schema version as deprecated.

func (*MemorySchemaRegistry) GetSchema

func (r *MemorySchemaRegistry) GetSchema(name, version string) (SchemaDefinition, bool)

GetSchema returns the schema definition for the given name and version.

func (*MemorySchemaRegistry) LatestVersion

func (r *MemorySchemaRegistry) LatestVersion(name string) (string, bool)

LatestVersion returns the latest version for a schema name.

func (*MemorySchemaRegistry) ListVersions

func (r *MemorySchemaRegistry) ListVersions(name string) []SchemaDefinition

ListVersions returns all registered versions for a schema name.

func (*MemorySchemaRegistry) Register

Register adds or replaces a schema version. It is the unrestricted setup form; use RegisterContext when the caller is an authenticated principal.

func (*MemorySchemaRegistry) RegisterContext

func (r *MemorySchemaRegistry) RegisterContext(ctx context.Context, d SchemaDefinition) error

RegisterContext adds or replaces a schema version. Schemas are shared infrastructure, so tenant-scoped credentials may read but not mutate them, matching the queue/topic/stream declaration rules.

func (*MemorySchemaRegistry) Validate

func (r *MemorySchemaRegistry) Validate(ctx context.Context, msg Message) error

type MemoryStateStore

type MemoryStateStore struct {
	// contains filtered or unexported fields
}

MemoryStateStore is the default state store. It is concurrency-safe and has no external dependencies. Use contrib/sqlitestore for persistent state.

func NewMemoryStateStore

func NewMemoryStateStore() *MemoryStateStore

func (*MemoryStateStore) AddConsumerEvent

func (s *MemoryStateStore) AddConsumerEvent(ctx context.Context, id string, n Notification) error

func (*MemoryStateStore) Close

func (s *MemoryStateStore) Close() error

func (*MemoryStateStore) ConsumerEvents

func (s *MemoryStateStore) ConsumerEvents(ctx context.Context, id, after string, limit int) ([]Notification, error)

func (*MemoryStateStore) DeleteConsumer

func (s *MemoryStateStore) DeleteConsumer(ctx context.Context, id string) error

func (*MemoryStateStore) DeleteTask

func (s *MemoryStateStore) DeleteTask(ctx context.Context, id string) error

func (*MemoryStateStore) GetBrokerState

func (s *MemoryStateStore) GetBrokerState(ctx context.Context, name string) (BrokerStateRecord, bool, error)

func (*MemoryStateStore) GetConsumer

func (s *MemoryStateStore) GetConsumer(ctx context.Context, id string) (ConsumerInfo, bool, error)

func (*MemoryStateStore) GetPublisherRecord

func (s *MemoryStateStore) GetPublisherRecord(ctx context.Context, id string) (PublisherRecord, bool, error)

func (*MemoryStateStore) GetTask

func (s *MemoryStateStore) GetTask(ctx context.Context, id string) (TaskInfo, bool, error)

func (*MemoryStateStore) ListConsumers

func (s *MemoryStateStore) ListConsumers(ctx context.Context) ([]ConsumerInfo, error)

func (*MemoryStateStore) ListPublisherRecords

func (s *MemoryStateStore) ListPublisherRecords(ctx context.Context, limit int) ([]PublisherRecord, error)

func (*MemoryStateStore) ListTasks

func (s *MemoryStateStore) ListTasks(ctx context.Context, st TaskStatus, limit int) ([]TaskInfo, error)

func (*MemoryStateStore) PutBrokerState

func (s *MemoryStateStore) PutBrokerState(ctx context.Context, rec BrokerStateRecord) error

func (*MemoryStateStore) PutConsumer

func (s *MemoryStateStore) PutConsumer(ctx context.Context, c ConsumerInfo) error

func (*MemoryStateStore) PutPublisherRecord

func (s *MemoryStateStore) PutPublisherRecord(ctx context.Context, rec PublisherRecord) error

func (*MemoryStateStore) PutTask

func (s *MemoryStateStore) PutTask(ctx context.Context, t TaskInfo) error

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

func NewMemoryStore

func NewMemoryStore() *MemoryStore

func (*MemoryStore) Ack

func (s *MemoryStore) Ack(ctx context.Context, req AckRequest) error

func (*MemoryStore) AckBatch

func (s *MemoryStore) AckBatch(ctx context.Context, reqs []AckRequest) []error

func (*MemoryStore) Append

func (s *MemoryStore) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

Append stores a message and returns one entry per destination.

The returned Messages share their Payload, Headers and Metadata with the stored message; only the struct fields differ. Treat those three as read-only. Use Get for a deep copy when the caller intends to modify them.

func (*MemoryStore) AppendAtomic

func (s *MemoryStore) AppendAtomic(ctx context.Context, entries []AppendEntry) ([]Message, error)

func (*MemoryStore) AppendAtomicMinimal

func (s *MemoryStore) AppendAtomicMinimal(ctx context.Context, entries []AppendEntry) error

func (*MemoryStore) AppendAtomicOwned

func (s *MemoryStore) AppendAtomicOwned(ctx context.Context, entries []AppendEntry) error

func (*MemoryStore) Cleanup

func (s *MemoryStore) Cleanup(maxHistoryPerMessage int)

Cleanup removes expired dedup entries, stale idempotency keys, and truncates history slices to prevent unbounded memory growth. Should be called periodically.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

func (*MemoryStore) ColdMessages

func (s *MemoryStore) ColdMessages() int

ColdMessages returns how many messages are currently held in compact form.

func (*MemoryStore) CommitOffset

func (s *MemoryStore) CommitOffset(ctx context.Context, commit OffsetCommit) error

func (*MemoryStore) CommitStreamTransaction

func (s *MemoryStore) CommitStreamTransaction(ctx context.Context, tx StreamTransaction) ([]Message, error)

func (*MemoryStore) CompactBacklogEnabled

func (s *MemoryStore) CompactBacklogEnabled() bool

CompactBacklogEnabled reports whether new queue messages are stored compactly.

func (*MemoryStore) ConfirmationLevel

func (*MemoryStore) ConfirmationLevel() ConfirmLevel

func (*MemoryStore) ConsumerOffset

func (s *MemoryStore) ConsumerOffset(ctx context.Context, commit OffsetCommit) (uint64, error)

func (*MemoryStore) DeclareQueue

func (s *MemoryStore) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*MemoryStore) DeclareStream

func (s *MemoryStore) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*MemoryStore) DeclareTopic

func (s *MemoryStore) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*MemoryStore) ExtendLease

func (s *MemoryStore) ExtendLease(ctx context.Context, req LeaseRequest) error

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, id string) (Message, bool, error)

func (*MemoryStore) History

func (s *MemoryStore) History(ctx context.Context, id string) ([]MessageHistory, error)

func (*MemoryStore) Lease

func (s *MemoryStore) Lease(ctx context.Context, req LeaseRequest) ([]Message, error)

Lease leases up to req.Limit messages.

The returned Messages share their Payload, Headers and Metadata with the stored message; only the struct fields differ. Treat those three as read-only. Use Get for a deep copy when the caller intends to modify them.

func (*MemoryStore) ListDLQ

func (s *MemoryStore) ListDLQ(ctx context.Context, name string, limit int) ([]Message, error)

func (*MemoryStore) ListQueue

func (s *MemoryStore) ListQueue(ctx context.Context, name string, limit int) ([]Message, error)

func (*MemoryStore) ListTopic

func (s *MemoryStore) ListTopic(ctx context.Context, name string, limit int) ([]Message, error)

ListTopic returns the retained messages of a topic in publish order.

Topics previously had no read path at all: ListQueue is queue-only and there was no topic equivalent, so a message published to a topic could not be read back, replayed or backfilled through the API, and topic retention grew unbounded with nothing able to consume it. Publishing to a topic is therefore not the same as a retained log, and callers needing replay should read a stream.

func (*MemoryStore) Move

func (s *MemoryStore) Move(ctx context.Context, req MoveRequest) (MoveResult, error)

func (*MemoryStore) Nack

func (s *MemoryStore) Nack(ctx context.Context, req NackRequest) error

func (*MemoryStore) PauseQueue

func (s *MemoryStore) PauseQueue(ctx context.Context, name string) error

func (*MemoryStore) PurgeQueue

func (s *MemoryStore) PurgeQueue(ctx context.Context, name string) (int, error)

func (*MemoryStore) QueueReady

func (s *MemoryStore) QueueReady(name string) <-chan struct{}

queueExists reports whether a queue is currently declared. Durable stores use it to validate before appending a control-plane WAL record, so a typo'd queue name cannot leave a record that fails on replay. QueueReady returns a channel that receives when the named queue may have leasable work, closing the poll-interval floor on pickup latency.

The send is coalescing and never blocks, so a publisher pays one non-blocking channel operation. The signal is advisory: a waiter must re-read the store, and a nil channel means the store does not support it, in which case the caller falls back to polling. Callers must hold s.mu.

func (*MemoryStore) ReadStream

func (s *MemoryStore) ReadStream(ctx context.Context, req StreamReadRequest) ([]Message, error)

func (*MemoryStore) ReadTopic

func (s *MemoryStore) ReadTopic(ctx context.Context, name, afterID string, limit int) ([]Message, error)

ReadTopic returns retained topic messages published after afterID, in publish order. It is the read side for topics, mirroring ReadStream, so a topic can be consumed from where a previous reader stopped rather than only from the start.

func (*MemoryStore) Restore

func (s *MemoryStore) Restore(snap MemoryStoreSnapshot)

Restore replaces the current store with a snapshot. Leased/running messages are converted back to queued during restore so a crashed consumer cannot keep work invisible forever after process recovery.

func (*MemoryStore) RestoreExact

func (s *MemoryStore) RestoreExact(snap MemoryStoreSnapshot)

RestoreExact replaces the store with a consensus snapshot without changing lease state. Lease expiry is itself a replicated mutation and must not be decided independently by a recovering follower.

func (*MemoryStore) ResumeQueue

func (s *MemoryStore) ResumeQueue(ctx context.Context, name string) error

func (*MemoryStore) SetCompactBacklog

func (s *MemoryStore) SetCompactBacklog(on bool)

SetCompactBacklog switches compact backlog storage on or off. Turning it off promotes every cold message so the store returns to its normal form.

func (*MemoryStore) SetHistoryLimit

func (s *MemoryStore) SetHistoryLimit(limit int)

func (*MemoryStore) SetRetainCompleted

func (s *MemoryStore) SetRetainCompleted(retain bool)

func (*MemoryStore) Snapshot

func (s *MemoryStore) Snapshot() MemoryStoreSnapshot

Snapshot returns a consistent deep-copy image of the store.

func (*MemoryStore) Stats

func (s *MemoryStore) Stats(ctx context.Context) (StoreStats, error)

func (*MemoryStore) StreamHeadOffset

func (s *MemoryStore) StreamHeadOffset(stream string) (uint64, error)

StreamHeadOffset returns the latest offset for a stream.

func (*MemoryStore) StreamHeadOffsetContext

func (s *MemoryStore) StreamHeadOffsetContext(ctx context.Context, stream, tenantID string) (uint64, error)

func (*MemoryStore) StreamLag

func (s *MemoryStore) StreamLag(stream, consumerGroup string) (uint64, error)

StreamLag returns the consumer lag (messages behind) for a given stream and consumer group.

func (*MemoryStore) StreamLagAll

func (s *MemoryStore) StreamLagAll(stream string) (map[string]uint64, error)

StreamLagAll returns the consumer lag for all consumer groups on a stream.

func (*MemoryStore) StreamLagAllContext

func (s *MemoryStore) StreamLagAllContext(ctx context.Context, stream, tenantID string) (map[string]uint64, error)

func (*MemoryStore) StreamLagContext

func (s *MemoryStore) StreamLagContext(ctx context.Context, stream, consumerGroup, tenantID string) (uint64, error)

StreamLagContext returns the number of messages visible to the caller after its committed offset. Counting visible records avoids including traffic from another tenant in the reported lag.

func (*MemoryStore) SweepLeases

func (s *MemoryStore) SweepLeases(ctx context.Context, now time.Time) (int, error)

func (*MemoryStore) Update

func (s *MemoryStore) Update(ctx context.Context, msg Message) error

func (*MemoryStore) UpdateBatch

func (s *MemoryStore) UpdateBatch(ctx context.Context, messages []Message) []error

type MemoryStoreSnapshot

type MemoryStoreSnapshot struct {
	Version   int                             `json:"version"`
	CreatedAt time.Time                       `json:"created_at"`
	Queues    map[string]MemoryQueueSnapshot  `json:"queues"`
	Topics    map[string]MemoryTopicSnapshot  `json:"topics"`
	Streams   map[string]MemoryStreamSnapshot `json:"streams"`
	Messages  map[string]Message              `json:"messages"`
	History   map[string][]MessageHistory     `json:"history"`
	Offsets   map[string]map[string]uint64    `json:"offsets"`
	Dedup     map[string]time.Time            `json:"dedup"`
	Idemp     map[string]string               `json:"idemp"`
	Producers map[string]ProducerState        `json:"producers,omitempty"`
	MoveOps   map[string]MoveResult           `json:"move_ops,omitempty"`
}

MemoryStoreSnapshot is a complete durable image of a MemoryStore. It is used by lightweight SQL stores and backup/restore tooling. File-WAL remains the preferred high-throughput append path; snapshot stores are intended for embedded/single-node persistent deployments that prefer a SQL database.

type MemoryStreamSnapshot

type MemoryStreamSnapshot struct {
	Config StreamConfig `json:"config"`
	IDs    []string     `json:"ids"`
	Offset uint64       `json:"offset"`
}

type MemoryTopicSnapshot

type MemoryTopicSnapshot struct {
	Config TopicConfig `json:"config"`
	IDs    []string    `json:"ids"`
	State  QueueState  `json:"state"`
}

type Message

type Message struct {
	ID               string            `json:"id"`
	ParentID         string            `json:"parent_id,omitempty"`
	Topic            string            `json:"topic,omitempty"`
	Queue            string            `json:"queue,omitempty"`
	Stream           string            `json:"stream,omitempty"`
	Partition        int               `json:"partition,omitempty"`
	Offset           uint64            `json:"offset,omitempty"`
	Key              string            `json:"key,omitempty"`
	RoutingKey       string            `json:"routing_key,omitempty"`
	Type             string            `json:"type,omitempty"`
	ContentType      string            `json:"content_type,omitempty"`
	Schema           string            `json:"schema,omitempty"`
	SchemaVersion    string            `json:"schema_version,omitempty"`
	Payload          []byte            `json:"payload,omitempty"`
	Headers          map[string]string `json:"headers,omitempty"`
	Metadata         map[string]string `json:"metadata,omitempty"`
	TraceID          string            `json:"trace_id,omitempty"`
	SpanID           string            `json:"span_id,omitempty"`
	CorrelationID    string            `json:"correlation_id,omitempty"`
	CausationID      string            `json:"causation_id,omitempty"`
	RequestID        string            `json:"request_id,omitempty"`
	ReplyTo          string            `json:"reply_to,omitempty"`
	ReplyGroup       string            `json:"reply_group,omitempty"`
	IdempotencyKey   string            `json:"idempotency_key,omitempty"`
	DeduplicationID  string            `json:"deduplication_id,omitempty"`
	Checksum         string            `json:"checksum,omitempty"`
	Priority         int               `json:"priority,omitempty"`
	CreatedAt        time.Time         `json:"created_at"`
	AvailableAt      time.Time         `json:"available_at,omitempty"`
	ExpiresAt        time.Time         `json:"expires_at,omitempty"`
	Attempts         int               `json:"attempts,omitempty"`
	MaxAttempts      int               `json:"max_attempts,omitempty"`
	Redeliveries     int               `json:"redeliveries,omitempty"`
	TenantID         string            `json:"tenant_id,omitempty"`
	ProducerID       string            `json:"producer_id,omitempty"`
	ProducerEpoch    int32             `json:"producer_epoch,omitempty"`
	ProducerSequence *uint64           `json:"producer_sequence,omitempty"`
	ConsumerID       string            `json:"consumer_id,omitempty"`
	ConsumerGroup    string            `json:"consumer_group,omitempty"`
	LeaseToken       string            `json:"lease_token,omitempty"`
	LeaseUntil       time.Time         `json:"lease_until,omitempty"`
	OriginalTopic    string            `json:"original_topic,omitempty"`
	OriginalQueue    string            `json:"original_queue,omitempty"`
	OriginalStream   string            `json:"original_stream,omitempty"`
	OriginalOffset   uint64            `json:"original_offset,omitempty"`
	Status           MessageStatus     `json:"status"`
	LastError        string            `json:"last_error,omitempty"`
	DeadLetterReason string            `json:"dead_letter_reason,omitempty"`
	TaskID           string            `json:"task_id,omitempty"`
	TaskName         string            `json:"task_name,omitempty"`
}

func DecodeMessageFrameBatch

func DecodeMessageFrameBatch(data []byte, codec FrameCodec, maxMessages int) ([]Message, error)

type MessageEvent

type MessageEvent struct {
	Message  Message
	Consumer string
	Queue    string
	Error    error
	Time     time.Time
}

type MessageFilter

type MessageFilter struct {
	Status   MessageStatus     `json:"status,omitempty"`
	Type     string            `json:"type,omitempty"`
	TenantID string            `json:"tenant_id,omitempty"`
	Headers  map[string]string `json:"headers,omitempty"`
}

type MessageHistory

type MessageHistory struct {
	MessageID string        `json:"message_id"`
	Status    MessageStatus `json:"status"`
	Event     string        `json:"event"`
	Source    string        `json:"source,omitempty"`
	Target    string        `json:"target,omitempty"`
	Reason    string        `json:"reason,omitempty"`
	Actor     string        `json:"actor,omitempty"`
	Error     string        `json:"error,omitempty"`
	Time      time.Time     `json:"time"`
}

type MessageReplay

type MessageReplay struct {
	// contains filtered or unexported fields
}

MessageReplay provides time-based and offset-based message replay.

func NewMessageReplay

func NewMessageReplay(b *Broker) *MessageReplay

NewMessageReplay creates a new message replay helper.

func (*MessageReplay) ReplayDLQ

func (mr *MessageReplay) ReplayDLQ(ctx context.Context, dlqQueue, destQueue string) (MoveResult, error)

ReplayDLQ replays messages from a DLQ.

func (*MessageReplay) ReplayFromOffset

func (mr *MessageReplay) ReplayFromOffset(ctx context.Context, stream string, afterOffset uint64, limit int) ([]Message, error)

ReplayFromOffset replays messages from a specific offset in a stream.

func (*MessageReplay) ReplayFromTime

func (mr *MessageReplay) ReplayFromTime(ctx context.Context, stream string, since time.Time, limit int) ([]Message, error)

ReplayFromTime replays messages from a specific timestamp in a stream. This scans the stream and returns messages created after the given time.

func (*MessageReplay) ReplayQueue

func (mr *MessageReplay) ReplayQueue(ctx context.Context, sourceQueue, destQueue string, limit int) (MoveResult, error)

ReplayQueue replays messages from a DLQ back to the source queue.

type MessageStatus

type MessageStatus string
const (
	MessageCreated        MessageStatus = "created"
	MessageValidated      MessageStatus = "validated"
	MessageAccepted       MessageStatus = "accepted"
	MessageRouted         MessageStatus = "routed"
	MessagePersisted      MessageStatus = "persisted"
	MessageScheduled      MessageStatus = "scheduled"
	MessageAvailable      MessageStatus = "available"
	MessageQueued         MessageStatus = "queued"
	MessageLeased         MessageStatus = "leased"
	MessageDelivered      MessageStatus = "delivered"
	MessageProcessing     MessageStatus = "processing"
	MessageProgressing    MessageStatus = "progressing"
	MessageAcked          MessageStatus = "acked"
	MessageCompleted      MessageStatus = "completed"
	MessageFailed         MessageStatus = "failed"
	MessageRetryScheduled MessageStatus = "retry_scheduled"
	MessageDeadLettered   MessageStatus = "dead_lettered"
	MessageCancelled      MessageStatus = "cancelled"
	MessageExpired        MessageStatus = "expired"
	MessageMoved          MessageStatus = "moved"
	MessageCopied         MessageStatus = "copied"
	MessageReplayed       MessageStatus = "replayed"
	MessageArchived       MessageStatus = "archived"
	MessagePurged         MessageStatus = "purged"
	MessageQuarantined    MessageStatus = "quarantined"
	MessageParked         MessageStatus = "parked"
)

type MinimalAtomicStore

type MinimalAtomicStore interface {
	AppendAtomicMinimal(context.Context, []AppendEntry) error
}

type Mode

type Mode string
const (
	ModeEmbedded    Mode = "embedded"
	ModeStandalone  Mode = "standalone"
	ModeDistributed Mode = "distributed"
)

type MoveMode

type MoveMode string
const (
	MoveRemoveSource MoveMode = "move"
	MoveCopy         MoveMode = "copy"
	MoveReplay       MoveMode = "replay"
	MoveReroute      MoveMode = "reroute"
	MoveQuarantine   MoveMode = "quarantine"
	MovePark         MoveMode = "park"
	MoveArchive      MoveMode = "archive"
)

type MoveRequest

type MoveRequest struct {
	SourceType      DestinationKind `json:"source_type"`
	Source          string          `json:"source"`
	DestinationType DestinationKind `json:"destination_type"`
	Destination     string          `json:"destination"`
	MessageIDs      []string        `json:"message_ids,omitempty"`
	Filter          MessageFilter   `json:"filter,omitempty"`
	Mode            MoveMode        `json:"mode"`
	PreserveID      bool            `json:"preserve_id"`
	PreserveOffset  bool            `json:"preserve_offset"`
	ResetAttempts   bool            `json:"reset_attempts"`
	ResetLease      bool            `json:"reset_lease"`
	ResetError      bool            `json:"reset_error"`
	Reason          string          `json:"reason,omitempty"`
	Actor           string          `json:"actor,omitempty"`
	DryRun          bool            `json:"dry_run"`
}

type MoveResult

type MoveResult struct {
	Moved       int      `json:"moved"`
	Copied      int      `json:"copied"`
	Skipped     int      `json:"skipped"`
	MessageIDs  []string `json:"message_ids,omitempty"`
	Destination string   `json:"destination"`
	DryRun      bool     `json:"dry_run"`
}

type MovementEvent

type MovementEvent struct {
	Request MoveRequest
	Result  MoveResult
	Error   error
	Time    time.Time
}

type MultiExporter

type MultiExporter struct {
	// contains filtered or unexported fields
}

MultiExporter exports to multiple exporters.

func NewMultiExporter

func NewMultiExporter(exporters ...TraceExporter) *MultiExporter

func (*MultiExporter) ExportSpan

func (m *MultiExporter) ExportSpan(ctx context.Context, span TraceSpan) error

func (*MultiExporter) Flush

func (m *MultiExporter) Flush(ctx context.Context) error

type NackAction

type NackAction string
const (
	NackRequeue NackAction = "requeue"
	NackRetry   NackAction = "retry"
	NackDLQ     NackAction = "dlq"
	NackReject  NackAction = "reject"
)

type NackOption

type NackOption func(*NackOptions)

func NackError

func NackError(v string) NackOption

func NackReason

func NackReason(v string) NackOption

func NackToDLQ

func NackToDLQ(v string) NackOption

func NackWithDelay

func NackWithDelay(v time.Duration) NackOption

type NackOptions

type NackOptions struct {
	Action NackAction
	Delay  time.Duration
	DLQ    string
	Reason string
	Error  string
}

type NackRequest

type NackRequest struct {
	MessageID        string        `json:"message_id,omitempty"`
	Queue            string        `json:"queue,omitempty"`
	LeaseToken       string        `json:"lease_token,omitempty"`
	ConsumerID       string        `json:"consumer_id,omitempty"`
	Action           NackAction    `json:"action,omitempty"`
	Reason           string        `json:"reason,omitempty"`
	Error            string        `json:"error,omitempty"`
	Delay            time.Duration `json:"delay,omitempty"`
	DLQ              string        `json:"dlq,omitempty"`
	ResetLease       bool          `json:"reset_lease,omitempty"`
	IncrementAttempt bool          `json:"increment_attempt,omitempty"`
}

type NativeChannel

type NativeChannel struct {
	ID uint16
	// contains filtered or unexported fields
}

NativeChannel provides a logical multiplexed channel over a shared client connection.

func (*NativeChannel) Commit

func (ch *NativeChannel) Commit(stream, group string, partition int, offset uint64) error

Commit records consumer offset over this multiplexed channel.

func (*NativeChannel) Fetch

func (ch *NativeChannel) Fetch(stream string, partition int, offset uint64, maxRecords, maxBytes int) ([][]byte, uint64, error)

Fetch retrieves records over this multiplexed channel.

func (*NativeChannel) Produce

func (ch *NativeChannel) Produce(stream string, partition int, payloads [][]byte) (uint64, error)

Produce sends records over this multiplexed channel.

type NativeRPCConfig

type NativeRPCConfig = GRPCConfig

NativeRPCConfig accurately names the legacy JSON/TCP RPC configuration.

type NativeRPCServer

type NativeRPCServer = GRPCServer

NativeRPCServer accurately names the legacy JSON/TCP RPC server.

func NewNativeRPCServer

func NewNativeRPCServer(b *Broker, cfg NativeRPCConfig) *NativeRPCServer

type NativeStreamClient

type NativeStreamClient struct {
	// contains filtered or unexported fields
}

NativeStreamClient is a persistent, correlation-safe client. One client may be used concurrently; requests are serialized intentionally to avoid a goroutine and allocation per in-flight response. Scale with a small pool.

func DialNativeStream

func DialNativeStream(addr string, timeout time.Duration) (*NativeStreamClient, error)

func DialNativeStreamWithOptions

func DialNativeStreamWithOptions(addr string, opts NativeStreamDialOptions) (*NativeStreamClient, error)

DialNativeStreamWithOptions connects to a BST1 server with explicit auth and TLS options.

func (*NativeStreamClient) Channel

func (c *NativeStreamClient) Channel(id uint16) *NativeChannel

Channel returns a multiplexed channel handle for logical channel id.

func (*NativeStreamClient) Close

func (c *NativeStreamClient) Close() error

func (*NativeStreamClient) Commit

func (c *NativeStreamClient) Commit(stream, group string, partition int, offset uint64) error

func (*NativeStreamClient) Fetch

func (c *NativeStreamClient) Fetch(stream string, partition int, offset uint64, maxRecords, maxBytes int) ([][]byte, uint64, error)

func (*NativeStreamClient) FetchRaw

func (c *NativeStreamClient) FetchRaw(stream string, partition int, offset uint64, maxRecords, maxBytes int) ([]byte, int, uint64, error)

FetchRaw retrieves a batch without creating one allocation per record. The returned buffer contains consecutive little-endian u32 lengths and payloads.

func (*NativeStreamClient) Offset

func (c *NativeStreamClient) Offset(stream, group string, partition int) (uint64, error)

func (*NativeStreamClient) Principal

func (c *NativeStreamClient) Principal() string

func (*NativeStreamClient) Produce

func (c *NativeStreamClient) Produce(stream string, partition int, payloads [][]byte) (uint64, error)

type NativeStreamConfig

type NativeStreamConfig struct {
	Dir              string
	Partitions       int
	SegmentBytes     int64
	GroupCommitDelay time.Duration
	GroupCommitBytes int
	MaxFrameBytes    int
	Sync             bool
	ACL              *ACL
	InsecureDev      bool
	TLSConfig        *tls.Config
}

type NativeStreamDialOptions

type NativeStreamDialOptions struct {
	Timeout   time.Duration
	Token     string
	TLSConfig *tls.Config
	AuthType  byte
}

NativeStreamDialOptions configures a BST1 client connection.

type NativeStreamServer

type NativeStreamServer struct {
	// contains filtered or unexported fields
}

func NewNativeStreamServer

func NewNativeStreamServer(cfg NativeStreamConfig) (*NativeStreamServer, error)

func (*NativeStreamServer) Close

func (s *NativeStreamServer) Close() error

func (*NativeStreamServer) ListenAndServe

func (s *NativeStreamServer) ListenAndServe(addr string) error

type NodeConfig

type NodeConfig struct {
	ID            string `json:"id"`
	AdvertiseAddr string `json:"advertise_addr,omitempty"`
	Zone          string `json:"zone,omitempty"`
	Rack          string `json:"rack,omitempty"`
}

NodeConfig identifies one broker node.

type NodeState

type NodeState string
const (
	NodeJoining  NodeState = "joining"
	NodeActive   NodeState = "active"
	NodeDraining NodeState = "draining"
	NodeLeft     NodeState = "left"
	NodeFailed   NodeState = "failed"
)

type Notification

type Notification struct {
	ID            string         `json:"id"`
	Type          string         `json:"type"`
	Source        string         `json:"source"`
	Severity      Severity       `json:"severity"`
	MessageID     string         `json:"message_id,omitempty"`
	TaskID        string         `json:"task_id,omitempty"`
	Topic         string         `json:"topic,omitempty"`
	Queue         string         `json:"queue,omitempty"`
	Stream        string         `json:"stream,omitempty"`
	Consumer      string         `json:"consumer,omitempty"`
	ConsumerGroup string         `json:"consumer_group,omitempty"`
	TenantID      string         `json:"tenant_id,omitempty"`
	TraceID       string         `json:"trace_id,omitempty"`
	Timestamp     time.Time      `json:"timestamp"`
	Data          map[string]any `json:"data,omitempty"`
}

type NotificationAuditLogger

type NotificationAuditLogger struct{ Bus *NotificationBus }

func (NotificationAuditLogger) LogAdmin

type NotificationAuditSink

type NotificationAuditSink struct {
	Bus *NotificationBus
}

NotificationAuditSink writes audit events to the notification bus.

func (NotificationAuditSink) Write

type NotificationBus

type NotificationBus struct {
	// contains filtered or unexported fields
}

func NewNotificationBus

func NewNotificationBus(capacity int) *NotificationBus

func (*NotificationBus) Close

func (b *NotificationBus) Close()

func (*NotificationBus) Enabled

func (b *NotificationBus) Enabled() bool

func (*NotificationBus) History

func (b *NotificationBus) History(limit int) []Notification

func (*NotificationBus) Publish

func (b *NotificationBus) Publish(n Notification)

func (*NotificationBus) Subscribe

func (b *NotificationBus) Subscribe(id string, cb Callback)

func (*NotificationBus) Unsubscribe

func (b *NotificationBus) Unsubscribe(id string)

type OTLPConfig

type OTLPConfig struct {
	Endpoint           string            `json:"endpoint"`
	Interval           time.Duration     `json:"interval"`
	ServiceName        string            `json:"service_name"`
	ResourceAttributes map[string]string `json:"resource_attributes"`
	Headers            map[string]string `json:"headers"`
	Client             *http.Client      `json:"-"`
}

OTLPConfig configures the OpenTelemetry Protocol exporter.

type OTLPExportRequest

type OTLPExportRequest struct {
	ResourceMetrics []otlpResourceMetrics `json:"resourceMetrics"`
}

OTLPExportRequest is the top-level body for /v1/metrics

type OTLPExporter

type OTLPExporter struct {
	// contains filtered or unexported fields
}

OTLPExporter pushes broker metrics to an OTEL collector via OTLP/HTTP.

func NewOTLPExporter

func NewOTLPExporter(endpoint string, interval time.Duration, metrics *PrometheusMetrics, opts ...OTLPOption) (*OTLPExporter, error)

NewOTLPExporter creates a new OTLP metrics exporter.

func (*OTLPExporter) Collect

func (e *OTLPExporter) Collect() *OTLPExportRequest

Collect reads the current PrometheusMetrics and converts them to OTLP JSON structure.

func (*OTLPExporter) Export

func (e *OTLPExporter) Export(ctx context.Context) error

Export collects and transmits metrics to the OTLP receiver.

func (*OTLPExporter) Run

func (e *OTLPExporter) Run(ctx context.Context)

Run executes periodic exports until context cancellation or Stop().

func (*OTLPExporter) Stop

func (e *OTLPExporter) Stop()

Stop terminates the exporter background loop.

type OTLPOption

type OTLPOption func(*OTLPConfig)

OTLPOption configures an OTLPConfig.

func WithOTLPHTTPClient

func WithOTLPHTTPClient(client *http.Client) OTLPOption

WithOTLPHTTPClient sets a custom HTTP client.

func WithOTLPHeaders

func WithOTLPHeaders(headers map[string]string) OTLPOption

WithOTLPHeaders sets HTTP request headers for export.

func WithOTLPResourceAttributes

func WithOTLPResourceAttributes(attrs map[string]string) OTLPOption

WithOTLPResourceAttributes sets custom resource attributes.

func WithOTLPServiceName

func WithOTLPServiceName(name string) OTLPOption

WithOTLPServiceName sets the service.name resource attribute.

type OffsetCommit

type OffsetCommit struct {
	Stream        string `json:"stream"`
	ConsumerGroup string `json:"consumer_group"`
	Offset        uint64 `json:"offset"`
	TenantID      string `json:"tenant_id,omitempty"`
}

type OpsConfig

type OpsConfig struct {
	ListenAddr string
	Broker     *Broker
}

type OpsServer

type OpsServer struct {
	// contains filtered or unexported fields
}

func NewOpsServer

func NewOpsServer(cfg OpsConfig) *OpsServer

func (*OpsServer) Start

func (s *OpsServer) Start() error

func (*OpsServer) Stop

func (s *OpsServer) Stop() error

type OrderMode

type OrderMode string
const (
	OrderNone      OrderMode = "none"
	OrderFIFO      OrderMode = "fifo"
	OrderKey       OrderMode = "key"
	OrderPartition OrderMode = "partition"
	OrderTenant    OrderMode = "tenant"
	OrderGlobal    OrderMode = "global"
)

type OutboxEvent

type OutboxEvent struct {
	ID          string            `json:"id"`
	Topic       string            `json:"topic"`
	Queue       string            `json:"queue"`
	Payload     []byte            `json:"payload"`
	Headers     map[string]string `json:"headers,omitempty"`
	Status      string            `json:"status"`
	CreatedAt   time.Time         `json:"created_at"`
	PublishedAt *time.Time        `json:"published_at,omitempty"`
	RetryCount  int               `json:"retry_count"`
	LastError   string            `json:"last_error,omitempty"`
}

type OwnedAtomicStore

type OwnedAtomicStore interface {
	AppendAtomicOwned(context.Context, []AppendEntry) error
}

OwnedAtomicStore is the zero-copy batch append path. Ownership of message payload/header/metadata slices and maps transfers to the store; callers must not mutate entries after the method returns.

type PartitionAssignment

type PartitionAssignment struct {
	Topic     string   `json:"topic"`
	Partition int      `json:"partition"`
	Leader    string   `json:"leader"`
	Replicas  []string `json:"replicas"`
}

type PartitionConfig

type PartitionConfig struct {
	// Partitions is the number of partitions per topic. Default: 1.
	Partitions int `json:"partitions,omitempty"`
	// Strategy is the partitioning strategy. Default: "hash".
	Strategy PartitionStrategy `json:"strategy,omitempty"`
}

PartitionConfig configures partition-based routing.

type PartitionInfo

type PartitionInfo struct {
	Partition int    `json:"partition"`
	Name      string `json:"name"`
	Depth     int    `json:"depth"`
	Offset    uint64 `json:"offset"`
}

type PartitionOrdering

type PartitionOrdering struct {
	// contains filtered or unexported fields
}

PartitionOrdering provides message ordering guarantees within a partition.

func NewPartitionOrdering

func NewPartitionOrdering(b *Broker) *PartitionOrdering

NewPartitionOrdering creates a new partition ordering manager.

func (*PartitionOrdering) OrderedPublish

func (po *PartitionOrdering) OrderedPublish(ctx context.Context, topic string, key string, payload any, opts ...PublishOption) (PublishResult, error)

OrderedPublish publishes a message with ordering guarantees within a partition. Messages with the same key are guaranteed to be delivered in order.

func (*PartitionOrdering) OrderedSubscribe

func (po *PartitionOrdering) OrderedSubscribe(ctx context.Context, cfg ConsumerConfig, handler Handler) (*Subscription, error)

OrderedSubscribe subscribes with ordering guarantees. Messages with the same key are delivered sequentially to the same consumer.

func (*PartitionOrdering) StreamOrderedPublish

func (po *PartitionOrdering) StreamOrderedPublish(ctx context.Context, stream string, partition int, key string, payload any, opts ...PublishOption) (PublishResult, error)

StreamOrderedPublish publishes to a stream with partition ordering.

func (*PartitionOrdering) StreamOrderedRead

func (po *PartitionOrdering) StreamOrderedRead(ctx context.Context, stream string, consumerGroup string, limit int) ([]Message, error)

StreamOrderedRead reads from a stream partition in order.

type PartitionReassignment

type PartitionReassignment struct {
	// contains filtered or unexported fields
}

PartitionReassignment handles dynamic partition reassignment.

func NewPartitionReassignment

func NewPartitionReassignment(b *Broker) *PartitionReassignment

NewPartitionReassignment creates a new partition reassignment manager.

func (*PartitionReassignment) AddRule

func (pr *PartitionReassignment) AddRule(rule ReassignmentRule)

AddRule adds a reassignment rule.

func (*PartitionReassignment) Execute

func (pr *PartitionReassignment) Execute(ctx context.Context) (int, error)

Execute performs a single reassignment pass for all active rules.

func (*PartitionReassignment) ListRules

func (pr *PartitionReassignment) ListRules() []ReassignmentRule

ListRules returns all reassignment rules.

func (*PartitionReassignment) RemoveRule

func (pr *PartitionReassignment) RemoveRule(sourceTopic string)

RemoveRule removes a reassignment rule by source topic.

func (*PartitionReassignment) StartReassignmentLoop

func (pr *PartitionReassignment) StartReassignmentLoop(ctx context.Context, interval time.Duration) context.CancelFunc

StartReassignmentLoop starts periodic partition reassignment.

type PartitionRouter

type PartitionRouter struct {
	// contains filtered or unexported fields
}

PartitionRouter routes messages to specific partitions.

func NewPartitionRouter

func NewPartitionRouter(cfg PartitionConfig) *PartitionRouter

NewPartitionRouter creates a new partition router.

func (*PartitionRouter) PartitionCount

func (pr *PartitionRouter) PartitionCount() int

PartitionCount returns the configured partition count.

func (*PartitionRouter) SelectPartition

func (pr *PartitionRouter) SelectPartition(msg Message) int

SelectPartition returns the partition index for a message.

type PartitionStrategy

type PartitionStrategy string

PartitionStrategy determines how messages are assigned to partitions.

const (
	PartitionHash       PartitionStrategy = "hash"
	PartitionRoundRobin PartitionStrategy = "round_robin"
	PartitionRandom     PartitionStrategy = "random"
	PartitionKey        PartitionStrategy = "key"
)

type PartitionedBinaryWALStore

type PartitionedBinaryWALStore struct {
	// contains filtered or unexported fields
}

PartitionedBinaryWALStore stripes messages across independent memory locks, WAL files, group-commit goroutines and fsync pipelines. Messages with the same producer identity, idempotency, deduplication, key, or routing key are pinned to one shard (in that precedence order, with stream placement fixed). Atomic batches are atomic per shard; cross-shard atomicity requires an outbox or external transaction coordinator.

func NewPartitionedBinaryWALStore

func NewPartitionedBinaryWALStore(dir string, shardCount int, codec FrameCodec) (*PartitionedBinaryWALStore, error)

func (*PartitionedBinaryWALStore) Ack

func (*PartitionedBinaryWALStore) AckBatch

func (s *PartitionedBinaryWALStore) AckBatch(ctx context.Context, reqs []AckRequest) []error

func (*PartitionedBinaryWALStore) Append

func (s *PartitionedBinaryWALStore) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

func (*PartitionedBinaryWALStore) AppendAtomic

func (s *PartitionedBinaryWALStore) AppendAtomic(ctx context.Context, entries []AppendEntry) ([]Message, error)

func (*PartitionedBinaryWALStore) AppendAtomicMinimal

func (s *PartitionedBinaryWALStore) AppendAtomicMinimal(ctx context.Context, entries []AppendEntry) error

func (*PartitionedBinaryWALStore) AppendAtomicOwned

func (s *PartitionedBinaryWALStore) AppendAtomicOwned(ctx context.Context, entries []AppendEntry) error

func (*PartitionedBinaryWALStore) Close

func (s *PartitionedBinaryWALStore) Close() error

func (*PartitionedBinaryWALStore) CommitOffset

func (*PartitionedBinaryWALStore) CommitStreamTransaction

func (s *PartitionedBinaryWALStore) CommitStreamTransaction(ctx context.Context, tx StreamTransaction) ([]Message, error)

func (*PartitionedBinaryWALStore) ConfirmationLevel

func (*PartitionedBinaryWALStore) ConfirmationLevel() ConfirmLevel

func (*PartitionedBinaryWALStore) ConsumerOffset

func (s *PartitionedBinaryWALStore) ConsumerOffset(ctx context.Context, c OffsetCommit) (uint64, error)

func (*PartitionedBinaryWALStore) DeclareQueue

func (s *PartitionedBinaryWALStore) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*PartitionedBinaryWALStore) DeclareStream

func (s *PartitionedBinaryWALStore) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*PartitionedBinaryWALStore) DeclareTopic

func (s *PartitionedBinaryWALStore) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*PartitionedBinaryWALStore) ExtendLease

func (s *PartitionedBinaryWALStore) ExtendLease(ctx context.Context, req LeaseRequest) error

func (*PartitionedBinaryWALStore) Get

func (*PartitionedBinaryWALStore) History

func (*PartitionedBinaryWALStore) Lease

func (*PartitionedBinaryWALStore) ListDLQ

func (s *PartitionedBinaryWALStore) ListDLQ(ctx context.Context, name string, limit int) ([]Message, error)

func (*PartitionedBinaryWALStore) ListQueue

func (s *PartitionedBinaryWALStore) ListQueue(ctx context.Context, name string, limit int) ([]Message, error)

func (*PartitionedBinaryWALStore) ListTopic

func (s *PartitionedBinaryWALStore) ListTopic(ctx context.Context, name string, limit int) ([]Message, error)

ListTopic gathers a topic's retained messages across shards. A topic is not partitioned in this store, so every shard is asked and the results are merged in publish order.

func (*PartitionedBinaryWALStore) Move

func (*PartitionedBinaryWALStore) Nack

func (*PartitionedBinaryWALStore) PauseQueue

func (s *PartitionedBinaryWALStore) PauseQueue(ctx context.Context, name string) error

func (*PartitionedBinaryWALStore) PurgeQueue

func (s *PartitionedBinaryWALStore) PurgeQueue(ctx context.Context, name string) (int, error)

func (*PartitionedBinaryWALStore) ReadStream

func (*PartitionedBinaryWALStore) ReadTopic

func (s *PartitionedBinaryWALStore) ReadTopic(ctx context.Context, name, afterID string, limit int) ([]Message, error)

ReadTopic resumes a topic read across shards from the message id last seen.

func (*PartitionedBinaryWALStore) ResumeQueue

func (s *PartitionedBinaryWALStore) ResumeQueue(ctx context.Context, name string) error

func (*PartitionedBinaryWALStore) SetHealthCallback

func (s *PartitionedBinaryWALStore) SetHealthCallback(fn func(error))

func (*PartitionedBinaryWALStore) SetHistoryLimit

func (s *PartitionedBinaryWALStore) SetHistoryLimit(limit int)

func (*PartitionedBinaryWALStore) SetRetainCompleted

func (s *PartitionedBinaryWALStore) SetRetainCompleted(retain bool)

func (*PartitionedBinaryWALStore) ShardCount

func (s *PartitionedBinaryWALStore) ShardCount() int

func (*PartitionedBinaryWALStore) Stats

func (*PartitionedBinaryWALStore) StoreHealth

func (s *PartitionedBinaryWALStore) StoreHealth() error

func (*PartitionedBinaryWALStore) StreamHeadOffsetContext

func (s *PartitionedBinaryWALStore) StreamHeadOffsetContext(ctx context.Context, stream, tenant string) (uint64, error)

func (*PartitionedBinaryWALStore) StreamLagAllContext

func (s *PartitionedBinaryWALStore) StreamLagAllContext(ctx context.Context, stream, tenant string) (map[string]uint64, error)

func (*PartitionedBinaryWALStore) StreamLagContext

func (s *PartitionedBinaryWALStore) StreamLagContext(ctx context.Context, stream, group, tenant string) (uint64, error)

func (*PartitionedBinaryWALStore) SweepLeases

func (s *PartitionedBinaryWALStore) SweepLeases(ctx context.Context, now time.Time) (int, error)

func (*PartitionedBinaryWALStore) Update

func (*PartitionedBinaryWALStore) UpdateBatch

func (s *PartitionedBinaryWALStore) UpdateBatch(ctx context.Context, messages []Message) []error

type PerformanceProfile

type PerformanceProfile string

PerformanceProfile selects a documented set of durability and resource trade-offs. ProfileDurable is the production default.

const (
	ProfileDurable     PerformanceProfile = "durable"
	ProfileLatency     PerformanceProfile = "latency"
	ProfileThroughput  PerformanceProfile = "throughput"
	ProfileLightweight PerformanceProfile = "lightweight"
)

type PermanentError

type PermanentError struct{ Err error }

func (PermanentError) Error

func (e PermanentError) Error() string

func (PermanentError) Unwrap

func (e PermanentError) Unwrap() error

type PersistentWebhookConfig

type PersistentWebhookConfig struct {
	HTTPClient       *http.Client
	MaxAttempts      int
	InitialBackoff   time.Duration
	MaxBackoff       time.Duration
	FailureThreshold int
	CooldownDuration time.Duration
	MaxHistoryPerURL int
}

PersistentWebhookConfig configures the PersistentWebhookDispatcher.

type PersistentWebhookDispatcher

type PersistentWebhookDispatcher struct {
	// contains filtered or unexported fields
}

PersistentWebhookDispatcher manages reliable webhook deliveries with retry and circuit breakers.

func NewPersistentWebhookDispatcher

func NewPersistentWebhookDispatcher(cfg PersistentWebhookConfig) *PersistentWebhookDispatcher

NewPersistentWebhookDispatcher creates a new dispatcher.

func (*PersistentWebhookDispatcher) CircuitState

func (d *PersistentWebhookDispatcher) CircuitState(url string) CircuitState

CircuitState returns the state of the circuit breaker for a URL.

func (*PersistentWebhookDispatcher) Dispatch

Dispatch executes durable webhook delivery with backoff and circuit breaking.

func (*PersistentWebhookDispatcher) History

History returns the delivery attempts for a given webhook URL.

func (*PersistentWebhookDispatcher) ReTrigger

func (d *PersistentWebhookDispatcher) ReTrigger(ctx context.Context, url string, notificationID string) error

ReTrigger replays a previously saved notification by ID.

func (*PersistentWebhookDispatcher) ResetCircuit

func (d *PersistentWebhookDispatcher) ResetCircuit(url string)

ResetCircuit manually resets the circuit breaker for a URL.

type PollRequest

type PollRequest struct {
	Queue               string `json:"queue"`
	ConsumerID          string `json:"consumer_id"`
	ConsumerGroup       string `json:"consumer_group"`
	TenantID            string `json:"tenant_id,omitempty"`
	Limit               int    `json:"limit"`
	WaitNS              int64  `json:"wait_ns,omitempty"`
	VisibilityTimeoutNS int64  `json:"visibility_timeout_ns,omitempty"`
}

type Predicate

type Predicate func(msg Message) bool

Predicate is a single evaluation condition on a message.

type ProducerRegistry

type ProducerRegistry struct {
	// contains filtered or unexported fields
}

ProducerRegistry maintains monotonic sequence tracking and epoch fencing per producer ID.

func NewProducerRegistry

func NewProducerRegistry() *ProducerRegistry

NewProducerRegistry creates an in-memory producer registry.

func (*ProducerRegistry) CheckAndRecord

func (r *ProducerRegistry) CheckAndRecord(producerID string, epoch int32, seq uint64, msgID string) (isDuplicate bool, existingID string, err error)

CheckAndRecord verifies the epoch and sequence of a message and updates the state.

func (*ProducerRegistry) GetProducer

func (r *ProducerRegistry) GetProducer(producerID string) (*ProducerState, bool)

GetProducer returns the current state for a producer.

func (*ProducerRegistry) RegisterProducer

func (r *ProducerRegistry) RegisterProducer(producerID string, epoch int32) (*ProducerState, error)

RegisterProducer registers or increments a producer's epoch.

type ProducerState

type ProducerState struct {
	ProducerID    string    `json:"producer_id"`
	Epoch         int32     `json:"epoch"`
	LastSequence  uint64    `json:"last_sequence"`
	LastMessageID string    `json:"last_message_id"`
	Initialized   bool      `json:"initialized"`
	UpdatedAt     time.Time `json:"updated_at"`
}

ProducerState tracks the current epoch and sequence for a specific producer ID.

type ProfileDefaults

type ProfileDefaults struct {
	Profile               PerformanceProfile `json:"profile"`
	Ack                   AckPolicy          `json:"ack"`
	Replication           ReplicationPolicy  `json:"replication"`
	PollInterval          time.Duration      `json:"poll_interval"`
	NotificationRetention int                `json:"notification_retention"`
}

ProfileDefaults exposes the concrete policy selected by a named profile.

func DefaultsForProfile

func DefaultsForProfile(profile PerformanceProfile) (ProfileDefaults, error)

type Progress

type Progress struct {
	Current   int64     `json:"current"`
	Total     int64     `json:"total"`
	Percent   float64   `json:"percent"`
	Message   string    `json:"message,omitempty"`
	UpdatedAt time.Time `json:"updated_at"`
}

type PrometheusMetrics

type PrometheusMetrics struct {
	// contains filtered or unexported fields
}

PrometheusMetrics holds all broker metrics in Prometheus exposition format.

func GlobalPrometheusMetrics

func GlobalPrometheusMetrics() *PrometheusMetrics

GlobalPrometheusMetrics returns the global metrics instance.

func NewPrometheusMetrics

func NewPrometheusMetrics() *PrometheusMetrics

NewPrometheusMetrics creates a new metrics collector.

func (*PrometheusMetrics) HookMetrics

func (m *PrometheusMetrics) HookMetrics() Hooks

HookMetrics creates a Hooks struct that records metrics for all broker operations.

func (*PrometheusMetrics) Middleware

func (m *PrometheusMetrics) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that records request metrics.

func (*PrometheusMetrics) PromHandler

func (m *PrometheusMetrics) PromHandler() http.Handler

PromHandler returns an HTTP handler that serves Prometheus exposition format.

func (*PrometheusMetrics) RecordAcked

func (m *PrometheusMetrics) RecordAcked(queue string, latency time.Duration)

RecordAcked records an acknowledged message.

func (*PrometheusMetrics) RecordDeadLettered

func (m *PrometheusMetrics) RecordDeadLettered(queue string)

RecordDeadLettered records a dead-lettered message.

func (*PrometheusMetrics) RecordDelivered

func (m *PrometheusMetrics) RecordDelivered(queue string, size int, latency time.Duration)

RecordDelivered records a delivered message.

func (*PrometheusMetrics) RecordMoved

func (m *PrometheusMetrics) RecordMoved()

RecordMoved records a moved message.

func (*PrometheusMetrics) RecordNacked

func (m *PrometheusMetrics) RecordNacked(queue string)

RecordNacked records a nacked message.

func (*PrometheusMetrics) RecordPublished

func (m *PrometheusMetrics) RecordPublished(topic string, size int, latency time.Duration)

RecordPublished records a published message.

func (*PrometheusMetrics) RecordRetried

func (m *PrometheusMetrics) RecordRetried()

RecordRetried records a retried message.

func (*PrometheusMetrics) RecordStoreFenced

func (m *PrometheusMetrics) RecordStoreFenced()

RecordStoreFenced records a storage fencing incident.

func (*PrometheusMetrics) SetActiveConsumers

func (m *PrometheusMetrics) SetActiveConsumers(n int)

SetActiveConsumers sets the active consumer count.

func (*PrometheusMetrics) SetActiveSubscriptions

func (m *PrometheusMetrics) SetActiveSubscriptions(n int)

SetActiveSubscriptions sets the active subscription count.

func (*PrometheusMetrics) UpdateGauges

func (m *PrometheusMetrics) UpdateGauges()

UpdateGauges refreshes gauge metrics from runtime.

func (*PrometheusMetrics) UpdateStoreStats

func (m *PrometheusMetrics) UpdateStoreStats(stats StoreStats)

UpdateStoreStats updates store-level gauge metrics.

type PublishBatchItem

type PublishBatchItem struct {
	Topic   string
	Payload any
	Options []PublishOption
}

PublishBatchItem allows a batch to target different topics, queues, streams, and option sets while still being committed with one capable store call.

type PublishEvent

type PublishEvent struct {
	Message      Message
	Destinations []Destination
	Result       PublishResult
	Error        error
	Time         time.Time
}

type PublishFuture

type PublishFuture interface {
	ID() string
	Done() <-chan struct{}
	Wait(context.Context) (PublishResult, error)
	Cancel(context.Context) error
}

type PublishHTTPPayload

type PublishHTTPPayload struct {
	Topic          string            `json:"topic"`
	Queue          string            `json:"queue,omitempty"`
	Stream         string            `json:"stream,omitempty"`
	Type           string            `json:"type,omitempty"`
	Payload        json.RawMessage   `json:"payload"`
	Headers        map[string]string `json:"headers,omitempty"`
	Metadata       map[string]string `json:"metadata,omitempty"`
	Key            string            `json:"key,omitempty"`
	RoutingKey     string            `json:"routing_key,omitempty"`
	Priority       int               `json:"priority,omitempty"`
	TenantID       string            `json:"tenant_id,omitempty"`
	CorrelationID  string            `json:"correlation_id,omitempty"`
	TimeoutNS      int64             `json:"timeout_ns,omitempty"`
	IdempotencyKey string            `json:"idempotency_key,omitempty"`

	// The fields below had no wire representation at all, so they were settable
	// through the embedded Publisher and silently dropped by every HTTP publish
	// path. Durations use nanoseconds to match timeout_ns and
	// visibility_timeout_ns.
	MessageID             string `json:"message_id,omitempty"`
	ContentType           string `json:"content_type,omitempty"`
	Schema                string `json:"schema,omitempty"`
	SchemaVersion         string `json:"schema_version,omitempty"`
	TraceID               string `json:"trace_id,omitempty"`
	CausationID           string `json:"causation_id,omitempty"`
	DeduplicationID       string `json:"deduplication_id,omitempty"`
	DeduplicationWindowNS int64  `json:"deduplication_window_ns,omitempty"`
	TTLNS                 int64  `json:"ttl_ns,omitempty"`
	DelayNS               int64  `json:"delay_ns,omitempty"`
	MaxAttempts           int    `json:"max_attempts,omitempty"`
	ProducerID            string `json:"producer_id,omitempty"`
	Strategy              string `json:"strategy,omitempty"`

	// PayloadEncoding selects how Payload is interpreted. "json" is the default
	// and means the payload already is JSON. "base64" means Payload is a base64
	// JSON string holding bytes that are not valid JSON.
	//
	// Without this, a []byte payload published by pkg/client was marshalled by
	// encoding/json into a base64 JSON *string*, and the server then stored the
	// literal quote-and-base64 characters. Six arbitrary bytes were stored as
	// eight ASCII bytes. The embedded path stores []byte verbatim, so this is
	// also what makes the two agree on binary payloads.
	PayloadEncoding string `json:"payload_encoding,omitempty"`
}

PublishHTTPPayload is the request body for /v1/publish, /v1/publish/batch and /v1/request. Keys are snake_case, matching PollRequest and the wire format documented in docs/CODEC_FORMAT.md.

This struct previously carried no tags, so encoding/json only ever matched the Go field names. Because Go's fallback matching is case-insensitive it happened to accept "Topic", but the underscore in "tenant_id" broke it: documented clients silently lost tenant scoping, routing keys, correlation ids, idempotency keys and request timeouts. UnmarshalJSON still accepts the old spellings so existing clients keep working.

func (PublishHTTPPayload) PayloadBytes

func (p PublishHTTPPayload) PayloadBytes() ([]byte, error)

PayloadBytes returns the payload as the publisher should store it, honouring PayloadEncoding.

func (PublishHTTPPayload) PublishOptions

func (p PublishHTTPPayload) PublishOptions() []PublishOption

PublishOptions converts a publish request body into publisher options.

Every option-based HTTP publish path goes through this one function. The mapping used to be written out separately in each handler, so any field added to PublishOptions had to be threaded through all of them by hand. That is how content_type, schema, schema_version, trace_id, causation_id, deduplication_id, ttl, delay, max_attempts, producer_id, strategy and a producer-chosen message_id ended up settable embedded and dropped remotely.

func (*PublishHTTPPayload) UnmarshalJSON

func (p *PublishHTTPPayload) UnmarshalJSON(data []byte) error

type PublishOption

type PublishOption func(*PublishOptions)

func WithCausationID

func WithCausationID(v string) PublishOption

func WithConfirmLevel

func WithConfirmLevel(v ConfirmLevel) PublishOption

func WithContentType

func WithContentType(v string) PublishOption

func WithCorrelationID

func WithCorrelationID(v string) PublishOption

func WithDeduplication

func WithDeduplication(id string, window time.Duration) PublishOption

func WithDelay

func WithDelay(v time.Duration) PublishOption

func WithHeader

func WithHeader(k, v string) PublishOption

func WithHeaders

func WithHeaders(v map[string]string) PublishOption

func WithIdempotencyKey

func WithIdempotencyKey(v string) PublishOption

func WithKey

func WithKey(v string) PublishOption

func WithMaxAttempts

func WithMaxAttempts(v int) PublishOption

func WithMessageID

func WithMessageID(v string) PublishOption

func WithMetadata

func WithMetadata(v map[string]string) PublishOption

func WithPriority

func WithPriority(v int) PublishOption

func WithProducer

func WithProducer(id string, epoch int32, seq uint64) PublishOption

WithProducer configures ProducerID, ProducerEpoch, and ProducerSequence on publish options.

func WithProducerEpoch

func WithProducerEpoch(epoch int32) PublishOption

WithProducerEpoch sets the producer epoch on publish options.

func WithProducerID

func WithProducerID(v string) PublishOption

func WithProducerSequence

func WithProducerSequence(seq uint64) PublishOption

WithProducerSequence sets the monotonic producer sequence on publish options.

func WithQueue

func WithQueue(v string) PublishOption

func WithRequireDestination

func WithRequireDestination(v bool) PublishOption

func WithRetryPolicy

func WithRetryPolicy(v RetryPolicy) PublishOption

func WithRoutingKey

func WithRoutingKey(v string) PublishOption

func WithRunAt

func WithRunAt(v time.Time) PublishOption

func WithSchema

func WithSchema(name, version string) PublishOption

func WithStrategy

func WithStrategy(v StrategyType) PublishOption

func WithStream

func WithStream(v string) PublishOption

func WithTTL

func WithTTL(v time.Duration) PublishOption

func WithTaskHeaders

func WithTaskHeaders(id, name string) PublishOption

func WithTenantID

func WithTenantID(v string) PublishOption

func WithTraceID

func WithTraceID(v string) PublishOption

func WithType

func WithType(v string) PublishOption

type PublishOptions

type PublishOptions struct {
	MessageID           string
	Key                 string
	RoutingKey          string
	Type                string
	ContentType         string
	Schema              string
	SchemaVersion       string
	Headers             map[string]string
	Metadata            map[string]string
	TraceID             string
	CorrelationID       string
	CausationID         string
	IdempotencyKey      string
	DeduplicationID     string
	DeduplicationWindow time.Duration
	Priority            int
	Delay               time.Duration
	RunAt               time.Time
	TTL                 time.Duration
	TenantID            string
	ProducerID          string
	ProducerEpoch       int32
	ProducerSequence    *uint64
	Queue               string
	Stream              string
	ConfirmLevel        ConfirmLevel
	RequireDestination  bool
	MaxAttempts         int
	RetryPolicy         RetryPolicy
	Strategy            StrategyType
}

type PublishResult

type PublishResult struct {
	MessageID    string          `json:"message_id"`
	Messages     []Message       `json:"messages,omitempty"`
	Destinations []Destination   `json:"destinations,omitempty"`
	Confirmed    ConfirmLevel    `json:"confirmed"`
	Partition    int             `json:"partition,omitempty"`
	Offset       uint64          `json:"offset,omitempty"`
	LeaderEpoch  uint64          `json:"leader_epoch,omitempty"`
	Replicas     int             `json:"replicas,omitempty"`
	Durability   DurabilityScope `json:"durability"`
	Duplicate    bool            `json:"duplicate,omitempty"`
}

type PublishRetryBuffer

type PublishRetryBuffer struct {
	// contains filtered or unexported fields
}

PublishRetryBuffer tracks failed publishes in memory for explicit retries. It is neither durable nor an application-database transactional outbox.

func NewPublishRetryBuffer

func NewPublishRetryBuffer(b *Broker) *PublishRetryBuffer

func (*PublishRetryBuffer) Cleanup

func (to *PublishRetryBuffer) Cleanup(maxAge time.Duration)

Cleanup removes published events older than the given age.

func (*PublishRetryBuffer) Pending

func (to *PublishRetryBuffer) Pending() []OutboxEvent

Pending returns all pending outbox events.

func (*PublishRetryBuffer) Publish

func (to *PublishRetryBuffer) Publish(ctx context.Context, topic string, payload any, opts ...PublishOption) (PublishResult, error)

Publish records an attempt and publishes it. The two actions are not atomic.

func (*PublishRetryBuffer) RetryPending

func (to *PublishRetryBuffer) RetryPending(ctx context.Context) (int, error)

RetryPending retries all pending outbox events.

type PublishTx

type PublishTx interface {
	Publish(topic string, payload any, opts ...PublishOption) error
	Commit(context.Context) ([]PublishResult, error)
	Rollback(context.Context) error
}

type Publisher

type Publisher struct {
	// contains filtered or unexported fields
}

func (*Publisher) BeginStreamTx

func (p *Publisher) BeginStreamTx(ctx context.Context, offset OffsetCommit, expectedOffset uint64) (PublishTx, error)

BeginStreamTx builds outputs whose commit atomically advances an input stream offset. A stale expectedOffset fails with ErrOffsetConflict. After an ambiguous I/O failure, reconcile the group offset before retrying application work.

func (*Publisher) BeginTx

func (p *Publisher) BeginTx(ctx context.Context, opts ...TxOption) (PublishTx, error)

func (*Publisher) Broadcast

func (p *Publisher) Broadcast(ctx context.Context, topic string, payload any, opts ...PublishOption) (PublishResult, error)

func (*Publisher) Command

func (p *Publisher) Command(ctx context.Context, command string, request any, response any, opts ...RequestOption) error

func (*Publisher) Publish

func (p *Publisher) Publish(ctx context.Context, topic string, payload any, opts ...PublishOption) (PublishResult, error)

func (*Publisher) PublishAfter

func (p *Publisher) PublishAfter(ctx context.Context, topic string, payload any, delay time.Duration, opts ...PublishOption) (ScheduleResult, error)

func (*Publisher) PublishAsync

func (p *Publisher) PublishAsync(ctx context.Context, topic string, payload any, opts ...PublishOption) PublishFuture

func (*Publisher) PublishAt

func (p *Publisher) PublishAt(ctx context.Context, topic string, payload any, at time.Time, opts ...PublishOption) (ScheduleResult, error)

func (*Publisher) PublishBatch

func (p *Publisher) PublishBatch(ctx context.Context, topic string, payloads []any, opts ...PublishOption) (BatchPublishResult, error)

func (*Publisher) PublishBatchAsync

func (p *Publisher) PublishBatchAsync(ctx context.Context, topic string, payloads []any, opts ...PublishOption) BatchPublishFuture

func (*Publisher) PublishConfirm

func (p *Publisher) PublishConfirm(ctx context.Context, topic string, payload any, opts ...PublishOption) (PublishResult, error)

func (*Publisher) PublishItems

func (p *Publisher) PublishItems(ctx context.Context, items []PublishBatchItem) (BatchPublishResult, error)

PublishItems publishes a heterogeneous batch. Successful entries are returned in input order; failures are listed in Errors.

func (*Publisher) PublishOwned

func (p *Publisher) PublishOwned(ctx context.Context, msg Message, opts ...PublishOption) (PublishResult, error)

PublishOwned publishes a message and transfers ownership of the payload, headers and metadata to the broker, skipping the deep copy Publish performs.

It exists because Publish has to copy: for a []byte payload the codec returns the caller's own buffer, so storing it without a copy would alias memory the caller still holds. Callers who know they are done with those buffers can hand them over instead and avoid the copy, which is worth about 1.5x on the append path (roughly 15 allocations per message down to 8).

After PublishOwned returns, the caller must not read or modify payload, headers or metadata, including any byte slice passed in opts. Publishing the same Message value twice, or one that came from Lease, Get or ListQueue, is a use-after-free style bug: the store and the caller end up sharing one payload. Build a fresh Message per publish, or use Publish.

This is the same path the HTTP data plane already uses for "Prefer: return=minimal", where ownership is safe because the payload was just decoded from the request and is discarded afterwards.

func (*Publisher) Request

func (p *Publisher) Request(ctx context.Context, subject string, request any, response any, opts ...RequestOption) error

func (*Publisher) RequestAsync

func (p *Publisher) RequestAsync(ctx context.Context, subject string, request any, opts ...RequestOption) ResponseFuture

func (*Publisher) RequestStream

func (p *Publisher) RequestStream(ctx context.Context, subject string, request any, opts ...RequestOption) (ResponseStream, error)

func (*Publisher) SubmitTask

func (p *Publisher) SubmitTask(ctx context.Context, name string, payload any, opts ...TaskOption) (TaskHandle, error)

func (*Publisher) SubmitTaskAsync

func (p *Publisher) SubmitTaskAsync(ctx context.Context, name string, payload any, opts ...TaskOption) TaskFuture

type PublisherRecord

type PublisherRecord struct {
	ID            string            `json:"id"`
	Operation     string            `json:"operation"`
	Topic         string            `json:"topic,omitempty"`
	Queue         string            `json:"queue,omitempty"`
	Stream        string            `json:"stream,omitempty"`
	Subject       string            `json:"subject,omitempty"`
	MessageID     string            `json:"message_id,omitempty"`
	TaskID        string            `json:"task_id,omitempty"`
	CorrelationID string            `json:"correlation_id,omitempty"`
	Status        string            `json:"status"`
	Error         string            `json:"error,omitempty"`
	CreatedAt     time.Time         `json:"created_at"`
	UpdatedAt     time.Time         `json:"updated_at"`
	Metadata      map[string]string `json:"metadata,omitempty"`
}

PublisherRecord tracks publish/request/task operations for audit, troubleshooting, and external persistence.

type PublisherStateStore

type PublisherStateStore interface {
	PutPublisherRecord(context.Context, PublisherRecord) error
	GetPublisherRecord(context.Context, string) (PublisherRecord, bool, error)
	ListPublisherRecords(context.Context, int) ([]PublisherRecord, error)
}

type QueueConfig

type QueueConfig struct {
	Name              string             `json:"name"`
	Workers           int                `json:"workers"`
	MaxInFlight       int                `json:"max_inflight"`
	MaxDepth          int                `json:"max_depth"`
	VisibilityTimeout time.Duration      `json:"visibility_timeout"`
	AckMode           AckMode            `json:"ack_mode"`
	RetryPolicy       RetryPolicy        `json:"retry_policy"`
	DLQ               string             `json:"dlq"`
	Ordering          OrderMode          `json:"ordering"`
	Backpressure      BackpressurePolicy `json:"backpressure"`
	Strategy          StrategyType       `json:"strategy,omitempty"`
}

type QueueDepthReporter

type QueueDepthReporter interface {
	// contains filtered or unexported methods
}

QueueDepthReporter exposes the O(1) queue depth and limit needed to enforce backpressure. The durable stores embed *MemoryStore, so they satisfy this without extra code; that matters because a concrete type assertion against *MemoryStore silently skipped backpressure on every WAL, segmented and distributed store.

type QueueRateLimiter

type QueueRateLimiter struct {
	// contains filtered or unexported fields
}

QueueRateLimiter manages rate limiters for multiple queues.

func NewQueueRateLimiter

func NewQueueRateLimiter(cfg RateLimitConfig) *QueueRateLimiter

NewQueueRateLimiter creates a new queue/topic rate limiter.

func (*QueueRateLimiter) AllowQueue

func (q *QueueRateLimiter) AllowQueue(queue string) bool

AllowQueue checks if a message for the given queue is rate-limited.

func (*QueueRateLimiter) AllowTopic

func (q *QueueRateLimiter) AllowTopic(topic string) bool

AllowTopic checks if a message for the given topic is rate-limited.

func (*QueueRateLimiter) Stop

func (q *QueueRateLimiter) Stop()

Stop halts the rate limiter.

type QueueSignaler

type QueueSignaler interface {
	QueueReady(name string) <-chan struct{}
}

QueueSignaler is implemented by stores that can wake a waiting consumer as soon as a message becomes available. The durable stores embed *MemoryStore, so they satisfy it without extra code.

type QueueState

type QueueState string
const (
	QueueDeclared QueueState = "declared"
	QueueCreated  QueueState = "created"
	QueueActive   QueueState = "active"
	QueuePaused   QueueState = "paused"
	QueueDraining QueueState = "draining"
	QueueFull     QueueState = "full"
	QueueBlocked  QueueState = "blocked"
	QueueDeleted  QueueState = "deleted"
	QueuePurged   QueueState = "purged"
	QueueArchived QueueState = "archived"
)

type RFC6455Config

type RFC6455Config struct {
	Path           string
	OriginPatterns []string
	MaxConnections int
	MaxMessageSize int64
	ACL            *ACL
	InsecureDev    bool
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
}

RFC6455Config configures the real WebSocket data-plane listener. It is deliberately separate from SSEConfig.

type RFC6455Server

type RFC6455Server struct {
	// contains filtered or unexported fields
}

func NewRFC6455Server

func NewRFC6455Server(b *Broker, cfg RFC6455Config) *RFC6455Server

func (*RFC6455Server) ConnectionCount

func (s *RFC6455Server) ConnectionCount() int

func (*RFC6455Server) Handler

func (s *RFC6455Server) Handler() http.Handler

func (*RFC6455Server) Stop

func (s *RFC6455Server) Stop()

type RaftStateResponse

type RaftStateResponse struct {
	State        string   `json:"state"`
	Term         uint64   `json:"term"`
	CommitIndex  uint64   `json:"commit_index"`
	AppliedIndex uint64   `json:"applied_index"`
	IsLeader     bool     `json:"is_leader"`
	Leader       string   `json:"leader"`
	Peers        []string `json:"peers"`
}

type RateLimitConfig

type RateLimitConfig struct {
	// PerQueue limits messages per second for a specific queue.
	PerQueue map[string]int `json:"per_queue,omitempty"`
	// PerTopic limits messages per second for a specific topic.
	PerTopic map[string]int `json:"per_topic,omitempty"`
	// DefaultRate is the default limit if no specific rate is configured. 0 = unlimited.
	DefaultRate int `json:"default_rate,omitempty"`
	// DefaultBurst is the default burst size. Default: uses rate value.
	DefaultBurst int `json:"default_burst,omitempty"`
}

RateLimitConfig configures per-queue or per-topic rate limits.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides per-key rate limiting using a token bucket algorithm.

func NewRateLimiter

func NewRateLimiter(ratePerSecond, burst int) *RateLimiter

NewRateLimiter creates a rate limiter with the given rate (tokens/sec) and burst size.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(key string) bool

Allow checks if a request with the given key is allowed.

func (*RateLimiter) AllowN

func (rl *RateLimiter) AllowN(key string, n int) bool

AllowN checks if n requests with the given key are allowed.

func (*RateLimiter) Reset

func (rl *RateLimiter) Reset(key string)

Reset clears all buckets for the given key.

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop halts the cleanup goroutine.

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context, key string) error

Wait blocks until the request with the given key is allowed or context is cancelled.

func (*RateLimiter) WaitN

func (rl *RateLimiter) WaitN(ctx context.Context, key string, n int) error

WaitN blocks until n requests are allowed or context is cancelled.

type RawCodec

type RawCodec struct{}

func (RawCodec) ContentType

func (RawCodec) ContentType() string

func (RawCodec) Marshal

func (RawCodec) Marshal(v any) ([]byte, error)

func (RawCodec) Unmarshal

func (RawCodec) Unmarshal(b []byte, v any) error

type ReassignmentRule

type ReassignmentRule struct {
	// SourceTopic is the topic to reassign from.
	SourceTopic string `json:"source_topic"`
	// DestTopic is the topic to reassign to.
	DestTopic string `json:"dest_topic"`
	// Filter is an optional message filter.
	Filter *MessageFilter `json:"filter,omitempty"`
	// PreserveOffset maintains the original offset.
	PreserveOffset bool `json:"preserve_offset,omitempty"`
	// BatchSize is messages per reassignment batch. Default: 100.
	BatchSize int `json:"batch_size,omitempty"`
	// Enabled controls whether this rule is active.
	Enabled bool `json:"enabled"`
}

type RebalanceHooks

type RebalanceHooks struct {
	OnBeforeRebalance func(group string, oldMembers, newMembers []string)
	OnAfterRebalance  func(group string, state *GroupState)
	OnDrainStarted    func(group, consumerID string)
	OnDrainCompleted  func(group, consumerID string)
}

type RemoteError

type RemoteError struct {
	Status    int
	Code      string
	Message   string
	Retryable bool
	Class     RetryClassification
	Details   map[string]string
}

RemoteError is a broker error recovered from the wire. It unwraps to the matching broker sentinel, so errors.Is(err, broker.ErrNotLeader) behaves the same for an embedded caller and a remote one.

func ParseRemoteError

func ParseRemoteError(status int, body []byte) *RemoteError

ParseRemoteError decodes a data-plane error response. It returns nil when the body is not an envelope, so a server that still answers with plain text keeps working.

func (*RemoteError) Error

func (e *RemoteError) Error() string

func (*RemoteError) RetryHint

func (e *RemoteError) RetryHint() (leader string, epoch uint64, retryAfter time.Duration)

RetryHint returns the leader address the broker advertised, if any, so a client can redirect instead of parsing the message text.

func (*RemoteError) Unwrap

func (e *RemoteError) Unwrap() error

Unwrap maps the wire code back to its sentinel.

type RemoteSubscription

type RemoteSubscription struct {
	Type       string `json:"type"`
	Name       string `json:"name"`
	Queue      string `json:"queue,omitempty"`
	Pattern    string `json:"pattern,omitempty"`
	AutoCreate bool   `json:"auto_create"`
}

type ReplicatedStore

type ReplicatedStore struct {
	Store
	// contains filtered or unexported fields
}

func (*ReplicatedStore) Ack

func (s *ReplicatedStore) Ack(ctx context.Context, req AckRequest) error

func (*ReplicatedStore) Append

func (s *ReplicatedStore) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

func (*ReplicatedStore) AppendAtomic

func (s *ReplicatedStore) AppendAtomic(ctx context.Context, entries []AppendEntry) ([]Message, error)

func (*ReplicatedStore) CommitOffset

func (s *ReplicatedStore) CommitOffset(ctx context.Context, commit OffsetCommit) error

func (*ReplicatedStore) ConfirmationLevel

func (s *ReplicatedStore) ConfirmationLevel() ConfirmLevel

ConfirmationLevel returns ConfirmReplicated when backed by etcd/raft consensus.

func (*ReplicatedStore) ConsumerOffset

func (s *ReplicatedStore) ConsumerOffset(ctx context.Context, commit OffsetCommit) (uint64, error)

func (*ReplicatedStore) DeclareQueue

func (s *ReplicatedStore) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*ReplicatedStore) DeclareStream

func (s *ReplicatedStore) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*ReplicatedStore) DeclareTopic

func (s *ReplicatedStore) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*ReplicatedStore) ExtendLease

func (s *ReplicatedStore) ExtendLease(ctx context.Context, req LeaseRequest) error

func (*ReplicatedStore) Get

func (s *ReplicatedStore) Get(ctx context.Context, id string) (Message, bool, error)

func (*ReplicatedStore) History

func (s *ReplicatedStore) History(ctx context.Context, id string) ([]MessageHistory, error)

func (*ReplicatedStore) Lease

func (s *ReplicatedStore) Lease(ctx context.Context, req LeaseRequest) ([]Message, error)

func (*ReplicatedStore) ListDLQ

func (s *ReplicatedStore) ListDLQ(ctx context.Context, name string, limit int) ([]Message, error)

func (*ReplicatedStore) ListQueue

func (s *ReplicatedStore) ListQueue(ctx context.Context, name string, limit int) ([]Message, error)

func (*ReplicatedStore) Move

func (*ReplicatedStore) Nack

func (s *ReplicatedStore) Nack(ctx context.Context, req NackRequest) error

func (*ReplicatedStore) PauseQueue

func (s *ReplicatedStore) PauseQueue(ctx context.Context, name string) error

func (*ReplicatedStore) PurgeQueue

func (s *ReplicatedStore) PurgeQueue(ctx context.Context, name string) (int, error)

func (*ReplicatedStore) ReadStream

func (s *ReplicatedStore) ReadStream(ctx context.Context, req StreamReadRequest) ([]Message, error)

func (*ReplicatedStore) ResumeQueue

func (s *ReplicatedStore) ResumeQueue(ctx context.Context, name string) error

func (*ReplicatedStore) Stats

func (s *ReplicatedStore) Stats(ctx context.Context) (StoreStats, error)

func (*ReplicatedStore) SweepLeases

func (s *ReplicatedStore) SweepLeases(ctx context.Context, now time.Time) (int, error)

func (*ReplicatedStore) Update

func (s *ReplicatedStore) Update(ctx context.Context, message Message) error

func (*ReplicatedStore) UpdateBatch

func (s *ReplicatedStore) UpdateBatch(ctx context.Context, messages []Message) []error

type ReplicationPolicy

type ReplicationPolicy struct {
	ReplicationFactor int       `json:"replication_factor"`
	MinInSyncReplicas int       `json:"min_in_sync_replicas"`
	Acknowledgement   AckPolicy `json:"acknowledgement"`
}

ReplicationPolicy defines the persistence quorum for a partition group.

type RequestOption

type RequestOption func(*RequestOptions)

func WithReplyTo

func WithReplyTo(v string) RequestOption

func WithRequestCorrelationID

func WithRequestCorrelationID(v string) RequestOption

func WithRequestHeader

func WithRequestHeader(k, v string) RequestOption

func WithRequestIdempotencyKey

func WithRequestIdempotencyKey(v string) RequestOption

func WithRequestTenantID

func WithRequestTenantID(v string) RequestOption

func WithRequireHandler

func WithRequireHandler(v bool) RequestOption

func WithTimeout

func WithTimeout(v time.Duration) RequestOption

type RequestOptions

type RequestOptions struct {
	Timeout          time.Duration
	ReplyTo          string
	CorrelationID    string
	ContentType      string
	MaxResponseBytes int64
	RequireHandler   bool
	RetryPolicy      RetryPolicy
	IdempotencyKey   string
	Headers          map[string]string
	TenantID         string
}

type Response

type Response struct {
	MessageID     string            `json:"message_id"`
	CorrelationID string            `json:"correlation_id"`
	Payload       []byte            `json:"payload,omitempty"`
	Headers       map[string]string `json:"headers,omitempty"`
	Error         *BrokerError      `json:"error,omitempty"`
	Status        ResponseStatus    `json:"status"`
}

type ResponseFuture

type ResponseFuture interface {
	RequestID() string
	CorrelationID() string
	Done() <-chan struct{}
	Wait(context.Context) (Response, error)
	Cancel(context.Context) error
}

type ResponseOption

type ResponseOption func(*ResponseOptions)

func WithEndStream

func WithEndStream(v bool) ResponseOption

func WithResponseHeader

func WithResponseHeader(k, v string) ResponseOption

func WithResponseStatus

func WithResponseStatus(v ResponseStatus) ResponseOption

type ResponseOptions

type ResponseOptions struct {
	Headers   map[string]string
	Status    ResponseStatus
	EndStream bool
}

type ResponseStatus

type ResponseStatus string
const (
	ResponseOK      ResponseStatus = "ok"
	ResponseError   ResponseStatus = "error"
	ResponseTimeout ResponseStatus = "timeout"
)

type ResponseStream

type ResponseStream interface {
	Next() bool
	Message() Response
	Err() error
	Close() error
}

type RetryClassification

type RetryClassification string
const (
	RetryNotLeader          RetryClassification = "not_leader"
	RetryStaleEpoch         RetryClassification = "stale_epoch"
	RetryQuorumUnavailable  RetryClassification = "quorum_unavailable"
	RetryThrottled          RetryClassification = "throttled"
	RetryTransactionAborted RetryClassification = "transaction_aborted"
	RetryStorageUnavailable RetryClassification = "storage_unavailable"
)

func ClassifyRetry

func ClassifyRetry(err error) (RetryClassification, bool)

type RetryError

type RetryError struct {
	Class       RetryClassification `json:"class"`
	Message     string              `json:"message,omitempty"`
	Leader      string              `json:"leader,omitempty"`
	LeaderEpoch uint64              `json:"leader_epoch,omitempty"`
	RetryAfter  time.Duration       `json:"retry_after,omitempty"`
	Cause       error               `json:"-"`
}

RetryError carries machine-readable routing and retry metadata.

func (*RetryError) Error

func (e *RetryError) Error() string

func (*RetryError) Unwrap

func (e *RetryError) Unwrap() error

type RetryEvent

type RetryEvent struct {
	Message Message
	Delay   time.Duration
	Error   error
	Time    time.Time
}

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts int           `json:"max_attempts"`
	Initial     time.Duration `json:"initial"`
	Max         time.Duration `json:"max"`
	Factor      float64       `json:"factor"`
	Jitter      bool          `json:"jitter"`
}

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

type Route

type Route struct {
	Name        string             `json:"name"`
	Mode        RouteMode          `json:"mode"`
	Match       string             `json:"match"`
	Headers     map[string]string  `json:"headers,omitempty"`
	PriorityMin int                `json:"priority_min,omitempty"`
	TenantID    string             `json:"tenant_id,omitempty"`
	To          []Destination      `json:"to,omitempty"`
	CopyTo      []Destination      `json:"copy_to,omitempty"`
	Enabled     bool               `json:"enabled"`
	Disabled    bool               `json:"disabled,omitempty"`
	Condition   func(Message) bool `json:"-"`

	// Strategy-based routing fields
	Strategy          StrategyType    `json:"strategy,omitempty"`
	Fallback          StrategyType    `json:"fallback,omitempty"`
	Weight            int             `json:"weight,omitempty"`
	HashKey           string          `json:"hash_key,omitempty"`
	StickyKey         string          `json:"sticky_key,omitempty"`
	MaxStickyBindings int             `json:"max_sticky_bindings,omitempty"`
	Capabilities      []string        `json:"capabilities,omitempty"`
	PriorityThreshold int             `json:"priority_threshold,omitempty"`
	Rules             []RoutingRule   `json:"rules,omitempty"`
	StrategyConfig    *StrategyConfig `json:"-"`
	// contains filtered or unexported fields
}

type RouteMode

type RouteMode string
const (
	RouteDirect          RouteMode = "direct"
	RouteTopic           RouteMode = "topic"
	RouteFanout          RouteMode = "fanout"
	RouteHeaders         RouteMode = "headers"
	RouteRules           RouteMode = "rules"
	RouteConsistentHash  RouteMode = "consistent_hash"
	RoutePriority        RouteMode = "priority"
	RouteDelay           RouteMode = "delay"
	RouteStream          RouteMode = "stream"
	RouteRoundRobin      RouteMode = "round_robin"
	RouteWeighted        RouteMode = "weighted_round_robin"
	RouteLeastLoaded     RouteMode = "least_loaded"
	RouteRandom          RouteMode = "random"
	RouteCapabilityBased RouteMode = "capability_based"
	RouteAdaptive        RouteMode = "adaptive_load_balance"
	RouteSticky          RouteMode = "sticky_session"
	RouteP2C             RouteMode = "power_of_two_choices"
	RouteSharded         RouteMode = "sharded"
	RouteDLX             RouteMode = "dead_letter_exchange"
)

type Router

type Router struct {
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

func (*Router) Add

func (r *Router) Add(route Route)

func (*Router) AddPlan

func (r *Router) AddPlan(plan RoutingPlan)

AddPlan adds a routing plan to the task router.

func (*Router) Clear

func (r *Router) Clear()

func (*Router) ConfigLoader

func (r *Router) ConfigLoader() *RoutingConfigLoader

ConfigLoader returns the routing configuration loader.

func (*Router) LoadRoutingConfig

func (r *Router) LoadRoutingConfig(data []byte) error

LoadRoutingConfig loads a complete routing configuration from bytes.

func (*Router) Remove

func (r *Router) Remove(name string) bool

Remove deletes a route by name and reports whether one was found. Every Add has a matching Remove: remote consumer subscriptions add routes to this global table, so without a way to take them out again a fleet of transient workers grew the routing table without bound.

func (*Router) RemovePlan

func (r *Router) RemovePlan(name string)

RemovePlan removes a routing plan from the task router.

func (*Router) RemovePrefix

func (r *Router) RemovePrefix(prefix string) int

RemovePrefix deletes every route whose name starts with prefix and returns how many were removed.

func (*Router) Route

func (r *Router) Route(ctx context.Context, msg Message) ([]Destination, []Route)

func (*Router) RouteWithStrategy

func (r *Router) RouteWithStrategy(ctx context.Context, msg Message, candidates []ConsumerCandidate) ([]ConsumerCandidate, []Route, error)

RouteWithStrategy selects consumers using the strategy assigned to the matched route.

func (*Router) Routes

func (r *Router) Routes() []Route

func (*Router) TaskRouter

func (r *Router) TaskRouter() *TaskRouter

TaskRouter returns the underlying TaskRouter for advanced configuration.

type RoutingConfig

type RoutingConfig struct {
	Plans           []RoutingPlan     `json:"plans,omitempty"`
	DefaultStrategy StrategyType      `json:"default_strategy"`
	GlobalHashKey   string            `json:"global_hash_key,omitempty"`
	Metadata        map[string]string `json:"metadata,omitempty"`
}

RoutingConfig is the top-level configuration for the task routing system.

func DefaultRoutingConfig

func DefaultRoutingConfig() RoutingConfig

DefaultRoutingConfig returns a RoutingConfig with sensible defaults.

func ParseBCLConfig

func ParseBCLConfig(bcl BCLRoutingConfig) (RoutingConfig, error)

ParseBCLConfig parses a BCL-format routing config and converts to internal RoutingConfig.

type RoutingConfigLoader

type RoutingConfigLoader struct {
	// contains filtered or unexported fields
}

RoutingConfigLoader handles loading and parsing routing configurations.

func NewRoutingConfigLoader

func NewRoutingConfigLoader() *RoutingConfigLoader

NewRoutingConfigLoader creates a new config loader with default strategies registered.

func (*RoutingConfigLoader) AddPlan

func (l *RoutingConfigLoader) AddPlan(plan RoutingPlan)

AddPlan adds or replaces a routing plan.

func (*RoutingConfigLoader) BuildStrategy

func (l *RoutingConfigLoader) BuildStrategy(plan RoutingPlan) ConsumerStrategy

BuildStrategy builds a ConsumerStrategy from a RoutingPlan.

func (*RoutingConfigLoader) GetConfig

func (l *RoutingConfigLoader) GetConfig() RoutingConfig

GetConfig returns a copy of the current routing configuration.

func (*RoutingConfigLoader) GetPlan

func (l *RoutingConfigLoader) GetPlan(name string) (RoutingPlan, bool)

GetPlan returns a routing plan by name.

func (*RoutingConfigLoader) GetPlanForQueue

func (l *RoutingConfigLoader) GetPlanForQueue(queue string) (RoutingPlan, bool)

GetPlanForQueue returns the first matching routing plan for a queue.

func (*RoutingConfigLoader) GetPlanForTopic

func (l *RoutingConfigLoader) GetPlanForTopic(topic string) (RoutingPlan, bool)

GetPlanForTopic returns the first matching routing plan for a topic.

func (*RoutingConfigLoader) LoadFromBytes

func (l *RoutingConfigLoader) LoadFromBytes(data []byte) error

LoadFromBytes parses routing configuration from JSON bytes.

func (*RoutingConfigLoader) LoadFromFile

func (l *RoutingConfigLoader) LoadFromFile(path string) error

LoadFromFile loads routing configuration from a JSON file.

func (*RoutingConfigLoader) LoadFromMap

func (l *RoutingConfigLoader) LoadFromMap(m map[string]any) error

LoadFromMap loads routing configuration from a map (useful for programmatic config).

func (*RoutingConfigLoader) Registry

func (l *RoutingConfigLoader) Registry() *StrategyRegistry

Registry returns the strategy registry.

func (*RoutingConfigLoader) RemovePlan

func (l *RoutingConfigLoader) RemovePlan(name string) bool

RemovePlan removes a routing plan by name.

type RoutingEvent

type RoutingEvent struct {
	Message      Message
	Route        Route
	Destinations []Destination
	Error        error
	Time         time.Time
}

type RoutingPlan

type RoutingPlan struct {
	Name              string        `json:"name"`
	Queue             string        `json:"queue,omitempty"`
	Topic             string        `json:"topic,omitempty"`
	Strategy          StrategyType  `json:"strategy"`
	Fallback          StrategyType  `json:"fallback,omitempty"`
	Weight            int           `json:"weight,omitempty"`
	HashKey           string        `json:"hash_key,omitempty"`
	StickyKey         string        `json:"sticky_key,omitempty"`
	MaxStickyBindings int           `json:"max_sticky_bindings,omitempty"`
	Capabilities      []string      `json:"capabilities,omitempty"`
	PriorityThreshold int           `json:"priority_threshold,omitempty"`
	Rules             []RoutingRule `json:"rules,omitempty"`
	Enabled           bool          `json:"enabled"`
	UpdatedAt         time.Time     `json:"updated_at"`
}

RoutingPlan defines a complete routing configuration for a queue or topic.

type RoutingRule

type RoutingRule struct {
	Name            string            `json:"name"`
	Priority        int               `json:"priority"`
	Enabled         bool              `json:"enabled"`
	MatchTopic      string            `json:"match_topic,omitempty"`
	MatchType       string            `json:"match_type,omitempty"`
	MatchHeaders    map[string]string `json:"match_headers,omitempty"`
	MatchTenantID   string            `json:"match_tenant_id,omitempty"`
	MatchPriority   int               `json:"match_priority_min,omitempty"`
	MatchKeyPattern string            `json:"match_key_pattern,omitempty"`
	TargetConsumers []string          `json:"target_consumers,omitempty"`
	Strategy        ConsumerStrategy  `json:"-"`
	StrategyType    StrategyType      `json:"strategy_type,omitempty"`
	Weight          int               `json:"weight,omitempty"`
	Metadata        map[string]string `json:"metadata,omitempty"`
}

RoutingRule defines a single routing rule for rule-based strategy.

func (*RoutingRule) Matches

func (r *RoutingRule) Matches(msg Message) bool

Matches returns true if the given message satisfies all conditions in this rule.

type SSEConfig

type SSEConfig = WebSocketConfig

type SSEServer

type SSEServer = WebSocketServer

func NewSSEServer

func NewSSEServer(b *Broker, cfg SSEConfig) *SSEServer

type SagaDefinition

type SagaDefinition struct {
	Name     string            `json:"name"`
	ID       string            `json:"id,omitempty"`
	Steps    []SagaStep        `json:"steps"`
	Metadata map[string]string `json:"metadata,omitempty"`
	TenantID string            `json:"tenant_id,omitempty"`
	Timeout  time.Duration     `json:"timeout,omitempty"`
}

type SagaEngine

type SagaEngine struct {
	// contains filtered or unexported fields
}

func NewSagaEngine

func NewSagaEngine(b *Broker) *SagaEngine

func (*SagaEngine) CleanupSagas

func (e *SagaEngine) CleanupSagas(maxAge time.Duration) int

CleanupSagas removes completed/failed/compensated sagas older than maxAge.

func (*SagaEngine) CreateSaga

func (e *SagaEngine) CreateSaga(ctx context.Context, def SagaDefinition) *SagaInstance

func (*SagaEngine) CreateSagaChecked

func (e *SagaEngine) CreateSagaChecked(ctx context.Context, def SagaDefinition) (*SagaInstance, error)

CreateSagaChecked applies the authenticated tenant scope before creating a saga. New code should use this method so authorization failures are explicit.

func (*SagaEngine) ExecuteSaga

func (e *SagaEngine) ExecuteSaga(ctx context.Context, sagaID string) error

func (*SagaEngine) GetSaga

func (e *SagaEngine) GetSaga(id string) (SagaInstance, bool)

func (*SagaEngine) GetSagaContext

func (e *SagaEngine) GetSagaContext(ctx context.Context, id string) (SagaInstance, bool)

func (*SagaEngine) ListSagas

func (e *SagaEngine) ListSagas() []SagaInstance

func (*SagaEngine) ListSagasByStatus

func (e *SagaEngine) ListSagasByStatus(st SagaStatus) []SagaInstance

func (*SagaEngine) ListSagasContext

func (e *SagaEngine) ListSagasContext(ctx context.Context) []SagaInstance

type SagaInstance

type SagaInstance struct {
	SagaDefinition
	ID          string           `json:"id"`
	Status      SagaStatus       `json:"status"`
	Results     []SagaStepResult `json:"results"`
	CurrentStep int              `json:"current_step"`
	CreatedAt   time.Time        `json:"created_at"`
	UpdatedAt   time.Time        `json:"updated_at"`
	FinishedAt  time.Time        `json:"finished_at,omitempty"`
	Error       string           `json:"error,omitempty"`
	// contains filtered or unexported fields
}

type SagaStatus

type SagaStatus string
const (
	SagaCreated      SagaStatus = "created"
	SagaExecuting    SagaStatus = "executing"
	SagaCompleted    SagaStatus = "completed"
	SagaCompensating SagaStatus = "compensating"
	SagaCompensated  SagaStatus = "compensated"
	SagaFailed       SagaStatus = "failed"
)

type SagaStep

type SagaStep struct {
	Name       string         `json:"name"`
	Action     SagaStepAction `json:"action"`
	Compensate SagaStepAction `json:"compensate,omitempty"`
	Optional   bool           `json:"optional,omitempty"`
}

type SagaStepAction

type SagaStepAction struct {
	TaskName string            `json:"task_name"`
	Queue    string            `json:"queue,omitempty"`
	Payload  any               `json:"payload,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
	Timeout  time.Duration     `json:"timeout,omitempty"`
}

type SagaStepResult

type SagaStepResult struct {
	StepName    string     `json:"step_name"`
	TaskID      string     `json:"task_id,omitempty"`
	Status      TaskStatus `json:"status"`
	StartedAt   time.Time  `json:"started_at"`
	CompletedAt time.Time  `json:"completed_at,omitempty"`
	Error       string     `json:"error,omitempty"`
	Result      []byte     `json:"result,omitempty"`
}

type ScheduleResult

type ScheduleResult struct {
	MessageID  string `json:"message_id"`
	ScheduleID string `json:"schedule_id"`
	RunAt      string `json:"run_at"`
}

type SchemaCompatibility

type SchemaCompatibility string

SchemaCompatibility represents the compatibility level between two schema versions.

const (
	SchemaCompatible    SchemaCompatibility = "compatible"
	SchemaIncompatible  SchemaCompatibility = "incompatible"
	SchemaForwardCompat SchemaCompatibility = "forward_compatible"
)

type SchemaDefinition

type SchemaDefinition struct {
	Name           string   `json:"name"`
	Version        string   `json:"version"`
	ContentType    string   `json:"content_type"`
	Required       []string `json:"required,omitempty"`
	AllowUnknown   bool     `json:"allow_unknown"`
	CompatibleWith string   `json:"compatible_with,omitempty"` // previous version this is compatible with
	Deprecated     bool     `json:"deprecated,omitempty"`
	Description    string   `json:"description,omitempty"`
}

type SchemaRegistry

type SchemaRegistry interface {
	Register(SchemaDefinition) error
	Validate(context.Context, Message) error
}

SchemaRegistry validates producer payloads before they enter the broker. It is deliberately small and dependency-free; production deployments can replace it with a JSON Schema, Protobuf, Avro, or external registry implementation.

type SecurityConfig

type SecurityConfig struct {
	InsecureDev       bool `json:"insecure_dev,omitempty"`
	RequireTLS        bool `json:"require_tls,omitempty"`
	RequireClientCert bool `json:"require_client_cert,omitempty"`
}

SecurityConfig centralizes the production listener security policy.

type SegmentCompactor

type SegmentCompactor struct {
	// contains filtered or unexported fields
}

SegmentCompactor runs active log compaction and segment retention in the background.

func (*SegmentCompactor) Compact

func (c *SegmentCompactor) Compact(ctx context.Context) error

Compact performs an active compaction pass: creates a snapshot checkpoint of live state, and deletes immutable segments that are older than retention or exceed maxSegments.

func (*SegmentCompactor) Start

func (c *SegmentCompactor) Start()

Start launches the compaction background goroutine.

func (*SegmentCompactor) Stop

func (c *SegmentCompactor) Stop()

Stop terminates the background compactor.

type SegmentMeta

type SegmentMeta struct {
	ID         uint64    `json:"id"`
	Filename   string    `json:"filename"`
	IndexFile  string    `json:"index_file"`
	SizeBytes  int64     `json:"size_bytes"`
	Records    uint64    `json:"records"`
	FirstSeq   uint64    `json:"first_seq"`
	LastSeq    uint64    `json:"last_seq"`
	CreatedAt  time.Time `json:"created_at"`
	ClosedAt   time.Time `json:"closed_at,omitempty"`
	CleanClose bool      `json:"clean_close"`
}

SegmentMeta tracks metadata about a single WAL segment.

type SegmentedWALConfig

type SegmentedWALConfig struct {
	Dir                string
	MaxSegmentSize     int64
	MaxSegments        int
	CompactionInterval time.Duration
	Retention          time.Duration
	Codec              FrameCodec
	WALCodec           *WALRecordCodec
	DisableCompactor   bool
}

SegmentedWALConfig configures the BWL2 segmented storage engine.

func (SegmentedWALConfig) LegacyCodec

func (cfg SegmentedWALConfig) LegacyCodec() FrameCodec

type SegmentedWALManifest

type SegmentedWALManifest struct {
	Version          int           `json:"version"`
	ActiveSegment    uint64        `json:"active_segment"`
	NextSeq          uint64        `json:"next_seq"`
	Segments         []SegmentMeta `json:"segments"`
	LastCompactionAt time.Time     `json:"last_compaction_at,omitempty"`
	CheckpointFile   string        `json:"checkpoint_file,omitempty"`
}

SegmentedWALManifest tracks all active and archived segments in the log.

type SegmentedWALStore

type SegmentedWALStore struct {
	*MemoryStore
	// contains filtered or unexported fields
}

SegmentedWALStore is a multi-segment, durable WAL store with manifest tracking, sparse indexing, active log compaction, and automatic migration from BWL1.

func NewSegmentedWALStore

func NewSegmentedWALStore(cfg SegmentedWALConfig) (*SegmentedWALStore, error)

NewSegmentedWALStore opens or initializes a segmented BWL2 store in the given directory.

func (*SegmentedWALStore) Ack

func (*SegmentedWALStore) AckBatch

func (s *SegmentedWALStore) AckBatch(ctx context.Context, reqs []AckRequest) []error

func (*SegmentedWALStore) Append

func (s *SegmentedWALStore) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

func (*SegmentedWALStore) AppendAtomic

func (s *SegmentedWALStore) AppendAtomic(ctx context.Context, entries []AppendEntry) ([]Message, error)

func (*SegmentedWALStore) AppendAtomicMinimal

func (s *SegmentedWALStore) AppendAtomicMinimal(ctx context.Context, entries []AppendEntry) error

func (*SegmentedWALStore) AppendAtomicOwned

func (s *SegmentedWALStore) AppendAtomicOwned(ctx context.Context, entries []AppendEntry) error

func (*SegmentedWALStore) Close

func (s *SegmentedWALStore) Close() error

func (*SegmentedWALStore) CommitOffset

func (s *SegmentedWALStore) CommitOffset(ctx context.Context, commit OffsetCommit) error

func (*SegmentedWALStore) CommitStreamTransaction

func (s *SegmentedWALStore) CommitStreamTransaction(ctx context.Context, tx StreamTransaction) ([]Message, error)

func (*SegmentedWALStore) ConfirmationLevel

func (*SegmentedWALStore) ConfirmationLevel() ConfirmLevel

func (*SegmentedWALStore) DeclareQueue

func (s *SegmentedWALStore) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*SegmentedWALStore) DeclareStream

func (s *SegmentedWALStore) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*SegmentedWALStore) DeclareTopic

func (s *SegmentedWALStore) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*SegmentedWALStore) ExtendLease

func (s *SegmentedWALStore) ExtendLease(ctx context.Context, req LeaseRequest) error

func (*SegmentedWALStore) Lease

func (s *SegmentedWALStore) Lease(ctx context.Context, req LeaseRequest) ([]Message, error)

func (*SegmentedWALStore) Move

func (*SegmentedWALStore) Nack

func (*SegmentedWALStore) PauseQueue

func (s *SegmentedWALStore) PauseQueue(ctx context.Context, name string) error

func (*SegmentedWALStore) PurgeQueue

func (s *SegmentedWALStore) PurgeQueue(ctx context.Context, name string) (int, error)

func (*SegmentedWALStore) ResumeQueue

func (s *SegmentedWALStore) ResumeQueue(ctx context.Context, name string) error

func (*SegmentedWALStore) SetHealthCallback

func (s *SegmentedWALStore) SetHealthCallback(fn func(error))

func (*SegmentedWALStore) StoreHealth

func (s *SegmentedWALStore) StoreHealth() error

func (*SegmentedWALStore) Update

func (s *SegmentedWALStore) Update(ctx context.Context, msg Message) error

func (*SegmentedWALStore) UpdateBatch

func (s *SegmentedWALStore) UpdateBatch(ctx context.Context, messages []Message) []error

type SegmentedWALVerificationReport

type SegmentedWALVerificationReport struct {
	Dir             string                   `json:"dir"`
	ManifestVersion int                      `json:"manifest_version"`
	ActiveSegment   uint64                   `json:"active_segment"`
	TotalSegments   int                      `json:"total_segments"`
	TotalRecords    uint64                   `json:"total_records"`
	TotalBytes      int64                    `json:"total_bytes"`
	SegmentReports  []WALVerificationReport  `json:"segment_reports"`
	Problems        []WALVerificationProblem `json:"problems,omitempty"`
	VerifiedAt      time.Time                `json:"verified_at"`
}

func VerifySegmentedWAL

func VerifySegmentedWAL(dir string, walCodec *WALRecordCodec, legacyCodec FrameCodec) (SegmentedWALVerificationReport, error)

VerifySegmentedWAL verifies all segments and manifest in a BWL2 segmented WAL directory.

func (SegmentedWALVerificationReport) Valid

type Severity

type Severity string
const (
	SeverityDebug Severity = "debug"
	SeverityInfo  Severity = "info"
	SeverityWarn  Severity = "warn"
	SeverityError Severity = "error"
)

type ShovelConfig

type ShovelConfig struct {
	// Source is the source queue to read from.
	Source string `json:"source"`
	// Destination is the destination queue to write to.
	Destination string `json:"destination"`
	// BatchSize is messages per batch. Default: 100.
	BatchSize int `json:"batch_size,omitempty"`
	// PollInterval is polling frequency. Default: 100ms.
	PollInterval time.Duration `json:"poll_interval,omitempty"`
}

ShovelConfig configures a shovel (one-directional message forwarding).

type ShovelManager

type ShovelManager struct {
	// contains filtered or unexported fields
}

ShovelManager manages shovels.

func NewShovelManager

func NewShovelManager(b *Broker) *ShovelManager

NewShovelManager creates a new shovel manager.

func (*ShovelManager) StartShovel

func (sm *ShovelManager) StartShovel(cfg ShovelConfig) string

StartShovel starts a shovel between two queues.

func (*ShovelManager) Stop

func (sm *ShovelManager) Stop()

Stop halts all shovels.

func (*ShovelManager) StopShovel

func (sm *ShovelManager) StopShovel(id string)

StopShovel stops a shovel.

type SparseIndex

type SparseIndex struct {
	// contains filtered or unexported fields
}

SparseIndex maintains an ordered list of index entries for fast seeks.

func LoadSparseIndex

func LoadSparseIndex(path string, step int) (*SparseIndex, error)

LoadSparseIndex reads a sparse index binary file into memory.

func NewSparseIndex

func NewSparseIndex(step int) *SparseIndex

NewSparseIndex creates an empty sparse index.

func (*SparseIndex) Add

func (idx *SparseIndex) Add(seq uint64, offset int64, t int64) bool

Add appends an entry if the step count is reached or if it's the very first entry.

func (*SparseIndex) Entries

func (idx *SparseIndex) Entries() []IndexEntry

Entries returns a copy of all index entries.

func (*SparseIndex) FindOffset

func (idx *SparseIndex) FindOffset(seq uint64) int64

FindOffset returns the closest file offset <= target sequence. If target sequence is before the first entry, returns 0.

func (*SparseIndex) ForceAdd

func (idx *SparseIndex) ForceAdd(seq uint64, offset int64, t int64)

ForceAdd unconditionally records an index entry (e.g. for segment start or key checkpoints).

func (*SparseIndex) SaveToFile

func (idx *SparseIndex) SaveToFile(path string) error

SaveToFile serializes the sparse index to disk in binary format: [Magic:4][Version:1][Reserved:3][Count:8][Entry1:24]...[EntryN:24]

type StateStore

StateStore persists broker/task/consumer/publisher control-plane state. The existing Store interface remains the high-performance message data-plane.

type StatsResponse

type StatsResponse struct {
	State          BrokerState      `json:"state"`
	StoreStats     StoreStats       `json:"store_stats"`
	Goroutines     int              `json:"goroutines"`
	Memory         runtime.MemStats `json:"memory"`
	Uptime         string           `json:"uptime"`
	StartedAt      time.Time        `json:"started_at"`
	LastGCDuration string           `json:"last_gc_duration"`
	NumGC          uint32           `json:"num_gc"`
	PauseTotal     string           `json:"pause_total"`
}

type StorageConfig

type StorageConfig struct {
	Directory       string `json:"directory,omitempty"`
	SegmentBytes    int64  `json:"segment_bytes,omitempty"`
	MaxDiskBytes    int64  `json:"max_disk_bytes,omitempty"`
	Sync            bool   `json:"sync"`
	EncryptionKeyID string `json:"encryption_key_id,omitempty"`
}

StorageConfig contains durable-store policy independent of a concrete Store.

type StorageEvent

type StorageEvent struct {
	Message   Message
	Operation string
	Error     error
	Time      time.Time
}

type StoreCircuitBreaker

type StoreCircuitBreaker struct {
	// contains filtered or unexported fields
}

StoreCircuitBreaker wraps a Store with circuit breaker protection.

func NewStoreCircuitBreaker

func NewStoreCircuitBreaker(store Store, cfg CircuitBreakerConfig) *StoreCircuitBreaker

NewStoreCircuitBreaker wraps a store with circuit breaker protection.

func (*StoreCircuitBreaker) Ack

func (scb *StoreCircuitBreaker) Ack(ctx context.Context, req AckRequest) error

func (*StoreCircuitBreaker) Append

func (scb *StoreCircuitBreaker) Append(ctx context.Context, msg Message, dests []Destination) ([]Message, error)

func (*StoreCircuitBreaker) Close

func (scb *StoreCircuitBreaker) Close() error

func (*StoreCircuitBreaker) CommitOffset

func (scb *StoreCircuitBreaker) CommitOffset(ctx context.Context, commit OffsetCommit) error

func (*StoreCircuitBreaker) ConsumerOffset

func (scb *StoreCircuitBreaker) ConsumerOffset(ctx context.Context, commit OffsetCommit) (uint64, error)

func (*StoreCircuitBreaker) DeclareQueue

func (scb *StoreCircuitBreaker) DeclareQueue(ctx context.Context, cfg QueueConfig) error

func (*StoreCircuitBreaker) DeclareStream

func (scb *StoreCircuitBreaker) DeclareStream(ctx context.Context, cfg StreamConfig) error

func (*StoreCircuitBreaker) DeclareTopic

func (scb *StoreCircuitBreaker) DeclareTopic(ctx context.Context, cfg TopicConfig) error

func (*StoreCircuitBreaker) ExtendLease

func (scb *StoreCircuitBreaker) ExtendLease(ctx context.Context, req LeaseRequest) error

func (*StoreCircuitBreaker) Get

func (scb *StoreCircuitBreaker) Get(ctx context.Context, id string) (Message, bool, error)

func (*StoreCircuitBreaker) History

func (scb *StoreCircuitBreaker) History(ctx context.Context, id string) ([]MessageHistory, error)

func (*StoreCircuitBreaker) Lease

func (scb *StoreCircuitBreaker) Lease(ctx context.Context, req LeaseRequest) ([]Message, error)

func (*StoreCircuitBreaker) ListDLQ

func (scb *StoreCircuitBreaker) ListDLQ(ctx context.Context, name string, limit int) ([]Message, error)

func (*StoreCircuitBreaker) ListQueue

func (scb *StoreCircuitBreaker) ListQueue(ctx context.Context, name string, limit int) ([]Message, error)

func (*StoreCircuitBreaker) Move

func (*StoreCircuitBreaker) Nack

func (scb *StoreCircuitBreaker) Nack(ctx context.Context, req NackRequest) error

func (*StoreCircuitBreaker) PauseQueue

func (scb *StoreCircuitBreaker) PauseQueue(ctx context.Context, name string) error

func (*StoreCircuitBreaker) PurgeQueue

func (scb *StoreCircuitBreaker) PurgeQueue(ctx context.Context, name string) (int, error)

func (*StoreCircuitBreaker) ReadStream

func (scb *StoreCircuitBreaker) ReadStream(ctx context.Context, req StreamReadRequest) ([]Message, error)

func (*StoreCircuitBreaker) ResumeQueue

func (scb *StoreCircuitBreaker) ResumeQueue(ctx context.Context, name string) error

func (*StoreCircuitBreaker) State

func (scb *StoreCircuitBreaker) State() CircuitState

State returns the circuit breaker state.

func (*StoreCircuitBreaker) Stats

func (scb *StoreCircuitBreaker) Stats(ctx context.Context) (StoreStats, error)

func (*StoreCircuitBreaker) SweepLeases

func (scb *StoreCircuitBreaker) SweepLeases(ctx context.Context, now time.Time) (int, error)

func (*StoreCircuitBreaker) Update

func (scb *StoreCircuitBreaker) Update(ctx context.Context, msg Message) error

type StoreHealthCallbackRegistrar

type StoreHealthCallbackRegistrar interface {
	SetHealthCallback(fn func(error))
}

StoreHealthCallbackRegistrar allows registering an immediate notification callback when a store suffers an unrecoverable I/O or fsync fault.

type StoreHealthMonitor

type StoreHealthMonitor struct {
	// contains filtered or unexported fields
}

StoreHealthMonitor watches storage health and transitions the broker to BrokerDegraded when storage becomes unavailable. While fenced, write operations fail fast with ErrStorageUnavailable.

func NewStoreHealthMonitor

func NewStoreHealthMonitor(b *Broker, store Store, interval time.Duration) *StoreHealthMonitor

NewStoreHealthMonitor creates a health monitor for the given broker and store.

func (*StoreHealthMonitor) CheckHealth

func (m *StoreHealthMonitor) CheckHealth(ctx context.Context) error

CheckHealth queries the underlying store for health issues and fences if faulty.

func (*StoreHealthMonitor) Fence

func (m *StoreHealthMonitor) Fence(err error)

Fence immediately marks the store as degraded and fenced.

func (*StoreHealthMonitor) FenceError

func (m *StoreHealthMonitor) FenceError() error

FenceError returns the error that caused the store to fence, or nil.

func (*StoreHealthMonitor) IsFenced

func (m *StoreHealthMonitor) IsFenced() bool

IsFenced reports whether the store is currently fenced.

func (*StoreHealthMonitor) SetOnFenced

func (m *StoreHealthMonitor) SetOnFenced(fn func(error))

SetOnFenced sets a hook to execute when the store enters a fenced state.

func (*StoreHealthMonitor) Start

func (m *StoreHealthMonitor) Start(ctx context.Context)

Start launches the background health check poller.

func (*StoreHealthMonitor) Stop

func (m *StoreHealthMonitor) Stop()

Stop terminates the polling loop.

type StoreHealthProvider

type StoreHealthProvider interface {
	StoreHealth() error
}

StoreHealthProvider exposes persistent write-path failures to readiness checks. A store that has fenced itself must return that error until reopened.

type StoreStats

type StoreStats struct {
	Queues     map[string]int               `json:"queues"`
	Topics     map[string]int               `json:"topics"`
	Streams    map[string]int               `json:"streams"`
	Offsets    map[string]map[string]uint64 `json:"offsets,omitempty"`
	DLQ        map[string]int               `json:"dlq"`
	Messages   int                          `json:"messages"`
	Leased     int                          `json:"leased"`
	DeadLetter int                          `json:"dead_letter"`
}

type StrategyConfig

type StrategyConfig struct {
	Type              StrategyType      `json:"type"`
	Queue             string            `json:"queue,omitempty"`
	Topic             string            `json:"topic,omitempty"`
	Weight            int               `json:"weight,omitempty"`
	HashKey           string            `json:"hash_key,omitempty"`
	StickyKey         string            `json:"sticky_key,omitempty"`
	MaxStickyBindings int               `json:"max_sticky_bindings,omitempty"`
	PriorityThreshold int               `json:"priority_threshold,omitempty"`
	Capabilities      []string          `json:"capabilities,omitempty"`
	FallbackStrategy  StrategyType      `json:"fallback_strategy,omitempty"`
	Rules             []RoutingRule     `json:"rules,omitempty"`
	Metadata          map[string]string `json:"metadata,omitempty"`
}

StrategyConfig holds configuration for a consumer strategy.

type StrategyRegistry

type StrategyRegistry struct {
	// contains filtered or unexported fields
}

func NewStrategyRegistry

func NewStrategyRegistry() *StrategyRegistry

func (*StrategyRegistry) Get

func (*StrategyRegistry) List

func (r *StrategyRegistry) List() []StrategyType

func (*StrategyRegistry) Register

func (r *StrategyRegistry) Register(strategy ConsumerStrategy)

type StrategyType

type StrategyType string

StrategyType enumerates all built-in consumer routing strategies.

const (
	StrategyRoundRobin          StrategyType = "round_robin"
	StrategyWeightedRoundRobin  StrategyType = "weighted_round_robin"
	StrategyLeastLoaded         StrategyType = "least_loaded"
	StrategyRandom              StrategyType = "random"
	StrategyConsistentHash      StrategyType = "consistent_hash"
	StrategyCapabilityBased     StrategyType = "capability_based"
	StrategyPriorityAware       StrategyType = "priority_aware"
	StrategyAdaptiveLoadBalance StrategyType = "adaptive_load_balance"
	StrategyStickySession       StrategyType = "sticky_session"
	StrategyFanOut              StrategyType = "fan_out"
	StrategyRuleBased           StrategyType = "rule_based"
	StrategyPowerOfTwoChoices   StrategyType = "power_of_two_choices"
	StrategySharded             StrategyType = "sharded"
	StrategyHealthBased         StrategyType = "health_based"
)

type StreamCompactionStats

type StreamCompactionStats struct {
	Stream     string `json:"stream"`
	TotalMsgs  int    `json:"total_messages"`
	Duplicates int    `json:"duplicates"`
	Compacted  int    `json:"compacted"`
}

StreamCompactionStats holds compaction statistics.

type StreamConfig

type StreamConfig struct {
	Name       string        `json:"name"`
	Partitions int           `json:"partitions"`
	Retention  time.Duration `json:"retention"`
	Compact    bool          `json:"compact"`
}

type StreamConsumerLag

type StreamConsumerLag struct {
	Stream      string            `json:"stream"`
	HeadOffset  uint64            `json:"head_offset"`
	ConsumerLag map[string]uint64 `json:"consumer_lag"`
}

StreamConsumerLag is a result type for stream lag queries.

type StreamLogCompaction

type StreamLogCompaction struct {
	// contains filtered or unexported fields
}

StreamLogCompaction provides log compaction for streams.

func NewStreamLogCompaction

func NewStreamLogCompaction(b *Broker) *StreamLogCompaction

NewStreamLogCompaction creates a new stream log compaction helper.

func (*StreamLogCompaction) CompactByDedup

func (slc *StreamLogCompaction) CompactByDedup(ctx context.Context, stream string, limit int) (int, error)

CompactByDedup removes duplicate messages from a stream based on deduplication key.

func (*StreamLogCompaction) StatsForStream

func (slc *StreamLogCompaction) StatsForStream(ctx context.Context, stream string) (*StreamCompactionStats, error)

StatsForStream returns compaction stats for a stream.

type StreamReadRequest

type StreamReadRequest struct {
	Stream        string `json:"stream"`
	ConsumerGroup string `json:"consumer_group,omitempty"`
	AfterOffset   uint64 `json:"after_offset,omitempty"`
	Limit         int    `json:"limit,omitempty"`
	TenantID      string `json:"tenant_id,omitempty"`
}

type StreamTransaction

type StreamTransaction struct {
	Offset         OffsetCommit  `json:"offset"`
	ExpectedOffset uint64        `json:"expected_offset"`
	Entries        []AppendEntry `json:"entries,omitempty"`
}

StreamTransaction atomically advances one consumer group's input offset and appends its outputs. ExpectedOffset must equal the currently committed offset; Offset.Offset must advance it and cannot exceed the input stream's end. All outputs belong to the same tenant as the offset commit.

type StreamTransactionHTTPPayload

type StreamTransactionHTTPPayload struct {
	ConsumerGroup  string               `json:"consumer_group"`
	TenantID       string               `json:"tenant_id,omitempty"`
	ExpectedOffset uint64               `json:"expected_offset"`
	Offset         uint64               `json:"offset"`
	Messages       []PublishHTTPPayload `json:"messages,omitempty"`
}

StreamTransactionHTTPPayload is the request body for POST /v1/streams/{input}/transactions. Messages use the normal publish payload and options, including JSON or base64 encoding for binary payloads.

type StreamTransactionStore

type StreamTransactionStore interface {
	CommitStreamTransaction(context.Context, StreamTransaction) ([]Message, error)
}

StreamTransactionStore is optional. Stores must either commit the entire operation or reject it; callers must never emulate it with separate appends and offset commits. External application side effects are outside this atomicity.

type Subscription

type Subscription struct {
	// contains filtered or unexported fields
}

func (*Subscription) ID

func (s *Subscription) ID() string

func (*Subscription) Pause

func (s *Subscription) Pause()

func (*Subscription) Resume

func (s *Subscription) Resume()

func (*Subscription) Stop

func (s *Subscription) Stop()

type TTLSweepResult

type TTLSweepResult struct {
	Inspected    int `json:"inspected"`
	Expired      int `json:"expired"`
	DeadLettered int `json:"dead_lettered"`
	Purged       int `json:"purged"`
}

TTLSweepResult summarizes the results of a TTL sweep iteration.

type TTLSweeper

type TTLSweeper struct {
	// contains filtered or unexported fields
}

TTLSweeper inspects queue messages and cleans up expired messages.

func NewTTLSweeper

func NewTTLSweeper(b *Broker, cfg TTLSweeperConfig) *TTLSweeper

NewTTLSweeper creates a new queue message TTL sweeper.

func (*TTLSweeper) Start

func (ts *TTLSweeper) Start(ctx context.Context)

Start runs the TTL sweeper loop in the background.

func (*TTLSweeper) Stop

func (ts *TTLSweeper) Stop()

Stop stops the background sweeper.

func (*TTLSweeper) Sweep

func (ts *TTLSweeper) Sweep(ctx context.Context) (TTLSweepResult, error)

Sweep inspects all queues for expired messages and moves them to DLQ or purges them.

type TTLSweeperConfig

type TTLSweeperConfig struct {
	Interval    time.Duration `json:"interval"`
	ExpireToDLQ bool          `json:"expire_to_dlq"`
	BatchSize   int           `json:"batch_size"`
}

TTLSweeperConfig configures queue message TTL sweeping.

type TaskDelivery

type TaskDelivery struct {
	Delivery
	Task TaskInfo
}

func (TaskDelivery) Decode

func (d TaskDelivery) Decode(out any) error

type TaskEvent

type TaskEvent struct {
	Task  TaskInfo
	Error error
	Time  time.Time
}

type TaskFuture

type TaskFuture interface{ TaskHandle }

type TaskHandler

type TaskHandler func(context.Context, TaskDelivery) (any, error)

type TaskInfo

type TaskInfo struct {
	ID         string            `json:"id"`
	Name       string            `json:"name"`
	Queue      string            `json:"queue"`
	Status     TaskStatus        `json:"status"`
	TenantID   string            `json:"tenant_id,omitempty"`
	MessageID  string            `json:"message_id,omitempty"`
	Attempts   int               `json:"attempts,omitempty"`
	Progress   Progress          `json:"progress,omitempty"`
	CreatedAt  time.Time         `json:"created_at"`
	StartedAt  time.Time         `json:"started_at,omitempty"`
	UpdatedAt  time.Time         `json:"updated_at"`
	FinishedAt time.Time         `json:"finished_at,omitempty"`
	LastError  string            `json:"last_error,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	Result     []byte            `json:"result,omitempty"`
}

type TaskOption

type TaskOption func(*TaskOptions)

func WithTaskDelay

func WithTaskDelay(v time.Duration) TaskOption

func WithTaskID

func WithTaskID(v string) TaskOption

func WithTaskIdempotencyKey

func WithTaskIdempotencyKey(v string) TaskOption

func WithTaskMaxAttempts

func WithTaskMaxAttempts(v int) TaskOption

func WithTaskMetadata

func WithTaskMetadata(v map[string]string) TaskOption

func WithTaskPriority

func WithTaskPriority(v int) TaskOption

func WithTaskProgressTopic

func WithTaskProgressTopic(v string) TaskOption

func WithTaskQueue

func WithTaskQueue(v string) TaskOption

func WithTaskResultTopic

func WithTaskResultTopic(v string) TaskOption

func WithTaskRetryPolicy

func WithTaskRetryPolicy(v RetryPolicy) TaskOption

func WithTaskRunAt

func WithTaskRunAt(v time.Time) TaskOption

func WithTaskTenantID

func WithTaskTenantID(v string) TaskOption

func WithTaskTimeout

func WithTaskTimeout(v time.Duration) TaskOption

type TaskOptions

type TaskOptions struct {
	ID             string
	Queue          string
	Priority       int
	Delay          time.Duration
	RunAt          time.Time
	Timeout        time.Duration
	MaxAttempts    int
	RetryPolicy    RetryPolicy
	Metadata       map[string]string
	IdempotencyKey string
	TenantID       string
	ProgressTopic  string
	ResultTopic    string
}

type TaskResult

type TaskResult struct {
	Task    TaskInfo `json:"task"`
	Payload []byte   `json:"payload,omitempty"`
	Error   error    `json:"-"`
}

type TaskRouter

type TaskRouter struct {
	// contains filtered or unexported fields
}

TaskRouter provides strategy-based message routing with fallback support.

func NewTaskRouter

func NewTaskRouter(loader *RoutingConfigLoader) *TaskRouter

NewTaskRouter creates a TaskRouter from a RoutingConfigLoader.

func (*TaskRouter) ListPlans

func (tr *TaskRouter) ListPlans() []string

ListPlans returns all active plan names.

func (*TaskRouter) RegisterPlan

func (tr *TaskRouter) RegisterPlan(plan RoutingPlan)

RegisterPlan adds a plan at runtime.

func (*TaskRouter) Reload

func (tr *TaskRouter) Reload() error

Reload re-reads configuration and recompiles all plans.

func (*TaskRouter) SelectConsumers

func (tr *TaskRouter) SelectConsumers(ctx context.Context, msg Message, candidates []ConsumerCandidate) ([]ConsumerCandidate, error)

SelectConsumers selects one or more consumers for the given message.

func (*TaskRouter) UnregisterPlan

func (tr *TaskRouter) UnregisterPlan(name string)

UnregisterPlan removes a plan at runtime.

type TaskStateStore

type TaskStateStore interface {
	PutTask(context.Context, TaskInfo) error
	GetTask(context.Context, string) (TaskInfo, bool, error)
	ListTasks(context.Context, TaskStatus, int) ([]TaskInfo, error)
	DeleteTask(context.Context, string) error
}

type TaskStatus

type TaskStatus string
const (
	TaskCreated      TaskStatus = "created"
	TaskValidated    TaskStatus = "validated"
	TaskScheduled    TaskStatus = "scheduled"
	TaskQueued       TaskStatus = "queued"
	TaskLeased       TaskStatus = "leased"
	TaskRunning      TaskStatus = "running"
	TaskProgressing  TaskStatus = "progressing"
	TaskWaiting      TaskStatus = "waiting"
	TaskBlocked      TaskStatus = "blocked"
	TaskRetrying     TaskStatus = "retrying"
	TaskSucceeded    TaskStatus = "succeeded"
	TaskFailed       TaskStatus = "failed"
	TaskCancelled    TaskStatus = "cancelled"
	TaskExpired      TaskStatus = "expired"
	TaskDeadLettered TaskStatus = "dead_lettered"
	TaskCompensating TaskStatus = "compensating"
	TaskCompensated  TaskStatus = "compensated"
	TaskArchived     TaskStatus = "archived"
)

type TenancyConfig

type TenancyConfig struct {
	// Enabled activates tenancy isolation. Default: false.
	Enabled bool `json:"enabled"`
	// DefaultTenant is the tenant for unauthenticated requests. Default: "default".
	DefaultTenant string `json:"default_tenant,omitempty"`
	// IsolationLevel determines how tenants are isolated. Default: "queue_prefix".
	IsolationLevel IsolationLevel `json:"isolation_level,omitempty"`
	// QueuePrefix is the prefix added to queue names per tenant. Default: "t.<tenant>.".
	QueuePrefix string `json:"queue_prefix,omitempty"`
	// MaxQueuesPerTenant limits queues per tenant. 0 = unlimited.
	MaxQueuesPerTenant int `json:"max_queues_per_tenant,omitempty"`
	// MaxMessagesPerTenant limits total messages per tenant. 0 = unlimited.
	MaxMessagesPerTenant int `json:"max_messages_per_tenant,omitempty"`
	// RateLimitPerTenant limits messages per second per tenant. 0 = unlimited.
	RateLimitPerTenant int `json:"rate_limit_per_tenant,omitempty"`
}

TenancyConfig configures multi-tenancy isolation.

type TenantManager

type TenantManager struct {
	// contains filtered or unexported fields
}

TenantManager manages multi-tenancy isolation.

func NewTenantManager

func NewTenantManager(b *Broker, cfg TenancyConfig) *TenantManager

NewTenantManager creates a new tenant manager.

func (*TenantManager) CheckPublishQuota

func (tm *TenantManager) CheckPublishQuota(ctx context.Context, tenant string, destinations []Destination) error

func (*TenantManager) CheckQuota

func (tm *TenantManager) CheckQuota(ctx context.Context, tenant string) error

CheckQuota checks if a tenant has exceeded its quotas.

func (*TenantManager) EnsureTenant

func (tm *TenantManager) EnsureTenant(name string) *TenantState

EnsureTenant creates a tenant if it doesn't exist.

func (*TenantManager) GetTenant

func (tm *TenantManager) GetTenant(name string) *TenantState

GetTenant returns the state for a tenant.

func (*TenantManager) ListTenants

func (tm *TenantManager) ListTenants() []*TenantState

ListTenants returns all tenant states.

func (*TenantManager) QueueName

func (tm *TenantManager) QueueName(tenant, queue string) string

QueueName returns the tenant-isolated queue name.

func (*TenantManager) StatsForTenant

func (tm *TenantManager) StatsForTenant(ctx context.Context, tenant string) (*TenantStats, error)

StatsForTenant returns stats for a specific tenant.

func (*TenantManager) Stop

func (tm *TenantManager) Stop()

func (*TenantManager) TenantAwarePublish

func (tm *TenantManager) TenantAwarePublish(ctx context.Context, tenant string, topic string, payload any, opts ...PublishOption) (PublishResult, error)

TenantAwarePublish wraps publish with tenant isolation.

func (*TenantManager) TenantAwareSubscribe

func (tm *TenantManager) TenantAwareSubscribe(ctx context.Context, tenant string, cfg ConsumerConfig, handler Handler) (*Subscription, error)

TenantAwareSubscribe wraps subscribe with tenant isolation.

func (*TenantManager) TopicName

func (tm *TenantManager) TopicName(tenant, topic string) string

TopicName returns the tenant-isolated topic name.

type TenantQuotas

type TenantQuotas struct {
	MaxQueues   int `json:"max_queues"`
	MaxMessages int `json:"max_messages"`
	RateLimit   int `json:"rate_limit"`
}

type TenantState

type TenantState struct {
	Name         string       `json:"name"`
	QueueCount   int          `json:"queue_count"`
	MessageCount int          `json:"message_count"`
	CreatedAt    time.Time    `json:"created_at"`
	Quotas       TenantQuotas `json:"quotas"`
}

type TenantStats

type TenantStats struct {
	Tenant       string `json:"tenant"`
	QueueCount   int    `json:"queue_count"`
	TopicCount   int    `json:"topic_count"`
	MessageCount int    `json:"message_count"`
	LeasedCount  int    `json:"leased_count"`
	DLQCount     int    `json:"dlq_count"`
}

TenantStats returns stats filtered by tenant.

type TopicConfig

type TopicConfig struct {
	Name       string        `json:"name"`
	Partitions int           `json:"partitions"`
	Retention  time.Duration `json:"retention"`
	Paused     bool          `json:"paused"`
}

type TopicPartition

type TopicPartition struct {
	Topic     string `json:"topic"`
	Partition int    `json:"partition"`
}

TopicPartition represents a partition within a topic.

type TopicPartitionStats

type TopicPartitionStats struct {
	Topic      string          `json:"topic"`
	Partitions []PartitionInfo `json:"partitions"`
	TotalMsgs  int             `json:"total_messages"`
}

TopicPartitionStats returns statistics for a topic's partitions.

type TraceExporter

type TraceExporter interface {
	ExportSpan(ctx context.Context, span TraceSpan) error
	Flush(ctx context.Context) error
}

TraceExporter is the interface for exporting trace spans.

type TraceSpan

type TraceSpan struct {
	TraceID    string            `json:"trace_id"`
	SpanID     string            `json:"span_id"`
	ParentID   string            `json:"parent_id,omitempty"`
	Operation  string            `json:"operation"`
	Service    string            `json:"service"`
	StartTime  time.Time         `json:"start_time"`
	EndTime    time.Time         `json:"end_time,omitempty"`
	Duration   time.Duration     `json:"duration,omitempty"`
	Status     TraceStatus       `json:"status"`
	Error      string            `json:"error,omitempty"`
	Attributes map[string]string `json:"attributes,omitempty"`
}

TraceSpan represents a single trace span.

type TraceStatus

type TraceStatus string

TraceStatus represents the status of a trace span.

const (
	TraceOK    TraceStatus = "ok"
	TraceError TraceStatus = "error"
)

type Tracer

type Tracer struct {
	// contains filtered or unexported fields
}

Tracer provides distributed tracing capabilities for the broker.

func NewTracer

func NewTracer(cfg TracerConfig) *Tracer

NewTracer creates a new tracer with the given configuration.

func (*Tracer) ClearSpans

func (t *Tracer) ClearSpans()

ClearSpans clears the in-memory span buffer.

func (*Tracer) EndSpan

func (t *Tracer) EndSpan(span *TraceSpan, err error)

EndSpan completes a trace span and records it.

func (*Tracer) Finish

func (t *Tracer) Finish(span *TraceSpan)

Finish completes a span successfully.

func (*Tracer) FinishWithErr

func (t *Tracer) FinishWithErr(span *TraceSpan, err error)

FinishWithErr completes a span, optionally recording an error.

func (*Tracer) Spans

func (t *Tracer) Spans() []TraceSpan

Spans returns a copy of the current in-memory spans.

func (*Tracer) Start

func (t *Tracer) Start()

Start begins background span flushing.

func (*Tracer) StartSpan

func (t *Tracer) StartSpan(ctx context.Context, operation string, attrs map[string]string) (context.Context, *TraceSpan)

StartSpan begins a new trace span.

func (*Tracer) Stop

func (t *Tracer) Stop()

Stop halts tracing and flushes remaining spans.

func (*Tracer) TracingHooks

func (t *Tracer) TracingHooks() Hooks

TracingHooks returns a Hooks struct that instruments broker operations with tracing.

type TracerConfig

type TracerConfig struct {
	// Enabled activates tracing. Default: false.
	Enabled bool

	// ServiceName is the service name for traces. Default: "fastworker-broker".
	ServiceName string

	// SampleRate is the probability of sampling a trace (0.0-1.0). Default: 1.0.
	SampleRate float64

	// Exporter is the trace exporter. Default: no-op.
	Exporter TraceExporter

	// MaxSpans limits in-memory span buffer. Default: 10000.
	MaxSpans int
}

TracerConfig configures the broker's tracing system.

type TransactionalOutbox

type TransactionalOutbox = PublishRetryBuffer

TransactionalOutbox is retained as a pre-v1 compatibility alias. Deprecated: use PublishRetryBuffer and do not treat it as transactional.

func NewTransactionalOutbox

func NewTransactionalOutbox(b *Broker) *TransactionalOutbox

NewTransactionalOutbox creates an in-memory publish retry buffer. Deprecated: use NewPublishRetryBuffer.

type TxOption

type TxOption func(*TxOptions)

type TxOptions

type TxOptions struct{}

type VersionedSchema

type VersionedSchema struct {
	Definition   SchemaDefinition `json:"definition"`
	RegisteredAt time.Time        `json:"registered_at"`
}

VersionedSchema stores a schema version and its metadata.

type WALCodecConfig

type WALCodecConfig struct {
	CompressThreshold int
	MaxRecordSize     int
	EncryptionKey     []byte
	SigningKey        []byte
}

WALCodecConfig configures the native BWL1 WAL record codec.

type WALCodecConfigProvider

type WALCodecConfigProvider interface {
	WALCodecConfig() WALCodecConfig
}

WALCodecConfigProvider lets a frame codec expose equivalent protection settings to the dedicated WAL codec. The built-in FWB1 and FWB2 codecs implement this interface.

type WALCompactionConfig

type WALCompactionConfig struct {
	// MaxSegmentSize is the maximum size in bytes before rotating to a new segment.
	// Default: 128 MiB.
	MaxSegmentSize int64

	// MaxSegments is the maximum number of active segments before oldest are archived.
	// Default: 10.
	MaxSegments int

	// CompactionInterval is how often to run compaction. Default: 5 minutes.
	CompactionInterval time.Duration

	// ArchiveDir is where archived (old) segments are moved. Empty = segments are deleted.
	ArchiveDir string

	// MaxAge is the maximum age of messages to keep during compaction.
	// Messages older than this are removed from active segments. Default: 0 (keep all).
	MaxAge time.Duration

	// RetainAcked controls whether acknowledged messages are kept during compaction.
	// Default: false (remove acked messages).
	RetainAcked bool

	// MinSegmentFiles is the minimum number of segment files to keep.
	// Compaction will not reduce below this count. Default: 1.
	MinSegmentFiles int
}

WALCompactionConfig controls WAL compaction and segment rotation behavior.

type WALCompactor

type WALCompactor struct {
	// contains filtered or unexported fields
}

WALCompactor handles WAL segment rotation and compaction.

func NewWALCompactor

func NewWALCompactor(dir string, cfg WALCompactionConfig, store *MemoryStore) *WALCompactor

NewWALCompactor creates a new WAL compactor for the given directory.

func (*WALCompactor) Compact

func (wc *WALCompactor) Compact() error

Compact performs a single compaction pass: rotates the active segment, archives old segments, and optionally prunes acknowledged messages.

func (*WALCompactor) ListSegments

func (wc *WALCompactor) ListSegments() ([]walSegment, error)

ListSegments returns the list of WAL segments in the directory.

func (*WALCompactor) Start

func (wc *WALCompactor) Start()

Start begins periodic compaction.

func (*WALCompactor) Stats

func (wc *WALCompactor) Stats() WALSegmentStats

Stats returns current compaction statistics.

func (*WALCompactor) Stop

func (wc *WALCompactor) Stop()

Stop halts compaction and waits for the goroutine to finish.

type WALRecordCodec

type WALRecordCodec struct {
	// contains filtered or unexported fields
}

WALRecordCodec encodes and decodes native BWL1 records. It is immutable and safe for concurrent use.

func NewWALRecordCodec

func NewWALRecordCodec(cfg WALCodecConfig) (*WALRecordCodec, error)

type WALSegmentStats

type WALSegmentStats struct {
	ActiveSegmentSize int64  `json:"active_segment_size"`
	ActiveSegmentPath string `json:"active_segment_path"`
	ArchivedSegments  int    `json:"archived_segments"`
	ArchivedTotalSize int64  `json:"archived_total_size"`
	TotalMessages     int    `json:"total_messages"`
}

WALSegmentStats returns compaction statistics.

type WALVerificationProblem

type WALVerificationProblem struct {
	Offset int64  `json:"offset"`
	Tail   bool   `json:"tail"`
	Error  string `json:"error"`
}

type WALVerificationReport

type WALVerificationReport struct {
	Path            string                   `json:"path"`
	SizeBytes       int64                    `json:"size_bytes"`
	GoodPrefixBytes int64                    `json:"good_prefix_bytes"`
	Records         uint64                   `json:"records"`
	NativeRecords   uint64                   `json:"native_records"`
	LegacyRecords   uint64                   `json:"legacy_records"`
	Problems        []WALVerificationProblem `json:"problems,omitempty"`
	VerifiedAt      time.Time                `json:"verified_at"`
}

func ExportBinaryWAL

func ExportBinaryWAL(path string, output io.Writer, walCodec *WALRecordCodec, legacyCodec FrameCodec) (WALVerificationReport, error)

ExportBinaryWAL writes one decoded JSON operation per line. The source WAL remains read-only and all native checksums, signatures and encryption tags are validated before an operation is emitted.

func ImportBinaryWAL

func ImportBinaryWAL(input io.Reader, path string, walCodec *WALRecordCodec) (report WALVerificationReport, err error)

ImportBinaryWAL creates a new BWL1 file from newline-delimited JSON operations. It refuses to overwrite any existing path and removes a partial destination if validation or persistence fails.

func RepairBinaryWALTail

func RepairBinaryWALTail(path string, walCodec *WALRecordCodec, legacyCodec FrameCodec) (WALVerificationReport, string, error)

RepairBinaryWALTail preserves the original as a timestamped backup and atomically installs a copy truncated to the last verified prefix. It refuses to modify WALs with corrupt middle records.

func VerifyBinaryWAL

func VerifyBinaryWAL(path string, walCodec *WALRecordCodec, legacyCodec FrameCodec) (WALVerificationReport, error)

VerifyBinaryWAL performs a read-only validation of every length prefix, checksum, signature, encryption envelope and operation payload.

func (WALVerificationReport) Valid

func (r WALVerificationReport) Valid() bool

type WebSocketConfig

type WebSocketConfig struct {
	// Path is the WebSocket endpoint path. Default: "/ws".
	Path string
	// MaxConnections limits concurrent connections. Default: 1000.
	MaxConnections int
	// HeartbeatInterval is the ping/pong interval. Default: 30s.
	HeartbeatInterval time.Duration
	ACL               *ACL
	InsecureDev       bool
}

WebSocketConfig configures the legacy SSE transport. Deprecated: use SSEConfig. This implementation is not RFC 6455 WebSocket.

type WebSocketServer

type WebSocketServer struct {
	// contains filtered or unexported fields
}

WebSocketServer provides the legacy SSE transport for the broker data plane. Deprecated: use SSEServer. This implementation is not RFC 6455 WebSocket.

func NewWebSocketServer

func NewWebSocketServer(b *Broker, cfg WebSocketConfig) *WebSocketServer

NewWebSocketServer creates a new WebSocket server.

func (*WebSocketServer) Broadcast

func (ws *WebSocketServer) Broadcast(msgType string, data any)

Broadcast sends a message to all connected clients.

func (*WebSocketServer) ConnectionCount

func (ws *WebSocketServer) ConnectionCount() int

ConnectionCount returns the number of active connections.

func (*WebSocketServer) Handler

func (ws *WebSocketServer) Handler() http.Handler

Handler returns an HTTP handler for WebSocket connections.

func (*WebSocketServer) SetToken

func (ws *WebSocketServer) SetToken(token string)

SetToken sets the authentication token for WebSocket connections.

func (*WebSocketServer) Stop

func (ws *WebSocketServer) Stop()

Stop closes all connections.

type WebhookAttempt

type WebhookAttempt struct {
	ID             string    `json:"id"`
	URL            string    `json:"url"`
	NotificationID string    `json:"notification_id"`
	Payload        []byte    `json:"payload,omitempty"`
	Attempt        int       `json:"attempt"`
	StatusCode     int       `json:"status_code,omitempty"`
	Error          string    `json:"error,omitempty"`
	Success        bool      `json:"success"`
	Timestamp      time.Time `json:"timestamp"`
}

WebhookAttempt records an individual delivery attempt for audit and replay.

type WebhookCallback

type WebhookCallback struct {
	URL         string
	Token       string
	Client      *http.Client
	Timeout     time.Duration
	MaxAttempts int
	RetryDelay  time.Duration
}

func (WebhookCallback) HandleNotification

func (w WebhookCallback) HandleNotification(ctx context.Context, n Notification) error

Directories

Path Synopsis
api
Package console serves an embedded operator web console for a broker.
Package console serves an embedded operator web console for a broker.
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL