goflux

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 14 Imported by: 6 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

Build Status Go Report Card GoDoc

goflux

goflux

Generic, transport-agnostic messaging patterns for Go.

Write business logic against core interfaces. Swap transports without touching handler code.

Architecture

Layer What it provides
Core Interfaces Publisher[T], Subscriber[T], Consumer[T], Requester[Req, Resp], Responder[Req, Resp], Message[T], Handler[T]
Transports Channel (in-process), NATS, JetStream, HTTP — each implements the core interfaces
Middleware Chain, Process, Peek, Distinct, Skip, Take, Throttle, AutoAck
Pipeline Operators Pipe, PipeMap, FanOut, FanIn, RoundRobin, BoundPublisher
Telemetry OpenTelemetry tracing and metrics built into every transport

Supported Patterns

  • Fire & Forget — publish with no delivery guarantee (channels, NATS core)
  • At-Least-Once — ack/nak with auto-ack or manual control (JetStream)
  • Pull Consumer — fetch messages on demand with explicit ack (JetStream)
  • Request-Reply — typed request/response (NATS, HTTP)
  • Queue Groups — competing consumers (NATS)
  • Fan-Out / Fan-In — broadcast, merge, round-robin (any transport)

Transport Feature Matrix

Interface Channel NATS JetStream HTTP
Publisher[T] yes yes yes yes
Subscriber[T] yes yes yes yes
Consumer[T] - - yes -
Requester[Req, Resp] - yes - yes
Responder[Req, Resp] - yes - yes

Installation

go get github.com/foomo/goflux

Quick Start

package main

import (
  "context"
  "fmt"

  "github.com/foomo/goflux"
  "github.com/foomo/goflux/transport/channel"
)

func main() {
  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()

  bus := channel.NewBus[string]()
  pub := channel.NewPublisher(bus)
  sub, _ := channel.NewSubscriber(bus, 1)

  go sub.Subscribe(ctx, "greetings", func(_ context.Context, msg goflux.Message[string]) error {
    fmt.Println(msg.Subject, msg.Payload)
    cancel()
    return nil
  })

  _ = pub.Publish(ctx, "greetings", "Hello, goflux!")
  <-ctx.Done()
}

Swap to NATS by changing the import and constructor — the handler stays the same. See the Getting Started guide.

Documentation

Full documentation: https://foomo.github.io/goflux/

Contributing

make check   # tidy + generate + lint + test + audit (full CI flow)

See CONTRIBUTING.md for details.

Contributors

License

Distributed under MIT License, see LICENSE for details.

Made with ♥ foomo by bestbytes

Documentation

Index

Examples

Constants

View Source
const MessageIDHeader = "X-Message-ID"

MessageIDHeader is the HTTP header name used to propagate a message ID across the HTTP transport.

Variables

This section is empty.

Functions

func MessageID

func MessageID(ctx context.Context) string

MessageID returns the message ID stored in ctx, or "" if none is set.

func ToChan

func ToChan[T any](ctx context.Context, sub Subscriber[T], subject string, bufSize int) <-chan T

ToChan bridges a Subscriber into a plain channel. It launches Subscribe in a goroutine and forwards each message payload into a buffered channel. The returned channel closes when ctx is cancelled.

bufSize controls backpressure: a full buffer blocks the subscriber's handler until the consumer catches up.

To convert to a stream.Stream, use stream.FromFunc:

s := stream.FromFunc(ctx, bufSize, func(ctx context.Context, send func(T) error) error {
    return sub.Subscribe(ctx, subject, func(ctx context.Context, msg goflux.Message[T]) error {
        return send(msg.Payload)
    })
})

func WithHeader

func WithHeader(ctx context.Context, h Header) context.Context

WithHeader returns a copy of ctx with the given header attached. Transports read this header during Publish and merge it into the outgoing transport headers.

func WithMessageID

func WithMessageID(ctx context.Context, id string) context.Context

WithMessageID returns a copy of ctx with the given message ID attached. The ID is purely opt-in: if set, transports propagate it via headers and RecordPublish / RecordProcess attach it as the goflux.message.id span attribute.

Types

type Acker

type Acker interface {
	Ack() error
	Nak() error
}

Acker is the minimal acknowledgment interface. Transports that support at-least-once delivery implement this on their message wrapper.

type BoundPublisher

type BoundPublisher[T any] struct {
	// contains filtered or unexported fields
}

BoundPublisher wraps a Publisher with a fixed subject.

func Bind

func Bind[T any](pub Publisher[T], subject string) *BoundPublisher[T]

Bind returns a BoundPublisher that always publishes to the given subject.

func (*BoundPublisher[T]) Close

func (b *BoundPublisher[T]) Close() error

Close delegates to the underlying Publisher.

func (*BoundPublisher[T]) Publish

func (b *BoundPublisher[T]) Publish(ctx context.Context, v T) error

Publish sends v to the bound subject.

type Consumer

type Consumer[T any] interface {
	// Fetch retrieves up to n messages. It blocks until at least one message
	// is available or ctx is cancelled.
	Fetch(ctx context.Context, n int) ([]Message[T], error)
	// Close releases any underlying resources.
	Close() error
}

