messaging

package module
v0.1.0 Latest Latest
Warning

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

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

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

README

messaging

messaging provides typed, transport-neutral messaging contracts for Go: a generic envelope, small publish/subscribe, request/reply and stream interfaces, and composable helpers around them. It is for application and library authors who want message-driven code that does not depend on one broker client, and for transport authors who want a shared contract and a conformance suite to test against.

Features

  • Envelope[T] with validated metadata, UUIDv7 message IDs and headers copied at every boundary.
  • Generic ports: Publisher[T], Subscriber[T], Delivery[T], Requester[Req, Resp] and Stream[T].
  • Explicit AtMostOnce and AtLeastOnce delivery with one-shot Ack/Nack.
  • Decorators: opaque authorization (AuthorizedPublisher, AuthorizedSubscriber), bounded parallel fan-out (FanoutPublisher) and in-process request/reply (HandlerRequester).
  • memory.Broker: a bounded in-process broker with back-pressure, for tests and process-local messaging.
  • conformance.Run: a test suite for third-party transport adapters.

Installation

go get github.com/justusschock/messaging@latest

Requires Go 1.25 or newer. The only dependency outside the standard library is github.com/justusschock/concurrency, used to bound fan-out parallelism.

Quick start

Publish and consume with at-least-once delivery on the in-memory broker (from memory/example_test.go):

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/justusschock/messaging"
	"github.com/justusschock/messaging/memory"
)

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

	broker := memory.NewBroker[string](10 * time.Millisecond)
	defer func() { _ = broker.Close() }()

	subscription := messaging.Subscription{
		Subject:     "orders.created",
		Consumer:    "audit",
		Semantics:   messaging.AtLeastOnce,
		MaxInFlight: 8,
	}
	received := make(chan string, 1)
	stopped := make(chan error, 1)
	go func() {
		stopped <- broker.Subscribe(ctx, subscription, func(ctx context.Context, delivery messaging.Delivery[string]) error {
			select {
			case received <- delivery.Envelope().Payload:
			default: // a duplicate from the publish loop below
			}
			return delivery.Ack(ctx)
		})
	}()

	envelope, err := messaging.NewEnvelope("orders.created", "order-42")
	if err != nil {
		fmt.Println(err)
		return
	}
	// Subscribe registers the consumer asynchronously, and an envelope
	// published before registration has no consumer. Publish until the
	// subscriber has received one.
	for delivered := false; !delivered; {
		if err := broker.Publish(ctx, envelope); err != nil {
			fmt.Println(err)
			return
		}
		select {
		case payload := <-received:
			fmt.Println("received", payload)
			delivered = true
		case <-time.After(time.Millisecond):
		}
	}

	cancel()
	fmt.Println("subscriber stopped:", <-stopped)
	// Prints:
	// received order-42
	// subscriber stopped: context canceled
}

More examples: ExampleFanoutPublisher.

Envelopes

An envelope owns its header map. NewEnvelope, WithHeader and Clone return copies, and every helper copies headers at its boundaries. Payloads are copied with normal Go value semantics; pointers, maps and slices inside a payload stay shared.

envelope, err := messaging.NewEnvelope("orders.created", Order{ID: "order-42"})
if err != nil {
	return err
}
envelope, err = envelope.WithHeader("trace", traceID)
if err != nil {
	return err
}
return publisher.Publish(ctx, envelope)

NewMessageID returns canonical lowercase UUIDv7 strings. Subjects must be non-empty and contain no whitespace; envelopes also need a non-empty ID, a non-zero SentAt and non-empty header keys.

Delivery semantics
  • AtMostOnce: the handler runs once per envelope. Handler errors and missing settlement do not cause a redelivery.
  • AtLeastOnce: an attempt that is not acknowledged (handler error, Nack, or no settlement) is redelivered after the broker's retry delay with the next attempt number, until it is acknowledged, the subscription context ends or the broker closes.

