msgin

package module
v0.0.0-...-0c820e1 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: Apache-2.0 Imports: 11 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.

Documentation

Overview

Package msgin implements the messaging patterns of Gregor Hohpe and Bobby Woolf's Enterprise Integration Patterns (EIP) in idiomatic, minimal-dependency Go.

Pipes and Filters

A flow is assembled as pipes and filters. A MessageChannel is the Pipe — the conduit a message travels along. A Step is the filter — one unit of processing. Chain assembles Steps into a pipeline. A MessageHandler is the endpoint where application code meets the messaging system.

The linear endpoints — Transform (Message Translator), Filter, and Activate/Consume (Service Activator) — are Steps composed by Chain; a content-based Router branches to a MessageChannel. End a producing Chain with To(sink) or Consume, or its final message is discarded.

A composed flow is a Handler[any], so NewConsumer[any](src, flow.Handle, …) drives it and it inherits retry, dead-letter, invalid-message, flow-control, and the worker pool. Typed endpoints assume the payload is the live Go value: this holds for live-value sources (memory); a WIRE source at T=any decodes to map[string]any, so decode to the concrete type in the first endpoint (a bytes-passthrough WithConsumerCodec[any] + Transform[[]byte, T]). Endpoint errors propagate into the runtime; a payload-type mismatch is ErrPayloadType, routed to the invalid-message channel — or to the dead-letter sink when none is configured (Permanent states all three arms).

Package layout

The root package holds the vocabulary and the SPI: messages, headers, the channel and handler interfaces, the adapter seams, and the error sentinels callers match with errors.Is. Implementations live in packages named for the EIP chapter that defines them:

  • endpoint — Consumer, Producer, Gateway, ChannelExchange (EIP ch.10)
  • routing — Filter, Router, Split, Aggregator (EIP ch.7)
  • transform — Transform (EIP ch.8)
  • channel — DirectChannel, QueueChannel, PublishSubscribeChannel, PubSub
  • resilience — ExponentialBackoff, circuit breaker, token bucket

Nothing in the root package imports one of these; no one of these imports another. Adapters and callers import them directly.

Publish-Subscribe

Beyond point-to-point channels, a PublishSubscribeChannel fans a message out to every subscriber; Subscribe returns a Subscription whose Cancel unsubscribes. A PubSub registry maps a topic name to such a channel (created on first Subscribe, dropped when empty) and satisfies the TopicPublisher/TopicSubscriber SPI that native-topic broker adapters implement. Dispatch is synchronous (no goroutine); the default settlement is all-subscribers-succeed (a subscriber error is joined and the message retried), with WithFanOut(FanOutBestEffort) to log-and-continue.

Scheduled and delayed send

An OutboundAdapter that can defer delivery implements the optional ScheduledSender capability; the sql adapter does so via its visible_after column. Producer.SendAfter(delay) is the skew-free relative primitive (the store computes now+delay) and SendAt(t) is absolute sugar over an injected clock; a sink that cannot schedule returns ErrScheduledSendUnsupported (never a silent immediate send). A negative or past delay delivers immediately. No goroutine is started — the delay lives in the durable row, so a scheduled send survives restarts and fires once across N competing consumers.

Messaging Gateway

Gateway and OutboundGateway are the request-reply members of the composition set, both built over the shared RequestReplyExchange SPI. The inbound Gateway[Req, Rep] is the application-facing entry point: Request turns a Req into a message, drives it through the exchange, and returns the correlated Rep. OutboundGateway is the in-flow counterpart — a Step that performs the exchange mid-flow and forwards the reply to next, saving and restoring the message's HeaderCorrelationID around a fresh per-exchange id so an upstream split/aggregate group key survives the round-trip.

Runtime-defined rules

Predicates and routing keys that must be defined at runtime — operator- or config-authored rules that change without a rebuild — are NOT part of this module. They will be supplied by a separate msgin/expr provider module, not yet written, offering expression-backed counterparts to the Go-func forms. Until it ships, the Go-func forms are the only forms; they remain the compile-time default regardless, so prefer them whenever the rule is known at build time, for their type safety and debuggability.

Index

Examples

Constants

View Source
const (
	HeaderMessageID     = "msgin.message-id"
	HeaderTimestamp     = "msgin.timestamp"
	HeaderContentType   = "msgin.content-type"
	HeaderCorrelationID = "msgin.correlation-id"
	HeaderDeliveryCount = "msgin.delivery-count"
	// HeaderSequenceNumber is the 1-based position of a child within a Splitter's
	// output (int). HeaderSequenceSize is the total number of children (int). A
	// Splitter stamps both so a downstream Aggregator can reassemble the group.
	//
	// HeaderSequenceSize IS AN UNVALIDATED GROUP SIZE. routing's DEFAULT release
	// strategy — the one in force until WithCompletionSize, WithReleaseStrategy
	// or WithReleaseWhen overrides it — holds a group until it has at least
	// HeaderSequenceSize members, and neither this header nor that strategy is
	// checked against routing.WithCompletionSize's ceiling. A message carrying an
	// implausible size (a hand-set header, or one framed in from an external
	// system) therefore holds its group open until the MessageGroupStore refuses
	// the next member with ErrOverflowDropped. That store cap is the bound:
	// adapter/memory's WithMaxGroupMembers, 65,536 members by DEFAULT, raisable
	// to 1,048,576, with no "unlimited" setting. A first member carrying no
	// HeaderSequenceSize at all never releases on this path.
	HeaderSequenceNumber = "msgin.sequence-number"
	HeaderSequenceSize   = "msgin.sequence-size"
)

Reserved header keys live under the "msgin." namespace.

Variables

