event

package
v0.6.108 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package event declares the events a service publishes and the reactors it runs. Events travel over the service's transport (NATS JetStream with CloudEvents metadata, design §8); without one Publish returns ErrUnavailable. Reactors are recorded in the manifest as durable consumers.

Payload compatibility

A payload is JSON (protojson for proto messages) and evolves additively: a field is added, never repurposed. A reader ignores fields it does not know, so a producer may ship a new field before its consumers; a reader gets the zero value for a field the payload lacks. Renaming a field is adding a new one: publish both until every reactor reads the new one. A payload a reactor cannot decode at all is dead-lettered at once.

Delivery

A reactor is at-least-once: a handler may see the same event again (Delivery.ID tells), so it is idempotent. Instances of the service share the reactor's durable consumer as competing consumers: each event goes to one instance. With Concurrency above 1, or with several instances, events of one key are not handled in order; Ordered makes a reactor strict at the cost of one event in flight across the whole service.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnavailable is returned while no transport carries events.
	ErrUnavailable = env.ErrUnavailable
	// ErrOption: a publish option has an invalid value (Publish fails).
	ErrOption = errors.New("event: invalid publish option")
)

Errors.

Functions

func React

func React[T any](scope deps.Scope, event string, fn func(ctx context.Context, v T) error, opts ...ReactOption)

React subscribes fn to another service's event by full name ("iam.UserRegistered": a service name, a dot, a CamelCase event); it panics on another shape. The durable consumer is named after the scope's node path and the event ("<path>:<event>", the event alone on the Root), so each reactor keeps its own position. Renaming or moving the component renames the consumer: the new one starts afresh (StartAt) and the old one stays on the server with its position. Consumer pins the name instead.

A handler that returns an error (or panics) gets the message again after a growing delay; when the last delivery fails too, or the error is Terminal, the message goes to the service's dead letters; a payload that does not decode is Terminal. A handler cancelled by the service's stop does not count as failed: the message comes back, never dead-lettered. The handler's ctx carries the event's Delivery. Options change the defaults: MaxDeliver 5, Concurrency 4, Timeout 30s, Redelivery 1s..1m, StartAt(StartNew). They panic on values that make no sense, at declaration.

func ReactRaw added in v0.6.47

func ReactRaw(
	scope deps.Scope, consumer, pattern string, fn func(ctx context.Context, ev Raw) error, opts ...ReactOption,
)

ReactRaw subscribes fn to the events of a pattern, undecoded: "*" is every service's events, "<service>.*" one service's. It is for services that handle events they do not know when they are built, e.g. a journal of whatever the installation's services publish; a handler that knows its event uses React. fn filters itself: what it does not want it returns nil for, acknowledged.

consumer names the durable consumer, unique within the service. With "*" it is one consumer per service stream, the same name in each; a service whose stream appears later is taken within half a minute, from where StartAt says. Delivery, dead letters and options are React's; a handler error is retried, Terminal dead-letters at once. It panics on another pattern or an empty consumer.

func Redrive

func Redrive(ctx context.Context, scope deps.Scope, consumer string) (int, error)

Redrive runs the handler of the service's reactor consumer (its name in the manifest's subscriptions) on the reactor's dead letters, oldest first, in this instance, and deletes each one it handles; one that fails again stays a dead letter. Other subscribers of the event do not see the events again. It returns how many were handled and an error when some failed again. Call it once, from one instance: two concurrent calls may handle a dead letter twice.

func Terminal

func Terminal(err error) error

Terminal marks a handler's error as final: the message is dead-lettered at once instead of being delivered again. Use it for input no retry can fix. Terminal(nil) is nil.

Types

type DeclareOption

type DeclareOption interface {
	// contains filtered or unexported methods
}

DeclareOption configures Declare.

func Describe

func Describe(s string) DeclareOption

Describe is the event's description in the manifest and the console.

type Delivery

type Delivery struct {
	ID       string    // ce-id: the same on every redelivery
	Source   string    // service that published it
	Type     string    // full event name "<service>.<Event>"
	Subject  string    // the Key it was published with
	Time     time.Time // when it happened (ce-time)
	Attempt  int       // delivery of this message, 1 for the first
	Consumer string    // the reactor's consumer (manifest subscriptions)
	// Extensions are the other ce-* headers by name without the prefix:
	// Header values and the SDK's instance and version.
	Extensions map[string]string
}

Delivery is the metadata of the event a reactor's handler runs for.

func DeliveryOf

func DeliveryOf(ctx context.Context) (Delivery, bool)