Consumer provides pull-based message consumption. The caller controls the fetch rate. Each fetched message MUST be explicitly acknowledged via Message.Ack, Message.Nak, or Message.Term.

type DeadLetterFunc

type DeadLetterFunc[T any] func(ctx context.Context, msg Message[T], err error)

DeadLetterFunc receives messages that could not be mapped or published after all retries are exhausted. Use it to log, alert, or forward to a DLQ.

type DelayedNaker

type DelayedNaker interface {
	Acker
	NakWithDelay(d time.Duration) error
}

DelayedNaker extends Acker with delayed negative acknowledgment, causing the message to be redelivered after the given delay.

type FanOutOption

type FanOutOption[T any] func(*fanoutConfig[T])

FanOutOption configures a FanOut publisher.

func WithFanOutAllOrNothing

func WithFanOutAllOrNothing[T any]() FanOutOption[T]

WithFanOutAllOrNothing makes the FanOut publisher treat any single publish failure as a failure for the entire call. The default is best-effort: publish to all, join errors from any that fail.

type Filter

type Filter[T any] func(ctx context.Context, msg Message[T]) (bool, error)

Filter decides whether a message should be forwarded. Returning false or a non-nil error drops the message and logs the reason.

type Handler

type Handler[T any] func(ctx context.Context, msg Message[T]) error

Handler is the callback signature used by Subscriber.Subscribe. Returning a non-nil error signals the subscriber to nack / requeue the message (behavior is implementation-specific).

func Pipe

func Pipe[T any](pub Publisher[T], opts ...PipeOption[T]) Handler[T]

Pipe returns a Handler[T] that forwards every accepted message to pub. Filters run first; a dropped message never reaches pub. A publish error is returned to the subscriber as-is — wrap pub with NewRetryPublisher to add retry/backoff before that error surfaces.

Example

ExamplePipe demonstrates wiring a source subscriber to a destination publisher using goflux.Pipe. Every message received on "events" is forwarded to the destination bus on the same subject.

package main

import (
	"context"
	"fmt"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/transport/channel"
	"github.com/foomo/gofuncy"
)

type Event struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func main() {
	// Source transport.
	srcBus := channel.NewBus[Event]()
	srcPub := channel.NewPublisher(srcBus)

	srcSub, err := channel.NewSubscriber(srcBus, 1)
	if err != nil {
		panic(err)
	}

	// Destination transport.
	dstBus := channel.NewBus[Event]()
	dstPub := channel.NewPublisher(dstBus)

	dstSub, err := channel.NewSubscriber(dstBus, 1)
	if err != nil {
		panic(err)
	}

	ctx, cancel := context.WithCancel(context.Background())

	// Listen on destination — print when a message arrives.
	// Pipe preserves the original subject, so we subscribe to "events".
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()

		return dstSub.Subscribe(ctx, "events", func(_ context.Context, msg goflux.Message[Event]) error {
			fmt.Println(msg.Subject, msg.Payload)
			cancel()

			return nil
		})
	}, gofuncy.WithName("dst-subscriber"))

	// Pipe: source subscriber forwards to destination publisher.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()
		return srcSub.Subscribe(ctx, "events", goflux.Pipe[Event](dstPub))
	}, gofuncy.WithName("pipe"))

	if err := srcPub.Publish(ctx, "events", Event{ID: "1", Name: "hello"}); err != nil {
		panic(err)
	}

	<-ctx.Done()
}
Output:
events {1 hello}
Example (WithDeadLetter)

ExamplePipe_withDeadLetter demonstrates the dead-letter handler on a Pipe. When the downstream publisher returns an error, the dead-letter function receives the original message and the error.

ctx := context.Background()

// Source transport.
srcBus := channel.NewBus[Event]()
srcPub := channel.NewPublisher(srcBus)

srcSub, err := channel.NewSubscriber(srcBus, 1)
if err != nil {
	panic(err)
}

// A publisher that always fails.
pubErr := errors.New("publish failed")
badPub := &failPublisher[Event]{err: pubErr}

received := make(chan struct{})

// Dead-letter handler prints the original message and error.
deadLetter := func(_ context.Context, msg goflux.Message[Event], err error) {
	fmt.Println("dead-letter:", msg.Subject, msg.Payload, err)
	close(received)
}

// Pipe with dead-letter: publish errors are routed to the handler.
gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
	ready()
	return srcSub.Subscribe(ctx, "events", goflux.Pipe[Event](badPub, goflux.WithDeadLetter[Event](deadLetter)))
}, gofuncy.WithName("pipe"))

if err := srcPub.Publish(ctx, "events", Event{ID: "1", Name: "hello"}); err != nil {
	panic(err)
}

<-received
Output:
dead-letter: events {1 hello} publish failed
Example (WithFilter)

ExamplePipe_withFilter demonstrates filtering messages before they are forwarded. Only events whose ID is not "skip" reach the destination.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/transport/channel"
	"github.com/foomo/gofuncy"
)

