eventbus

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 6 Imported by: 1

Documentation

Overview

Package eventbus provides a lightweight in-process event bus with middleware support and observability metrics.

This package is intentionally **memory-only** — it handles synchronous and asynchronous in-process pub/sub with wildcard topic matching. For cross-process, persistent, or broker-backed messaging (RabbitMQ, Kafka, RocketMQ, ActiveMQ, Redis Streams), use the [mq] package instead, which provides a unified Broker abstraction with pluggable backends.

Architecture

The bus is built around three core concepts:

  • Event: a typed message with a name, timestamp, payload, and metadata.
  • Handler: a function that processes events.
  • Bus: the central dispatcher that routes events to handlers.

Dispatch modes

  • Sync — Publish blocks until all handlers complete (default)
  • Async — Publish returns immediately; handlers run in background
  • Parallel — handlers run concurrently; Publish waits for all

Middleware

Handlers can be wrapped with middleware for cross-cutting concerns:

  • LoggingMiddleware — structured logging of each event
  • MetricsMiddleware — per-handler count, latency, error rate
  • RetryMiddleware — automatic retry with backoff
  • RecoverMiddleware — panic recovery
  • DeadLetterMiddleware— route failed events to a dead-letter handler

Observability

Every Bus implementation exposes a Metrics snapshot:

m := bus.Metrics()
fmt.Println(m.Published, m.Delivered, m.Failed, m.AvgLatency)

Basic usage

bus := eventbus.NewBus()
defer bus.Close()

bus.Subscribe("user.created", func(ctx context.Context, e *eventbus.Event) error {
    log.Printf("user created: %s", e.Payload)
    return nil
})

bus.Publish(ctx, eventbus.New("user.created", userID))

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = fmt.Errorf("eventbus: bus is closed")

ErrClosed is returned when publishing to a closed bus.

Functions

func GenerateID

func GenerateID() string

GenerateID produces a unique event ID (exported for backend use).

func IsClosed

func IsClosed(err error) bool

IsClosed reports whether err is a bus-closed error.

func TopicMatches

func TopicMatches(pattern, name string) bool

TopicMatches checks if a topic pattern matches an event name. Supports:

  • exact match: "user.created" == "user.created"
  • single-level wildcard: "user.*" matches "user.created" but not "user.profile.updated"
  • multi-level wildcard: "user.>" matches "user.created" and "user.profile.updated"

Types

type Bus

type Bus interface {
	// Publish sends an event to all matching subscribers.
	// In sync mode, this blocks until all handlers complete.
	// In async mode, this returns immediately after enqueuing.
	Publish(ctx context.Context, e *Event) error

	// Subscribe registers a handler for the given topic.
	// Topic may contain wildcards:
	//   - "user.*"     matches "user.created", "user.deleted", etc.
	//   - "user.>"     matches "user.created", "user.profile.updated", etc.
	// Returns a Subscription that can be used to Unsubscribe.
	Subscribe(topic string, handler Handler) Subscription

	// Unsubscribe removes a subscription.
	Unsubscribe(sub Subscription) error

	// Close shuts down the bus, releasing all resources.
	// Pending events may be drained or dropped depending on the backend.
	Close() error

	// Metrics returns a snapshot of bus metrics.
	Metrics() Metrics
}

Bus is the core event bus interface. Every backend implements this.

func NewBus

func NewBus(opts ...Option) Bus

NewBus creates a new in-memory event bus.

type DispatchMode

type DispatchMode int

DispatchMode controls how events are delivered to handlers.

const (
	// Sync dispatches events synchronously — Publish blocks until all
	// handlers complete. Errors from one handler stop delivery to
	// subsequent handlers.
	Sync DispatchMode = iota

	// Async dispatches events in goroutines — Publish returns immediately
	// after enqueuing. Handler errors are collected but not returned to
	// the publisher.
	Async

	// Parallel dispatches events to all handlers concurrently in
	// separate goroutines, then waits for all to complete. Publish
	// blocks until all handlers finish.
	Parallel
)

type Event

type Event struct {
	// ID is a unique identifier for this event instance. Auto-generated
	// if empty.
	ID string `json:"id"`

	// Name is the event type, e.g. "user.created". Used for routing.
	Name string `json:"name"`

	// Time is when the event was created.
	Time time.Time `json:"time"`

	// Source is the originator of the event (optional, untyped).
	Source any `json:"source,omitempty"`

	// Payload is the event data (must be serializable for persistent backends).
	Payload any `json:"payload,omitempty"`

	// Headers are arbitrary key-value metadata.
	Headers map[string]string `json:"headers,omitempty"`

	// Attempt is the current delivery attempt (1-based). Incremented by
	// retry middleware.
	Attempt int `json:"attempt,omitempty"`
}

Event is a message published to the bus. It carries a name, timestamp, optional payload, and arbitrary metadata (headers).

func New

func New(name string, payload any) *Event

New creates a new Event with the given name and payload.

func NewWithSource

func NewWithSource(name string, source, payload any) *Event