View Source
var (
	// ErrPayloadType is returned when a value cannot be asserted to the type the
	// caller declared for it. It has TWO producer classes and errors.Is cannot
	// tell them apart:
	//
	//   - PAYLOAD SIDE — a Message[any] payload cannot be asserted to T. Its
	//     producers wrap INCONSISTENTLY and live in more than one module, so do
	//     not identify this side by a wrap: PayloadOf wraps as "want %T, got
	//     %T"; the consumer's live-value and wire type assertions return it
	//     BARE; and each msgin/expr provider's payload assertion wraps with the
	//     source expression. What they share is the ABSENCE of the expression
	//     side's marker, below.
	//   - EXPRESSION SIDE (the msgin/expr provider module, and any future
	//     CEL/starlark provider) — a compiled expression EVALUATED to a value
	//     that is not the declared result type. Wrapped as
	//     "expr result %T is not %T" (ADR 0029 §5.0b, decision D-K).
	//
	// Both classes are deterministic: the same input yields the same wrong type
	// on every redelivery. IsPermanent names this sentinel (reliability.go), so
	// neither is ever retried, and each is diverted WITHOUT a Permanent wrap —
	// to WithInvalidMessageSink if one is configured, else single-shot to
	// RetryPolicy.DeadLetter, else logged and discarded (ADR 0007 D7, as
	// amended by D-N and D-P). That is D-K's whole reason for reusing this
	// sentinel.
	//
	// ACCEPTED TRADE-OFF, not an absence: errors.Is(err, ErrPayloadType) does
	// not separate the two, which buys callers ONE target instead of one per
	// expression provider — but the two remedies are disjoint (fix the codec or
	// the producing adapter, versus fix the expression). Match the string
	// "expr result" to tell them apart: only the expression side carries a
	// discriminator, so its ABSENCE is what identifies the payload side.
	ErrPayloadType = errors.New("msgin: payload is not of the expected type")
	// ErrPayloadDecode is returned when a wire payload ([]byte) cannot be decoded into T.
	ErrPayloadDecode = errors.New("msgin: payload decode failed")
	// ErrNilAdapter is returned by constructors when a required adapter is nil.
	ErrNilAdapter = errors.New("msgin: adapter is nil")
	// ErrPayloadTooLarge is returned when a wire payload ([]byte) exceeds the
	// WithMaxPayloadBytes cap. It is PERMANENT (an over-size payload will not
	// shrink on redelivery), so the message is diverted like a decode failure
	// rather than retried (ADR 0009 D5) — to the invalid-message sink, or the
	// dead-letter sink when none is configured ([Permanent] states all three
	// arms).
	ErrPayloadTooLarge = errors.New("msgin: payload exceeds the configured maximum size")
	// ErrUnexpectedCodec is returned when a live-value source (memory) is given a codec.
	ErrUnexpectedCodec = errors.New("msgin: live-value source must not have a payload codec")
	// ErrInvalidConcurrency is returned when WithConcurrency's value is outside
	// its documented [lo, hi] range (below 1, or above endpoint's concurrency
	// ceiling) — see the option's own godoc for the bounds and their rationale.
	ErrInvalidConcurrency = errors.New("msgin: concurrency out of range")
	// ErrUnsupportedSource is returned when a Source is neither Polling nor Streaming.
	ErrUnsupportedSource = errors.New("msgin: source implements neither PollingSource nor EventDrivenSource")
	// ErrHandlerPanic wraps a value recovered from a panicking handler. It is a
	// TRANSIENT failure (retried per the RetryPolicy), not permanent.
	ErrHandlerPanic = errors.New("msgin: handler panicked")
	// ErrNoDeadLetter is returned when a RetryPolicy has a finite MaxAttempts
	// (> 0) but no DeadLetter sink to receive exhausted messages.
	ErrNoDeadLetter = errors.New("msgin: finite MaxAttempts requires a DeadLetter sink")
	// ErrInvalidMaxAttempts is returned when a RetryPolicy's MaxAttempts is negative.
	ErrInvalidMaxAttempts = errors.New("msgin: MaxAttempts must be >= 0")

	// ErrInvalidRetryAfterCap is returned by NewProducer when an explicit
	// WithProducerRetryAfterCap is <= 0. Leaving the option unset takes the
	// documented default instead of reaching this error (the set-flag pattern,
	// as in WithMaxInFlight/WithAttemptTTL): only an explicit non-positive value
	// is rejected, so a caller mistake is a construction error rather than a
	// silently-disabled clamp.
	ErrInvalidRetryAfterCap = errors.New("msgin: retry-after cap must be > 0")

	// ErrInvalidRetryBudget is returned by NewProducer when an explicit
	// WithProducerRetryBudget is <= 0. As with the cap, the unset case takes the
	// documented default; only an explicit non-positive value is an error.
	ErrInvalidRetryBudget = errors.New("msgin: retry budget must be > 0")

	// ErrUnboundedRetry is returned by NewProducer for a producer RetryPolicy
	// that is unbounded in BOTH dimensions: MaxAttempts == 0 (retry forever) with
	// a nil Backoff (no delay). That combination — which is exactly the valid
	// RetryPolicy zero value — is a zero-delay infinite loop on the CALLER'S
	// goroutine, so the producer rejects it at construction. It stays valid on
	// NewConsumer, where "retry forever, immediately" means broker redelivery,
	// not a spin. Set a MaxAttempts (with a DeadLetter) or a Backoff, or both.
	//
	// The check is deliberately STRUCTURAL — it tests Backoff for nil rather than
	// evaluating it — because BackoffStrategy is a public interface and calling
	// caller code inside a constructor may panic, may block, and is
	// non-deterministic for a jittered strategy. Two consequences follow, both
	// accepted:
	//
	//   - A non-nil strategy that always yields 0 (ExponentialBackoff{}) is
	//     accepted here and bounded at RUNTIME instead, by the 100ms floor and
	//     the always-on WithProducerRetryBudget.
	//   - A TYPED-NIL strategy (a nil *T stored in the interface) is non-nil to
	//     this check, so it is accepted and panics on the first retry, on the
	//     caller's goroutine. That panic is the caller's own nil pointer and
	//     propagates with their stack intact, which is the debuggable outcome;
	//     msgin does not recover it, exactly as it does not recover a panicking
	//     OutboundAdapter.Send.
	ErrUnboundedRetry = errors.New("msgin: producer retry policy must bound attempts or delay")

	// ErrRetryBudgetExhausted is joined onto the error returned by Producer.Send
	// when the retry loop stopped because the next wait would have overrun
	// WithProducerRetryBudget, rather than because MaxAttempts was spent. The
	// budget always applies — including to a finite MaxAttempts — so this
	// sentinel is what stops it silently truncating an explicit attempt count:
	// errors.Is(err, ErrRetryBudgetExhausted) says "the policy wanted more time
	// than the caller allowed", which is a different operational signal from
	// "we tried N times and gave up".
	ErrRetryBudgetExhausted = errors.New("msgin: retry budget exhausted before attempts were spent")

	// ErrInvalidDeadLetterTimeout is returned by NewProducer when an explicit
	// WithProducerDeadLetterTimeout is <= 0. The unset case takes the documented
	// 30-second default; there is deliberately no "no timeout" value, because the
	// divert runs on a ctx detached from the caller's and an unbounded detached
	// call can block the caller's goroutine forever.
	ErrInvalidDeadLetterTimeout = errors.New("msgin: dead-letter timeout must be > 0")

	// ErrDeadLettered is joined onto the error returned by Producer.Send when the
	// retry loop ended — because attempts were spent, because the retry budget
	// was exhausted, or because ctx was cancelled during a backoff wait — AND the
	// message was successfully diverted to the policy's DeadLetter sink. It lets
	// a caller tell "the message is safely in the DLQ" from "the send failed
	// outright" — errors.Is(err, ErrDeadLettered) — while the causing error stays
	// matchable through the same wrap chain.
	//
	// The guarantee is scoped to errors PRODUCED BY THIS PRODUCER. Being an
	// exported sentinel, nothing stops a third-party OutboundAdapter from wrapping
	// it into an error of its own, so errors.Is(err, ErrDeadLettered) on an error
	// that did not come out of Producer.Send proves nothing. Do not use it as an
	// authorization or audit primitive.
	//
	// NESTING BREAKS THE "THE DLQ" READING, and this is reachable with supported
	// configuration, not just a hostile adapter. RetryPolicy.DeadLetter may itself
	// be another msgin adapter, including a Producer with its own retry — so when
	// an OUTER divert fails, the joined inner error can carry ErrDeadLettered from
	// the INNER producer. errors.Is then reports true although the outer divert
	// did not happen. The same applies when p.out is a nested retrying Producer,
	// whose error passes through the IsPermanent and no-DLQ arms unchanged. The
	// sentinel therefore answers "was something dead-lettered somewhere in this
	// chain", not "is this message in the sink I configured". Where the
	// distinction matters, give each level its own sink and inspect that sink.
	ErrDeadLettered = errors.New("msgin: message diverted to the dead-letter sink")
	// ErrInvalidMaxInFlight is returned when WithMaxInFlight's value is outside
	// its documented [lo, hi] range (below 1, or above endpoint's max-in-flight
	// ceiling) — see the option's own godoc for the bounds and their rationale.
	ErrInvalidMaxInFlight = errors.New("msgin: max in-flight out of range")
	// ErrInvalidRateLimit is returned when a rate-limit configuration is invalid
	// (non-positive rps or burst on the default token bucket).
	ErrInvalidRateLimit = errors.New("msgin: rate limit must have positive rps and burst")
	// ErrInvalidAttemptTTL is returned when WithAttemptTTL is given a non-positive
	// duration (ADR 0009 D3).
	ErrInvalidAttemptTTL = errors.New("msgin: attempt TTL must be > 0")
	// ErrOverflowDropped reports that a message was refused or shed because a
	// BOUND was reached. Every bound in the library that can refuse an
	// individual message reports it through this one sentinel, so a caller has a
	// single errors.Is target for "capacity, not corruption".
	//
	// The producers are named by CLASS rather than enumerated, because the list
	// grows with every new bounded store and a count in a doc comment rots.
	// Locate them with:
	//
	//	grep -rn 'ErrOverflowDropped' --include='*.go' . | grep -v _test.go
	//
	//   - CONSUMER FLOW CONTROL — a streaming source's overflow policy sheds a
	//     delivery under credit contention. Here it is the CAUSE handed to the
	//     OnRetry hook and the logs, not a returned error (endpoint's consumer).
	//   - BOUNDED CHANNEL STORES — a full-buffer Enqueue. Under OverflowReject
	//     always; under OverflowDropOldest ONLY when nothing is evictable
	//     (every entry in flight), which is the one Drop* path that reports
	//     rather than drops silently. OverflowDropNewest never reports.
	//   - BOUNDED GROUP STORES — an over-cap Add, from either bound: too many
	//     GROUPS, or too many MEMBERS in one group. Wrapped with the site, the
	//     key and the counts, and Permanent-wrapped when the group cannot drain
	//     itself (see MessageGroupStore.Add). This covers the first-party memory
	//     store and every SQL dialect's AddMember, and it is the shape a
	//     third-party GroupStore must match.
	//   - THE AGGREGATOR, which is the one producer that MINTS this sentinel
	//     FRESH rather than propagating a store's. When an over-cap Add hands
	//     back a live snapshot and the re-fired release drains the group — or
	//     tries to and fails — Handle returns a newly built ErrOverflowDropped
	//     naming what happened. That error is ALWAYS TRANSIENT BY CONSTRUCTION:
	//     it wraps nothing, so no Permanent marker and no permanence-bearing
	//     sentinel from the store or from the caller's own aggregate/Send can
	//     travel up it and terminally settle a member the store never stored
	//     (ADR 0033 D-AX).
	//
	// So errors.Is(err, ErrOverflowDropped) means the bound spoke; it does NOT
	// by itself tell you whether the message is retryable. Ask IsPermanent.
	ErrOverflowDropped = errors.New("msgin: message dropped by overflow policy")
	// ErrInvalidPollInterval is returned when WithPollInterval is given a
	// non-positive duration.
	ErrInvalidPollInterval = errors.New("msgin: poll interval must be > 0")
	// ErrInvalidPollMaxBatch is returned when WithPollMaxBatch is given n < 1.
	ErrInvalidPollMaxBatch = errors.New("msgin: poll max batch must be >= 1")
	// ErrChannelSubscribed is returned by a point-to-point channel's Subscribe
	// when a handler is already registered (single-consumer invariant).
	ErrChannelSubscribed = errors.New("msgin: channel already has a subscriber")
	// ErrNoSubscriber is returned by a point-to-point channel's Send when no
	// handler is subscribed — a message is never silently dropped.
	ErrNoSubscriber = errors.New("msgin: channel has no subscriber")
	// ErrNilHandler is returned when a nil MessageHandler is subscribed.
	ErrNilHandler = errors.New("msgin: nil message handler")
	// ErrNilSubscription is returned when a SubscribableChannel breaks its
	// Subscribe contract by returning a nil Subscription together with a nil
	// error. Subscribe must return either a usable Subscription or a non-nil
	// error; a nil-nil pair leaves the caller holding a handle it cannot Cancel.
	//
	// SubscribableChannel is public SPI that third-party adapters implement, so a
	// faulty implementation is caller input: it is rejected at CONSTRUCTION with
	// this typed error — naming the contract that was broken — rather than
	// deferred into a nil-pointer panic when the owner later cancels the
	// subscription. Constructors that own a subscription for their lifetime (e.g.
	// NewChannelExchange) return it.
	ErrNilSubscription = errors.New("msgin: channel returned a nil subscription")
	// ErrSharedReplyChannel is returned by endpoint.NewChannelExchange when the
	// reply channel reports (via ExclusiveSubscribable) that its POLICY permits
	// recipients other than this exchange — not that another subscriber exists.
	// That covers a local fan-out channel and a channel whose deliveries reach
	// other processes alike. Such a channel delivers a full copy of every reply to
	// every other recipient. Pass channel.WithSingleSubscriber() to the channel, or
	// endpoint.WithSharedReplyChannel() to accept the fan-out deliberately.
	//
	// THERE IS A THIRD CAUSE, and it is not a policy report at all: the channel's
	// SingleSubscriber PANICKED. msgin recovers it and fails closed (the probe
	// proved nothing, so the conservative answer is non-exclusive), and the
	// recovered value is WRAPPED INTO THIS ERROR — read err.Error(), or errors.As
	// past this sentinel, before hunting for a second subscriber. The channel may
	// well be exclusive; what failed is the probe. See ExclusiveSubscribable's
	// "MUST NOT block and MUST NOT panic" clause.
	ErrSharedReplyChannel = errors.New("msgin: reply channel permits multiple subscribers; it is not exclusive to this exchange")
	// ErrNilSink is returned, wrapped in [Permanent], by To when its
	// OutboundAdapter sink is nil.
	//
	// To captures sink at construction, so the fault cannot change for the
	// message's lifetime: the handler returns it wrapped in [Permanent] with the
	// position ("msgin.To: nil sink"), and the driving Consumer routes the
	// message to the invalid-message channel rather than retrying it to the
	// dead-letter sink. errors.Is(err, ErrNilSink) still matches; the sentinel
	// itself stays bare, so [IsPermanent] on the bare value reports false.
	ErrNilSink = errors.New("msgin: nil outbound sink")
	// ErrNilFunc is returned, wrapped in [Permanent], by an endpoint
	// (Transform/Filter/Activate/Consume/Router/Split) constructed with a nil
	// function, and by [Chain] for a nil Step ELEMENT, which is a nil
	// function too — instead of panicking at dispatch. A nil OPTION ELEMENT
	// of a constructor's variadic opts is a nil function too, but which of
	// three things happens to it depends on what the constructor can report
	// through: most constructors return it BARE, at construction, instead of
	// panicking there; a few with no error return of their own — e.g.
	// routing.NewRouter, via Handle — latch it and return it wrapped in
	// [Permanent] at the product's first use, exactly like the two dispatch
	// cases above; and msgin.New and sqlite.DSN, which have no
	// error-returning surface at all, silently skip it and never return
	// ErrNilFunc for it.
	//
	// The governing invariant, which decides whether any msgin sentinel is
	// wrapped in [Permanent] at the point it is produced:
	//
	// every typed error msgin returns from inside a MessageHandler body msgin
	// itself constructs, whose cause was fixed at construction and cannot change
	// for the message's lifetime, is Permanent; a fault a later Subscribe, config
	// reload or drain could resolve stays bare and transient; every one returned
	// from a constructor is bare, because construction never reaches a
	// RetryPolicy; and everything else — handed to a caller from a
	// non-constructor API — is bare too.
	//
	// Applied here: an endpoint's handler returns it wrapped in [Permanent] with
	// the position that names the mis-wired constructor (e.g.
	// "transform.Transform: nil fn", or "msgin.Chain: nil step at index 1" for a
	// nil element), errors.Is(err, ErrNilFunc) still matches,
	// and the CONSTRUCTORS — routing.NewAggregator (nil fn or nil strategy) and
	// endpoint.NewConsumer (nil handler) — return it bare. A nil OPTION element
	// follows the same rule, read from the other direction: a constructor that
	// can report through its own return (e.g. endpoint.NewConsumer) returns it
	// bare, with the position "endpoint.NewConsumer: nil option at index 1";
	// one whose product first surfaces the fault at a later call (e.g.
	// routing.NewRouter, via Handle) wraps it in [Permanent] there instead,
	// naming the same position shape. The sentinel itself is never wrapped, so
	// [IsPermanent] on the bare value reports false.
	ErrNilFunc = errors.New("msgin: nil endpoint function")
	// ErrNoRoute is returned by a Router when pick resolves no destination and no
	// WithDefaultChannel is configured (Spring resolutionRequired=true).
	ErrNoRoute = errors.New("msgin: no route for message")
	// ErrScheduledSendUnsupported is returned by Producer.SendAfter/SendAt when the
	// underlying OutboundAdapter does not implement ScheduledSender (it cannot defer
	// delivery). It is never a silent immediate send — the caller is told the sink
	// cannot schedule. It is errors.Is-able.
	ErrScheduledSendUnsupported = errors.New("msgin: outbound adapter does not support scheduled send")
	// ErrNilStore is returned by NewQueueChannel when the ChannelStore is nil.
	ErrNilStore = errors.New("msgin: channel store is nil")
	// ErrInvalidCapacity is returned when a sizing option's value is outside
	// its documented [lo, hi] range (Spec 016 §3.1/§3.5). It is shared by
	// every option whose value is the sole bound on a structure that grows
	// by insertion (Spec 016 §1.3), since one sentinel cannot state four
	// different stated ranges. As of Plan 029 Task 5 all FOUR producers have
	// landed — memory.NewQueueStore (WithCapacity), memory.NewGroupStore
	// (WithMaxGroups), routing.NewAggregator (WithCompletionSize), and
	// memory.WithBuffer, which alone reports through Send/Stream rather than a
	// constructor return (family R2) and alone has a range starting at 0.
	// Spec 016 §3.5 enumerates them in a different fixed order
	// (NewQueueStore, NewGroupStore, WithBuffer, NewAggregator), so its
	// "fourth" is routing.NewAggregator; the set is the same.
	// The sentinel's own message stays generic ("capacity out of range") —
	// the offending site, value and range live in the wrapping error each
	// producer returns; see each option's own godoc for its bounds.
	ErrInvalidCapacity = errors.New("msgin: capacity out of range")
	// ErrNoCorrelation is returned when an Aggregator's correlation strategy
	// yields no key for a message. It is always wrapped with Permanent (a
	// missing correlation id will not appear on redelivery), so the runtime
	// diverts it rather than retrying — to the invalid-message channel, or the
	// dead-letter sink when none is configured ([Permanent] states all three
	// arms).
	ErrNoCorrelation = errors.New("msgin: message has no correlation key")
	// ErrNilOutput is returned by NewAggregator when no output channel is set
	// (WithOutputChannel is required).
	ErrNilOutput = errors.New("msgin: aggregator output channel is nil")
	// ErrExpiryChannelRequired is returned by NewAggregator when
	// WithGroupTimeout is set without WithExpiredGroupChannel — an expired
	// partial group must have a visible sink, never a silent drop.
	ErrExpiryChannelRequired = errors.New("msgin: group timeout requires an expired-group channel")
	// ErrNilMessageGroup is returned when a MessageGroupStore breaks its Add
	// contract by returning a nil MessageGroup together with a nil error. Add
	// must return either a usable group snapshot or a non-nil error; a nil-nil
	// pair leaves the Aggregator holding a group it cannot read.
	//
	// MessageGroupStore is public SPI that third-party adapters implement, so a
	// faulty implementation is caller input: it is rejected with this typed
	// error — naming the contract that was broken — rather than deferred into a
	// nil-pointer panic inside whichever release strategy is configured.
	//
	// It catches a nil INTERFACE only. A store that returns a typed nil — a
	// (*myGroup)(nil) boxed into the interface — is not nil by this test and
	// still fails inside the release strategy; distinguishing it would need
	// reflection on the Aggregator's hot path, for every message. No shipped
	// store does this. The same caveat applies to expr.RouteFunc's nil-channel
	// check.
	//
	// It is always wrapped with Permanent: a store that returns nil snapshots is
	// a deterministic implementation fault, so redelivery cannot fix it and
	// retrying only burns MaxAttempts. The runtime therefore diverts it — to the
	// invalid-message channel, or the dead-letter sink when none is configured
	// ([Permanent] states all three arms). It is NOT a hold: returning nil here
	// would Ack the source for a message the store just said it cannot read
	// back, which risks a message durable nowhere.
	ErrNilMessageGroup = errors.New("msgin: message group store returned a nil group")

	// ErrGatewayClosed is returned by ChannelExchange.Exchange (and any Gateway
	// built on it) once Close has been called: new exchanges are rejected and
	// any waiter pending at Close time fails with it. Part of graceful shutdown.
	ErrGatewayClosed = errors.New("msgin: request-reply exchange is closed")

	// ErrReplyTimeout is returned by Exchange when no correlated reply arrives
	// before the effective deadline (min of the caller ctx deadline and the
	// configured reply timeout, default 30s). Distinct from ctx cancellation,
	// which returns the ctx error.
	ErrReplyTimeout = errors.New("msgin: timed out awaiting reply")

	// ErrNilExchange is returned by NewGateway when the RequestReplyExchange is
	// nil. adapter/http/stdlib.NewInboundGateway (the I2 sync inbound gateway
	// constructor) is a second legitimate caller: it returns this same
	// sentinel when its exchange argument is nil.
	//
	// endpoint.OutboundGateway is the third, and the only one that wraps it in
	// [Permanent]: it returns a Step rather than an error, so the nil surfaces
	// from inside a handler body at EVALUATION ("endpoint.OutboundGateway: nil
	// exchange") instead of at construction. That is ErrNilFunc's invariant
	// applied to this sentinel — see [ErrNilFunc] — and the reason the two
	// constructor call sites above stay bare while this one does not.
	ErrNilExchange = errors.New("msgin: request-reply exchange is nil")

	// ErrNilChannel is returned by NewChannelExchange when the request or reply
	// MessageChannel is nil.
	ErrNilChannel = errors.New("msgin: request or reply channel is nil")

	// ErrInvalidReplyTimeout is returned by NewChannelExchange when an explicit
	// WithReplyTimeout is set to a non-positive duration. An unset timeout takes
	// the 30s default and never yields this error.
	ErrInvalidReplyTimeout = errors.New("msgin: reply timeout must be > 0")

	// ErrDuplicateCorrelation is returned by Exchange when the request's
	// HeaderCorrelationID already has an in-flight request registered on the same
	// exchange (audit G1). Correlation ids must be unique per concurrent
	// in-flight request; the gateway façades mint a fresh id so they never trigger
	// this — it guards direct ChannelExchange users who set the header by hand.
	ErrDuplicateCorrelation = errors.New("msgin: correlation id already has an in-flight request")
)