type Event struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Source transport.
	srcBus := channel.NewBus[Event]()
	srcPub := channel.NewPublisher(srcBus)

	srcSub, err := channel.NewSubscriber(srcBus, 1)
	if err != nil {
		panic(err)
	}

	// Destination transport.
	dstBus := channel.NewBus[Event]()
	dstPub := channel.NewPublisher(dstBus)

	dstSub, err := channel.NewSubscriber(dstBus, 1)
	if err != nil {
		panic(err)
	}

	// Filter: drop events with ID "skip".
	filter := func(_ context.Context, msg goflux.Message[Event]) (bool, error) {
		return msg.Payload.ID != "skip", nil
	}

	// Listen on destination — expect exactly one message.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()

		return dstSub.Subscribe(ctx, "events", func(_ context.Context, msg goflux.Message[Event]) error {
			fmt.Println(msg.Subject, msg.Payload)
			cancel()

			return nil
		})
	}, gofuncy.WithName("dst-subscriber"))

	// Pipe with filter.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()
		return srcSub.Subscribe(ctx, "events", goflux.Pipe[Event](dstPub, goflux.WithFilter[Event](filter)))
	}, gofuncy.WithName("pipe"))

	// Allow goroutines to register on their buses before publishing.
	time.Sleep(10 * time.Millisecond)

	// First message is filtered out.
	if err := srcPub.Publish(ctx, "events", Event{ID: "skip", Name: "ignored"}); err != nil {
		panic(err)
	}
	// Second message passes the filter.
	if err := srcPub.Publish(ctx, "events", Event{ID: "keep", Name: "accepted"}); err != nil {
		panic(err)
	}

	<-ctx.Done()
}
Output:
events {keep accepted}

func PipeMap

func PipeMap[T, U any](pub Publisher[U], mapFn MapFunc[T, U], opts ...PipeOption[T]) Handler[T]

PipeMap returns a Handler[T] that maps each message from T to U before publishing. Filters run on T before the map. A map error routes the original Message[T] to the dead-letter handler (if set) and drops the message. A publish error after a successful map is also dead-lettered with the original T message.

Example

ExamplePipeMap demonstrates transforming messages from one type to another. Events are mapped to Summary values and published to the destination bus.

package main

import (
	"context"
	"fmt"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/transport/channel"
	"github.com/foomo/gofuncy"
)

type Event struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Summary struct {
	Label string `json:"label"`
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	// Source transport (Event).
	srcBus := channel.NewBus[Event]()
	srcPub := channel.NewPublisher(srcBus)

	srcSub, err := channel.NewSubscriber(srcBus, 1)
	if err != nil {
		panic(err)
	}

	// Destination transport (Summary).
	dstBus := channel.NewBus[Summary]()
	dstPub := channel.NewPublisher(dstBus)

	dstSub, err := channel.NewSubscriber(dstBus, 1)
	if err != nil {
		panic(err)
	}

	// Map function: Event → Summary, keeping the same subject.
	mapFn := func(_ context.Context, msg goflux.Message[Event]) (goflux.Message[Summary], error) {
		return goflux.NewMessage(msg.Subject, Summary{Label: msg.Payload.Name}), nil
	}

	// Listen on destination — PipeMap publishes with the subject from the MapFunc result.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()

		return dstSub.Subscribe(ctx, "events", func(_ context.Context, msg goflux.Message[Summary]) error {
			fmt.Println(msg.Subject, msg.Payload)
			cancel()

			return nil
		})
	}, gofuncy.WithName("dst-subscriber"))

	// PipeMap: source subscriber maps Event→Summary and forwards.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()
		return srcSub.Subscribe(ctx, "events", goflux.PipeMap[Event, Summary](dstPub, mapFn))
	}, gofuncy.WithName("pipe-map"))

	if err := srcPub.Publish(ctx, "events", Event{ID: "1", Name: "hello"}); err != nil {
		panic(err)
	}

	<-ctx.Done()
}
Output:
events {hello}
Example (WithDeadLetter)

ExamplePipeMap_withDeadLetter demonstrates the dead-letter handler on a PipeMap. When the MapFunc returns an error, the dead-letter function receives the original source message and the map error.

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/transport/channel"
	"github.com/foomo/gofuncy"
)