Each attempt can be settled once; a second Ack or Nack returns ErrDeliverySettled.

Composition
fanout, err := messaging.NewFanoutPublisher(
	[]messaging.Publisher[Event]{auditPublisher, eventPublisher, metricsPublisher},
	2, // at most two targets in parallel
)
if err != nil {
	return err
}
secured, err := messaging.NewAuthorizedPublisher[Event](fanout, authorizer)
if err != nil {
	return err
}
return secured.Publish(ctx, envelope)

FanoutPublisher runs every target, wraps failures as publisher N: … in input order and joins them with errors.Join. The authorization decorators call your Authorizer with action publish (headers as attributes) or subscribe (attribute consumer); a denial matches both ErrUnauthorized and the authorizer's error, and the wrapped port is not called. HandlerRequester adapts a RequestHandler to Requester, validating and copying both the request and the response.

Adapter conformance
func TestAdapter(t *testing.T) {
	conformance.Run(t, func(t *testing.T) (messaging.Publisher[string], messaging.Subscriber[string], func()) {
		adapter := newAdapter(t)
		return adapter, adapter, func() { _ = adapter.Close() }
	})
}

The suite checks an at-least-once round trip (ID, payload and headers preserved), gives Publish and Subscribe a shared one-second deadline, and requires Subscribe to keep running until its context ends. Purely in-process adapters can run it inside a testing/synctest bubble.

Packages

Package Import path Purpose
messaging github.com/justusschock/messaging Envelope, ports, errors and decorators.
memory github.com/justusschock/messaging/memory Bounded in-process broker implementing Publisher and Subscriber.
conformance github.com/justusschock/messaging/conformance Test suite for transport adapters.

Packages under internal/, if any, are not part of the API.

Design and guarantees

  • Concurrency. memory.Broker is safe for concurrent use. The decorators are safe for concurrent use when the components they wrap are. A consumer's deliveries are processed sequentially.
  • Cancellation. Every blocking operation takes a context.Context and returns its error when it ends. Subscribe blocks until its context ends or the transport closes; cancelling the context is how you unsubscribe.
  • Bounded resources. Each broker consumer buffers at most MaxInFlight envelopes; when the buffer is full, Publish blocks (back-pressure). Fan-out runs at most maxParallel targets at once.
  • Errors. Sentinel errors (ErrInvalidEnvelope, ErrInvalidSubscription, ErrUnauthorized, ErrDeliverySettled, ErrConsumerExists, ErrClosed, ErrNilDependency) are matched with errors.Is. NewFanoutPublisher wraps concurrency.ErrInvalidLimit for a non-positive limit. The library never logs.
  • Not provided. Durable or networked brokers, exactly-once delivery, subject wildcards or routing, credential handling or policy evaluation, and payload serialization. These belong in adapters or higher-level packages.
  • Stability. The module is v0.x: minor releases may break the API. Every break is listed in the changelog.

Documentation

Contributing

Contributions go through pull requests; nothing is pushed to main directly. Read AGENTS.md first: it describes the docs-first process (PRDs and ADRs), the public API rules, and the checks to run before opening a pull request.

License

Apache License 2.0. See LICENSE and NOTICE.

Documentation

Overview

Package messaging defines typed, transport-neutral messaging contracts and small composition helpers.

The core types are Envelope, an immutable-by-convention message with metadata and a typed payload, and the generic ports Publisher, Subscriber, Delivery, Requester and Stream. Transports implement the ports; application code depends only on them.

The package also provides decorators that compose with any transport: AuthorizedPublisher and AuthorizedSubscriber consult an opaque Authorizer, FanoutPublisher publishes to several targets with bounded parallelism, and HandlerRequester adapts an in-process RequestHandler to Requester.

Every helper copies envelope headers at its boundaries, so callers and transports never share a header map. Payloads are copied with normal Go value semantics; pointers, maps and slices inside a payload remain shared.