Functions

func IsPermanent

func IsPermanent(err error) bool

IsPermanent reports whether err must skip retry: an explicit Permanent marker, a decode/type mismatch (ErrPayloadDecode / ErrPayloadType), or an over-size payload (ErrPayloadTooLarge — an over-size message will not shrink on redelivery). A recovered handler panic (ErrHandlerPanic) is NOT permanent — it is retried.

func NewID

func NewID() string

NewID returns a random 128-bit id, hex-encoded, used as the default msgin.message-id when New is not given an explicit WithID.

func Permanent

func Permanent(err error) error

Permanent marks err as permanent (non-retryable). A handler that returns Permanent(err) diverts the message without consuming retry attempts. Permanent(nil) returns nil.

THE DESTINATION, canonically — every other "routed to the invalid-message sink" statement in msgin is shorthand for these three arms (ADR 0007 D7 as amended by decisions D-N and D-P):

  1. the consumer's invalid-message sink, when one is configured (endpoint.WithInvalidMessageSink);
  2. otherwise the RetryPolicy's DeadLetter sink, when one is configured — so a fault this library used to capture durably is never downgraded to a discard;
  3. otherwise it is logged at WARN and discarded.

EXACTLY ONE CLASS SKIPS ARM 2: ErrPayloadTooLarge, the byte-cap reject from endpoint.WithMaxPayloadBytes, goes straight from arm 1 to arm 3. That cap exists to bound memory and durable storage against untrusted wire input, so writing its rejects into the operator's dead-letter store — which arm 2 would do in the default shape of every finite-retry consumer — would turn the defence into the vector. The class was already discarded before arm 2 existed, so this loses nothing arm 2 had captured. See endpoint.WithMaxPayloadBytes.