NewWithSource creates a new Event with a source.

func (*Event) String

func (e *Event) String() string

String returns a human-readable representation.

func (*Event) WithHeader

func (e *Event) WithHeader(key, val string) *Event

WithHeader adds a header and returns the event for chaining.

type Handler

type Handler func(ctx context.Context, e *Event) error

Handler processes a single event. Returning an error causes the event to be considered failed (subject to retry / dead-letter middleware).

func ApplyMiddleware

func ApplyMiddleware(handler Handler, mw ...Middleware) Handler

ApplyMiddleware wraps a handler with the given middleware chain. Middleware are applied in order: the first middleware in the slice becomes the outermost wrapper.

type HandlerMetrics

type HandlerMetrics struct {
	Calls   map[string]int64
	Errors  map[string]int64
	Latency map[string]time.Duration
	// contains filtered or unexported fields
}

HandlerMetrics tracks per-topic handler execution counts, errors, and latency.

func NewHandlerMetrics

func NewHandlerMetrics() *HandlerMetrics

NewHandlerMetrics creates a HandlerMetrics collector.

func (*HandlerMetrics) Get

func (h *HandlerMetrics) Get(topic string) (calls int64, errors int64, avgLatency time.Duration)

Get returns the metrics for a topic.

func (*HandlerMetrics) Record

func (h *HandlerMetrics) Record(topic string, latency time.Duration, err error)

Record records a handler call result.

func (*HandlerMetrics) Topics

func (h *HandlerMetrics) Topics() []string

Topics returns all tracked topic names.

type Metrics

type Metrics struct {
	Published    int64         // total events published
	Delivered    int64         // total events delivered to handlers
	Failed       int64         // total handler failures
	Pending      int64         // events currently in-flight
	Subscribers  int64         // active subscriber count
	AvgLatency   time.Duration // average publish→deliver latency
	TotalLatency time.Duration // cumulative latency (for avg computation)
}

Metrics is a point-in-time snapshot of bus observability data.

type MetricsCollector

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

Snapshot captures metrics atomically. Implementations should call this from their Metrics() method.

func (*MetricsCollector) RecordDelivered

func (m *MetricsCollector) RecordDelivered(latency time.Duration)

RecordDelivered increments delivered and accumulates latency.

func (*MetricsCollector) RecordFailed

func (m *MetricsCollector) RecordFailed()

RecordFailed increments the failed counter.

func (*MetricsCollector) RecordPending

func (m *MetricsCollector) RecordPending()

RecordPending increments the pending counter.

func (*MetricsCollector) RecordPublish

func (m *MetricsCollector) RecordPublish()

RecordPublish increments the published counter.

func (*MetricsCollector) RecordSubscribe

func (m *MetricsCollector) RecordSubscribe()

RecordSubscribe increments the subscriber counter.

func (*MetricsCollector) RecordUnsubscribe

func (m *MetricsCollector) RecordUnsubscribe()

RecordUnsubscribe decrements the subscriber counter.

func (*MetricsCollector) Snapshot

func (m *MetricsCollector) Snapshot() Metrics

Snapshot returns the current metrics.

type Middleware

type Middleware func(next Handler) Handler

Middleware wraps a Handler, adding cross-cutting behavior.

func DeadLetterMiddleware

func DeadLetterMiddleware(dlqHandler Handler) Middleware

DeadLetterMiddleware routes events that fail after all retries to a dead-letter handler. This is useful for logging, alerting, or re-processing failed events.

func LoggingMiddleware

func LoggingMiddleware(logger *log.Logger) Middleware

LoggingMiddleware logs each event before and after handler execution.

func MetricsMiddleware

func MetricsMiddleware(collector *HandlerMetrics) Middleware

MetricsMiddleware wraps a handler with per-topic metrics collection.

func RecoverMiddleware

func RecoverMiddleware() Middleware

RecoverMiddleware catches panics in handlers and converts them to errors.

func RetryMiddleware

func RetryMiddleware(maxRetries int, backoff time.Duration) Middleware

RetryMiddleware retries a failed handler up to maxRetries times with the given backoff. The event's Attempt field is incremented on each retry.

type Option

type Option func(*bus)

Option configures the Bus.

func WithAsyncBufferSize

func WithAsyncBufferSize(n int) Option

WithAsyncBufferSize sets the buffer size for async dispatch. Only effective with Async mode. Default: 1024.

func WithDispatchMode

func WithDispatchMode(mode DispatchMode) Option

WithDispatchMode sets the dispatch mode (default: Sync).

func WithMiddleware

func WithMiddleware(mw ...Middleware) Option

WithMiddleware adds middleware applied to all handlers.

type Subscription

type Subscription interface {
	// ID returns the unique subscription identifier.
	ID() string
	// Topic returns the subscribed topic pattern.
	Topic() string
}

Subscription represents an active subscription.

func NewSubscription

func NewSubscription(id, topic string) Subscription

NewSubscription creates a Subscription with the given id and topic. This is intended for backend implementations.

Jump to

Keyboard shortcuts

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