Errors are reported through sentinel values such as ErrInvalidEnvelope that support errors.Is. Blocking operations take a context.Context and return its error when it ends.

The memory sub-package provides a bounded in-process broker; the conformance sub-package provides a test suite for transport adapters.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidEnvelope reports incomplete or malformed envelope metadata.
	ErrInvalidEnvelope = errors.New("messaging: invalid envelope")
	// ErrInvalidSubscription reports an invalid subscription identity,
	// semantics or capacity.
	ErrInvalidSubscription = errors.New("messaging: invalid subscription")
	// ErrUnauthorized reports that an authorization decorator denied the
	// operation. The authorizer's own error is wrapped alongside it.
	ErrUnauthorized = errors.New("messaging: unauthorized")
	// ErrDeliverySettled reports that a delivery attempt was already
	// acknowledged or negatively acknowledged.
	ErrDeliverySettled = errors.New("messaging: delivery settled")
	// ErrConsumerExists reports that the subject already has an active
	// consumer with the same name.
	ErrConsumerExists = errors.New("messaging: consumer exists")
	// ErrClosed reports that a transport, or an active subscription on it, has
	// been closed.
	ErrClosed = errors.New("messaging: closed")
	// ErrNilDependency reports that a required publisher, subscriber,
	// authorizer or handler is nil.
	ErrNilDependency = errors.New("messaging: nil dependency")
)

Functions

This section is empty.

Types

type AuthorizationRequest

type AuthorizationRequest struct {
	Action     string
	Subject    string
	Attributes map[string]string
}

AuthorizationRequest describes an operation for an Authorizer. Action is "publish" or "subscribe". Attributes is a copy owned by the authorizer.

type AuthorizedPublisher

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

AuthorizedPublisher is a Publisher decorator that authorizes every publish before forwarding it. It is safe for concurrent use if the wrapped publisher and authorizer are.

func NewAuthorizedPublisher

func NewAuthorizedPublisher[T any](next Publisher[T], authorizer Authorizer) (*AuthorizedPublisher[T], error)

NewAuthorizedPublisher wraps next with authorizer. It returns ErrNilDependency if either is nil.

func (*AuthorizedPublisher[T]) Publish

func (publisher *AuthorizedPublisher[T]) Publish(ctx context.Context, envelope Envelope[T]) error

Publish validates the envelope, asks the authorizer for action "publish" with a copy of the headers as attributes, and forwards a clone of the envelope. A denial returns an error wrapping both ErrUnauthorized and the authorizer's error; the wrapped publisher is not called.

type AuthorizedSubscriber

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

AuthorizedSubscriber is a Subscriber decorator that authorizes every subscription before forwarding it. It is safe for concurrent use if the wrapped subscriber and authorizer are.

func NewAuthorizedSubscriber

func NewAuthorizedSubscriber[T any](next Subscriber[T], authorizer Authorizer) (*AuthorizedSubscriber[T], error)

NewAuthorizedSubscriber wraps next with authorizer. It returns ErrNilDependency if either is nil.

func (*AuthorizedSubscriber[T]) Subscribe

func (subscriber *AuthorizedSubscriber[T]) Subscribe(ctx context.Context, subscription Subscription, handler Handler[T]) error

Subscribe validates the subscription and handler, asks the authorizer for action "subscribe" with the consumer name as the "consumer" attribute, and forwards the call. A denial returns an error wrapping both ErrUnauthorized and the authorizer's error; the wrapped subscriber is not called.

type Authorizer

type Authorizer interface {
	Authorize(context.Context, AuthorizationRequest) error
}

Authorizer decides whether an operation is allowed. It returns nil to allow the operation and any error to deny it. The package does not interpret identities, credentials or policies; those belong to the implementation.

type Delivery

type Delivery[T any] interface {
	Envelope() Envelope[T]
	Attempt() uint
	Ack(context.Context) error
	Nack(context.Context, error) error
}