type Event struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Summary struct {
	Label string `json:"label"`
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	// Source transport (Event).
	srcBus := channel.NewBus[Event]()
	srcPub := channel.NewPublisher(srcBus)

	srcSub, err := channel.NewSubscriber(srcBus, 1)
	if err != nil {
		panic(err)
	}

	// Destination transport (Summary).
	dstBus := channel.NewBus[Summary]()
	dstPub := channel.NewPublisher(dstBus)

	dstSub, err := channel.NewSubscriber(dstBus, 1)
	if err != nil {
		panic(err)
	}

	// Map function that fails for events with ID "bad".
	mapErr := errors.New("bad event")
	mapFn := func(_ context.Context, msg goflux.Message[Event]) (goflux.Message[Summary], error) {
		if msg.Payload.ID == "bad" {
			return goflux.Message[Summary]{}, mapErr
		}

		return goflux.NewMessage(msg.Subject, Summary{Label: msg.Payload.Name}), nil
	}

	// Dead-letter handler prints the original message and error.
	deadLetter := func(_ context.Context, msg goflux.Message[Event], err error) {
		fmt.Println("dead-letter:", msg.Subject, msg.Payload, err)
	}

	// Listen on destination for the valid message.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()

		return dstSub.Subscribe(ctx, "events", func(_ context.Context, msg goflux.Message[Summary]) error {
			fmt.Println(msg.Subject, msg.Payload)
			cancel()

			return nil
		})
	}, gofuncy.WithName("dst-subscriber"))

	// PipeMap with dead-letter.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()
		return srcSub.Subscribe(ctx, "events", goflux.PipeMap[Event, Summary](dstPub, mapFn, goflux.WithDeadLetter[Event](deadLetter)))
	}, gofuncy.WithName("pipe-map"))

	// First message fails the map — routed to dead-letter.
	if err := srcPub.Publish(ctx, "events", Event{ID: "bad", Name: "broken"}); err != nil {
		panic(err)
	}
	// Second message succeeds — arrives at destination.
	if err := srcPub.Publish(ctx, "events", Event{ID: "1", Name: "hello"}); err != nil {
		panic(err)
	}

	<-ctx.Done()
}
Output:
dead-letter: events {bad broken} bad event
events {hello}
Example (WithFilter)

ExamplePipeMap_withFilter demonstrates filtering messages before they are mapped and forwarded. The filter runs on the source type (Event); only passing events are transformed into Summary values.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/foomo/goflux"
	"github.com/foomo/goflux/transport/channel"
	"github.com/foomo/gofuncy"
)

type Event struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Summary struct {
	Label string `json:"label"`
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Source transport (Event).
	srcBus := channel.NewBus[Event]()
	srcPub := channel.NewPublisher(srcBus)

	srcSub, err := channel.NewSubscriber(srcBus, 1)
	if err != nil {
		panic(err)
	}

	// Destination transport (Summary).
	dstBus := channel.NewBus[Summary]()
	dstPub := channel.NewPublisher(dstBus)

	dstSub, err := channel.NewSubscriber(dstBus, 1)
	if err != nil {
		panic(err)
	}

	// Map function: Event → Summary.
	mapFn := func(_ context.Context, msg goflux.Message[Event]) (goflux.Message[Summary], error) {
		return goflux.NewMessage(msg.Subject, Summary{Label: msg.Payload.Name}), nil
	}

	// Filter: drop events with ID "skip".
	filter := func(_ context.Context, msg goflux.Message[Event]) (bool, error) {
		return msg.Payload.ID != "skip", nil
	}

	// Listen on destination — expect exactly one message.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()

		return dstSub.Subscribe(ctx, "events", func(_ context.Context, msg goflux.Message[Summary]) error {
			fmt.Println(msg.Subject, msg.Payload)
			cancel()

			return nil
		})
	}, gofuncy.WithName("dst-subscriber"))

	// PipeMap with filter.
	gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
		ready()
		return srcSub.Subscribe(ctx, "events", goflux.PipeMap[Event, Summary](dstPub, mapFn, goflux.WithFilter[Event](filter)))
	}, gofuncy.WithName("pipe-map"))

	// Allow goroutines to register on their buses before publishing.
	time.Sleep(10 * time.Millisecond)

	// First message is filtered out before the map runs.
	if err := srcPub.Publish(ctx, "events", Event{ID: "skip", Name: "ignored"}); err != nil {
		panic(err)
	}
	// Second message passes the filter, gets mapped, and arrives.
	if err := srcPub.Publish(ctx, "events", Event{ID: "keep", Name: "accepted"}); err != nil {
		panic(err)
	}

	<-ctx.Done()
}
Output:
events {accepted}
type Header map[string][]string

Header carries message metadata (trace context, message ID, custom KV). Keys are case-sensitive, values are slices — matching http.Header semantics.

func HeaderFromContext

func HeaderFromContext(ctx context.Context) Header

HeaderFromContext returns the header stored in ctx, or nil if none is set.

func (Header) Add

func (h Header) Add(key, value string)

Add appends a value for the given key.

func (Header) Clone

func (h Header) Clone() Header

Clone returns a deep copy of the header.

func (Header) Del

func (h Header) Del(key string)

Del removes the given key.

func (Header) Get

func (h Header) Get(key string) string

Get returns the first value for the given key, or "" if not present.

func (Header) Set

func (h Header) Set(key, value string)

Set replaces any existing values for the given key.

type MapFunc

type MapFunc[T, U any] func(ctx context.Context, msg Message[T]) (Message[U], error)

MapFunc transforms a Message[T] into a Message[U]. A non-nil error drops the message and routes it to the DeadLetterFunc if set.

type Message

type Message[T any] struct {
	Subject string `json:"subject"`
	Payload T      `json:"payload"`
	Header  Header `json:"header,omitempty"`
	// contains filtered or unexported fields
}