The divert is SINGLE-SHOT on ALL of them: one attempt at one sink. If that Send fails — arm 1's configured sink and arm 2's fallback alike — the message is logged at WARN (naming the classification cause and the sink error) and discarded, never requeued, because requeueing a permanent message is an unbounded loop no retry budget, backoff or circuit breaker can observe. The accepted cost is that a transient outage of a configured invalid-message sink discards that window's invalid messages; see endpoint.WithInvalidMessageSink. The DEAD-LETTER path is the opposite: a retry-exhausted message IS transient, so a failed dead-letter Send is Nacked with backoff, not discarded. The one exception to "never requeued" is SHUTDOWN: a Send that fails only because the consumer's settle context was already cancelled by the shutdown deadline proved nothing about the sink, so the message is Nacked for redelivery and no terminal event is reported.

KEEP PAYLOAD AND PII OUT OF err. That WARN renders the cause VERBATIM, so Permanent(fmt.Errorf("invalid email %q", m.Payload().Email)) — an ordinary validation shape — writes the email to the log. msgin redacts exactly one class, the payload-decode one (ErrPayloadDecode, whose text comes from a caller-supplied codec quoting untrusted wire bytes); every other cause, including this one, is logged as written. Sensitive detail belongs behind the OnInvalidMessage hook, which always receives the UNREDACTED cause under the caller's own disclosure policy. See endpoint.WithInvalidMessageSink.

OnInvalidMessage fires on all three (it reports the CLASSIFICATION, not the destination); OnRetry and OnDeadLetter fire on none of them. An operator who must tell retries-exhausted from permanently-invalid in a shared dead-letter store has to configure endpoint.WithInvalidMessageSink: msgin stamps no settlement-reason header.

msgin uses its own marker rather than a third-party backoff library's Permanent so the core runtime stays stdlib + clockwork (ADR 0007). ADR 0005 once reserved cenkalti/backoff/v4 for an adapter-side outbound-HTTP retry loop; that clause is SUPERSEDED by ADR 0025 — outbound retry is producer-side and reuses RetryPolicy (see WithProducerRetry), and cenkalti/backoff is not a dependency of this module.

func RetryAfter

func RetryAfter(err error, d time.Duration) error

RetryAfter marks err as transient with a server-provided MINIMUM delay: a producer configured with WithProducerRetry waits at least d before the next attempt. It is how an adapter relays an explicit server instruction (an HTTP Retry-After header on a 429 or 503) that a BackoffStrategy, being stateless and closed-form, cannot express.

d is a FLOOR, not an override (RFC 9110 §10.2.3: Retry-After is the minimum time the client should wait). The effective wait is

max(policyBackoff, min(d, WithProducerRetryAfterCap))

and is always additionally bounded by ctx and by WithProducerRetryBudget. A server therefore cannot SHORTEN the client's own backoff — including to zero, which would be a remote-triggerable hot spin — it can only lengthen it, up to the cap.

It mirrors Permanent: same wrapper shape, same Unwrap transparency, same nil handling. RetryAfter(nil, d) returns nil. A negative d is normalized to 0 (meaning "no server-instructed floor") rather than rejected, so a skewed or already-elapsed server deadline degrades to the computed backoff instead of an error.

Permanent WINS over RetryAfter when both markers are present, in either nesting order: permanent means do not retry, so a delay is meaningless.

A RetryAfter marker on an error returned to a Producer WITHOUT WithProducerRetry is inert — there is no retry loop to honour it.

func RetryAfterOf

func RetryAfterOf(err error) (time.Duration, bool)

RetryAfterOf reports the server-instructed minimum delay carried by err, if any, matching IsPermanent's structure (errors.As over the wrap chain).

Deliberately NO `if err == nil` guard: errors.As(nil, &re) already returns false, and the only caller (nextDelay) never passes nil, so the guard would be both redundant and blackbox-unreachable.

Types

type BackoffStrategy

type BackoffStrategy interface {
	Delay(attempt int) time.Duration
}

BackoffStrategy computes the redelivery delay for a given 0-based retry index (0 = first retry). It is stateless and clock-agnostic: pure arithmetic, safe to share across goroutines. This is RetryPolicy.Backoff (spec §8).

type BytesPayloadCodec

type BytesPayloadCodec struct{}

BytesPayloadCodec is the identity PayloadCodec for []byte payloads: it passes the bytes through unchanged in both directions.

Pair it EXPLICITLY whenever T is []byte and the adapter is a wire adapter:

endpoint.NewProducer[[]byte](out, endpoint.WithProducerCodec[[]byte](msgin.BytesPayloadCodec{}))

Without it, the codec resolution defaults to JSONPayloadCodec, and json.Marshal of a []byte is a quoted base64 STRING — so a raw body would go on the wire as "cGF5bG9hZA==" rather than payload. That is almost never what a caller sending raw bytes intends.

It is deliberately NOT the automatic default for T == []byte: adapters that already persist base64-encoded envelopes (database/sql, redis, nats) would silently change their on-wire format. The pairing is the caller's explicit choice.

Both methods COPY, so neither the caller's slice nor the returned one can be mutated through the other. Messages are immutable by contract, and a message may be shared across a pub-sub channel; aliasing would break that.

TWO RESIDUALS, both consequences of the pass-through being exact:

  • It removes an ACCIDENTAL escaping layer. JSONPayloadCodec's quoting and escaping neutralised some hostile bytes as a side effect — never as a security control, but in practice. This codec emits the caller's bytes verbatim, so sanitising or validating the payload for whatever the sink interprets it as (SQL, a shell, HTML, a log) is wholly the caller's and the adapter's responsibility.
  • Encode(nil) returns nil, where JSONPayloadCodec returned the four bytes null. A store with a NOT NULL payload column that accepted a nil payload before will now reject it. Encode an explicit empty or sentinel payload if the sink cannot take a NULL.

func (BytesPayloadCodec) Decode

func (BytesPayloadCodec) Decode(b []byte) ([]byte, error)

Decode returns a copy of b, so the decoded payload never aliases the adapter's buffer. A nil b decodes to nil.

func (BytesPayloadCodec) Encode

func (BytesPayloadCodec) Encode(v []byte) ([]byte, error)

Encode returns a copy of v, so the encoded bytes never alias the caller's slice. A nil v encodes to nil.

type ChannelStore

type ChannelStore interface {
	// Enqueue durably appends msg to the tail of the queue.
	Enqueue(ctx context.Context, msg Message[any]) error
	// Claim leases up to max ready messages in FIFO order and returns them as
	// settleable Deliveries (Ack removes, Nack returns/redelivers). It upholds
	// the msgin.PollingSource.Poll contract: at most max deliveries, and never a
	// non-empty result alongside a non-nil error.
	Claim(ctx context.Context, max int) ([]Delivery, error)
	// EmitsLiveValue reports whether this store carries live Go values (no codec,
	// in-memory) or []byte (wire). It drives NewConsumer/NewProducer codec pairing
	// via the channel's LiveValueSource.
	EmitsLiveValue() bool
}

ChannelStore is the swappable buffer behind a QueueChannel: a durable FIFO with lease/claim settlement. It is the extension seam that makes a queue channel's buffer in-memory or persistent. Implementations live in adapter packages (adapter/memory, adapter/database/sql); the core never imports them.

A future id-addressable MessageStore or group-keyed MessageGroupStore can be added later as a separate interface this one embeds — a non-breaking change for existing implementers (ADR 0018, Spec 007 D3).

type CircuitBreaker

type CircuitBreaker interface {
	Allow() bool
	Record(success bool)
	HalfOpen() <-chan struct{}
}

CircuitBreaker gates dispatch on downstream health (spec §7.4.5, NF-10).

  • Allow reports whether work may proceed now (closed or half-open).
  • Record feeds the outcome of an allowed dispatch back to the breaker.
  • HalfOpen returns a channel the runtime parks on while Allow reports false; it is closed (or replaced with a fresh open channel per open-cycle) only when the breaker transitions to half-open. Implementations MUST NOT return an already-closed channel while Allow continues to report false — doing so causes the runtime's ingress loop (admitBreaker) to busy-spin (it re-subscribes, re-checks Allow, and immediately falls through the already-closed channel in a tight loop, with no cooldown to rate-limit the spin). The default NewCircuitBreaker mints a fresh channel per open-cycle and only closes it from toHalfOpen, so this contract holds by construction.

The default is a dependency-free clockwork breaker (NewCircuitBreaker); sony/gobreaker can be adapted via its OnStateChange callback.

Implementations MUST NOT panic: the runtime invokes Allow/Record/HalfOpen directly on the ingress and worker goroutines and does not recover a panic here (unlike handler/hooks, which are recovered by safeHandle/safeFire), so a panicking implementation crashes the process. The shipped default (NewCircuitBreaker) never panics.

type Delivery

type Delivery struct {
	Msg  Message[any]
	Ack  func(ctx context.Context) error
	Nack func(ctx context.Context, requeue bool, delay time.Duration) error
}

Delivery is one received message plus the means to settle it. Msg.Payload is []byte for wire adapters or a live value for the in-memory adapter.

type EventDrivenSource

type EventDrivenSource interface {
	Stream(ctx context.Context, out chan<- Delivery) error
}

EventDrivenSource is a pushed inbound adapter that owns a blocking, cancellable loop. The name follows EIP's Event-Driven Consumer (Spring Integration: EventDrivenConsumer); the Stream method keeps its name because it describes the mechanism and has no Spring counterpart to align with (ADR 0029 §1).

type ExclusiveSubscribable