Delivery is one delivery attempt of an envelope to a handler.

Envelope returns a copy of the delivered envelope and Attempt the 1-based attempt number. Ack and Nack settle the attempt; each attempt can be settled once, and a second settlement returns ErrDeliverySettled.

type DeliverySemantics

type DeliverySemantics uint8

DeliverySemantics selects how a subscriber treats unacknowledged deliveries.

const (
	// AtMostOnce invokes the handler once per message; handler errors and
	// missing settlement do not cause a redelivery.
	AtMostOnce DeliverySemantics = iota + 1
	// AtLeastOnce redelivers a message until the handler acknowledges it.
	AtLeastOnce
)

type Envelope

type Envelope[T any] struct {
	ID      MessageID
	Subject string
	SentAt  time.Time
	Headers map[string]string
	Payload T
}

Envelope is a message with metadata and a typed payload.

Treat envelopes as values: use Envelope.WithHeader and Envelope.Clone rather than mutating Headers of an envelope that has been shared. Every helper in this module copies Headers at its boundaries. Payload is copied with normal Go value semantics only.

func NewEnvelope

func NewEnvelope[T any](subject string, payload T) (Envelope[T], error)

NewEnvelope returns a valid envelope with a new MessageID, the current UTC time as SentAt and an empty header map. It returns an error wrapping ErrInvalidEnvelope if subject is empty or contains whitespace.

func (Envelope[T]) Clone

func (envelope Envelope[T]) Clone() Envelope[T]

Clone returns a copy of the envelope with its own header map. The payload is copied by value only.

func (Envelope[T]) Validate

func (envelope Envelope[T]) Validate() error

Validate reports whether the envelope metadata is well-formed: a non-empty ID, a non-empty subject without whitespace, a non-zero SentAt and no empty header keys. Failures wrap ErrInvalidEnvelope.

func (Envelope[T]) WithHeader

func (envelope Envelope[T]) WithHeader(key, value string) (Envelope[T], error)

WithHeader returns a copy of the envelope with the header key set to value. The receiver is not modified. An empty key yields ErrInvalidEnvelope.

type FanoutPublisher

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

FanoutPublisher is a Publisher that publishes each envelope to every configured target with bounded parallelism. It is safe for concurrent use if the targets are.

Example

FR-MSG-09

package main

import (
	"context"
	"fmt"
	"slices"
	"strings"
	"sync"

	"github.com/justusschock/messaging"
)

type recordingPublisher struct {
	name  string
	mu    *sync.Mutex
	names *[]string
}

func (publisher recordingPublisher) Publish(_ context.Context, _ messaging.Envelope[string]) error {
	publisher.mu.Lock()
	defer publisher.mu.Unlock()
	*publisher.names = append(*publisher.names, publisher.name)
	return nil
}

// FR-MSG-09
func main() {
	var mu sync.Mutex
	names := []string{}
	fanout, _ := messaging.NewFanoutPublisher([]messaging.Publisher[string]{
		recordingPublisher{"audit", &mu, &names},
		recordingPublisher{"events", &mu, &names},
	}, 2)
	envelope, _ := messaging.NewEnvelope("created", "item-1")
	_ = fanout.Publish(context.Background(), envelope)
	slices.Sort(names)
	fmt.Println(strings.Join(names, " "))
}
Output:
audit events

func NewFanoutPublisher

func NewFanoutPublisher[T any](publishers []Publisher[T], maxParallel int) (*FanoutPublisher[T], error)

NewFanoutPublisher returns a fan-out over a copy of publishers that runs at most maxParallel targets at once. It returns ErrNilDependency if the list is empty or contains nil, and an error wrapping concurrency.ErrInvalidLimit if maxParallel is not positive.

func (*FanoutPublisher[T]) Publish

func (publisher *FanoutPublisher[T]) Publish(ctx context.Context, envelope Envelope[T]) error