Message is the unit passed to every Handler. Subject carries the routing key (e.g. a NATS subject or HTTP path); Payload holds the decoded value; Header carries optional metadata; acker provides acknowledgment controls.

func NewMessage

func NewMessage[T any](subject string, payload T) Message[T]

NewMessage creates a new Message.

func NewMessageWithHeader

func NewMessageWithHeader[T any](subject string, payload T, header Header) Message[T]

NewMessageWithHeader creates a new Message with the given header.

func (Message[T]) Ack

func (m Message[T]) Ack() error

Ack acknowledges successful processing. No-op if the transport does not support acknowledgments.

func (Message[T]) HasAcker

func (m Message[T]) HasAcker() bool

HasAcker reports whether the message carries acknowledgment controls.

func (Message[T]) Nak

func (m Message[T]) Nak() error

Nak signals processing failure; the message should be redelivered. No-op if the transport does not support acknowledgments.

func (Message[T]) NakWithDelay

func (m Message[T]) NakWithDelay(d time.Duration) error

NakWithDelay signals processing failure with a redelivery delay hint. Falls back to Nak if the transport does not support delayed redelivery.

func (Message[T]) Term

func (m Message[T]) Term() error

Term terminates processing — the message will not be redelivered. Falls back to Ack if the transport does not support terminal rejection, to prevent infinite redelivery loops.

func (Message[T]) WithAcker

func (m Message[T]) WithAcker(a Acker) Message[T]

WithAcker returns a copy of the message with the given acker attached. This is intended for transport implementations, not application code.

type Middleware

type Middleware[T any] func(Handler[T]) Handler[T]

Middleware wraps a Handler[T] to add cross-cutting behaviour such as logging, rate-limiting, or circuit-breaking.

func AutoAck

func AutoAck[T any]() Middleware[T]

AutoAck returns a Middleware that acknowledges messages automatically: nil handler error triggers Ack, non-nil error triggers Nak. Messages without an acker (fire-and-forget transports) are passed through as-is.

func Chain

func Chain[T any](mws ...Middleware[T]) Middleware[T]

Chain composes middlewares left-to-right: the first middleware in the list is the outermost wrapper. Chain(a, b)(h) is equivalent to a(b(h)).

Example

ExampleChain demonstrates composing handler middlewares. Middlewares execute left-to-right (outermost first).

var trace []string

mwA := func(next goflux.Handler[Event]) goflux.Handler[Event] {
	return func(ctx context.Context, msg goflux.Message[Event]) error {
		trace = append(trace, "A-before")
		err := next(ctx, msg)

		trace = append(trace, "A-after")

		return err
	}
}

mwB := func(next goflux.Handler[Event]) goflux.Handler[Event] {
	return func(ctx context.Context, msg goflux.Message[Event]) error {
		trace = append(trace, "B-before")
		err := next(ctx, msg)

		trace = append(trace, "B-after")

		return err
	}
}

base := func(_ context.Context, msg goflux.Message[Event]) error {
	trace = append(trace, "handler:"+msg.Payload.Name)
	return nil
}

handler := goflux.Chain[Event](mwA, mwB)(base)

msg := goflux.NewMessage("events", Event{ID: "1", Name: "hello"})
_ = handler(context.Background(), msg)

for _, s := range trace {
	fmt.Println(s)
}
Output:
A-before
B-before
handler:hello
B-after
A-after

func Distinct

func Distinct[T any](key func(Message[T]) string) Middleware[T]

Distinct returns a Middleware that deduplicates messages using a key function. The first message for each key passes through; subsequent messages with the same key are silently dropped. The seen set is not bounded — use a custom middleware if memory is a concern.

Example

ExampleDistinct demonstrates deduplicating messages by ID. The second message with ID "1" is silently dropped.

var received []string

handler := goflux.Chain[Event](
	goflux.Distinct[Event](func(msg goflux.Message[Event]) string {
		return msg.Payload.ID
	}),
)(func(_ context.Context, msg goflux.Message[Event]) error {
	received = append(received, msg.Payload.Name)
	return nil
})

ctx := context.Background()
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "1", Name: "first"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "1", Name: "duplicate"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "2", Name: "second"}))

for _, r := range received {
	fmt.Println(r)
}
Output:
first
second

func Peek

func Peek[T any](fn func(context.Context, Message[T])) Middleware[T]

Peek returns a Middleware that calls fn as a side-effect for each message before forwarding to the next handler. The fn function should not modify the message. Errors from fn are intentionally ignored — use a regular middleware if error handling is needed.

Example

ExamplePeek demonstrates observing messages as a side-effect without modifying them.

var (
	peeked  []string
	handled []string
)

handler := goflux.Chain[Event](
	goflux.Peek[Event](func(_ context.Context, msg goflux.Message[Event]) {
		peeked = append(peeked, "peek:"+msg.Payload.Name)
	}),
)(func(_ context.Context, msg goflux.Message[Event]) error {
	handled = append(handled, "handle:"+msg.Payload.Name)
	return nil
})

ctx := context.Background()
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "1", Name: "hello"}))