type ExclusiveSubscribable interface {
	SubscribableChannel
	// SingleSubscriber reports whether every message sent to this channel
	// reaches at most one recipient, counted across every process. It is a
	// statement about the channel's POLICY, not its current subscriber count:
	// an implementation MUST NOT compute it from a live subscriber count.
	//
	// A channel MUST return false whenever a message sent to it can be received by
	// any recipient other than the single subscriber registered on it — INCLUDING a
	// recipient in another process. A broadcast broker subject, a Redis pub/sub
	// channel, or an SSE stream fanned out to N instances MUST therefore return
	// false even when its local handle admits one subscriber. A broker-backed
	// channel MAY return true only when the broker guarantees the destination is
	// private to this process's subscription — a per-instance NATS _INBOX reply
	// subject, an exclusive auto-delete AMQP reply queue. That is the Return
	// Address pattern, and it is what an honest true means here.
	//
	// SingleSubscriber MUST NOT block and MUST NOT panic. msgin calls it inside
	// NewChannelExchange, on the caller's goroutine, with no context and no
	// timeout; it must be a constant-time accessor over state fixed at
	// construction. A panic is recovered and read as false (fail closed), and a
	// blocking implementation hangs the constructor with nothing to cancel.
	//
	// The value MUST be constant for the lifetime of the channel. msgin calls it
	// once, at construction, and treats the answer as an invariant; a value that can
	// change afterwards makes the check a TOCTOU race the core cannot detect.
	// Implementations must also be safe for concurrent use.
	//
	// EMBEDDING CUTS BOTH WAYS. A type that embeds a *channel.DirectChannel or a
	// *channel.PublishSubscribeChannel inherits SingleSubscriber by method
	// promotion, so it reports on the EMBEDDED channel even when it overrides
	// Subscribe with its own multi-subscriber dispatch. A wrapper that changes
	// subscription behavior MUST declare its own SingleSubscriber.
	SingleSubscriber() bool
}

ExclusiveSubscribable is the optional capability a SubscribableChannel implements to report whether every message sent to it reaches at most one recipient.

It is OPTIONAL in the established sense of NativeReliability / ScheduledSender / LiveValueSource: endpoint.NewChannelExchange type-asserts for it and accepts a channel that does not implement it. Both in-tree channels do — channel.DirectChannel always reports true, and channel.PublishSubscribeChannel reports whether channel.WithSingleSubscriber() was passed, which is how a pub-sub reply channel becomes usable as an exchange's dedicated reply channel (ADR 0030).

type HandlerFunc

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

HandlerFunc adapts an ordinary function to a MessageHandler.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(ctx context.Context, msg Message[any]) error

Handle calls f(ctx, msg).

type Headers

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

Headers is an immutable set of message metadata. The backing map is never handed out mutably; construction copies the input. Immutability is shallow: the map itself is copied, but header values are not deep-cloned, so callers should store immutable value types.

func NewHeaders

func NewHeaders(m map[string]any) Headers

NewHeaders returns immutable Headers copied from m (nil m yields empty Headers). The copy is shallow: header values are not deep-cloned, so callers should store immutable value types.

func (Headers) All

func (h Headers) All() iter.Seq2[string, any]

All iterates the headers read-only (no mutable map is exposed).

func (Headers) Get

func (h Headers) Get(key string) (any, bool)

Get returns the raw value for key and whether it was present.

func (Headers) Int

func (h Headers) Int(key string) (int, bool)

Int returns the value for key as an int, and whether it was present and held an int.

func (Headers) String

func (h Headers) String(key string) (string, bool)

String returns the value for key as a string, and whether it was present and held a string.

func (Headers) Time

func (h Headers) Time(key string) (time.Time, bool)

Time returns the value for key as a time.Time, and whether it was present and held a time.Time.

type Hooks

type Hooks struct {
	OnRetry          func(ctx context.Context, msg Message[any], err error)
	OnDeadLetter     func(ctx context.Context, msg Message[any], err error)
	OnInvalidMessage func(ctx context.Context, msg Message[any], err error)
	OnAck            func(ctx context.Context, msg Message[any], err error)
}

Hooks are optional, nil-safe callbacks fired on the operationally important settlement events (spec §7 observability). The error argument carries the triggering error (nil on a successful Ack).

ONE EXCEPTION, ON OnInvalidMessage. An invalid message is diverted to the invalid-message sink (or, failing that, the dead-letter sink) and the divert is SINGLE-SHOT: when a CONFIGURED sink refuses the message, it is discarded rather than retried, and OnInvalidMessage is the only event that fires — no OnRetry, no OnDeadLetter. To keep that discard from being indistinguishable from a healthy divert, OnInvalidMessage then receives the triggering error JOINED (errors.Join) with the sink's send failure.

The join is safe to ignore: errors.Is against the triggering error still matches, so a callback that classifies on it behaves exactly as before. It is also the ONLY machine-detectable signal that a message was lost here — a callback that wants to count or alert on the loss tests errors.Is against the sink's own error, or simply compares the received error to the triggering one. A successful divert, and the case where no sink is configured at all, both pass the bare triggering error.

type JSONPayloadCodec

type JSONPayloadCodec[T any] struct{}

JSONPayloadCodec is the default PayloadCodec using encoding/json.

func (JSONPayloadCodec[T]) Decode

func (JSONPayloadCodec[T]) Decode(b []byte) (T, error)

Decode unmarshals JSON bytes b into a value of type T.

func (JSONPayloadCodec[T]) Encode

func (JSONPayloadCodec[T]) Encode(v T) ([]byte, error)

Encode marshals v to its JSON representation.

type LiveValueSource

type LiveValueSource interface {
	EmitsLiveValue() bool
}

LiveValueSource is an optional capability: a source emitting live Go values (in-memory) rather than []byte, so NewConsumer can enforce codec pairing.

type Message

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

Message is the immutable EIP envelope: a typed payload plus header metadata. Every Message is stamped with a msgin.message-id and msgin.timestamp by New; transformers and enrichers return a new Message rather than mutating one in place, so a Message shared across a pub-sub channel is safe to read concurrently.

func New

func New[T any](payload T, opts ...MessageOption) Message[T]

New builds an immutable Message wrapping payload, always stamping msgin.message-id (random unless WithID is given) and msgin.timestamp (from the clock, real by default).

New is the PRODUCING-path constructor: it always stamps a fresh id and timestamp. An inbound adapter reconstructing a message that already exists in an external system (its id/timestamp were framed at publish time and decoded back from storage) must use NewMessage instead, which preserves the pre-built Headers verbatim.

A nil element in opts is ignored — New has no error to return, and Message has no error-returning method to degrade at, so there is nowhere to report the fault (Spec 015 §3.3). It is therefore SILENT, and the consequence is the caller's to avoid: a dropped WithID means New stamps a fresh random id, a dropped WithHeaders means those headers are absent, and a dropped WithClock means the timestamp comes from the real clock; if the id is an idempotency key, build the option unconditionally. Every non-nil element still applies, whether it sits before or after the nil one. (A nil opts SLICE — New(payload) or New(payload, nils...) — is a normal zero-option call, unaffected.)

func NewMessage

func NewMessage[T any](payload T, headers Headers) Message[T]

NewMessage wraps an explicit payload and a pre-built Headers set as a Message, WITHOUT stamping msgin.message-id/msgin.timestamp — for adapters reconstructing a message that already exists in an external system (its id, timestamp, and custom headers were framed at publish time and decoded back from storage). Contrast New, which STAMPS a fresh id + timestamp for a newly-produced message.

The Headers are used verbatim: NewMessage neither adds nor overwrites any reserved key, so a caller building a FRESH message this way (rather than reconstructing a persisted one) is responsible for supplying msgin.message-id and msgin.timestamp in headers if it needs them — prefer New for that case.

func PayloadOf

func PayloadOf[T any](m Message[any]) (Message[T], error)

PayloadOf asserts m's payload to T, returning a typed Message[T] with the same headers (no re-stamp). On mismatch it wraps the package sentinel ErrPayloadType with the wanted/actual types; because IsPermanent classifies ErrPayloadType as permanent, the driving Consumer diverts it to the invalid-message channel — or to the dead-letter sink when none is configured (Permanent states all three arms) — never a panic. PayloadOf[any] succeeds for any non-nil payload. An untyped-nil payload (a message built with New[any](nil)) has no dynamic type, so the assertion fails and PayloadOf returns ErrPayloadType — even for T = any.

func WithPayload

func WithPayload[A, B any](m Message[A], payload B) Message[B]

WithPayload returns a new Message carrying payload but the SAME headers as m (id, timestamp, correlation-id, custom keys preserved). It is the header-propagating way to write a Transformer/Activator body — prefer it over New, which stamps a fresh id and drops the incoming headers.

func (Message[T]) Header

func (m Message[T]) Header(key string) (any, bool)

Header returns the raw header value for key and whether it was present.

func (Message[T]) Headers

func (m Message[T]) Headers() Headers

Headers returns the message's immutable header set.

func (Message[T]) ID

func (m Message[T]) ID() string

ID returns the message's msgin.message-id header.

func (Message[T]) Payload

func (m Message[T]) Payload() T

Payload returns the message's typed payload.

func (Message[T]) WithHeader

func (m Message[T]) WithHeader(key string, v any) Message[T]

WithHeader returns a copy of the message with key=v set on its headers, leaving the receiver unchanged (copy-on-write).

func (Message[T]) WithoutHeader

func (m Message[T]) WithoutHeader(key string) Message[T]

WithoutHeader returns a copy of the message with key removed from its headers, leaving the receiver unchanged (copy-on-write). Removing an absent key is a no-op copy. Used by OutboundGateway to strip a transient correlation id when the inbound message carried none.

type MessageChannel

type MessageChannel interface {
	Send(ctx context.Context, msg Message[any]) error
}

MessageChannel is the EIP **Pipe**: the conduit an endpoint sends into. It is send-only — subscribing is the separate SubscribableChannel contract — so every channel implementation in the library satisfies it: a DirectChannel, a pollable QueueChannel, a PublishSubscribeChannel, and any OutboundAdapter.

METHOD-IDENTICAL TO OutboundAdapter BY DESIGN. The two interfaces declare the same single method and are freely interchangeable under Go's structural typing, yet both are kept because they name two different EIP patterns: MessageChannel is the Pipe of Pipes and Filters (EIP ch.3), the concept this library's composition model is built on, while OutboundAdapter is a Channel Adapter at a system boundary (EIP ch.4). Collapsing them would erase the Pipe from the type system of a pipes-and-filters library. Use MessageChannel for a destination inside a flow, OutboundAdapter for the edge of one (ADR 0028 §5).

type MessageGroup

type MessageGroup interface {
	Key() string
	Messages() []Message[any]
	CreatedAt() time.Time
}

