API Reference
Full API documentation is available on pkg.go.dev. This page is an index: every exported function and type of the eight library packages, grouped by theme, with a link to its documentation.
Packages
| Package | Description | Link |
|---|---|---|
event |
Core interfaces (Event, Bus, Invoker, Registry, Observer), LocalBus, the failure model and the DLQ record | pkg.go.dev |
invoker |
Execution pipeline components: chain, retry, circuit breaker, rate limiter, idempotency, DLQ | pkg.go.dev |
json |
JSON serialization with envelope format | pkg.go.dev |
jetstream |
NATS JetStream transport, DLQ publisher and replayer | pkg.go.dev |
nats |
NATS Core transport | pkg.go.dev |
redis |
Redis-backed idempotency and rate-limit stores | pkg.go.dev |
telemetry |
OpenTelemetry: tracing, span events and OTel metrics | pkg.go.dev |
prometheus |
Observer with a fixed Prometheus metric set |
pkg.go.dev |
The root package is imported as event. Every name removed or renamed in v0.4.0 is listed in the CHANGELOG, which is the migration guide.
Core (event)
Events, buses and subscribers
Event- Base event interface:Name() stringWithId- Optional interface: an event chooses its own message id (Id() string)WithVersion- Optional interface: the schema version of an event (Version() int)OnErr- Optional interface: the event’s own failure callback, called afterObserver.FailureBus- Bus interface (Subscribe, Close)SyncBus- Synchronous dispatch interface (EmitSyncreturns(Event, error))Shutdowner- Optional bus interface: gracefulShutdown(ctx)that drains in-flight handlersRegisterSubscribers- Bulk registration ofSubscribervalues on a busSubscriber- Grouped handler interfaceSubscribeOptionsProvider- Optional interface for subscriber-level subscribe optionsHandleFn- Handler function type,func(context.Context, Event) errorHandlerFunc- Generic typed handler,func(ctx, E) errorInvoker- Middleware interfaceLocalBus- In-process busNewLocalBus- Creates aLocalBusfrom its optionsLocalBusOptions- LocalBus configuration: Invoker, Observer, DLQPublisher, MaxConcurrent, Overflow and moreOverflowPolicy- What LocalBus does with an external emit when every slot is busy and the queue is fullLifecycle- Shutdown state machine shared by every bus: admission, in-flight accounting, bounded drain
Emit and subscribe options
EmitOption- Functional option for EmitEmitOptions- Resolved emit configurationApplyEmitOptions- Applies emit options for an event; the subject defaults toevt.Name()WithSubject- Overrides the publish subject (defaults toevt.Name())SubscribeOption- Functional option for SubscribeSubscribeOptions- Resolved subscribe configurationApplyOptions- Applies subscribe optionsWithHandlerName- Sets handler name for metrics/loggingWithStream- JetStream stream name (required for JetStream)WithConsumer- JetStream durable consumer nameWithMaxDeliver- Limits the number of redelivery attempts per messageWithBackOff- Sets the delays between redelivery attempts
Registry, envelope and decode
Registry- Serialization interfaceEnvelope- Wire formatFactory- Creates a new empty event instance for the registryUpcaster- Migrates a payload from one schema version to the nextEnvelopeEncoder- Optional registry interface:EncodeWithencodes with already resolvedMetadataEncodeEvent- Encodes withEncodeWithwhen the registry implementsEnvelopeEncoder, elseEncodeDecodeError- Wraps a decode failure with the event name and version;errors.Isanderrors.Asboth workWrapDecodeError- Wraps an error as a*DecodeErrorunless it already is one
Context and metadata
Metadata- Identity, causal lineage and headers of one event, read by handlersWithMetadata- Returns a context that carries aMetadataMetadataFromContext- Reads theMetadataof the event being handled from the handler contextResolveOutbound- Resolves theMetadataof an event about to be emitted (id, correlation, causation, headers)NewID- Generates a UUIDv7 message idWithID- Sets the message id of an emitted eventWithCorrelationID- Sets the correlation id of an emitted eventWithHeader- Attaches a user header to an emitted event (repeatable)Delivery- Count, maximum, subject, raw bytes, headers and stream position of one delivery attempt, carried in the handler contextWithDelivery- Returns a context that carries aDeliveryDeliveryFromContext- Reads theDeliveryof the message being handledExecution- The handler run in progress: handler name and start timeWithExecution- Returns a context that carries anExecutionExecutionFromContext- Reads theExecutionof the handler being run
Failure semantics and DLQ
InvokeHandler- The single handler entry point of every transport: runs the chain, recovers panics, emitsHandlerDoneSettle- The one post-chain policy shared by every transport: dispose, dead-letter backstop, report onceSettleInput- WhatSettleneeds to decide the fate of one handled messageSettlement- The decisionSettlereachedDispose- Maps a handler chain error to aDispositionfor a givenDeliveryDisposition- What a transport does with a message: Ack, Retry, RetryDelayed or TerminalOutcome- Terminal resultSettlereports; values are metric label values and never changeOutcomeOf- Maps a handler chain error to theHandlerDoneoutcomeReasonOf- Returns the stable reason code for an errorFailureError- Failure of a handler after the in-process retry policy: attempts and historyAttemptsOf- How many in-process handler attempts led to an errorAttempt- One in-process handler attempt of a deliveryNewAttempt- Builds anAttemptAttemptClass- Class of an attempt error: transient, terminal, timeout or panic (closed set)AttemptClassOf- Classifies the error of one attemptFailingInvoker- Names the part of the pipeline that produced a terminal failure (closed set)FailingInvokerOf- Names the part of the pipeline that produced an errorPanicError- A panic recovered from a handler or an invokerHandlerError- Identifies the failing handler inside the errorLocalBus.EmitSyncreturnsDeadLetteredError- Returned by the DLQ invoker once the message was dead-letteredDeadLetterFailedError- Returned when publishing to the dead-letter queue failedIsInterrupted- Reports whether an error is the result of the subscription context endingWrapInterrupted- Marks a handler error caused by a shutdownDLQPublisher- Publishes a failed message to a dead-letter queueDLQRecord- Everything a publisher needs to dead-letter one message: original bytes, headers, causeNewDLQRecord- Builds theDLQRecordfor a message that failed with a causePublishDeadLetter- Publishes a record through a publisher and reportsDeadLetteredorDLQPublishFailedMemoryDLQ- In-memoryDLQPublisherfor tests and examplesNewMemoryDLQ- Returns an emptyMemoryDLQEncodeHistoryHeader- Encodes the retry history as theEventbus-Dlq-Historyheader valueTruncateHeader- Makes a string safe to use as a header value of bounded size
Observability
Observer- The ten typed signals through which invokers and transports report; one per busNopObserver- Observer whose methods do nothing; embed it to implement only some signalsMultiObserver- Calls several observers in order and isolates a panic in any of themWithObserver- Returns a context that carries anObserverObserverFromContext- Reads theObserverof the bus from the handler contextSlogObserver- Observer that writes structuredlog/slogrecords with deduplication; the defaultNewSlogObserver- Creates aSlogObserver; a nil logger usesslog.Default()SlogOption- Option forNewSlogObserverWithLogEvery- Sets the log deduplication windowFailureContext- Payload ofObserver.Failure: outcome, reason, attempts, delivery, invoker, breaker stateHandlerResult- Payload ofObserver.HandlerDone: outcome, duration and error of one invocationRetryAttemptInfo- Payload ofObserver.RetryAttemptDeadLetterInfo- Payload ofObserver.DeadLettered: a summary, never the recordDecodeFailure- Payload ofObserver.DecodeFailedDLQPublishFailure- Payload ofObserver.DLQPublishFailedStoreErrorInfo- Payload ofObserver.StoreErrorIdempotencyStaleInfo- Payload ofObserver.IdempotencyStaleInternalErrorInfo- Payload ofObserver.InternalErrorBreakerTransition- Payload ofObserver.BreakerTransition: one circuit breaker state changeBreakerState- State of a circuit breaker: closed, open or half_openBreakerReason- Why a circuit breaker changed state (closed set)FailureScope- Per-delivery recorder that makesObserver.Failurefire exactly onceWithFailureScope- Installs a freshFailureScopein a contextFailureScopeFromContext- Reads theFailureScopeof a context
Constant groups, by their first name: OutcomeOK (Outcome values), ReasonTerminal (Reason codes), ComponentTransport (InternalError components), OpConsume (InternalError operations), DispositionAck (Disposition values), BreakerClosed and BreakerReasonFailureThreshold (breaker values), AttemptTransient (AttemptClass values), InvokerRetry (FailingInvoker values), OverflowBlock (OverflowPolicy values), HeaderDLQPrefix and HeaderDLQTraceparent (dead-letter and replay header names), and DefaultMaxConcurrent (LocalBus and shutdown defaults).
Error values
ErrUnknownEvent- Decode: the envelope names an event that is not registeredErrMalformedEnvelope- Decode: undecodable bytes, missing name, negative version or a payload that does not fit the eventErrMissingUpcaster- Decode: no upcaster for an intermediate versionErrUnknownVersion- Decode: the envelope version is newer than the latest registered versionErrDuplicate- Duplicate detection; the transport acknowledges itErrCircuitOpen- Circuit breaker open; the handler did not runErrRateLimited- Rate limit exceeded; the handler did not runErrInProgress- Another execution of the same event and handler is in progressErrSendToDLQ- Terminal error signalErrRetriesExhausted- The in-process retry policy gave upErrDeadLettered- The message was published to the dead-letter queueErrDeadLetterFailed- Publishing to the dead-letter queue failedErrHandlerPanic- A handler or invoker panicked; matchesPanicErrorErrHandlerTimeout- The handler timeout elapsed while the subscription context was still aliveErrBusClosed- Emit or Subscribe after shutdown startedErrShutdownInterrupted- A handler was interrupted by a forced shutdownErrQueueFull- LocalBus dropped an emit because the queue was full (OverflowDrop)
JSON Registry
Registry- JSON registry: encodes, decodes and upcasts envelopesNewRegistry- Returns an emptyRegistry; options are optionalOption- Functional option forjson.NewRegistryWithPropagator- Replaces the default W3C trace context and baggage propagatorWithIDGenerator- Sets the id generator used for events without an explicit idEncodeWith- Encodes an event with explicitMetadata
Invoker
The names below also have error values re-exported from the root package: ErrDuplicate, ErrRateLimited, ErrCircuitOpen and ErrSendToDLQ.
Chain- Invoker chain compositionNewChain- Builds aChainfrom invokers, outermost firstRetry- Retry with backoffNewRetry- Creates theRetryinvoker from a policyRetryPolicy- Maximum attempts, base and maximum delay, and history size ofRetryCircuitBreaker- Per-handler circuit breakerNewCircuitBreaker- Creates theCircuitBreakerinvokerCircuitBreakerConfig- Failure and success thresholds, open timeout and theOnStateChangecallback of the breakerRateLimiter- Rate limitingNewRateLimiter- Creates theRateLimiterinvoker over a storeRateLimitConfig- Rate, period, burst and key prefixRateLimitStore- Token-bucket store interfaceIdempotency- Duplicate detectionNewIdempotency- Creates theIdempotencyinvoker over a storeIdempotencyConfig- Processing TTL of the invokerIdempotencyStore- Idempotency record store interfaceIdempotencyRecord- Status and times of one execution recordIdempotencyStatus- Status of a record: processing, completed, failed or dead_letteredMemoryIdempotencyStore- In-memory idempotency storeNewMemoryIdempotencyStore- Creates aMemoryIdempotencyStoreDLQ- Dead letter queue invokerNewDLQ- Creates theDLQinvoker over aDLQPublisherDLQPublisher- Alias ofevent.DLQPublisherFailureError- Alias ofevent.FailureErrorWithIdempotencyKey- Optional event interface: the idempotency keyWithRateLimitKey- Optional event interface: the rate limit keyPermanentError- Terminal errorRetryableError- Retryable errorRetryable- Optional error interface:Retryable() bool, false means never retryTerminal- Optional error interface:Terminal() bool, true means never retry
NATS Core
Bus- NATS Core busNewNatsBus- Creates aBusover a NATS connection and a registryBusOptions- Invoker, Observer, DLQPublisher,ReplyErrorMessage, request timeout and shutdown optionsRemoteError- WhatEmitSyncreturns when the responder replied with anEventbus-Errorheader
JetStream
Bus- JetStream busNewBus- Creates aBusover a JetStream backend and a registryBusOptions- Invoker, Observer, DLQPublisher, publish retry, redelivery delays and shutdown optionsPublishRetryPolicy- Bounds the internal retry of transient publish failuresDLQ- Publishes dead-lettered messages to JetStream with the original bytesNewDLQ- Creates aDLQfor a prefix (defaultdlq.)DLQOption- Option forNewDLQWithDLQRegistry- Sets the registry that encodes a record with no original bytesReplayer- Republishes dead-lettered messages from a DLQ streamNewReplayer- Creates aReplayerReplayerOption- Option forNewReplayerWithReplayTracerProvider- Sets the provider of the replay spansReplayOptions- WhatReplayreads and where it publishesReplayResult- Counts the records handled by oneReplaycallErrStreamRequired-Subscribecalled withoutWithStreamErrInvalidConfig- Invalid consumer configuration (for exampleMaxDeliverinconsistent with the backoff length)ErrNoEnvelope- A record with neither original bytes nor a registry cannot be encodedErrReplaySubject- A replay record has no valid target subject
Redis
IdempotencyStore- Redis-backedinvoker.IdempotencyStoreNewIdempotencyStore- Creates the Redis idempotency storeRateLimitStore- Redis-backed token bucketNewRedisRateLimitStore- Creates the Redis rate limit store
Telemetry
TracerInvoker- Invoker that creates one consumer span per handler invocationNewTracerInvoker- Creates aTracerInvoker; it goes first in the chainTracerOption- Option forNewTracerInvokerWithTracerProvider- Sets the provider used to build the tracerWithSpanDestination- Overrides the destination of the consumer spanObserver-event.Observerthat reports in-chain signals as span events and OpenTelemetry metricsNewObserver- Creates the telemetryObserverObserverOption- Option forNewObserverWithMeterProvider- Enables the OpenTelemetry metric set on a meter provider
Prometheus
Observer-event.Observerwith a fixed set of Prometheus metric familiesNewObserver- Registers the metric set on a registerer and returns theObserverOption- Option forNewObserverWithNamespace- Prefixes every metric name with a namespace