fmt.Println(peeked)
fmt.Println(handled)
Output:
[peek:hello]
[handle:hello]

func Process

func Process[T any](n int) Middleware[T]

Process returns a Middleware that limits concurrent handler invocations to n. When all n slots are occupied, the handler blocks until a slot frees up or the context is cancelled. Each handler invocation runs synchronously — errors are returned to the caller as-is.

Example

ExampleProcess demonstrates limiting concurrent handler invocations.

var (
	maxConcurrent atomic.Int64
	current       atomic.Int64
	mu            sync.Mutex
	received      []string
	wg            sync.WaitGroup
)

handler := goflux.Chain[Event](
	goflux.Process[Event](2),
)(func(_ context.Context, msg goflux.Message[Event]) error {
	cur := current.Add(1)
	defer current.Add(-1)

	// Track peak concurrency.
	for {
		old := maxConcurrent.Load()
		if cur <= old || maxConcurrent.CompareAndSwap(old, cur) {
			break
		}
	}

	mu.Lock()

	received = append(received, msg.Payload.Name)
	mu.Unlock()

	return nil
})

ctx := context.Background()

for i := range 5 {
	wg.Go(func() {
		_ = handler(ctx, goflux.NewMessage("events", Event{
			ID:   fmt.Sprintf("%d", i),
			Name: fmt.Sprintf("msg-%d", i),
		}))
	})
}

wg.Wait()

fmt.Println("count:", len(received))
fmt.Println("max concurrent <= 2:", maxConcurrent.Load() <= 2)
Output:
count: 5
max concurrent <= 2: true

func Skip

func Skip[T any](n int) Middleware[T]

Skip returns a Middleware that drops the first n messages and passes the rest through to the next handler. The counter is safe for concurrent use.

Example

ExampleSkip demonstrates dropping the first 2 messages.

var received []string

handler := goflux.Chain[Event](
	goflux.Skip[Event](2),
)(func(_ context.Context, msg goflux.Message[Event]) error {
	received = append(received, msg.Payload.Name)
	return nil
})

ctx := context.Background()
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "1", Name: "first"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "2", Name: "second"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "3", Name: "third"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "4", Name: "fourth"}))

for _, r := range received {
	fmt.Println(r)
}
Output:
third
fourth

func Take

func Take[T any](n int) Middleware[T]

Take returns a Middleware that passes the first n messages through and silently drops all subsequent messages. The counter is safe for concurrent use.

Example

ExampleTake demonstrates handling only the first 2 messages.

var received []string

handler := goflux.Chain[Event](
	goflux.Take[Event](2),
)(func(_ context.Context, msg goflux.Message[Event]) error {
	received = append(received, msg.Payload.Name)
	return nil
})

ctx := context.Background()
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "1", Name: "first"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "2", Name: "second"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "3", Name: "third"}))

for _, r := range received {
	fmt.Println(r)
}
Output:
first
second

func Throttle

func Throttle[T any](d time.Duration) Middleware[T]

Throttle returns a Middleware that rate-limits handler invocations to at most one per duration d. The first message passes immediately; subsequent messages block until the ticker fires. Context cancellation is respected while waiting.

Example

ExampleThrottle demonstrates rate-limiting handler calls to at most one per 50ms. The first message passes immediately; the second waits.

var received []string

handler := goflux.Chain[Event](
	goflux.Throttle[Event](50 * time.Millisecond),
)(func(_ context.Context, msg goflux.Message[Event]) error {
	received = append(received, msg.Payload.Name)
	return nil
})

ctx := context.Background()
start := time.Now()

_ = handler(ctx, goflux.NewMessage("events", Event{ID: "1", Name: "first"}))
_ = handler(ctx, goflux.NewMessage("events", Event{ID: "2", Name: "second"}))

elapsed := time.Since(start)

fmt.Println("messages:", received)
fmt.Println("waited:", elapsed >= 50*time.Millisecond)
Output:
messages: [first second]
waited: true

type PipeOption

type PipeOption[T any] func(*pipeConfig[T])

PipeOption configures a Pipe or PipeMap call.

func WithDeadLetter

func WithDeadLetter[T any](fn DeadLetterFunc[T]) PipeOption[T]

WithDeadLetter registers a dead-letter handler called when MapFunc returns an error or when the publisher fails after all retries are exhausted. The original Message[T] and the terminal error are passed to the handler.

func WithFilter

func WithFilter[T any](f Filter[T]) PipeOption[T]

WithFilter registers a filter that runs before publish (or before map in PipeMap). Messages for which the filter returns false are silently dropped and logged. Filter errors are treated as false.

type ProcessOption

type ProcessOption func(*processConfig)

ProcessOption configures Telemetry.RecordProcess.

func WithRemoteSpanContext

func WithRemoteSpanContext(sc trace.SpanContext) ProcessOption

WithRemoteSpanContext attaches the given span context as a span link instead of using it as the parent. Use this for async transports (e.g. NATS) where the producer and consumer are temporally decoupled — the consumer span becomes a root span linked to the producer, rather than a child of it.

type Publisher