MessageGroup is a snapshot of one correlation group held by a MessageGroupStore: its key, members in arrival order, and the arrival time of the first member (used for expiry). The Messages slice is a copy — mutating it does not affect the store.

type MessageGroupClaim

type MessageGroupClaim interface {
	MessageGroup
	// Epoch is the fence token: SettleGroup/AbandonGroup take effect only while
	// the store's lease for the key still carries this epoch. A lease that
	// expired and was re-claimed (epoch bumped) makes a stale holder's settle a
	// no-op — no phantom delete.
	Epoch() int64
}

MessageGroupClaim is an exclusive lease over the members of a group that were present at claim time. An Aggregator claims a complete group, aggregates and forwards it, then SettleGroups the claim (fenced by Epoch). Members that arrive during the lease are NOT part of the claim and survive settlement as a fresh group (loss-free — ADR 0020 §8).

type MessageGroupStore

type MessageGroupStore interface {
	// Add durably appends msg to group key and returns the resulting group
	// snapshot of the LIVE (unclaimed) members — the residual when a claim is in
	// flight, else all members (audit R2 M-C: memory and sql must agree, so the
	// release check sees the same set; a member arriving during a lease is a
	// fresh-residual member, not part of the in-flight claim). Idempotent by msg
	// id: re-adding an already-stored member is a no-op (a redelivered member
	// does not double-count toward release — at-least-once).
	//
	// # The per-group member bound is part of this contract (Spec 017 §3.7)
	//
	// An implementation MUST bound the number of members it retains for a
	// single group, and MUST report an Add that would exceed that bound as
	// ErrOverflowDropped rather than growing without limit. The Aggregator's
	// release strategy cannot supply this bound: three of its four paths are a
	// caller-supplied closure or a message header — and the store is the only
	// site that can refuse a member BEFORE retaining it.
	//
	// The counted set MUST include every member the implementation still
	// retains for that group — LIVE AND CLAIMED — and MUST be stated in the
	// implementation's godoc. Both first-party stores count live + claimed: a
	// bound that ignores the claimed set does not bound, because a claim moves
	// members out of the live set without removing them (Spec 017 §3.4).
	//
	// An implementation SHOULD mark the rejection Permanent when the group
	// cannot drain itself, and leave it transient when a claim is in flight
	// that will drain it (Spec 017 §3.3.1). A bare transient rejection of a
	// group that will never drain HOT-SPINS under the default RetryPolicy,
	// which has neither a MaxAttempts nor a Backoff.
	//
	// An implementation MAY return the group's current LIVE snapshot ALONGSIDE
	// the overflow error. When it does, the Aggregator re-evaluates the release
	// strategy against that snapshot and releases the group if it is ready, so
	// a full-but-releasable group is not deadlocked by its own bound (Spec 017
	// §3.3a). Returning (nil, err) remains valid and is what every pre-existing
	// implementation does.
	//
	// THE RE-EVALUATION IS CONDITIONAL. Three gates decide whether the
	// Aggregator touches the snapshot at all, and when any of them fails the
	// error is returned unchanged and the snapshot is ignored entirely
	// (Spec 017 §3.3a.1):
	//
	//   - The error must carry ErrOverflowDropped. This clause is the OVERFLOW
	//     contract, so a snapshot handed back beside any OTHER fault is never
	//     acted on: an implementation must not have a group claimed,
	//     aggregated, emitted and settled because an unrelated error path
	//     happened to return its zero-value snapshot.
	//   - The snapshot must be non-nil, TYPED NILS INCLUDED. A
	//     (*yourGroup)(nil) — the value the conformance idiom
	//     "var _ MessageGroup = (*yourGroup)(nil)" produces — is rejected
	//     exactly like an untyped nil, because its methods would panic.
	//   - The snapshot must hold at least one member. An empty live residual
	//     means another holder's claim already covers every member, so there is
	//     nothing left here to release. That is evidence the group is LEASED,
	//     NOT proof it drains — a holder ending in AbandonGroup leaves the group
	//     exactly as full (Plan 031 finding R-13). Nothing turns on the
	//     difference at this gate, which returns the error unchanged either way;
	//     it matters at the downgrade below, which does classify.
	//
	// When the Aggregator does act on that snapshot it NEVER UPGRADES the
	// implementation's classification ON ITS OWN ACCOUNT: no path of its own
	// re-marks a transient rejection permanent. It either DOWNGRADES the
	// rejection to a fresh, TRANSIENT overflow error, or REPLACES the overflow
	// error entirely with the distinct fault it hit, which then carries that
	// fault's own classification rather than the implementation's.
	//
	// THE DOWNGRADE IS NOT ALWAYS BACKED BY PROOF OF DRAINAGE, and an
	// implementation must not design against it as though it were (Plan 031
	// finding R-13). Three exits downgrade, on evidence of three different
	// strengths: the group PROVABLY drained, because the Aggregator claimed it
	// and released it; a claim was REFUSED because another holder's lease is in
	// flight, which is evidence a drain is in progress and not proof one
	// completes, since a holder ending in AbandonGroup leaves the group exactly
	// as full; or the claim SUCCEEDED and the RELEASE THEN FAILED, which is
	// evidence of the opposite of drainage. The last is downgraded deliberately
	// all the same — see the paragraph after next.
	//
	// EXACTLY ONE EXIT REPLACES: a failing ClaimGroup, whose store fault is
	// returned verbatim, because masking a store fault behind ErrOverflowDropped
	// would point an operator at the cap. It is unmarked, hence transient, so a
	// persistently failing claim path RETRIES rather than terminating. That is
	// deliberate: marking a store fault permanent because it was reached through
	// an overflow would dead-letter messages for a cause that has nothing to do
	// with the cap.
	//
	// A FAILING RELEASE DOES NOT REPLACE. The Aggregator re-mints a fresh,
	// TRANSIENT ErrOverflowDropped carrying the release fault's rendered TEXT
	// and not the fault itself, so errors.Is/errors.As cannot reach that cause
	// through the returned error. Severing the chain is the point: propagating
	// the fault verbatim let a Permanent-marked aggregate or output Send
	// TERMINALLY SETTLE a member the implementation never stored, LOSING it, for
	// a fault in the other, already-claimed members' payloads (ADR 0033 D-AX;
	// Plan 031 finding R-2).
	//
	// THE NEVER-UPGRADES PROMISE IS NOT UNCONDITIONAL, and an implementation
	// must not design against it as one. When the CALLER's release strategy
	// FAILS — a strategy that returned an ERROR, which is a different exit from
	// the aggregate/Send failure above — the
	// Aggregator returns errors.Join(overflowErr, strategyErr); IsPermanent
	// uses errors.As, which traverses the join, so a Permanent-marked strategy
	// error makes the reported error permanent even though the implementation
	// classified its own rejection transient. The marker is the caller's, not
	// the Aggregator's — but it reaches the consumer all the same (Spec 017
	// §3.3b; ADR 0033 D-AW).
	//
	// An implementation MUST NOT assume its Permanent marker survives to the
	// consumer on every path either: per the two paragraphs above, a failing
	// claim reports the store's own unmarked fault and a failing release
	// reports a fresh transient overflow error, so BOTH drop the marker and a
	// persistently failing claim/release path RETRIES rather than terminating
	// (Spec 017 §3.3a.1).
	Add(ctx context.Context, key string, msg Message[any]) (MessageGroup, error)
	// ClaimGroup atomically leases the members present now for key and returns
	// them plus a fence epoch. It returns (nil, nil) when key is absent or is
	// already leased by another holder whose lease has not expired — the caller
	// then treats the group as held (someone else is releasing it). The lease
	// TTL is store-owned (each implementation exposes its own configuration,
	// e.g. a WithGroupLeaseTTL-style option — this core interface makes no
	// assumption about it); a crash before SettleGroup lets the lease age out
	// so another holder re-claims (duplicate, never loss).
	ClaimGroup(ctx context.Context, key string) (MessageGroupClaim, error)
	// SettleGroup deletes exactly the claimed member set (fenced on claim.Epoch)
	// after a successful release. Members added during the lease survive as a
	// fresh live group. A fence miss (the lease was stolen) is a no-op, not an
	// error.
	SettleGroup(ctx context.Context, claim MessageGroupClaim) error
	// AbandonGroup releases the lease WITHOUT deleting (the release Send failed,
	// or the reaper found a not-actually-expired group): the claimed members
	// return to live so a retry / next member / next reaper tick re-releases.
	// Fenced on claim.Epoch; a fence miss is a no-op.
	AbandonGroup(ctx context.Context, claim MessageGroupClaim) error
	// Expired returns groups the reaper's settlement sweep must re-examine: any
	// group whose LEASE has expired (a crashed holder — sql) regardless of age,
	// PLUS (when before is non-zero) unleased groups whose CreatedAt is before the
	// cutoff. Excludes groups under a live lease. (audit R2 H-A: the crashed-lease
	// case is how a durable store's stuck complete group is found and re-released.)
	Expired(ctx context.Context, before time.Time) ([]MessageGroup, error)
	// RecoverInterval is the cadence at which the reaper sweeps for crashed leases,
	// independent of WithGroupTimeout (audit R2 H-A). memory returns 0 (unconditional
	// lease — no crash-recovery sweep needed); sql returns its lease TTL, so a
	// crashed holder's group is recovered within ~one TTL even with no expiry timeout.
	RecoverInterval() time.Duration
	// EmitsLiveValue reports live Go values (memory) vs []byte (wire, sql).
	EmitsLiveValue() bool
}

MessageGroupStore is the swappable state behind an Aggregator: correlation-keyed groups of held messages, with a store-level atomic lease-claim that makes release exactly-once within AND across processes. Implementations live in adapter packages (adapter/memory, adapter/database/sql); the core never imports them. It mirrors ChannelStore (ADR 0018) one level up.

type MessageHandler

type MessageHandler interface {
	Handle(ctx context.Context, msg Message[any]) error
}

MessageHandler is one processing step in an in-process flow: it consumes a message and MAY forward a (possibly transformed) message onward. For a DirectChannel it runs synchronously on the caller's goroutine, so an error it returns propagates back to the driving Consumer, which owns retry/dead-letter/invalid-message. A MessageHandler is structurally a Handler[any], so a composed flow drives off NewConsumer[any](src, flow.Handle, …).

func Chain

func Chain(steps ...Step) MessageHandler