Publish validates the envelope and publishes a separate clone to every target. A failing target does not stop the others. Target errors are wrapped as "publisher N: ..." in input order and joined with errors.Join. If ctx ends, targets not yet started are skipped and the context's cause is returned.

type Handler

type Handler[T any] func(context.Context, Delivery[T]) error

Handler processes one delivery. Under AtLeastOnce semantics a delivery that the handler does not acknowledge is redelivered.

type HandlerRequester

type HandlerRequester[Req, Resp any] struct {
	// contains filtered or unexported fields
}

HandlerRequester adapts an in-process RequestHandler to Requester. It is safe for concurrent use if the handler is.

func NewHandlerRequester

func NewHandlerRequester[Req, Resp any](handler RequestHandler[Req, Resp]) (*HandlerRequester[Req, Resp], error)

NewHandlerRequester returns a requester that calls handler. It returns ErrNilDependency if handler is nil.

func (*HandlerRequester[Req, Resp]) Request

func (requester *HandlerRequester[Req, Resp]) Request(ctx context.Context, request Envelope[Req]) (Envelope[Resp], error)

Request validates the request, passes a clone to the handler, validates the response and returns a clone of it. Handler errors are returned unchanged.

type MessageID

type MessageID string

MessageID uniquely identifies a message.

func NewMessageID

func NewMessageID() (MessageID, error)

NewMessageID returns a new canonical, lowercase UUIDv7 string: a Unix millisecond timestamp followed by cryptographically random bits. IDs generated later in time sort after earlier ones at millisecond precision.

type Publisher

type Publisher[T any] interface {
	Publish(context.Context, Envelope[T]) error
}

Publisher publishes envelopes to a transport.

Publish returns after the transport has accepted the envelope, or with the context's error if ctx ends first. Implementations must not retain or mutate the caller's header map.

type RequestHandler

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

RequestHandler answers a request envelope with a response envelope.

type Requester

type Requester[Req, Resp any] interface {
	Request(context.Context, Envelope[Req]) (Envelope[Resp], error)
}

Requester sends a request envelope and waits for the response envelope.

type Stream

type Stream[T any] interface {
	Send(context.Context, Envelope[T]) error
	Receive(context.Context) (Envelope[T], error)
	Close() error
}

Stream is a bidirectional sequence of envelopes. Send and Receive block until they complete or ctx ends; Close releases the stream.

The package defines the port only; implementations live in transports.

type Subscriber

type Subscriber[T any] interface {
	Subscribe(context.Context, Subscription, Handler[T]) error
}

Subscriber runs a handler for a subscription.

Subscribe validates the subscription, registers the consumer and then blocks, invoking handler for each delivery, until ctx ends, the transport closes, or a terminal error occurs. Successful registration alone does not make it return.

type Subscription

type Subscription struct {
	Subject     string
	Consumer    string
	Semantics   DeliverySemantics
	MaxInFlight int
}

Subscription identifies a consumer of a subject and configures delivery.

Subject and Consumer together identify the consumer; a transport may reject a second active subscription with the same pair (ErrConsumerExists). MaxInFlight bounds how many messages the transport buffers for the consumer.

func (Subscription) Validate

func (subscription Subscription) Validate() error

Validate reports whether the subscription is well-formed. Subject must be non-empty without whitespace, Consumer non-empty, Semantics one of AtMostOnce or AtLeastOnce, and MaxInFlight positive. Failures wrap ErrInvalidSubscription.

Directories

Path Synopsis
Package conformance provides a reusable test suite for implementations of the messaging Publisher and Subscriber ports.
Package conformance provides a reusable test suite for implementations of the messaging Publisher and Subscriber ports.
Package memory provides a bounded, process-local implementation of the messaging Publisher and Subscriber ports.
Package memory provides a bounded, process-local implementation of the messaging Publisher and Subscriber ports.

Jump to

Keyboard shortcuts

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