type Publisher[T any] interface {
	// Publish serializes v via the bound Codec and delivers it to the subject.
	Publish(ctx context.Context, subject string, v T) error
	// Close releases any underlying connections.
	Close() error
}

Publisher sends encoded messages to a subject/topic.

func FanOut

func FanOut[T any](publishers []Publisher[T], opts ...FanOutOption[T]) Publisher[T]

FanOut returns a Publisher[T] that forwards every Publish call to all inner publishers. Errors from individual publishers are joined via errors.Join.

Close is a no-op — the caller owns the inner publishers and is responsible for closing them.

Example

ExampleFanOut demonstrates broadcasting a message to multiple publishers.

ctx := context.Background()

a := &collectPublisher[Event]{}
b := &collectPublisher[Event]{}

pub := goflux.FanOut[Event]([]goflux.Publisher[Event]{a, b})

if err := pub.Publish(ctx, "events", Event{ID: "1", Name: "hello"}); err != nil {
	panic(err)
}

fmt.Println("a:", a.get())
fmt.Println("b:", b.get())
Output:
a: [{1 hello}]
b: [{1 hello}]
Example (AllOrNothing)

ExampleFanOut_allOrNothing shows that all-or-nothing mode returns the first error immediately without publishing to remaining publishers.

ctx := context.Background()

bad := &failPublisher[Event]{err: errors.New("down")}
good := &collectPublisher[Event]{}

pub := goflux.FanOut[Event](
	[]goflux.Publisher[Event]{bad, good},
	goflux.WithFanOutAllOrNothing[Event](),
)

err := pub.Publish(ctx, "events", Event{ID: "1", Name: "hello"})
fmt.Println("error:", err)
fmt.Println("good received:", good.get())
Output:
error: down
good received: []
Example (BestEffort)

ExampleFanOut_bestEffort shows that best-effort mode publishes to all publishers even when some fail, and joins the errors.

ctx := context.Background()

good := &collectPublisher[Event]{}
bad := &failPublisher[Event]{err: errors.New("down")}

pub := goflux.FanOut[Event]([]goflux.Publisher[Event]{bad, good})

err := pub.Publish(ctx, "events", Event{ID: "1", Name: "hello"})
fmt.Println("error:", err)
fmt.Println("good received:", good.get())
Output:
error: down
good received: [{1 hello}]

func RoundRobin

func RoundRobin[T any](publishers ...Publisher[T]) Publisher[T]

RoundRobin returns a Publisher[T] that distributes each Publish call to a single inner publisher, cycling through them in round-robin order.

Close is a no-op — the caller owns the inner publishers and is responsible for closing them.

Example

ExampleRoundRobin demonstrates distributing messages across publishers in round-robin order.

ctx := context.Background()

a := &collectPublisher[Event]{}
b := &collectPublisher[Event]{}

pub := goflux.RoundRobin[Event](a, b)

_ = pub.Publish(ctx, "events", Event{ID: "1", Name: "first"})
_ = pub.Publish(ctx, "events", Event{ID: "2", Name: "second"})
_ = pub.Publish(ctx, "events", Event{ID: "3", Name: "third"})

fmt.Println("a:", a.get())
fmt.Println("b:", b.get())
Output:
a: [{1 first} {3 third}]
b: [{2 second}]

type RequestHandler

type RequestHandler[Req, Resp any] func(ctx context.Context, req Req) (Resp, error)

RequestHandler processes a request and returns a response.

type Requester

type Requester[Req, Resp any] interface {
	// Request sends req to the given subject and returns the response.
	Request(ctx context.Context, subject string, req Req) (Resp, error)
	// Close releases any underlying resources.
	Close() error
}

Requester sends a typed request and waits for a typed response.

type Responder

type Responder[Req, Resp any] interface {
	// Serve registers the handler for the given subject. The call blocks
	// until ctx is cancelled or a fatal error occurs.
	Serve(ctx context.Context, subject string, handler RequestHandler[Req, Resp]) error
	// Close releases any underlying resources.
	Close() error
}

Responder handles incoming requests and produces typed responses.

type Subscriber

type Subscriber[T any] interface {
	// Subscribe registers handler for the subject. The call blocks until ctx is
	// canceled or the implementation encounters a fatal error.
	Subscribe(ctx context.Context, subject string, handler Handler[T]) error
	// Close unsubscribes and releases resources.
	Close() error
}

Subscriber listens on one or more subjects and dispatches decoded messages to a Handler.

func FanIn

func FanIn[T any](subscribers ...Subscriber[T]) Subscriber[T]

FanIn returns a Subscriber[T] that subscribes to the same subject on all provided subscribers and dispatches every message to a single handler. Subscribe blocks until all inner subscriptions complete (i.e. all contexts are cancelled or all return an error).

Close is a no-op — the caller owns the inner subscribers and is responsible for closing them.

Example

ExampleFanIn demonstrates merging two subscribers into one handler. Messages from both source buses are dispatched to the same handler.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

busA := channel.NewBus[Event]()
pubA := channel.NewPublisher(busA)