DeliveryOf returns the metadata of the event being handled; false outside a reactor's handler.

type PublishOption

type PublishOption interface {
	// contains filtered or unexported methods
}

PublishOption configures Publish.

func Header(name, value string) PublishOption

Header sets a CloudEvents extension attribute, sent as header ce-<name> and read back from Delivery.Extensions. name is lowercase letters and digits (CloudEvents); the SDK's own attributes (id, source, type, time, subject, instance, version, ...) are not accepted, nor a value with a line break.

func ID

func ID(s string) PublishOption

ID sets the event's id (ce-id), by default a new UUID. JetStream drops a second publish with the same id within the stream's dedup window (nats.dedup_window), so an outbox that republishes a row under the row's id publishes it once. It must not be empty.

func Key

func Key(k string) PublishOption

Key sets the CloudEvents subject (ordering key).

func Time

func Time(t time.Time) PublishOption

Time sets when the event happened (ce-time), by default the publish time; the zero time keeps the default.

type Raw added in v0.6.47

type Raw struct {
	Delivery

	Data []byte
}

Raw is an event as it was published: its delivery and its payload, the JSON the publisher encoded.

type ReactOption

type ReactOption interface {
	// contains filtered or unexported methods
}

ReactOption configures React.

func Concurrency

func Concurrency(n int) ReactOption

Concurrency bounds the handler calls in flight at once, per instance. Concurrency(1) runs them one at a time in one instance; a failed message still comes back after its delay, behind the ones that followed it, and other instances run theirs meanwhile (see Ordered). It panics unless n >= 1.

func Consumer

func Consumer(name string) ReactOption

Consumer pins the reactor's consumer name, unique within the service, so that renaming or moving the component keeps the consumer and its position. To adopt an existing consumer, pin its current name. It panics on an empty name.

func InactiveThreshold

func InactiveThreshold(d time.Duration) ReactOption

InactiveThreshold lets the server delete the reactor's consumer after d without any instance consuming, e.g. a reactor that was removed or renamed. A consumer deleted so is recreated at the next start where StartAt says, and what was published meanwhile is skipped with StartNew. It panics unless d > 0.

func MaxDeliver

func MaxDeliver(n int) ReactOption

MaxDeliver bounds the deliveries of one message, the first included; after the n-th failure it is dead-lettered. MaxDeliver(1) never retries. It panics unless n >= 1.

func Ordered

func Ordered() ReactOption

Ordered handles the reactor's events strictly in stream order across all instances: one event in flight for the whole service (the consumer's max_ack_pending is 1, Concurrency 1). A failed event blocks the ones after it until it succeeds or is dead-lettered. The throughput is one handler call at a time, round trip included, whatever the replica count. Combined with Concurrency above 1 it panics.

func Redelivery

func Redelivery(minDelay, maxDelay time.Duration) ReactOption

Redelivery bounds the delay before a failed message comes back: minDelay after the first failure, doubling with every delivery up to maxDelay. It panics unless 0 < minDelay <= maxDelay.

func StartAt

func StartAt(s Start) ReactOption

StartAt chooses where the reactor's consumer starts when it is first created. It applies at creation only: an existing consumer keeps its position, so adding StartAt(StartAll) to a running reactor replays nothing. It panics on an unknown Start.

func Timeout

func Timeout(d time.Duration) ReactOption

Timeout of one handler call: its ctx is cancelled after d and the call counts as failed. A message nobody settled (the instance died) comes back after d plus a margin. It panics unless d > 0.

type Ref

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

Ref is a declared event. The zero Ref is undeclared: Publish fails.

func Declare

func Declare[T any](scope deps.Scope, name string, opts ...DeclareOption) Ref[T]

Declare registers an event the service publishes. Declare it where it is raised: any component can. name is CamelCase ([A-Z][A-Za-z0-9]*); on the wire it is "<service>.<name>". It panics on an invalid name.

func (Ref[T]) Name

func (r Ref[T]) Name() string

Name is the full event name <service>.<Name>.

func (Ref[T]) Publish

func (r Ref[T]) Publish(ctx context.Context, v T, opts ...PublishOption) error

Publish sends the event and returns once the transport stored it. It waits no longer than ctx allows; a ctx without a deadline gets the transport's own (nats.publish_timeout, 5s). An invalid option fails with ErrOption.

type Start

type Start int

Start is where a reactor's consumer starts when it is created.

const (
	// StartNew: events published after the consumer is created (default).
	StartNew Start = iota
	// StartAll: every event the source stream still retains.
	StartAll
)

Starts of StartAt.

Jump to

Keyboard shortcuts

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