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 ¶
- Variables
- type AuthorizationRequest
- type AuthorizedPublisher
- type AuthorizedSubscriber
- type Authorizer
- type Delivery
- type DeliverySemantics
- type Envelope
- type FanoutPublisher
- type Handler
- type HandlerRequester
- type MessageID
- type Publisher
- type RequestHandler
- type Requester
- type Stream
- type Subscriber
- type Subscription
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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") // 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 ¶
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 ¶
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 ¶
Clone returns a copy of the envelope with its own header map. The payload is copied by value only.
func (Envelope[T]) Validate ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
Source Files
¶
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. |