Chain composes steps into one MessageHandler, running them in order (steps[0] first). The innermost next is a no-op consume, so:

CONTRACT: a flow whose last producing step (Transform/Filter-pass/Activate) has no downstream terminal will DISCARD its final message silently. Always end a producing flow with a terminal — To(sink) to deliver outward, or Consume for a side-effect sink. Chain() with no steps is a no-op consume.

A nil ELEMENT is not a panic (no panic on caller input) and is NOT skipped: it is replaced in place by a step whose handler fails with Permanent(ErrNilFunc) naming its index, so the flow degrades exactly as To(nil) or Activate(nil) does. Skipping was rejected — a step built conditionally (steps = append(steps, maybeStep())) that came back nil is a WIRING BUG, and deleting it would silently change what the flow does: a dropped Filter stops filtering, a dropped To discards the message. Steps BEFORE the nil still run; the chain stops at it.

Example

ExampleChain shows a linear in-process flow: filter unpaid orders, translate Order->Invoice (preserving headers via WithPayload), charge, and deliver.

package main

import (
	"context"
	"fmt"

	"github.com/kartaladev/msgin"
	"github.com/kartaladev/msgin/endpoint"
	"github.com/kartaladev/msgin/routing"
	"github.com/kartaladev/msgin/transform"
)

func main() {
	type Order struct {
		ID   string
		Paid bool
	}
	type Invoice struct{ OrderID string }
	type Receipt struct{ OrderID string }

	receipts := make(chan Receipt, 1)

	flow := msgin.Chain(
		routing.Filter(func(_ context.Context, m msgin.Message[Order]) (bool, error) { return m.Payload().Paid, nil }),
		transform.Transform(func(_ context.Context, m msgin.Message[Order]) (msgin.Message[Invoice], error) {
			return msgin.WithPayload(m, Invoice{OrderID: m.Payload().ID}), nil
		}),
		endpoint.Activate(func(_ context.Context, m msgin.Message[Invoice]) (msgin.Message[Receipt], error) {
			return msgin.WithPayload(m, Receipt{OrderID: m.Payload().OrderID}), nil
		}),
		endpoint.Consume(func(_ context.Context, m msgin.Message[Receipt]) error { receipts <- m.Payload(); return nil }),
	)

	_ = flow.Handle(context.Background(), msgin.New[any](Order{ID: "o-1", Paid: true}))
	_ = flow.Handle(context.Background(), msgin.New[any](Order{ID: "o-2", Paid: false})) // filtered

	fmt.Println((<-receipts).OrderID)
}
Output:
o-1

type MessageOption

type MessageOption func(*msgConfig)

MessageOption configures a Message constructed by New.

func WithClock

func WithClock(c clockwork.Clock) MessageOption

WithClock injects the clock New uses to stamp msgin.timestamp. The default is the real wall clock; tests typically inject a clockwork.FakeClock. A nil clock is a no-op (leaves the real-clock default in place) rather than a caller-triggered nil-panic on the next New call (no panic on caller input).

func WithHeaders

func WithHeaders(m map[string]any) MessageOption

WithHeaders seeds additional headers on the Message. The reserved msgin.message-id and msgin.timestamp keys are always overwritten by New, regardless of what is passed here.

func WithID

func WithID(id string) MessageOption

WithID sets an explicit msgin.message-id instead of New's default random 128-bit hex id. An empty string is treated as unset: New falls back to generating a random id rather than stamping an empty msgin.message-id.

type NativeReliability

type NativeReliability interface {
	NativeRedelivery() bool
	NativeDeadLetter() bool
}

NativeReliability is an optional capability: two independent booleans (ADR 0002).

type OutboundAdapter

type OutboundAdapter interface {
	Send(ctx context.Context, msg Message[any]) error
}

OutboundAdapter writes a message to the external system — the EIP Channel Adapter at a system boundary (EIP ch.4).

METHOD-IDENTICAL TO MessageChannel BY DESIGN. Since ADR 0028 narrowed MessageChannel to Send, the two interfaces declare the same single method and are interchangeable under Go's structural typing. Both are kept because they name two different patterns: MessageChannel is the Pipe of Pipes and Filters (EIP ch.3), OutboundAdapter is the Channel Adapter here. A consequence worth stating plainly: every shipped OutboundAdapter is now also a legal filter discard target, router default channel, router destination, and exchange request channel.

type OverflowPolicy

type OverflowPolicy int

OverflowPolicy selects what a push source's ingress does when the credit pool is exhausted (spec §7.4.6). Block backpressures; the Drop/Reject policies shed.

const (
	// OverflowBlock backpressures the stream loop until a credit frees (default).
	OverflowBlock OverflowPolicy = iota
	// OverflowDropNewest drops the just-arrived message (Nack, no requeue).
	OverflowDropNewest
	// OverflowDropOldest is accepted for API stability; on a streaming source
	// with no discrete buffer stage it behaves as OverflowDropNewest until the
	// Poller buffer lands (Plan 004) — see ADR 0008 D9.
	OverflowDropOldest
	// OverflowReject is HTTP-semantics (503/429); on a non-HTTP streaming source
	// it behaves as OverflowDropNewest until adapter/http lands — see ADR 0008 D9.
	OverflowReject
)

func (OverflowPolicy) String

func (p OverflowPolicy) String() string

String renders the policy; unknown values render as OverflowBlock (the safe default).

type PayloadCodec

type PayloadCodec[T any] interface {
	Encode(T) ([]byte, error)
	Decode([]byte) (T, error)
}

PayloadCodec (de)serializes a typed payload to/from bytes. It lives in the typed runtime (which knows T); wire adapters never see T (spec §3, ADR 0001).

type PollingSource

type PollingSource interface {
	Poll(ctx context.Context, max int) ([]Delivery, error)
}

PollingSource is a pulled inbound adapter, driven by the runtime's Poller.

Poll fetches up to max claimable deliveries. The runtime acquires max credits BEFORE calling Poll (credit-at-fetch, spec §7.4.1), so it never over-pulls past WithMaxInFlight. An implementation MUST honor three invariants — the runtime enforces the first defensively and relies on the other two:

  1. Return AT MOST max deliveries. Returning more corrupts the credit accounting; the runtime defensively clamps and Nacks the excess, but a correct source never returns more than asked.
  2. Return NO deliveries alongside a non-nil error. A partial (rows, err) is forbidden: the runtime discards rows on error, which for a lock/tx-carrying Delivery would leak the transaction/connection it holds.
  3. Own the cleanup (rollback) of any partial or claimed work on the error or ctx-cancel path, returning (nil, err) — a claimed-but-not-returned row must be released back to the source so it is redelivered, not lost.

type ProbeGate

type ProbeGate interface {
	TryProbe() bool
}

ProbeGate is an OPTIONAL CircuitBreaker capability (ADR 0009 D2). A breaker that also implements it lets the runtime admit a bounded number of half-open probes at the DISPATCH gate rather than the whole half-open state — fixing the probe storm under WithConcurrency(N>1), where otherwise every worker reaching the gate while half-open is admitted instead of a single canary.

TryProbe is a CONSUMING acquire (it may set internal probe state) called ONLY at the dispatch gate and ALWAYS paired with a following Record; the runtime's ingress open-check keeps using the idempotent Allow. It reports whether THIS dispatch may proceed: closed → true (unlimited); open → false; half-open → true for one probe, false for the rest until a Record settles it. A returned false consumes nothing (the message is Nacked without a Record).

A CircuitBreaker that does NOT implement ProbeGate keeps the prior behavior (the dispatch gate falls back to Allow, admitting the whole half-open state). The default NewCircuitBreaker implements ProbeGate; a sony/gobreaker wrapper SHOULD implement TryProbe (mirroring gobreaker's own half-open MaxRequests) to get single-probe under N>1 — otherwise the runtime logs a one-time warning at Run.

Implementations MUST NOT panic (same contract as CircuitBreaker); the runtime fail-opens (admits) on a panic but cannot rescue a plug-in that wedges its own probe state (ADR 0009 D1).

type RateLimiter

type RateLimiter interface {
	Wait(ctx context.Context) error
}

RateLimiter paces ingress. Wait blocks until the caller may proceed or ctx is done. The default is a dependency-free clockwork token bucket (NewTokenBucket); golang.org/x/time/rate.Limiter satisfies this interface directly.

Implementations MUST NOT panic: the runtime invokes Wait directly on the ingress goroutine and does not recover a panic here (unlike handler/hooks, which are recovered by safeHandle/safeFire), so a panicking implementation crashes the process. The shipped default (NewTokenBucket) never panics.

type RequestReplyExchange

type RequestReplyExchange interface {
	Exchange(ctx context.Context, req Message[any]) (Message[any], error)
}

RequestReplyExchange is the narrow SPI a gateway delegates to: it sends a request and returns the correlated reply (or an error). ChannelExchange is the in-process implementation; a future HTTP/NATS adapter implements Exchange for a real external round-trip, so both gateway façades work over it unchanged.

"EXCHANGE" HERE IS THE EIP REQUEST-REPLY OPERATION — send a request, receive the reply correlated to it — and is NOT AMQP's exchange. An AMQP exchange is a broker-side routing table that binds routing keys to queues; it is a topology object you declare on a broker. This SPI names an operation a gateway delegates to, which is a different kind of thing entirely. An AMQP-backed adapter would implement RequestReplyExchange OVER an AMQP exchange — publish to it, wait on a reply queue — rather than BE one (ADR 0029 §2).

Contract: an implementation MUST release every piece of request-scoped state it acquires — a correlator entry, an in-flight connection, a response body — on EVERY exit path, including a panic unwinding out of a downstream call. Deferred cleanup is the only reliable way to honour this; an implementation that cleans up at each return site alone will leak whenever a caller-supplied handler panics. An implementation MUST NOT recover such a panic into an error return: the panic belongs to the caller's code and must propagate with its original value and stack (ADR 0022 Addendum A3; Spec 012) — unless a CALLER-SUPPLIED hook on the cleanup path itself panics, which replaces the original (see WithUnmatchedReplySink and WithExchangeLogger).

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is COUNTED PER INSTANCE, not across the deployment. What the
	// consumer actually tests is THE PRESENCE OF THE HeaderDeliveryCount HEADER
	// on the delivery: carry one and that native count wins. Carry none and the
	// count comes from an in-memory attempt tracker owned by the Consumer —
	// one tracker per NewConsumer call, so even two Consumers draining the same
	// source in the SAME process keep independent counts. (A source stamping
	// that header typically also reports NativeReliability.NativeRedelivery,
	// but that capability is two booleans and obliges nobody to stamp
	// anything: a source claiming native redelivery while omitting the header
	// still falls back to the tracker.)
	//
	// A message redelivered to a DIFFERENT node therefore starts its count at
	// zero, so behind a load balancer with N nodes the effective global bound
	// is N × MaxAttempts, and a caller sizing a poison-message threshold
	// silently gets N times what they asked for. Read that as an UPPER-BOUND
	// APPROXIMATION rather than an exact bound: the tracker also evicts ids
	// idle for longer than endpoint.WithAttemptTTL, so a message bouncing among
	// the other nodes can age out of a given node's map and restart its count
	// there. A source that DOES stamp HeaderDeliveryCount is unaffected: the
	// broker counts, and every node reads the same number.
	//
	// The distributed answer is that native redelivery count, or a shared
	// idempotency/dedup store keyed by message id — not a smaller MaxAttempts,
	// which only moves the error (Spec 014 §10).
	MaxAttempts int
	Backoff     BackoffStrategy
	DeadLetter  OutboundAdapter
}