subA, err := channel.NewSubscriber(busA, 1)
if err != nil {
	panic(err)
}

busB := channel.NewBus[Event]()
pubB := channel.NewPublisher(busB)

subB, err := channel.NewSubscriber(busB, 1)
if err != nil {
	panic(err)
}

var (
	mu       sync.Mutex
	received []string
)

merged := goflux.FanIn[Event](subA, subB)

done := make(chan struct{})

gofuncy.StartWithReady(ctx, func(ctx context.Context, ready gofuncy.ReadyFunc) error {
	ready()

	return merged.Subscribe(ctx, "events", func(_ context.Context, msg goflux.Message[Event]) error {
		mu.Lock()

		received = append(received, msg.Payload.Name)
		if len(received) == 2 {
			close(done)
		}
		mu.Unlock()

		return nil
	})
}, gofuncy.WithName("fanin-subscriber"))

time.Sleep(10 * time.Millisecond)

_ = pubA.Publish(ctx, "events", Event{ID: "1", Name: "from-a"})
_ = pubB.Publish(ctx, "events", Event{ID: "2", Name: "from-b"})

<-done

mu.Lock()
sort.Strings(received)

for _, r := range received {
	fmt.Println(r)
}
mu.Unlock()
Output:
from-a
from-b

type Telemetry

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

Telemetry holds OTel instruments (tracer, metrics, propagator) for a single transport instance. Construct with NewTelemetry.

func NewTelemetry

func NewTelemetry(opts ...TelemetryOption) (*Telemetry, error)

NewTelemetry creates a Telemetry instance. Without options it reads from the current OTel globals, so callers that have already called otel.SetTracerProvider / otel.SetMeterProvider need not pass anything.

func (*Telemetry) ExtractContext

func (t *Telemetry) ExtractContext(ctx context.Context, carrier propagation.TextMapCarrier) context.Context

ExtractContext extracts span context from carrier and returns an enriched context with the remote span as parent. Use this for synchronous transports (e.g. HTTP) where parent-child relationship is appropriate.

func (*Telemetry) ExtractSpanContext

func (t *Telemetry) ExtractSpanContext(ctx context.Context, carrier propagation.TextMapCarrier) trace.SpanContext

ExtractSpanContext extracts the remote span context from carrier without injecting it as parent into ctx. Use this with WithRemoteSpanContext for async transports where the consumer span should link to (not be a child of) the producer span.

func (*Telemetry) InjectContext

func (t *Telemetry) InjectContext(ctx context.Context, carrier propagation.TextMapCarrier)

InjectContext injects the span context from ctx into the carrier. Transports call this on the publish side to propagate trace context across wire boundaries (e.g. NATS headers, HTTP headers).

func (*Telemetry) RecordFetch

func (t *Telemetry) RecordFetch(ctx context.Context, subject string, system semconvmsg.SystemAttr, count int, fn func(context.Context) error) error

RecordFetch opens a consumer span for a pull-based fetch operation.

func (*Telemetry) RecordProcess

func (t *Telemetry) RecordProcess(ctx context.Context, subject string, system semconvmsg.SystemAttr, fn func(context.Context) error, opts ...ProcessOption) error

RecordProcess opens a consumer span, calls fn, records duration and counter. Pass WithRemoteSpanContext to attach the producer span as a link rather than a parent (recommended for async transports like NATS).

func (*Telemetry) RecordPublish

func (t *Telemetry) RecordPublish(ctx context.Context, subject string, system semconvmsg.SystemAttr, fn func(context.Context) error) error

RecordPublish opens a producer span, calls fn, records duration and counter.

func (*Telemetry) RecordRequest

func (t *Telemetry) RecordRequest(ctx context.Context, subject string, system semconvmsg.SystemAttr, fn func(context.Context) error) error

RecordRequest opens a client span for a request-reply call.

func (*Telemetry) RegisterLag

func (t *Telemetry) RegisterLag(subject string, lagFn func() int64) (metric.Int64ObservableGauge, error)

RegisterLag registers the goflux.consumer.lag observable gauge. Uses the meter provider that was passed to NewTelemetry.

type TelemetryOption

type TelemetryOption func(*telemetryConfig)

TelemetryOption configures a Telemetry instance.

func WithMeterProvider

func WithMeterProvider(mp metric.MeterProvider) TelemetryOption

WithMeterProvider sets the meter provider. Defaults to otel.GetMeterProvider.

func WithPropagator

WithPropagator sets the text-map propagator. Defaults to otel.GetTextMapPropagator.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) TelemetryOption

WithTracerProvider sets the tracer provider. Defaults to otel.GetTracerProvider.

type Terminator

type Terminator interface {
	Acker
	Term() error
}

Terminator extends Acker with terminal rejection — the message will not be redelivered. Use for dead-letter patterns where handler errors are non-retryable.

type Topic

type Topic[T any] struct {
	Publisher[T]
	Subscriber[T]
}

Topic bundles a Publisher and Subscriber sharing the same Codec. Use it when a service needs to both produce and consume the same message type.

Directories

Path Synopsis
bridge module
transport
jetstream module
nats module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL