Documentation
¶
Overview ¶
Package narad is the Go client for the Narad message broker.
The front door is SQS and the inside is Kafka.
What you write against is a work queue. You take one message, hold it under a visibility timeout, and ack it or let it come back. There are no consumer groups, no partition assignment and no offsets to commit. Bring an SQS mental model and almost everything here is where you expect it.
Underneath, a topic is a partitioned append-only log with offsets and retention, the way Kafka is. That is what pays for the things a queue normally cannot do: a message survives being consumed, replay is a read at an offset rather than a redelivery, and fanning out to a child topic is cheap because the log is already there.
Getting started ¶
Three calls cover almost everything:
client, err := narad.New("localhost:7942")
if err != nil {
return err
}
defer client.Close()
err = client.Produce(ctx, "orders", order)
err = client.Consume(ctx, "orders", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
var order Order
if err := msg.Into(&order); err != nil {
return err
}
return process(ctx, order)
}))
The defaults are meant to be right without thinking about them. Consume long-polls, runs one worker, keeps each message's lease alive while its handler runs, acks on success and hands the message back on failure. Everything is adjustable with options, and none of it has to be.
Pass every node you have, comma separated, and the client spreads work across them and routes around the ones that are failing:
client, err := narad.New("n1:7942,n2:7942,n3:7942",
narad.WithAuth("svc", os.Getenv("NARAD_PASSWORD")))
Batches ¶
Client.ProduceBatch stores up to MaxBatch messages in one request, all or none, and WithBatch has a consumer take and ack them in batches without changing its handler. Both need Narad 3.1.0.
var batch narad.Batch
for _, order := range orders {
if err := batch.Add(order); err != nil {
return err
}
}
err = client.ProduceBatch(ctx, "orders", &batch)
At-least-once, and what it asks of you ¶
Handlers must be idempotent. Narad delivers at least once and does not deduplicate, so a broker restart can redeliver a message whose ack was still in the batch being persisted. This is not something to plan around later.
The same property shapes producing. When a produce fails, Uncertain reports whether the broker may have applied it anyway. Those are retried by default, because a duplicate is recoverable and a lost message is not, and WithCautiousRetries hands that choice back to you. A batch is the same, for the whole batch.
Errors ¶
Errors answer the questions a caller acts on, so nobody has to match on strings:
narad.Retryable(err) // worth trying again narad.Uncertain(err) // might have happened anyway errors.Is(err, narad.ErrNotFound) // which assumption was wrong
Error carries the status, the server's message and the node that answered. A read changes nothing on the server, so it is never uncertain, and WithCautiousRetries still retries one that failed.
Metrics ¶
WithEvents reports every request, retry and circuit-breaker change as an Event, for metrics and logging. Ready-made Prometheus metrics live in the github.com/debanganthakuria/narad-go/prometheus package. This package imports nothing beyond the standard library, so only programs that import that one compile the Prometheus client.
What this package will not do for you ¶
It will not give you ordering, because Narad does not have it. It will not deduplicate. It will not hide the lease: a handler that runs longer than the visibility timeout without renewing loses its message, and Consume renews it rather than pretending otherwise.
Example ¶
The whole of a working producer.
package main
import (
"context"
"log"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, err := narad.New("localhost:7942")
if err != nil {
log.Fatal(err)
}
defer client.Close()
err = client.Produce(context.Background(), "orders", Order{ID: "ord_1", Amount: 4999})
if err != nil {
log.Fatal(err)
}
}
Output:
Index ¶
- Constants
- Variables
- func EnvelopeSchema(schema json.RawMessage) (json.RawMessage, error)
- func Retryable(err error) bool
- func Uncertain(err error) bool
- type Batch
- type Client
- func (c *Client) Close() error
- func (c *Client) Consume(ctx context.Context, topic string, h Handler, opts ...ConsumeOption) error
- func (c *Client) CreateTopic(ctx context.Context, name string, opts ...TopicOption) (Topic, error)
- func (c *Client) DeleteTopic(ctx context.Context, name string) error
- func (c *Client) EnsureTopic(ctx context.Context, name string, opts ...TopicOption) (Topic, error)
- func (c *Client) Health() []NodeHealth
- func (c *Client) Nodes() []string
- func (c *Client) Ping(ctx context.Context, address string) error
- func (c *Client) Produce(ctx context.Context, topic string, value any, opts ...ProduceOption) error
- func (c *Client) ProduceBatch(ctx context.Context, topic string, batch *Batch) error
- func (c *Client) ReadAt(ctx context.Context, topic string, partition int, offset int64) (*Message, error)
- func (c *Client) ReadFrom(ctx context.Context, topic string, partition int, offset int64, h Handler) error
- func (c *Client) Receive(ctx context.Context, topic string, opts ...ConsumeOption) (*Message, error)
- func (c *Client) Replay(ctx context.Context, topic string, h Handler) error
- func (c *Client) Retry(ctx context.Context, msg *Message, cause error, topic string) error
- func (c *Client) SetSchema(ctx context.Context, name string, opts ...TopicOption) (Topic, error)
- func (c *Client) Topic(ctx context.Context, name string) (Topic, error)
- func (c *Client) Topics(ctx context.Context) ([]Topic, error)
- type ConnError
- type ConsumeOption
- func FromPartition(partition int) ConsumeOption
- func WithBatch(n int) ConsumeOption
- func WithErrorHandler(fn func(msg *Message, err error)) ConsumeOption
- func WithShutdownGrace(d time.Duration) ConsumeOption
- func WithWait(d time.Duration) ConsumeOption
- func WithWorkers(n int) ConsumeOption
- func WithoutAutoExtend() ConsumeOption
- func WithoutRequeue() ConsumeOption
- type Envelope
- type Error
- type Event
- type EventKind
- type Handler
- type HandlerFunc
- type Logger
- type Message
- func (m *Message) Ack(ctx context.Context) error
- func (m *Message) Bytes() ([]byte, error)
- func (m *Message) Envelope() (*Envelope, error)
- func (m *Message) Extend(ctx context.Context) error
- func (m *Message) ID() string
- func (m *Message) Into(v any) error
- func (m *Message) Leased() bool
- func (m Message) MarshalJSON() ([]byte, error)
- func (m *Message) Nack(ctx context.Context) error
- func (m *Message) String() string
- func (m *Message) Text() string
- func (m *Message) Time() time.Time
- func (m *Message) UnmarshalJSON(data []byte) error
- type NodeHealth
- type Option
- func WithAuth(username, password string) Option
- func WithBackoff(first, max time.Duration) Option
- func WithBreaker(failures int, cooldown time.Duration) Option
- func WithCautiousRetries() Option
- func WithEvents(fn func(Event)) Option
- func WithHTTPClient(hc *http.Client) Option
- func WithIdleConnections(n int) Option
- func WithLogger(l Logger) Option
- func WithRetries(attempts int) Option
- func WithTimeout(d time.Duration) Option
- func WithUserAgent(name string) Option
- func WithoutBreaker() Option
- type PartitionStats
- type ProduceOption
- type Topic
- type TopicOption
- func WithDelay(d time.Duration) TopicOption
- func WithEnvelopeSchema(schema json.RawMessage) TopicOption
- func WithMaxInFlight(n int64) TopicOption
- func WithParent(parent string) TopicOption
- func WithPartitionCount(n int) TopicOption
- func WithRetention(d time.Duration) TopicOption
- func WithRetentionForever() TopicOption
- func WithSchema(schema json.RawMessage) TopicOption
- func WithSchemaBaseVersion(version int) TopicOption
- func WithVisibilityTimeout(d time.Duration) TopicOption
Examples ¶
Constants ¶
const DefaultPollWait = 10 * time.Second
DefaultPollWait is how long a consume waits for a message before asking again. It matches the ceiling a stock broker applies; a longer wait is clamped by the server rather than refused.
const MaxBatch = 100
MaxBatch is the most messages one batch request may carry: a Client.ProduceBatch, and the batch consume and batch ack that WithBatch turns on.
const MaxMessageBytes = 1 << 20
MaxMessageBytes is the largest message the broker accepts.
const Version = "0.1.0"
Version is this client's version, sent in the User-Agent.
Variables ¶
var ( // ErrBadRequest means the server rejected the request as malformed. // Sending it again unchanged will fail the same way. Among the // reasons: a payload nested deeper than 256 levels on a topic with a // schema, a new topic name over 200 bytes, an empty batch, and a // produce to a delayed fan-out child, which only its parent feeds. ErrBadRequest = errors.New("narad: bad request") // ErrUnauthenticated means the credentials were missing or wrong. ErrUnauthenticated = errors.New("narad: unauthenticated") // ErrForbidden means the credentials were valid but hold no grant // for this action on this topic. ErrForbidden = errors.New("narad: forbidden") // ErrNotFound means the topic, user or other named thing is not // there. ErrNotFound = errors.New("narad: not found") // ErrExists means the state you assumed is not the state that is // there. Creating a topic that already exists reports it, which is // why EnsureTopic treats it as success, and so does a conditional // schema update whose base version is no longer current. The two // more specific conflicts below match it as well. ErrExists = errors.New("narad: already exists") // ErrNameTaken means a topic could not be created because one whose // name differs only in letter case already exists. The two would // share a directory on a case-insensitive filesystem, so the broker // refuses the second. Choose another name. It also matches // [ErrExists], though the topic you asked for does not exist. ErrNameTaken = errors.New("narad: topic name taken in another letter case") // ErrTopicChanged means the topic was changed underneath the // request, twice, while the broker was applying it: deleted and // recreated, or given more partitions. Read the topic again and // decide whether the change still makes sense. It also matches // [ErrExists]. ErrTopicChanged = errors.New("narad: topic changed since it was read") // ErrLeaseLost means the message's visibility window closed before // the ack arrived, or it was already acked and redelivered under a // new handle. The message is not lost; it is on its way to somebody, // possibly another consumer, so do not treat its work as committed. ErrLeaseLost = errors.New("narad: lease lost") // ErrNoLease means Ack, Nack or Extend was called on a message that // holds no lease. Only ReadAt returns such messages: a read at an // offset reserves nothing, so there is nothing to settle. ErrNoLease = errors.New("narad: message holds no lease") // ErrOffsetGone means a read asked for an offset that is no longer // readable, because it aged out of retention. Skip forward; it is // not coming back. ErrOffsetGone = errors.New("narad: offset gone") // ErrTooLarge means the message exceeded the server's size limit. // See MaxMessageBytes. ErrTooLarge = errors.New("narad: message too large") // ErrThrottled means the server is shedding load, or this identity // has too many consumes or produces in flight, or too many failed // logins have been seen lately. Back off, or use fewer workers. ErrThrottled = errors.New("narad: throttled") // a partition's owner is down, the node is being decommissioned, or // its schema validator is busy. Another node, or the same one later, // may do better, and the client tries another node by itself. // // The client raises it itself for a topic with a partition that // cannot be read now, such as one whose owner is down or, on a topic // created a moment ago, one the node answering has not seen assigned // yet. [Client.Replay] waits for such a partition for a while before // reporting it. [Retryable] is true for it either way. ErrUnavailable = errors.New("narad: unavailable") // ErrServer means the server failed internally. ErrServer = errors.New("narad: server error") // ErrNoNodes means every node is currently failing its circuit // breaker, so nothing was sent. ErrNoNodes = errors.New("narad: no healthy nodes") // ErrClosed means the client has been closed. ErrClosed = errors.New("narad: client closed") )
Sentinel errors. Match them with errors.Is rather than comparing status codes or reading messages.
var ErrBatchFull = errors.New("narad: batch is full")
ErrBatchFull means a Batch cannot take another message: it already holds MaxBatch, or the message would take the request past the broker's 1 MiB body limit. The message was not added. Send the batch and start another.
var ErrNoEnvelope = errors.New("narad: message has no envelope")
ErrNoEnvelope means the message was produced without one.
Functions ¶
func EnvelopeSchema ¶
func EnvelopeSchema(schema json.RawMessage) (json.RawMessage, error)
EnvelopeSchema wraps a schema for the message in a schema for the envelope around it, so a topic can enforce both at once.
The result validates the envelope's own fields and checks the given schema against the message in its body. WithEnvelopeSchema applies it for you; this is exported so you can see what will be stored, or register it with other tooling.
One caveat about references. Any $defs or definitions in the schema are lifted to the top of the result, so an internal "#/$defs/..." reference still resolves. A reference to the document root itself ("#") will not, because the root is now the envelope.
func Retryable ¶
Retryable reports whether sending the same request again could plausibly succeed.
It says nothing about whether doing so is safe. A retryable error can also be uncertain, and for anything that changes state those two together mean a retry may duplicate. Ask Uncertain as well when that matters.
ErrUnavailable is retryable whether a node sent it or the client raised it itself, as it does for a partition that cannot be read now.
func Uncertain ¶
Uncertain reports whether the server may have carried out the request even though it returned an error.
This is the question that decides whether retrying can duplicate, and the status alone cannot answer it. A 503 means opposite things depending on the operation: on ack and consume the router declined before anything could act, while a produce can get one from a proxy that gave up after passing the request on. Getting that backwards would make an ack that never happened look as though it did, which is the one outcome the lease exists to prevent.
A 503 on a topic write (Client.CreateTopic, Client.DeleteTopic, Client.SetSchema) is uncertain too, as is any 503 whose message says the change may still be applied: the leader may have taken the change before the answer was lost. A resend can then meet its own change, so a create that worked reports ErrExists. Read the topic back before deciding.
A read is never uncertain, however it failed: Client.ReadAt, Client.ReadFrom, Client.Replay, Client.Topic, Client.Topics and Client.Ping change nothing on the server, so there is nothing a retry could duplicate. A consume is not a read in this sense, since it takes a lease.
Types ¶
type Batch ¶
type Batch struct {
// contains filtered or unexported fields
}
A Batch is a list of messages for Client.ProduceBatch, stored all or none. The zero value is an empty batch, ready to use.
var batch narad.Batch
for _, order := range orders {
if err := batch.Add(order, narad.WithKey(order.Customer)); err != nil {
return err
}
}
err := client.ProduceBatch(ctx, "orders", &batch)
A Batch is not safe for concurrent use.
func (*Batch) Add ¶
func (b *Batch) Add(value any, opts ...ProduceOption) error
Add encodes a message and appends it to the batch.
The value and options mean what they mean to Client.Produce: WithKey and WithPartition place this message, and WithEnvelope wraps it. The encoding happens here, so an envelope's id is fixed when the message is added, and sending the same batch again after an uncertain failure sends the same ids.
It reports ErrBatchFull when the batch has no room for the message, ErrTooLarge when the message could not fit in any batch, and ErrBadRequest for a message Produce would refuse too.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
A Client talks to a Narad cluster.
It is safe for concurrent use and meant to be long lived: it owns the connection pool and the per-node circuit breakers, so one created per request throws both away.
func New ¶
New connects to a Narad cluster.
The address is one or more node addresses, comma separated. The scheme defaults to http, so "localhost:7942" and "n1:7942,n2:7942,n3:7942" both work.
Give it every node you have. The client spreads work across them and routes around the ones that are failing, which is what makes a node restart invisible. One address works too, and then the load balancer in front, rather than this client, decides what to do about a dead node.
Example ¶
In production, give it every node and its credentials. Nothing else needs configuring.
package main
import (
"log"
"log/slog"
"os"
narad "github.com/debanganthakuria/narad-go"
)
func main() {
client, err := narad.New("n1:7942,n2:7942,n3:7942",
narad.WithAuth("svc-orders", os.Getenv("NARAD_PASSWORD")),
narad.WithLogger(slog.Default()),
)
if err != nil {
log.Fatal(err)
}
defer client.Close()
}
Output:
func (*Client) Close ¶
Close releases the client's connections. It may be called more than once. The client cannot be used afterwards.
func (*Client) Consume ¶
Consume takes messages and hands them to h until ctx ends.
It is the call most programs want. It long-polls, runs a pool of workers, keeps each message's lease alive while its handler runs, acks on success and hands the message back on failure. A panicking handler is recovered so one bad message cannot take the consumer down.
err := client.Consume(ctx, "orders", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
return process(ctx, msg)
}))
It returns nil on a clean shutdown, which is what a cancelled context is. In-flight handlers get WithShutdownGrace to finish and ack; anything still running then is abandoned, and its message is redelivered.
Example ¶
Consume is the call most programs want: it long-polls, runs a worker pool, keeps each message's lease alive while its handler runs, and settles it afterwards.
package main
import (
"context"
"log"
"log/slog"
"os/signal"
"syscall"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
// Ctrl-C drains: in-flight handlers finish and ack before Consume
// returns, so their work is not repeated on the next start.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
err := client.Consume(ctx, "orders", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
var order Order
if err := msg.Into(&order); err != nil {
// A message that will never decode is poison. Returning
// an error would redeliver it forever, so swallow it and
// record it somewhere a person will look.
slog.Error("undecodable message, dropping", "id", msg.ID(), "err", err)
return nil
}
return process(ctx, order)
}),
narad.WithWorkers(8),
)
if err != nil {
log.Fatal(err)
}
}
func process(ctx context.Context, order Order) error { return nil }
Output:
Example (SlowWork) ¶
Slow work keeps its message: the lease is renewed underneath the handler, and the handler's context is cancelled if it is ever lost.
package main
import (
"context"
"time"
narad "github.com/debanganthakuria/narad-go"
)
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
_ = client.Consume(context.Background(), "transcodes", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
for range 100 {
// Checking the context is what makes losing the lease
// safe: once cancelled, somebody else may have this
// message.
if ctx.Err() != nil {
return ctx.Err()
}
time.Sleep(time.Second)
}
return nil
}))
}
Output:
func (*Client) CreateTopic ¶
CreateTopic creates a topic.
_, err := client.CreateTopic(ctx, "orders", narad.WithPartitionCount(6), narad.WithRetention(24*time.Hour))
Creating one that already exists reports ErrExists. When that is not an error for you, which it usually is not, use Client.EnsureTopic.
A new name may be up to 200 bytes; a longer one is ErrBadRequest. One that differs from an existing topic's only in letter case is ErrNameTaken, since on a case-insensitive filesystem the two would share a directory.
A new topic's partitions may take a moment to be readable on every node: the broker assigns them owners after the create, and a node that has not seen the assignment yet reports them unavailable. Producing is unaffected, and Client.Replay waits for it.
func (*Client) DeleteTopic ¶
DeleteTopic removes a topic and everything in it. This cannot be undone.
A topic that is already gone counts as deleted: the usual way to see that is a retry whose first attempt actually worked. A topic deleted and recreated under the same name while the delete was being applied reports ErrTopicChanged; look at it again before deciding.
func (*Client) EnsureTopic ¶
EnsureTopic creates a topic, treating one that already exists as success and returning what is actually there.
This is what a service starting up wants: every replica of it races every other to create the same topics, and only one can win.
A topic whose name differs only in letter case is not the one asked for, so that is reported as ErrNameTaken rather than success.
It makes no promise that a topic it just created is readable on every node yet; see Client.CreateTopic.
func (*Client) Health ¶
func (c *Client) Health() []NodeHealth
Health reports what the client currently believes about each node.
It is derived from the requests already made rather than from a probe, so a node nothing has been sent to reads as healthy. To ask a node directly, use Client.Ping.
func (*Client) Ping ¶
Ping asks one node whether it is alive and ready to serve.
The address must be one the client was created with. Probing a named node is the only useful shape for this: a probe sent through the client's own load balancing would answer for whichever node came next, which is the opposite of the question.
It reports ErrUnavailable for a node that is up but not ready, which is the ordinary state during a rolling restart. The probe does not count against the node's circuit breaker, because polling readiness must not be the thing that takes a cluster out of rotation.
func (*Client) Produce ¶
Produce sends a message and returns once the broker has it on disk.
The value decides the encoding: []byte is sent as it is, a string is sent as text, and anything else is marshalled to JSON. Prefer a struct or a map, because the broker stores valid JSON verbatim and hands it back verbatim, which a bare string does not do.
err := client.Produce(ctx, "orders", order) err := client.Produce(ctx, "orders", order, narad.WithKey(order.Customer))
Returning nil means the payload was fsynced before the broker answered. It does not mean anyone has consumed it.
On an error, ask Uncertain. A produce whose reply was lost may still be committed, and the default retry policy will already have tried again, which can duplicate. Consumers have to be idempotent anyway.
A delayed fan-out child takes messages only from its parent, so a produce to one is refused with ErrBadRequest; produce to the parent.
func (*Client) ProduceBatch ¶
ProduceBatch sends every message in the batch and returns once the broker has all of them on disk. It is all or nothing: a message the broker refuses fails the whole batch, the error's message names it ("message 3: ..."), and nothing is stored.
Use it when messages belong together, or to cut the cost of producing many at once: one request and one disk sync carry up to MaxBatch messages. Client.Produce stays the call for one message.
Failures are read as for Produce, with one thing added. A batch whose reply was lost may have been stored, so ask Uncertain; the default retry policy resends the whole batch, which can duplicate it. A batch the broker failed partway through storing can also have its leading messages delivered. Either way at-least-once holds, and consumers have to be idempotent already.
A broker older than 3.1.0 has no batch endpoint and answers ErrNotFound. Fall back to Produce there, knowing it is not atomic. As with Produce, a batch sent to a delayed fan-out child is refused with ErrBadRequest.
Example ¶
A batch is stored all or none, in one request. Fill it until it says it is full, send it, and start another.
package main
import (
"context"
"errors"
"log"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
ctx := context.Background()
orders := []Order{{ID: "ord_1", Amount: 4999}, {ID: "ord_2", Amount: 1250}}
var batch narad.Batch
for _, order := range orders {
err := batch.Add(order, narad.WithKey(order.ID))
if errors.Is(err, narad.ErrBatchFull) {
if err := client.ProduceBatch(ctx, "orders", &batch); err != nil {
log.Fatal(err)
}
batch = narad.Batch{}
err = batch.Add(order, narad.WithKey(order.ID))
}
if err != nil {
log.Fatal(err)
}
}
// An empty batch is refused, and there is nothing to send anyway.
if batch.Len() > 0 {
if err := client.ProduceBatch(ctx, "orders", &batch); err != nil {
log.Fatal(err)
}
}
}
Output:
func (*Client) ReadAt ¶
func (c *Client) ReadAt(ctx context.Context, topic string, partition int, offset int64) (*Message, error)
ReadAt reads the record at an offset without taking it off the queue.
This is replay: it reserves nothing and settles nothing, so the message holds no lease and must not be acked. It is how you re-read history that has already been consumed.
It returns nil when the offset has not been written yet, which is how you know you have caught up with the end of the log, and ErrOffsetGone when the offset has aged out of retention.
Example ¶
Replay reads history without taking it off the queue.
package main
import (
"context"
"errors"
"fmt"
"log"
narad "github.com/debanganthakuria/narad-go"
)
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
for offset := int64(0); ; offset++ {
msg, err := client.ReadAt(context.Background(), "orders", 0, offset)
if errors.Is(err, narad.ErrOffsetGone) {
continue // aged out of retention, skip forward
}
if err != nil {
log.Fatal(err)
}
if msg == nil {
break // caught up with the end of the log
}
fmt.Println(msg.Offset, msg.Key)
}
}
Output:
func (*Client) ReadFrom ¶
func (c *Client) ReadFrom(ctx context.Context, topic string, partition int, offset int64, h Handler) error
ReadFrom streams a partition's records into h, starting at offset and stopping when it reaches the end of the log.
Nothing is reserved and nothing is settled, so the messages hold no lease and must not be acked. This is the call for reading history back: auditing what was published, rebuilding a projection, or working out what a consumer did with a message last Tuesday.
Offsets that have aged out of retention are skipped rather than reported, because a replay that starts before the retention window is the normal case and stopping on it would be useless. A handler error stops the read and is returned, and so does a read that still fails after the client's own retries: unlike Client.Replay, ReadFrom does not wait for a partition to come back.
err := client.ReadFrom(ctx, "orders", 0, 0, narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
return audit(msg)
}))
func (*Client) Receive ¶
func (c *Client) Receive(ctx context.Context, topic string, opts ...ConsumeOption) (*Message, error)
Receive takes one message, waiting until there is one.
It keeps polling until a message arrives or ctx ends, so it returns either a message or an error and never both nil. Give ctx a deadline to bound the wait.
The message holds a lease for the topic's visibility timeout. Settle it with Message.Ack, Message.Nack or Message.Extend. For anything beyond one message, use Client.Consume, which manages the lease for you.
Example ¶
Taking one message and settling it yourself, when a loop is not what you want.
package main
import (
"context"
"errors"
"log"
"time"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
msg, err := client.Receive(ctx, "orders")
if err != nil {
log.Fatal(err)
}
var order Order
if err := msg.Into(&order); err != nil {
log.Fatal(err)
}
if err := process(ctx, order); err != nil {
// Hand it back at once rather than making the next consumer wait
// out the visibility timeout.
_ = msg.Nack(ctx)
return
}
if err := msg.Ack(ctx); err != nil && errors.Is(err, narad.ErrLeaseLost) {
// Too slow: the message went back and somebody else will do it.
// Nothing to undo, since handlers are idempotent.
return
}
}
func process(ctx context.Context, order Order) error { return nil }
Output:
func (*Client) Replay ¶
Replay streams every record the topic still retains into h, one partition at a time, oldest first.
It is the "something went wrong, let me look at everything" call. Nothing is reserved and nothing is settled, so a replay does not disturb consumers working the same topic and can be run against production without taking work away from anybody.
It reads what exists when it starts and stops at the end of each partition, so it terminates on a live topic rather than following new writes. Records that aged out of retention are not there to be read: this is the log, not the whole history.
There is no ordering across partitions. Within one, records come in offset order.
It never starts reading while a partition cannot be read, since that partition's placeholder offsets would make it look empty. It waits instead, because the usual causes clear by themselves: a topic created a moment ago whose partitions the answering node has not seen assigned yet, or an owner that is down or being moved. A read that fails in transit is waited out the same way and resumes where it failed, so no record is handed over twice. Waits use jittered backoff and honour the server's Retry-After, for as long as ctx allows and at most 30 seconds of continuous failure per partition. Then it returns the last error, ErrUnavailable naming the partitions for a topic that stays partial. Pass a ctx deadline to give up sooner. Errors that waiting cannot change, such as ErrNotFound, ErrForbidden and ErrBadRequest, and the handler's own errors, return at once.
err := client.Replay(ctx, "orders", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
fmt.Println(msg.Partition, msg.Offset, msg.ID())
return nil
}))
func (*Client) Retry ¶
Retry acks the message and publishes it again with its attempt count raised and cause recorded, so the next consumer can see how many times this has failed and why.
It only works on an enveloped message: a plain payload has nowhere to keep the count. It is a real republish, so the copy gets a new offset and a new receipt, and the original is settled. That is the difference between this and returning an error from a handler, which hands the same bytes back and leaves the count where it was.
Pass a topic to send the retry somewhere else, which is how you build a delay or a parking queue out of a delay child. An empty topic republishes to the same one.
if attempts := env.Attempts; attempts >= 5 {
return client.Retry(ctx, msg, err, "orders-parked")
}
return client.Retry(ctx, msg, err, "")
Example ¶
Retry is what advances the attempt count, because the broker never rewrites a stored payload. Pair it with a delay child to back off.
package main
import (
"context"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
_ = client.Consume(context.Background(), "orders", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
var order Order
if err := msg.Into(&order); err != nil {
return err
}
err := process(ctx, order)
if err == nil {
return nil
}
env, envErr := msg.Envelope()
if envErr != nil {
return err // no envelope, so let the ordinary redelivery handle it
}
if env.Attempts >= 5 {
// Out of road. Park it where a person can look, and ack
// the original so it stops coming back.
return client.Retry(ctx, msg, err, "orders-parked")
}
return client.Retry(ctx, msg, err, "orders-retry-30s")
}))
}
func process(ctx context.Context, order Order) error { return nil }
Output:
func (*Client) SetSchema ¶
SetSchema registers a new schema version for a topic.
Versions are append-only and checked for compatibility, so a consumer written against an older one keeps working. Use WithSchema or WithEnvelopeSchema to supply it, and WithSchemaBaseVersion to make the change conditional on the version you read. A topic that changed under the request reports ErrTopicChanged: read it again and retry.
topic, _ := client.Topic(ctx, "orders") _, err := client.SetSchema(ctx, "orders", narad.WithEnvelopeSchema(schema), narad.WithSchemaBaseVersion(topic.SchemaVersion))
func (*Client) Topic ¶
Topic describes one topic, including its per-partition state.
While a partition's owner is down the answer is still a topic, with Partial set and that partition's stats left as placeholders; see PartitionStats.Available.
type ConnError ¶
type ConnError struct {
// Op is the operation attempted.
Op string
// Topic is the topic involved, empty when there was none.
Topic string
// Node is the address the request went to.
Node string
// Err is the underlying cause.
Err error
// contains filtered or unexported fields
}
A ConnError is a request that never got a reply: the connection failed, the deadline passed, or the response was cut off.
type ConsumeOption ¶
type ConsumeOption func(*consumeConfig)
A ConsumeOption adjusts a receive or a consume loop.
func FromPartition ¶
func FromPartition(partition int) ConsumeOption
FromPartition takes messages from one partition only, instead of whichever has work.
func WithBatch ¶
func WithBatch(n int) ConsumeOption
WithBatch has each Client.Consume worker take up to n messages per request instead of one, and ack the ones its handler succeeded on together. It is off by default, and n is capped at MaxBatch.
The handler is unchanged: it still gets one message at a time, and everything Message.Ack and friends mean holds per message. What changes is the traffic. A worker asks for n messages, each with its own lease, handles them in order, and then acks every one its handler succeeded on in one request. The broker answers that ack with a status per message, and each is honoured: a lease that lapsed meanwhile is reported to WithErrorHandler as ErrLeaseLost, just as a single ack would report it. A failed message is still handed back at once.
Every lease in the batch is renewed from the poll until its message is settled, together, in one request per round, so a slow message early in a batch does not cost the rest theirs. That holds with WithoutAutoExtend too: it is for a handler that outruns its own lease, and in a batch a message also waits for the ones ahead of it and for the batch ack.
On shutdown, the messages already handled are acked at once and the messages not yet started are handed back at once, while the message in hand is still running, so a handler abandoned at the end of WithShutdownGrace costs only its own message.
The trade: a message's ack goes out when its whole batch is done, not when it is, so a crash mid-batch redelivers messages already handled. Handlers must be idempotent anyway. And a broker with a per-identity cap on consumes in flight counts each poll as n, so workers times n is what that cap sees; past it the answer is ErrThrottled. It needs a 3.1.0 broker; an older one hands out one message at a time and refuses the batch ack, and the worker then acks one at a time.
Example ¶
WithBatch cuts the requests a busy consumer makes: each worker takes up to 50 messages at once and acks its successes together. The handler does not change.
package main
import (
"context"
"log"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
err := client.Consume(context.Background(), "orders", narad.HandlerFunc(
func(ctx context.Context, msg *narad.Message) error {
var order Order
if err := msg.Into(&order); err != nil {
return nil
}
return process(ctx, order)
}),
narad.WithBatch(50),
)
if err != nil {
log.Fatal(err)
}
}
func process(ctx context.Context, order Order) error { return nil }
Output:
func WithErrorHandler ¶
func WithErrorHandler(fn func(msg *Message, err error)) ConsumeOption
WithErrorHandler is called when a handler returns an error, when a lease is lost mid-handler, or when an ack fails after the work succeeded. The message is nil when the failure was not about one.
With one worker it is never called twice at once. With WithWorkers above one, the workers call it concurrently, so it must be safe for that.
With WithBatch it is also called for a message the batch brought that this client could not decode. That message carries only its position and receipt, no payload, and is left to wait out its visibility timeout.
func WithShutdownGrace ¶
func WithShutdownGrace(d time.Duration) ConsumeOption
WithShutdownGrace sets how long Client.Consume waits for in-flight handlers once its context ends. It defaults to thirty seconds.
It is a bound, not a suggestion. A handler that ignores its context cannot be stopped, and waiting for it means Consume outlives the grace period its orchestrator gave the process, which gets the process killed and every in-flight ack lost. Abandoning the work costs one redelivery instead; with WithBatch, the messages the batch already handled are acked as soon as shutdown begins, so that holds there too.
func WithWait ¶
func WithWait(d time.Duration) ConsumeOption
WithWait sets how long one poll waits for a message before it gives up and asks again. It defaults to DefaultPollWait.
Long polling is what keeps an idle consumer from spinning: the broker holds the request open until something arrives.
func WithWorkers ¶
func WithWorkers(n int) ConsumeOption
WithWorkers sets how many messages Client.Consume handles at once. It defaults to one.
Each worker runs its own poll, because the broker hands out one message per request unless WithBatch asks for more. Raising this raises the connections held open, so see WithIdleConnections if you go far above the default.
func WithoutAutoExtend ¶
func WithoutAutoExtend() ConsumeOption
WithoutAutoExtend stops Client.Consume renewing a message's lease while its handler runs.
Only turn it off when handlers are reliably faster than the visibility timeout. Otherwise the message is redelivered underneath the handler and the work is done twice. With WithBatch the leases of a batch are renewed regardless, since its messages wait on each other.
func WithoutRequeue ¶
func WithoutRequeue() ConsumeOption
WithoutRequeue leaves a failed message to wait out its visibility timeout instead of handing it back at once.
Requeuing is the right default for a transient failure and the wrong one for a message that will always fail: Narad has no dead-letter queue, so a message handed back forever is redelivered forever.
type Envelope ¶
type Envelope struct {
// Version marks the envelope format. It is set for you.
Version int `json:"_narad"`
// ID identifies this message. A UUIDv7 unless you set your own, so
// ids sort by creation time, which is what you want when reading
// them back in a log.
ID string `json:"id"`
// Body is the message you produced.
Body json.RawMessage `json:"body"`
// ProducedAt is when the envelope was created, in Unix
// milliseconds.
ProducedAt int64 `json:"produced_at"`
// Attempts is how many times this message has been published,
// starting at 1. See the note above about what does and does not
// move it.
Attempts int `json:"attempts,omitempty"`
// LastError is what went wrong on the previous attempt, empty on the
// first.
LastError string `json:"last_error,omitempty"`
// Headers carries whatever else you want to travel with the message,
// such as a trace id or a tenant. Narad itself ignores it.
Headers map[string]string `json:"headers,omitempty"`
}
An Envelope carries a message alongside the things you wish you had when something goes wrong: an id to trace it by, when it was produced, how many times it has been tried, and what went wrong last time.
Producing with one is opt-in, because it changes the bytes on the wire:
err := client.Produce(ctx, "orders", order, narad.WithEnvelope())
It does not work with a topic schema ¶
If the topic enforces a JSON Schema, that schema describes your message, and an envelope is a different shape. The broker validates before it accepts, so the produce is rejected with ErrBadRequest. Pick one: a schema on the topic, or envelopes in it. (Unless the schema describes the envelope itself, which works but means every producer must use one.)
Attempts advance only when you republish ¶
Narad never rewrites a stored payload, so redelivery hands back the same bytes and the same Attempts. The counter moves when you call Client.Retry, which acks the message and publishes a fresh copy with the count raised and the error recorded. That is a real republish: a new offset, and a new message. Redelivery through the visibility timeout is invisible to it.
type Error ¶
type Error struct {
// Op is the operation attempted, such as "produce" or "ack".
Op string
// Topic is the topic involved, empty when there was none.
Topic string
// Status is the HTTP status code.
Status int
// Message is the server's explanation.
Message string
// Node is the address that answered.
Node string
// RetryAfter is the delay the server asked for, zero when it asked
// for none.
RetryAfter time.Duration
// contains filtered or unexported fields
}
An Error is a reply the server sent that could not be treated as success.
type Event ¶
type Event struct {
Kind EventKind
Op string
Topic string
Node string
// Attempt is the zero-based attempt number, for requests and
// retries.
Attempt int
// Status is the HTTP status, for a request that got one.
Status int
// Took is how long a request took.
Took time.Duration
// Wait is how long a retry is about to sleep.
Wait time.Duration
// State is the node's new circuit-breaker state, for EventNode.
State string
// Err is the failure, nil on success.
Err error
// Uncertain reports whether the failure being retried may have been
// applied by the server anyway.
Uncertain bool
}
An Event reports something the client did, for metrics and logging. Which fields are set depends on Kind.
type EventKind ¶
type EventKind string
EventKind says what an Event is reporting.
const ( // EventRequest is one completed HTTP attempt, successful or not. EventRequest EventKind = "request" // EventRetry is a retry about to be waited out. EventRetry EventKind = "retry" // EventNode is a node changing circuit-breaker state. EventNode EventKind = "node" )
The kinds of event a client reports.
type Handler ¶
A Handler processes one message.
Returning nil acks it. Returning an error hands it back for redelivery, so a handler must be idempotent: Narad is at-least-once, and a message can arrive again after a broker restart even when the handler succeeded.
The context is cancelled when the consumer is shutting down and, more importantly, when the message's lease is lost. A cancelled context means another consumer may already have this message, so stop rather than finish and write the result twice.
type HandlerFunc ¶
A HandlerFunc turns a function into a Handler.
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
A Logger receives the client's diagnostic messages.
The method set is *slog.Logger's, so the standard library satisfies it with no adapter:
client, err := narad.New(addr, narad.WithLogger(slog.Default()))
Any other logger needs a handful of forwarding methods. Arguments come as alternating keys and values, the way slog takes them.
The client logs sparingly, because a library that fills someone else's logs is a library they turn off: retries and node state changes at warn, and the failures a consumer cannot report any other way at error. For anything finer grained, use WithEvents.
type Message ¶
type Message struct {
// Topic is where it was delivered. For a fan-out child this is the
// child, not the topic it was produced to.
Topic string `json:"topic"`
// Partition is which partition it came from.
Partition int `json:"partition"`
// Offset is its position in that partition's log.
Offset int64 `json:"offset"`
// Key is the partition key it was produced with, byte for byte, or
// empty when it was produced without one. (A broker before 3.1.0
// invented a key-<n> for a keyless message; from 3.1.0 on the broker
// sends no key, and messages it stored before keep theirs.)
//
// It is a string because [WithKey] takes one, but read it as bytes:
// a key can be any bytes, and one that is not valid UTF-8 (a hash,
// a packed id) arrives base64-encoded and is decoded here, so Key
// holds what the producer sent rather than its transport form. Use
// []byte(msg.Key) when the bytes matter, and check utf8.ValidString
// before treating it as text.
Key string `json:"key,omitempty"`
// Receipt is the token that proves the lease. It is opaque, and
// empty for a message from [Client.ReadAt], which reserves nothing.
Receipt string `json:"receipt_handle,omitempty"`
// Payload is the body as the server encoded it. Read it with
// [Message.Into], [Message.Bytes] or [Message.Text].
Payload json.RawMessage `json:"payload"`
// Encoding is "base64" when the body was binary, empty otherwise.
Encoding string `json:"payload_encoding,omitempty"`
// Timestamp is when the broker committed it, in Unix seconds.
Timestamp int64 `json:"timestamp"`
// contains filtered or unexported fields
}
A Message is one record handed to a consumer.
Settle it with Message.Ack when the work is done, Message.Nack to hand it straight back, or Message.Extend when the work is taking longer than the visibility timeout. Client.Consume does all of that for you.
func (*Message) Ack ¶
Ack settles the message. It will not be delivered again.
An ack whose reply is lost is the awkward case, and this handles it. The retry finds the receipt already spent and the server says 410, which is indistinguishable from a lease that lapsed. Since the first attempt failed in flight, the ack almost certainly landed, so that is reported as success. A 410 on the first attempt is ErrLeaseLost, because there it really does mean the lease was gone before the ack arrived.
func (*Message) Bytes ¶
Bytes returns the message body.
It is best effort, and the one case it cannot get right is worth knowing. The broker encodes a payload three ways: valid JSON stays verbatim, other UTF-8 text becomes a JSON string, and binary becomes base64 with Encoding set. Only the third is marked on the wire, so a payload arriving as a JSON string is either text the broker quoted for transport or a JSON string the producer really sent. This unquotes it, which is right for the first and loses the quotes on the second.
Send a JSON object and read it with Message.Into and the question never comes up.
func (*Message) Envelope ¶
Envelope returns the message's envelope.
It reports ErrNoEnvelope for a message produced without one, which is the normal case for anything published by another system.
func (*Message) Extend ¶
Extend restarts the visibility window, so slow work keeps its message instead of having it redelivered underneath.
Unlike Ack it gets no benefit of the doubt: if it fails, assume the lease is at risk and stop the work. Client.Consume calls this for you.
func (*Message) ID ¶
ID is the envelope's message id, or empty when the message was produced without an envelope.
It appears in the message's own error messages and in everything the client logs about it, which is the point of having one: a failure three services away can be traced back to the message that caused it.
func (*Message) Into ¶
Into decodes the message into v.
It unwraps the envelope when there is one, so v is the value that was produced either way and a caller does not have to know which. Read the envelope's own fields with Message.Envelope.
func (*Message) Leased ¶
Leased reports whether the message holds a lease that must be settled. Messages from Client.ReadAt do not.
func (Message) MarshalJSON ¶
MarshalJSON encodes a message the way the broker does, so a message written out and read back keeps its key. A key that is not valid UTF-8 goes as base64 with "key_encoding":"base64"; plain JSON would replace its invalid bytes and lose the key.
func (*Message) Nack ¶
Nack hands the message back at once, without waiting out the visibility timeout, so another consumer can take it.
It is not a failure signal to the broker. Narad has no dead-letter queue, so a message nacked forever is redelivered forever. Deal with a poison message by acking it and recording the failure somewhere a person will look.
func (*Message) Text ¶
Text returns the payload as a string. It is empty if the payload could not be decoded; use Message.Bytes when that matters.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON decodes a message as the broker sends it.
The broker sends a key that is not valid UTF-8 as base64 with "key_encoding":"base64" beside it, the way it flags a binary payload. This decodes that key, so Message.Key is the key that was produced and not its base64 text. The payload is left as the broker encoded it, for Message.Bytes to decode.
type NodeHealth ¶
type NodeHealth struct {
// Address is the node's base URL.
Address string
// Healthy is true while the client is sending it requests.
Healthy bool
// State is "closed", "open" or "half-open".
State string
// LastError is the failure that last counted against it, nil when
// healthy.
LastError error
}
NodeHealth is one node's state as the client sees it.
type Option ¶
type Option func(*config)
An Option adjusts a Client. The defaults suit ordinary use, so most programs pass none.
func WithAuth ¶
WithAuth sets the credentials sent with every request. Narad requires them outside development mode.
func WithBackoff ¶
WithBackoff sets the delay before the first retry and the ceiling it grows to. It defaults to 50ms and 5s.
The delay is randomized across the whole interval, and that is not decoration. When a broker sheds load, every client talking to it retries; without the spread they all retry in the same millisecond and knock it over again just as it recovers.
func WithBreaker ¶
WithBreaker sets how many consecutive failures take a node out of rotation, and for how long. It defaults to five failures and two seconds.
The breaker is per node on purpose. Narad keeps producing while any node lives, so one dead node should cost the requests already in flight to it and nothing else. A client-wide breaker would turn one bad node into a total outage.
func WithCautiousRetries ¶
func WithCautiousRetries() Option
WithCautiousRetries stops the client retrying when it cannot tell whether the server already applied the request.
The trade cannot be avoided, only chosen. Retrying an uncertain produce may write the message twice; not retrying may drop it. The default retries, because consumers have to tolerate duplicates under at-least-once anyway and a lost message is not recoverable. Choose this when a duplicate is the worse outcome, and reconcile yourself: Uncertain reports exactly this case. It covers topic writes too, whose resend can report a conflict with the change it made itself.
Example ¶
Turning off uncertain retries is right when a duplicate is worse than a loss. You then reconcile yourself.
package main
import (
"context"
"log"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942", narad.WithCautiousRetries())
defer client.Close()
err := client.Produce(context.Background(), "payments", Order{ID: "pay_1"})
if narad.Uncertain(err) {
log.Printf("unknown outcome, check before sending again: %v", err)
}
}
Output:
func WithEvents ¶
WithEvents installs a callback for metrics and logging. Metrics.Observe in the github.com/debanganthakuria/narad-go/prometheus package is the ready-made one for Prometheus.
It runs on the calling goroutine, so keep it cheap and do not call back into the client from it.
func WithHTTPClient ¶
WithHTTPClient supplies the HTTP client to use, for callers who need their own transport, proxy or TLS settings.
Leave its Timeout at zero. It applies to every request including long polls, so a Timeout shorter than a consume's wait cancels polls that were behaving correctly.
func WithIdleConnections ¶
WithIdleConnections sets how many idle connections to keep per node. It defaults to 64.
The default is far above Go's own, because consuming is a long poll: N workers hold N connections open for seconds at a time, and with Go's default of two, every worker past the second reconnects on each poll.
func WithLogger ¶
WithLogger sends the client's diagnostics to a logger. Without one it stays silent.
func WithRetries ¶
WithRetries sets how many attempts a request gets in total, including the first. It defaults to four. One disables retrying.
func WithTimeout ¶
WithTimeout sets how long one attempt may take. It defaults to ten seconds.
It deliberately does not bound a long-polling consume, whose deadline comes from its own wait. A client-wide timeout shorter than the poll would cancel every poll that was doing exactly what it was told to.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent, and the X-Narad-Client header that satisfies the server's cross-site guard. An empty value is ignored, since the guard requires a non-empty one.
func WithoutBreaker ¶
func WithoutBreaker() Option
WithoutBreaker sends to every node regardless of how it has been behaving. Useful against a single node, or behind a load balancer that is already doing this job.
type PartitionStats ¶
type PartitionStats struct {
Index int `json:"index"`
Segments int `json:"segments"`
Bytes int64 `json:"size_bytes"`
// Oldest is the lowest offset still on disk. Anything below it has
// aged out of retention.
Oldest int64 `json:"oldest_offset"`
// Next is the offset the next record will get.
Next int64 `json:"next_offset"`
// Committed is the exclusive upper bound of what consumers can see.
Committed int64 `json:"high_watermark"`
// Owner is the node whose disk holds this partition.
Owner string `json:"owner_node"`
// Status is "ok" when the numbers are the owner's, and
// "owner_unavailable" when the owner could not report them and they
// are zero placeholders. A broker older than 3.1.0 leaves it empty,
// and its numbers are always real.
Status string `json:"status,omitempty"`
// OwnerLiveness says why an unavailable partition's owner could not
// report: "dead", "unreachable", "unknown" or "unassigned". It is
// empty for a partition whose numbers are real.
OwnerLiveness string `json:"owner_liveness,omitempty"`
}
PartitionStats is one partition's storage state.
func (PartitionStats) Available ¶
func (p PartitionStats) Available() bool
Available reports whether the partition's numbers are real. A total over a topic must leave out the ones that are not.
func (PartitionStats) Depth ¶
func (p PartitionStats) Depth() int64
Depth is how many records the partition still holds: the committed frontier less what has aged out.
It is not a backlog. A record in that range may already have been consumed and acked, because Narad tracks progress with leases rather than a cursor. For a real backlog, read the broker's lag metrics.
type ProduceOption ¶
type ProduceOption func(*produceConfig)
A ProduceOption adjusts one produce.
func WithEnvelope ¶
func WithEnvelope() ProduceOption
WithEnvelope wraps the message in an Envelope, giving it an id, a timestamp and a place to record attempts.
It cannot be used on a topic that enforces a JSON Schema for the message itself; see Envelope.
Example ¶
An envelope gives the message an id, a timestamp and somewhere to record attempts.
package main
import (
"context"
"log"
narad "github.com/debanganthakuria/narad-go"
)
type Order struct {
ID string `json:"id"`
Amount int64 `json:"amount"`
}
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
err := client.Produce(context.Background(), "orders", Order{ID: "ord_1"},
narad.WithEnvelope(),
narad.WithHeaders(map[string]string{"trace": "abc123"}),
)
if err != nil {
log.Fatal(err)
}
}
Output:
func WithHeaders ¶
func WithHeaders(headers map[string]string) ProduceOption
WithHeaders attaches metadata to the envelope, such as a trace id. It implies WithEnvelope. Calling it more than once merges.
func WithID ¶
func WithID(id string) ProduceOption
WithID sets the envelope's id instead of generating one. It implies WithEnvelope.
Use it to carry an id your system already has, so the message can be traced back without a second lookup.
func WithKey ¶
func WithKey(key string) ProduceOption
WithKey sets the partition key.
Keyed messages land on one partition in steady state, which keeps a key's messages together and makes fan-out cheap. It is not an ordering guarantee: Narad does not offer one, and while a node is down a key's messages walk forward to a live partition.
A key can be any bytes, text or not, and a consumer reads back the same bytes in Message.Key.
func WithPartition ¶
func WithPartition(partition int) ProduceOption
WithPartition pins the message to one partition, overriding where its key would have put it. The call fails if the partition does not exist.
type Topic ¶
type Topic struct {
Name string
Partitions int
// Retention is how long records are kept. Zero means they are kept
// forever.
Retention time.Duration
// VisibilityTimeout is how long a consumer holds a message before it
// is redelivered.
VisibilityTimeout time.Duration
// Owner is the user that created it, empty when security is off.
Owner string
// Parent names the topic this one fans out from, empty unless it is
// a child.
Parent string
// Children names the topics this one fans out to.
Children []string
// Delay is how long a delay child holds each copy back.
Delay time.Duration
// Schema is the JSON Schema the broker enforces on produce, absent
// when the topic has none.
Schema json.RawMessage
// SchemaVersion is the version currently in force, 0 when there is
// no schema. Pass it to [Client.SetSchema] to update without
// clobbering a concurrent change.
SchemaVersion int
// Created is when the topic was created.
Created time.Time
// Partitions detail, one per partition.
PartitionStats []PartitionStats
// Partial is true when some partitions could not report, because
// their owner is down, unreachable or not assigned yet. Those
// entries in PartitionStats are zero placeholders; see
// [PartitionStats.Available].
Partial bool
}
A Topic describes a topic as the broker reports it.
type TopicOption ¶
type TopicOption func(*topicConfig)
A TopicOption adjusts a topic being created or changed.
func WithDelay ¶
func WithDelay(d time.Duration) TopicOption
WithDelay holds each copy back by d on a fan-out child, which is how Narad schedules work for later. It only means anything alongside WithParent.
func WithEnvelopeSchema ¶
func WithEnvelopeSchema(schema json.RawMessage) TopicOption
WithEnvelopeSchema validates enveloped messages, checking the given schema against the message inside the envelope.
This is how a topic gets both: producers use WithEnvelope, the broker still rejects a malformed message, and the envelope's own fields are checked too. The schema stored on the topic is the wrapped one, which EnvelopeSchema will show you.
Producers must then always use an envelope. A plain message will not validate against it.
Example ¶
A topic can enforce a schema and still carry envelopes: the SDK wraps the schema so the broker validates the envelope and the message inside it.
package main
import (
"context"
"encoding/json"
"log"
"time"
narad "github.com/debanganthakuria/narad-go"
)
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
schema := json.RawMessage(`{
"type": "object",
"properties": {
"id": {"type": "string"},
"amount": {"type": "integer", "minimum": 0}
},
"required": ["id", "amount"],
"additionalProperties": false
}`)
_, err := client.EnsureTopic(context.Background(), "orders",
narad.WithPartitionCount(6),
narad.WithRetention(24*time.Hour),
narad.WithEnvelopeSchema(schema),
)
if err != nil {
log.Fatal(err)
}
// Producers must now use an envelope, and a message that does not
// match the schema is rejected before it reaches the log.
}
Output:
func WithMaxInFlight ¶
func WithMaxInFlight(n int64) TopicOption
WithMaxInFlight caps how many messages may be unacked at once per partition.
func WithParent ¶
func WithParent(parent string) TopicOption
WithParent makes the new topic a fan-out child of another: every message produced to the parent is copied to it.
func WithPartitionCount ¶
func WithPartitionCount(n int) TopicOption
WithPartitionCount sets how many partitions the topic has. More partitions means more consumers can work at once. The broker picks a default if you do not.
func WithRetention ¶
func WithRetention(d time.Duration) TopicOption
WithRetention sets how long records are kept. The broker enforces a floor of one hour. Without it, or with zero, the topic gets the operator's default. Anything under a millisecond is refused with ErrBadRequest, since it is almost always a bare number meant as another unit: WithRetention(24) is 24 nanoseconds.
func WithRetentionForever ¶
func WithRetentionForever() TopicOption
WithRetentionForever keeps the topic's records forever, whatever the operator's default is. It needs a 3.1.0 broker; an older one reads it as asking for the default.
Example ¶
Keep a topic's records forever, whatever the operator's default.
package main
import (
"context"
"log"
narad "github.com/debanganthakuria/narad-go"
)
func main() {
client, _ := narad.New("localhost:7942")
defer client.Close()
_, err := client.EnsureTopic(context.Background(), "ledger",
narad.WithPartitionCount(6),
narad.WithRetentionForever())
if err != nil {
log.Fatal(err)
}
}
Output:
func WithSchema ¶
func WithSchema(schema json.RawMessage) TopicOption
WithSchema makes the broker validate every message against this JSON Schema and reject the ones that do not fit, before they reach the log.
The schema describes the message itself, so producing with WithEnvelope to such a topic fails. Use WithEnvelopeSchema when you want both.
func WithSchemaBaseVersion ¶
func WithSchemaBaseVersion(version int) TopicOption
WithSchemaBaseVersion makes a schema change conditional on that version still being current, so two writers cannot silently overwrite each other. A mismatch reports ErrExists: read the topic again and retry against the version you find.
func WithVisibilityTimeout ¶
func WithVisibilityTimeout(d time.Duration) TopicOption
WithVisibilityTimeout sets how long a consumer holds a message before it is handed to somebody else.
Set it a little above how long handling actually takes. Client.Consume renews the lease for slow work, so this is a backstop rather than a deadline.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package prometheus reports a Narad client's activity to Prometheus.
|
Package prometheus reports a Narad client's activity to Prometheus. |