RetryPolicy governs how the runtime settles a failed delivery (spec §7).

  • MaxAttempts == 0 : retry forever (no dead-letter).
  • MaxAttempts > 0 : after that many delivery attempts a still-failing message is diverted to DeadLetter (required); DeadLetter may be any OutboundAdapter, including another msgin adapter.
  • Backoff nil : immediate redelivery (zero delay).

The zero value is valid and means "retry forever, immediately, no DLQ".

THE SAME POLICY READS DIFFERENTLY ON THE TWO PATHS. The description above is the CONSUMER path (NewConsumer), where a retry is a broker REDELIVERY: the message goes back to the source and the broker paces it, so "forever, immediately" costs no local resource. On the PRODUCER path (WithProducerRetry) a retry is a live re-send on the CALLER'S OWN goroutine with no broker in between, so the same fields are bounded further:

  • MaxAttempts == 0 does NOT mean forever. Every producer retry is bounded by WithProducerRetryBudget (2 minutes by default, always on) — including a finite MaxAttempts, which the budget can cut short. A stop caused by the budget rather than by spent attempts is marked ErrRetryBudgetExhausted so the two remain distinguishable.
  • Backoff nil, or any strategy yielding a non-positive delay, is floored to 100ms per wait rather than spinning.
  • The ZERO VALUE IS REJECTED by NewProducer with ErrUnboundedRetry: MaxAttempts == 0 with a nil Backoff is a zero-delay infinite loop on the caller's goroutine, which is a caller mistake worth failing loudly on. It remains valid for a Consumer.

See WithProducerRetry, WithProducerRetryBudget and ADR 0025 §1.1.

func (RetryPolicy) Validate

func (p RetryPolicy) Validate() error

Validate reports whether the policy is internally consistent. A finite MaxAttempts requires a DeadLetter; a negative MaxAttempts is invalid. Called by NewConsumer so a bad policy fails at construction (spec §5).

type ScheduledSender

type ScheduledSender interface {
	SendAfter(ctx context.Context, msg Message[any], delay time.Duration) error
}

ScheduledSender is an optional capability of an OutboundAdapter: it delivers a message so that it becomes consumable only after a delay elapses (durable delayed send). An adapter that can defer delivery — e.g. the database/sql adapter via its visible_after column — implements it; the producer discovers it by type-assertion and returns ErrScheduledSendUnsupported when the sink does not.

The capability carries the RELATIVE primitive only: the delivery time is computed by the adapter's own store as now+delay, so it is free of app-vs-store clock skew. A delay <= 0 delivers immediately (equivalent to Send). Absolute-time scheduling is a producer-side concern (Producer.SendAt), never pushed into the adapter.

type Step

type Step = func(next MessageHandler) MessageHandler

Step is a composable pipeline stage: it wraps next and returns a handler that does its work then (usually) forwards to next. The Go middleware idiom; the typed endpoint constructors (Transform/Filter/Activate) return a Step.

func To

func To(sink OutboundAdapter) Step

To is a terminal Step that sends the message to sink (any OutboundAdapter — a *DirectChannel, a *memory.Broker, or a real outbound adapter) and ignores next. A nil sink yields ErrNilSink at send time (no panic on caller input), named with its position. sink is captured here at construction, so that fault is PERMANENT (D-M): the message is routed to the invalid-message channel rather than retried to the dead-letter sink, and errors.Is(err, ErrNilSink) still matches. See ErrNilFunc for the governing invariant.

type SubscribableChannel

type SubscribableChannel interface {
	MessageChannel
	Subscribe(h MessageHandler) (Subscription, error)
}

SubscribableChannel is a MessageChannel that also accepts a push subscriber, returning a Subscription whose Cancel unsubscribes. DirectChannel (one subscriber) and PublishSubscribeChannel (fan-out) implement it; a pollable QueueChannel deliberately does not — it is drained through PollingSource.

CONTRACT FOR IMPLEMENTERS. Subscribe must return either a non-nil Subscription and a nil error, or a nil Subscription and a non-nil error — never a nil-nil pair, which hands the caller a subscription it cannot Cancel. Callers that retain the Subscription reject a nil-nil return with ErrNilSubscription.

OPTIONAL CAPABILITY — ExclusiveSubscribable. An implementation that can report whether every message sent to it reaches at most one recipient should also declare SingleSubscriber. endpoint.NewChannelExchange probes for it and rejects a channel that reports non-exclusive with ErrSharedReplyChannel; a channel that does not implement it is accepted unprobed, so a fan-out channel that stays silent here is silently accepted as an exchange reply channel.

TOPOLOGY — IN-PROCESS ONLY. A subscriber is a Go func in this process's memory, so nothing reached through this interface crosses a process boundary: under N horizontally-scaled instances, a message published on instance A is never seen by a subscriber registered on instance B. That is a deliberate scope, not an oversight. The distributed answers are the Return Address pattern for request-reply (carry the reply destination in the message, so the reply is routed rather than assumed local — see RequestReplyExchange, whose seam is kept in root precisely so an external adapter can implement it) and a broker's own topics/consumer groups for fan-out (see TopicSubscriber).

type Subscription

type Subscription interface{ Cancel() }

Subscription is a handle to an active subscription. Cancel removes the subscriber; it is idempotent (a second Cancel is a safe no-op).

It lives here, not in the channel package, because it is the return type of SubscribableChannel.Subscribe and of the root-level TopicSubscriber SPI: moving it would make root import channel (Spec 014 decision D-C).

type TopicPublisher

type TopicPublisher interface {
	Publish(ctx context.Context, topic string, msg Message[any]) error
}

TopicPublisher publishes a message to a named topic. Native-topic broker adapters (Kafka, NATS, Redis) implement this using their own topics, so topic support is handled generically through one SPI.

type TopicSubscriber

type TopicSubscriber interface {
	Subscribe(topic string, h MessageHandler) (Subscription, error)
}

TopicSubscriber subscribes a handler to a named topic, returning a Subscription whose Cancel unsubscribes. The counterpart SPI to TopicPublisher (split per the interface-segregation principle: a publish-only or subscribe-only adapter is legitimate).

Directories

Path Synopsis
adapter
cron
Package cron is the msgin channel adapter that ORIGINATES messages on a recurring / cron schedule — the Enterprise Integration Scheduled Producer / Polling Consumer shape.
Package cron is the msgin channel adapter that ORIGINATES messages on a recurring / cron schedule — the Enterprise Integration Scheduled Producer / Polling Consumer shape.
database/sql
Package sql is the msgin channel adapter for any database/sql-compatible SQL database, using a table as a durable, at-least-once message queue: a polling SELECT ...
Package sql is the msgin channel adapter for any database/sql-compatible SQL database, using a table as a durable, at-least-once message queue: a polling SELECT ...
http
Package msghttp is the framework-agnostic core of the msgin HTTP channel adapter (adapter/http).
Package msghttp is the framework-agnostic core of the msgin HTTP channel adapter (adapter/http).
http/stdlib
Package stdlib is the net/http binding for the msgin HTTP channel adapter: a thin peer of the framework-agnostic core (adapter/http, package msghttp) that composes msghttp's handler cores (ServeAsync via NewInbound, ServeGateway via NewInboundGateway) into ordinary http.Handlers.
Package stdlib is the net/http binding for the msgin HTTP channel adapter: a thin peer of the framework-agnostic core (adapter/http, package msghttp) that composes msghttp's handler cores (ServeAsync via NewInbound, ServeGateway via NewInboundGateway) into ordinary http.Handlers.
memory
Package memory is an in-process, at-most-once msgin adapter backed by a Go channel.
Package memory is an in-process, at-most-once msgin adapter backed by a Go channel.
Package channel implements the Messaging Channels patterns of Enterprise Integration Patterns chapter 3 — in particular the Point-to-Point Channel and, from chapter 4, the Publish-Subscribe Channel.
Package channel implements the Messaging Channels patterns of Enterprise Integration Patterns chapter 3 — in particular the Point-to-Point Channel and, from chapter 4, the Publish-Subscribe Channel.
Package endpoint implements the Message Endpoint patterns of Enterprise Integration Patterns chapter 10 — the boundary where application code meets the messaging system.
Package endpoint implements the Message Endpoint patterns of Enterprise Integration Patterns chapter 10 — the boundary where application code meets the messaging system.
Package resilience holds the concrete implementations of the root package's cross-cutting governor and strategy interfaces: msgin.BackoffStrategy, msgin.CircuitBreaker, and msgin.RateLimiter.
Package resilience holds the concrete implementations of the root package's cross-cutting governor and strategy interfaces: msgin.BackoffStrategy, msgin.CircuitBreaker, and msgin.RateLimiter.
Package routing implements the Message Routing patterns of Enterprise Integration Patterns chapter 7 — deciding where a message goes next.
Package routing implements the Message Routing patterns of Enterprise Integration Patterns chapter 7 — deciding where a message goes next.
Package transform implements the Message Transformation patterns of Enterprise Integration Patterns chapter 8 — changing a message's content without changing where it goes.
Package transform implements the Message Transformation patterns of Enterprise Integration Patterns chapter 8 — changing a message's content without changing where it goes.

Jump to

Keyboard shortcuts

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