snodra

package module
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 52 Imported by: 2 modules, 0 packages

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

README

Snodra Messaging for Go mascot

Snodra Messaging (Go)

Commands, queries, streams, scatter-gathers and subscriptions — events through an outbox, processors with control, sagas and idempotent external calls — for Go services, routed by Snodra Server.

ci Go reference release Go docs license


What it is

One package, snodra, that gives a Go service what it needs to send and serve requests in a Snodra system, with the same wire protocol as services written with any Snodra library: you write functions, the library keeps the hub streams, permits, retries and timeouts.

  • Commands and queries through Snodra Server, with deadlines, retries and routing keys. A command or a query that is not shared, of a type the service handles itself, is answered in-process by its own handler, without the hub; snodra.AlwaysRouteThroughHub(true) sends it through the hub like any other request.
  • Every query mode: point, scatter-gather, streaming and subscription; streams and updates are iter.Seq2.
  • Message contracts: an optional MessageVersion() (default 1) names the version of a message type, and the library generates the JSON Schema of every handled request, reply, stream item, subscription type and consumed event from the Go types with reflect alone (JSONSchema() and ResponseJSONSchema() replace a generated document). Register declares one contract per handled type and one per consumed event type, so Snodra Server 0.8's schema catalogue lists them, and a changed schema at the same version is refused by the hub with FAILED_PRECONDITION (App.Rejection). Every request carries snodra-schema-version and snodra-response-schema-version, in every mode, in-process answers and the saga relay included, and the hub routes it only to an instance serving exactly that contract. Every published event carries snodra-schema-version, and a consumer skips and acknowledges a record of another version of a type it handles.
  • Events through an outbox: Publish appends the event in the transaction the context carries, and a relay in every instance publishes it to the event store, at least once. Key is the order key.
  • Event handlers with processed-event markers: HandleEvent runs in the default processor or in a named one (InProcessor), each with one subscription and processor:<processor>:<eventId> markers, so a redelivery is skipped and one processor's failure does not hold another's.
  • Processors, status and control: every started processor reports its state, segments, counters and dead-letter count to the hub. The dashboard pauses and resumes it persistently; a leased reset stops its subscription, runs the HandleReset handlers when anything replays, deletes the replayed range's markers, and replays from earliest, latest, timestamp or explicit positions. DisallowReplay() keeps a handler out of a replay, and all control runs off the hub read loop.
  • Sagas: HandleSaga runs in the default processor after the event handlers (stage 2), with associations, an optimistic state version, parked failures, deadlines and the local SagaCommandFailed notice. A saga records what it sends; a relay dispatches each saga's commands and events after its transaction committed, in order under a lease. A command is sent by its wire type with idempotency-key/saga-id, the handled event's correlation and trace, and no caller identity; transient failures are retried by the relay, permanent ones come back as the notice. A deadline scheduler claims each due deadline with a lease, runs its handler and marks it fired in one transaction.
  • Idempotent external calls: HandleIdempotentCommand records each call under the idempotency-key header in external_calls: the first insert wins, a repeat after success returns the first reply, a permanent failure is replayed, and a lapsed call is given up as unknown (or taken over with ExternalIdempotent()). Retryable and UnknownOutcome write the two reserved Error.details markers, which IsRetryable and IsUnknownOutcome read locally and from a hub; the saga relay owns the backoff.
  • Events from outside: VerifyWebhook checks a partner's webhook request, by the shared secret in X-Snodra-Webhook-Secret or the HMAC-SHA256 of the raw body in X-Snodra-Signature, with the current or the previous secret and in constant time. AcceptExternal applies the decoded event to the service's event handlers and sagas, synchronously and once per <source>:<dedupeKey> (an ingress: marker recorded after success), and never publishes it.
  • Dead letters: a record that exhausts its attempts is parked according to DeadLetterMode (SNODRA_DEAD_LETTER_MODE): collection keeps it in the message store's dead letters, with list, retry, retry-all and discard driven from the dashboard; event-store publishes it to the <source>.dlt source with the six snodra-dlt-* headers, when the store declares native-dead-letter; log logs it and moves on.
  • Add-ons: Kafka and RabbitMQ Streams for the event store; MongoDB and SQL (PostgreSQL, MySQL) for the outbox, the markers, the dead letters, the processor control, the external calls and the saga records; in-memory stores for tests. Each add-on is a module of its own, and snodratest is the add-on kit.
  • The hub connection: registration, heartbeats, reconnects, flow control, several hubs and an ordered shutdown.
  • Credentials and identity: a token (static, or a file read again), an OAuth2 JWT (renewed) or a client certificate (rolled over to a renewed pair); the caller's token verified against the issuer's keys, and guards on handlers.
  • Telemetry behind an interface, with an OpenTelemetry implementation in the separate observability module.
  • Checked by tests anyone can run: the 39 checks of the conformance runner, the event-store and message-store kits on every add-on, and an interop run in which one saga continues across services on shared stores.

Install

go get github.com/snodra/snodra-messaging-go@latest
go get github.com/snodra/snodra-messaging-go/observability@latest   # optional: OpenTelemetry

# One event store and one message store, when the service publishes or handles events:
go get github.com/snodra/snodra-messaging-go/kafka@latest           # Kafka event store
go get github.com/snodra/snodra-messaging-go/rabbitmq@latest        # RabbitMQ Streams event store
go get github.com/snodra/snodra-messaging-go/mongo@latest           # MongoDB message store
go get github.com/snodra/snodra-messaging-go/sql@latest             # SQL message store (PostgreSQL, MySQL)

The modules are on the Go module proxy and need Go 1.26 or later; the core depends only on gRPC and protobuf. The modules of a release share its version. Each add-on depends on the core and on its own store client, never the reverse.

Add-ons

Add-on Module Holds
Kafka event store github.com/snodra/snodra-messaging-go/kafka Events, in ordered partitions
RabbitMQ Streams event store github.com/snodra/snodra-messaging-go/rabbitmq Events, in partitioned streams
MongoDB message store github.com/snodra/snodra-messaging-go/mongo Outbox, markers, dead letters, processor control, external calls and saga records, in the shared collections
SQL message store github.com/snodra/snodra-messaging-go/sql Outbox, markers, dead letters, processor control, external calls and saga records, in the shared V1 tables

A service needs one event store and one message store, each passed to snodra.New with WithEventStore and WithStore. The event stores follow the shared wire layouts and declare their capabilities; the message stores follow the shared SQL V1 and MongoDB layouts. The Go event-store add-ons have no event browser, so they declare no browse. The settings and guarantees are on https://snodra.damoreira.com/docs/add-ons/.

A handler

app, err := snodra.New(snodra.Service("orders-service"), snodra.FromEnv())
if err != nil {
	return err
}
err = snodra.HandleCommand(app, func(ctx context.Context, cmd PlaceOrder) (Receipt, error) {
	return Receipt{OrderID: cmd.OrderID, Total: cmd.Cents}, nil
})
if err != nil {
	return err
}
return app.Run(ctx) // connects to every hub, serves until ctx ends, then shuts down in order

A message is a Go type with a MessageType() string method; its payload is JSON by default (see snodra.Codec). Settings are options, and snodra.FromEnv() reads the SNODRA_* variables; options given after it win.

Documentation

The hub must be Snodra Server 0.8 or later, whose schema catalogue is on by default and refuses a Register without contracts (this library declares them). Go generates its own schemas and the generators of the libraries differ, so a service in another language that serves the same type must declare the same checked-in schema as this one (Services in different languages). Quick start, the settings map, the API, events and testing: https://snodra.damoreira.com/docs/messaging/go/, and go doc -all for the package. A complete service is examples/quickstart. The library speaks the Snodra protocol (snodra.hub.v1). Where the specification is silent, SPEC-GAPS.md records what this library does. Other languages: https://snodra.damoreira.com/.

Contributing

Branches off main, conventional commits, a pull request with a green workflow.

Releases

Versions are cut by CI from the commit types. Never push a tag. When the checks pass on a push to main, the subjects since the last v* tag decide. Any feat is the next minor. Otherwise any fix or perf is the next patch. Anything else (docs, test, chore, ci, refactor, build, style) releases nothing.

The six modules share one version, and each has its own tag: vX.Y.Z for github.com/snodra/snodra-messaging-go and observability/vX.Y.Z, kafka/vX.Y.Z, rabbitmq/vX.Y.Z, mongo/vX.Y.Z and sql/vX.Y.Z for the add-on modules under it. CI commits release: X.Y.Z (Version in version.go, the requirement of each add-on's go.mod on the root module with its hashes in go.sum, and the go.work replacement) and tags that commit six times. Before anything is pushed, every module is built and tested as a consumer gets them, from the new tags. A last job, which builds nothing, pushes the commit and all six tags together or not at all. The release workflow then has the Go proxy fetch every version and creates the GitHub release. Pull before you push: main then carries that commit.

  • Below 1.0.0, any type!: subject and any line starting BREAKING CHANGE: in a message count as a minor, never a major. 1.0.0 is declared by hand.
  • A revert (Revert "feat: ...", revert:) is not a release reason. The reverted change stays in the last published version until the next feat, fix or perf.
  • Only tags shaped vN.N.N count. The highest one reachable from main is the last release.
  • The Go proxy keeps a version forever: a tag is never moved or deleted. A wrong release is fixed by the next one.
  • scripts/next-version.sh holds the rule. for t in scripts/*.test.sh; do sh "$t"; done tests it.

If a release fails after the push (the tags exist, the GitHub release does not), use Re-run failed jobs on that run: every step is safe to repeat. Or run the release workflow by hand with the existing vX.Y.Z tag. Re-run all jobs on a run that released does nothing, because main has moved to its release commit. If it fails before the push, nothing was pushed: fix the cause and re-run the failed jobs (while main has not moved), or push the fix, whose run releases.

License

Apache-2.0 © 2026 Guilherme D'Amoreira.

Documentation

Overview

Package snodra is the official Go client library of the Snodra messaging suite.

The package is named snodra while its import path ends in snodra-messaging-go; by convention the import spells the name out (goimports writes it so), though Go binds snodra either way:

import snodra "github.com/snodra/snodra-messaging-go"

The protocol and the behaviour a library must have are described at https://snodra.damoreira.com/docs/library-authors/.

Example (Credentials)
package main

import (
	snodra "github.com/snodra/snodra-messaging-go"
)

func main() {
	// snippet:begin credentials
	app, err := snodra.New(
		snodra.Service("orders-service"),
		snodra.Hubs("https://hub.example.test:7000"), // https:// implies TLS
		snodra.JWT(snodra.NewClientCredentials(snodra.ClientCredentials{
			TokenURL:         "https://idp.example.test/oauth2/token",
			ClientSecretFile: "/run/secrets/orders-service-secret",
		})),
	)
	// snippet:end
	_, _ = app, err
}
Example (Guards)
package main

import (
	"context"
	"fmt"

	snodra "github.com/snodra/snodra-messaging-go"
)

type ArchiveOrder struct {
	OrderID string `json:"orderId"`
}

func (ArchiveOrder) MessageType() string { return "orders.ArchiveOrder" }

func main() {
	var app *snodra.App
	// snippet:begin guards
	// An anonymous caller is refused before the payload is decoded; a guard needs snodra.JWKS.
	_ = snodra.HandleCommand(app, func(ctx context.Context, cmd ArchiveOrder) (snodra.Empty, error) {
		caller, _ := snodra.CallerFrom(ctx)
		fmt.Println("archived by", caller.Subject)
		return snodra.Empty{}, nil
	}, snodra.RequireRole("orders-admin"))
	// snippet:end
}
Example (Handler)
package main

import (
	"context"

	snodra "github.com/snodra/snodra-messaging-go"
)

type PlaceOrder struct {
	OrderID string `json:"orderId"`
	Cents   int64  `json:"cents"`
}

func (PlaceOrder) MessageType() string { return "orders.PlaceOrder" }

type Receipt struct {
	OrderID string `json:"orderId"`
	Total   int64  `json:"total"`
}

func main() {
	serve := func(ctx context.Context) error {
		// snippet:begin handler
		app, err := snodra.New(snodra.Service("orders-service"), snodra.FromEnv())
		if err != nil {
			return err
		}
		err = snodra.HandleCommand(app, func(ctx context.Context, cmd PlaceOrder) (Receipt, error) {
			return Receipt{OrderID: cmd.OrderID, Total: cmd.Cents}, nil
		})
		if err != nil {
			return err
		}
		return app.Run(ctx) // connects to every hub, serves until ctx ends, then shuts down in order
		// snippet:end
	}
	_ = serve
}
Example (Send)
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	snodra "github.com/snodra/snodra-messaging-go"
)

type PlaceOrder struct {
	OrderID string `json:"orderId"`
	Cents   int64  `json:"cents"`
}

func (PlaceOrder) MessageType() string { return "orders.PlaceOrder" }

type Receipt struct {
	OrderID string `json:"orderId"`
	Total   int64  `json:"total"`
}

type GetOrder struct {
	OrderID string `json:"orderId"`
}

func (GetOrder) MessageType() string { return "orders.GetOrder" }

func main() {
	var (
		ctx context.Context
		app *snodra.App
	)
	// snippet:begin send
	receipt, err := snodra.Send[Receipt](ctx, app, PlaceOrder{OrderID: "o-1", Cents: 1250},
		snodra.RoutingKey("o-1"), snodra.Timeout(3*time.Second))
	if err != nil {
		var e *snodra.Error
		switch {
		case errors.As(err, &e):
			fmt.Println("the hub or the handler answered", e.Code, e.Message)
		case errors.Is(err, snodra.ErrNeverSent):
			fmt.Println("no handler saw it: sending it again is safe")
		case errors.Is(err, snodra.ErrOutcomeUnknown):
			fmt.Println("it may or may not have run")
		}
		return
	}
	order, err := snodra.Query[Receipt](ctx, app, GetOrder{OrderID: receipt.OrderID})
	// snippet:end
	_, _ = order, err
}
Example (Streams)
package main

import (
	"context"
	"fmt"
	"time"

	snodra "github.com/snodra/snodra-messaging-go"
)

type Receipt struct {
	OrderID string `json:"orderId"`
	Total   int64  `json:"total"`
}

type GetOrder struct {
	OrderID string `json:"orderId"`
}

func (GetOrder) MessageType() string { return "orders.GetOrder" }

type ListOrders struct{}

func (ListOrders) MessageType() string { return "orders.ListOrders" }

func main() {
	var (
		ctx context.Context
		app *snodra.App
	)
	// snippet:begin streams
	// Serving a stream: the items go out under the caller's credit.
	_ = snodra.HandleStream(app, func(ctx context.Context, _ ListOrders, w *snodra.StreamWriter[Receipt]) error {
		for _, r := range []Receipt{{OrderID: "o-1", Total: 1250}, {OrderID: "o-2", Total: 80}} {
			if err := w.Send(ctx, r); err != nil {
				return err // the caller stopped reading, or the hub stream is gone
			}
		}
		return nil
	})

	// Reading one: breaking out of the loop cancels the stream at the hub.
	for r, err := range snodra.Stream[Receipt](ctx, app, ListOrders{}) {
		if err != nil {
			return // the last thing the sequence yields
		}
		fmt.Println(r.OrderID, r.Total)
	}

	// Asking every instance of every owner of a shared query type.
	gathered, err := snodra.Gather[Receipt](ctx, app, GetOrder{OrderID: "o-1"}, snodra.Timeout(2*time.Second))
	if err == nil {
		fmt.Println(len(gathered.Parts), "answers from", gathered.Targets, "targets")
	}
	// snippet:end
}
Example (Subscriptions)
package main

import (
	"context"
	"fmt"

	snodra "github.com/snodra/snodra-messaging-go"
)

type WatchOrder struct {
	OrderID string `json:"orderId"`
}

func (WatchOrder) MessageType() string { return "orders.WatchOrder" }

type OrderStatus struct {
	Status string `json:"status"`
}

func main() {
	var (
		ctx context.Context
		app *snodra.App
	)
	// snippet:begin subscriptions
	// Serving a subscription: the initial result now, updates whenever you emit them. The type
	// arguments are the query, its initial result and its updates, as Subscribe[I, U] reads them.
	updates, _ := snodra.HandleSubscription[WatchOrder, OrderStatus, OrderStatus](app, func(_ context.Context, q WatchOrder) (OrderStatus, error) {
		return OrderStatus{Status: "placed"}, nil
	})
	updates.Emit(func(q WatchOrder) bool { return q.OrderID == "o-1" }, OrderStatus{Status: "shipped"})

	// Following one.
	sub, err := snodra.Subscribe[OrderStatus, OrderStatus](ctx, app, WatchOrder{OrderID: "o-1"})
	if err != nil {
		return
	}
	defer sub.Close()
	fmt.Println(sub.Initial.Status)
	for u, err := range sub.Updates() {
		if err != nil {
			return
		}
		fmt.Println(u.Status)
	}
	// snippet:end
}
Example (Webhook)
package main

import (
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"os"

	snodra "github.com/snodra/snodra-messaging-go"
)

// PaymentNotification is the body a payment provider posts to the service's webhook.
type PaymentNotification struct {
	DeliveryID string `json:"deliveryId"`
	OrderID    string `json:"orderId"`
}

// PaymentConfirmed is the service's own event for it.
type PaymentConfirmed struct {
	OrderID string `json:"orderId"`
}

func (PaymentConfirmed) MessageType() string { return "orders.PaymentConfirmed" }

func main() {
	var app *snodra.App
	// snippet:begin webhook
	secret, previous := os.Getenv("PAYMENTS_WEBHOOK_SECRET"), os.Getenv("PAYMENTS_WEBHOOK_PREVIOUS_SECRET")
	http.HandleFunc("POST /payments/webhook", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
		if err != nil || !snodra.VerifyWebhook(secret, previous, r.Header, body) { // the raw bytes
			http.Error(w, "unverified", http.StatusUnauthorized)
			return
		}
		var n PaymentNotification
		if err := json.Unmarshal(body, &n); err != nil {
			http.Error(w, "unreadable", http.StatusBadRequest)
			return
		}
		// IngressAccepted or IngressDuplicate: both are a success for the provider.
		_, err = snodra.AcceptExternal(r.Context(), app, "payments", n.DeliveryID, PaymentConfirmed{OrderID: n.OrderID})
		switch {
		case errors.Is(err, snodra.ErrIngressRefused): // refused before anything ran: a blank delivery id
			http.Error(w, err.Error(), http.StatusBadRequest)
		case err != nil: // a handler or the store failed: the provider sends it again, applied then
			http.Error(w, "try again", http.StatusServiceUnavailable)
		default:
			w.WriteHeader(http.StatusOK)
		}
	})
	// snippet:end
}

Index

Examples

Constants

View Source
const (
	// DeadLetterModeCollection parks it in the message store's dead letters, the default: an
	// operator lists, retries and discards it through the hub.
	DeadLetterModeCollection = "collection"
	// DeadLetterModeEventStore publishes it to the event store's dead-letter source
	// (<source>.dlt); the event store must declare CapabilityNativeDeadLetter (the in-memory one
	// does not, as the reference memory stores do not).
	DeadLetterModeEventStore = "event-store"
	// DeadLetterModeLog logs it and skips it; nothing is parked or published.
	DeadLetterModeLog = "log"
)

Where a record that exhausts its attempts goes (ProcessorStatus.dead_letter_mode).

View Source
const (
	// HeaderType is the event's type name.
	HeaderType = "type"
	// HeaderID is the event's id.
	HeaderID = "id"
	// HeaderCorrelationID ties the event to the request that caused it.
	HeaderCorrelationID = "correlationId"
	// HeaderTimestamp is when the event was recorded, RFC 3339 in UTC with milliseconds.
	HeaderTimestamp = "timestamp"
	// HeaderSource is the publishing service's name, not the event store's source.
	HeaderSource = "source"
	// HeaderUserID is the caller's user id; empty when none.
	HeaderUserID = "userId"
	// HeaderTraceparent is the W3C trace context of the message that caused the event.
	HeaderTraceparent = "traceparent"
	// HeaderSchemaVersion is the version of the event's type, a positive integer as decimal text.
	// Every event the library publishes carries it, always explicit; a consumer skips a record
	// that names another version than the one registered for its type, reads an absent one as 1
	// and treats a malformed one as an invalid record. It is not one of the seven [EventHeaders]:
	// an event store carries it as any other header.
	HeaderSchemaVersion = "snodra-schema-version"
)

The headers every event carries, as the event store's native metadata.

View Source
const (
	// MaxSegmentBytes is the most bytes of a segment's name; the hub drops a longer one.
	MaxSegmentBytes = 128
	// MaxPositionBytes is the most bytes of a position; the hub reads a longer one as
	// unknown.
	MaxPositionBytes = 128
)
View Source
const (
	// DefaultMemoryEventStoreSegments is how many segments a MemoryEventStore has per source
	// unless configured otherwise.
	DefaultMemoryEventStoreSegments = 4
	// MaxMemoryEventStoreSegments is the most segments per source a MemoryEventStore takes.
	MaxMemoryEventStoreSegments = 1024
)
View Source
const (
	// WebhookSecretHeader holds the shared secret itself.
	WebhookSecretHeader = "X-Snodra-Webhook-Secret"
	// WebhookSignatureHeader holds "sha256=<hex>", the HMAC-SHA256 of the raw body keyed by the
	// secret (the "sha256=" prefix is optional and the case of the hex does not matter).
	WebhookSignatureHeader = "X-Snodra-Signature"
)

The two headers a partner's webhook request is verified by.

View Source
const DefaultEventsSource = "snodra.events"

DefaultEventsSource is the source a service publishes its events to and its processors read (EventsSource, SNODRA_EVENTS_SOURCE) unless configured otherwise.

View Source
const DefaultProcessor = "default"

DefaultProcessor is the processor of the event handlers registered without InProcessor. Its subscription is "<service>.default" and its stage-1 markers are "processor:default:<eventId>".

View Source
const FirstAssignmentWithin = 10 * time.Second

FirstAssignmentWithin is the longest a new event subscription takes to yield its first event, an Assigned (empty when it holds no segment).

View Source
const IngressMarkerPrefix = "ingress:"

IngressMarkerPrefix is the prefix of the processed-event marker that remembers a finished AcceptExternal call: "ingress:<source>:<dedupeKey>", next to the processors' and the sagas' own markers.

View Source
const MaxDeadLetterErrorChars = 2000

The most characters of a dead letter's error message.

View Source
const MaxPayloadDepth = 100

MaxPayloadDepth is the deepest an outbox payload may be, as MySQL's JSON_DEPTH counts: a scalar or an empty object or array is 1, a non-empty one 1 + its deepest member. MySQL keeps no document nesting more than 100 objects and arrays, so the shared bound is depth 100 (one under MySQL's own limit for a document ending in a scalar).

View Source
const (
	// MemoryMessageStoreName is the in-memory message store's name (MessageStore.Name).
	MemoryMessageStoreName = "memory"
)
View Source
const ResetKind = "reset"

ResetKind is ControlOperation.Kind of a reset, the only kind there is.

View Source
const Version = "0.13.0"

Version is the version of this library.

Variables

View Source
var (
	// ErrNeverSent: the request was not written to any hub; sending it again
	// is safe.
	ErrNeverSent = errors.New("snodra: the request was never sent")
	// ErrOutcomeUnknown: the request was written but no answer arrived; the
	// handler may or may not have run.
	ErrOutcomeUnknown = errors.New("snodra: the outcome of the request is unknown")
	// ErrLostParts: a stream or gather lost parts that were already announced.
	ErrLostParts = errors.New("snodra: parts of the answer were lost")
	// ErrReservedHeader: a header name is reserved for the library.
	ErrReservedHeader = errors.New("snodra: header name is reserved")
	// ErrRegistrationClosed: handlers can no longer be registered.
	ErrRegistrationClosed = errors.New("snodra: registration is closed")
)

Errors the library itself reports, to be tested with errors.Is.

View Source
var (
	// ErrUnsupported: the store does not offer the operation or the capability. An
	// *UnsupportedError names the capability.
	ErrUnsupported = errors.New("snodra: the operation is not supported")
	// ErrInvalid: a bad argument, such as an unknown segment or a position the segment does
	// not have.
	ErrInvalid = errors.New("snodra: invalid argument")
	// ErrSubscribersActive: another instance still reads the subscription, so its positions
	// cannot move. A *SubscribersActiveError names the members.
	ErrSubscribersActive = errors.New("snodra: the subscription has active subscribers")
	// ErrRejected: the event store refused the event for good (too large, not authorized, a
	// destination it cannot have). Publishing it again cannot succeed, so the outbox relay
	// gives it up at once.
	ErrRejected = errors.New("snodra: the event store rejected the event")
	// ErrFailed: the event store failed or cannot be reached; trying again may succeed.
	ErrFailed = errors.New("snodra: the event store failed")
	// ErrNotOwner: a conditional write found the claim held by another owner. The whole
	// operation is retried or given up; the caller never overwrites the owner's state.
	ErrNotOwner = errors.New("snodra: the claim is held by another owner")
	// ErrLeaseLost: the lease of a claim expired before the operation committed. What the
	// operation wrote is not the caller's any more.
	ErrLeaseLost = errors.New("snodra: the lease was lost")
	// ErrClosed: the event subscription was closed.
	ErrClosed = errors.New("snodra: the subscription is closed")
)

Errors store operations report, to be tested with errors.Is. The message-store ports use ErrNotOwner and ErrLeaseLost for their conditional writes and leases.

AllCapabilities lists the capabilities the protocol names, in protocol order.

View Source
var ErrConflict = errors.New("snodra: another writer got there first")

ErrConflict: another writer got to a record first (a duplicate key, a write conflict, a version check or a stale transaction). The whole attempt is retried, in a new transaction.

View Source
var ErrIngressRefused = fmt.Errorf("%w: an event from outside is refused", ErrInvalid)

ErrIngressRefused is the error, wrapping ErrInvalid, of an AcceptExternal call refused before anything ran: a blank source or dedupe key, or a reserved source name. Sending the same request again cannot succeed, so a webhook answers it with a client error; any other error of the call may pass with a retry.

EventHeaders lists the seven standard headers (HeaderSchemaVersion comes on top of them), in the order the specification gives them.

View Source
var RetryNeverRan = RetryPolicy{MaxAttempts: 3, InitialBackoff: 100 * time.Millisecond, Multiplier: 2, MaxBackoff: 2 * time.Second}

RetryNeverRan is the default policy: 3 attempts, 100 ms doubling up to 2 s. Retries are opt-in: pass it to DefaultRetry or Retry (or set SNODRA_SERVER_RETRY_ENABLED).

Functions

func CheckOutboxPayload added in v0.2.0

func CheckOutboxPayload(typeName string, payload []byte) error

CheckOutboxPayload verifies the outbox contract on a payload: JSON (UTF-8, no leading byte order mark, no lone surrogate escape, no number a double cannot hold), a JSON object at most MaxPayloadDepth deep, and every integer in it (a number written without '.', 'e' or 'E') within the signed 64-bit range. The integers are read from the text itself, since a JSON parser reads one outside the range as a float that a store would keep changed. Any other payload is refused with an error wrapping ErrInvalid.

func DeadLetterSource added in v0.2.0

func DeadLetterSource(source string) string

DeadLetterSource is the dead-letter source of source ("<source>.dlt"): where the dead-letter mode event-store sends what a processor cannot handle, on an event store declaring CapabilityNativeDeadLetter.

func HandleCommand

func HandleCommand[C Message, R any](app *App, h func(context.Context, C) (R, error), opts ...HandlerOption) error

HandleCommand registers h as the handler of the command type C, by C's MessageType. C may be a struct type or a pointer to one (Message may have a pointer receiver); the payload is decoded into a fresh C. R is the answer: Empty (or a nil pointer) answers {}.

Handlers are registered before App.Start. A registration error (after Start: ErrRegistrationClosed; a type registered twice, as a command and a query, an empty type name, an interface type parameter, a nil handler, a RequireCaller without a function, a guard without JWKS, a command with Shared) is returned, and also kept: Start returns every one of them, joined, and does not start. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Handling a request).

func HandleEvent added in v0.3.0

func HandleEvent[E Message](app *App, h func(context.Context, E) error, opts ...EventOption) error

HandleEvent registers h as a handler of the event type E, by E's MessageType. The handler runs in the DefaultProcessor unless InProcessor names another processor; several handlers of one type in one processor all run, in registration order, and an error in one fails the record.

A handler of a delivered event runs in the processor's transaction with the event's stage-1 marker: its writes and the marker commit together, and an event whose marker is recorded already (a duplicate) runs no handler. An event of a type no handler of the processor handles is acknowledged and runs nothing.

The handler's context carries what MessageFrom reads (the event's id, type, correlation id and headers) and, through Publish, the event's correlation id, userId and trace context. An event handler has no caller (CallerFrom reports false): an event carries a userId, never a token. Events are handled at least once: a handler that fails is tried again, and a record that fails every attempt is parked as a dead letter (mode collection, the default) and acknowledged.

Handlers are registered before App.Start, like commands, queries and subscription handlers. An event handler needs the message store (WithStore) and the event store (WithEventStore) of the service: App.Start fails without them, naming the missing add-on. Commands, queries and subscription queries need neither. See https://snodra.damoreira.com/docs/library-authors/messages/ (Events) and https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/ (The rule).

func HandleIdempotentCommand added in v0.7.0

func HandleIdempotentCommand[C Message, R any](app *App, h func(context.Context, C) (R, error), opts ...HandlerOption) error

HandleIdempotentCommand registers h as the idempotent handler of the command type C, by C's MessageType. Each call is recorded in the message store's external calls under the `idempotency-key` header (which a saga's relay sets to `<sagaId>:<seq>`): the first insert wins, a repeat after success returns the first reply without running h, a repeat after a permanent failure returns the stored error, and a repeat after an unknown outcome reports it again.

A body that fails with Retryable resets the record so the next call runs it again (the saga relay owns the backoff); UnknownOutcome leaves the record UNKNOWN, so no later call runs the body automatically. Any other failure is stored FAILED with HANDLER_ERROR and its message, and replayed. A call still IN_PROGRESS within its lease asks the caller to come back (Retryable); past the lease it is given up as UNKNOWN unless ExternalIdempotent was given, in which case it is taken over and the body runs again. Every write matches the record the call owns or read, so a call whose lease ran out never overwrites the record of the call that took it over.

The records are written in short writes of their own, outside the caller's transaction: a rolled-back caller never forgets a call that happened. The handler needs a message store (Start refuses one without) and is registered like HandleCommand (guards apply, Shared is refused).

func HandleQuery

func HandleQuery[Q Message, R any](app *App, h func(context.Context, Q) (R, error), opts ...HandlerOption) error

HandleQuery registers h as the handler of the query type Q, by Q's MessageType, as HandleCommand does for a command.

func HandleReset added in v0.6.0

func HandleReset(app *App, processor string, h func(context.Context, ResetContext) error) error

HandleReset registers h as a reset handler of processor (the DefaultProcessor or a named one): every reset of that processor runs its handlers, in registration order, when anything replays, before any marker or position moves. Reset handlers are registered before App.Start, like event handlers, and a processor with a reset handler needs an event handler in it.

A reset handler clears the projections a replay will rebuild, so the replayed events apply
to empty state; it sees the target and the replay ranges of the reset.

func HandleSaga added in v0.7.0

func HandleSaga[S any](app *App, name string, define func(*SagaDefinition[S])) error

HandleSaga registers a saga named name, defined by define, to run in the default processor. The state S must encode to a JSON object and round-trip through the library's codec. A definition error names the saga and the handler; it is returned here and kept for App.Start like every other registration error. A name may be registered once.

A handler records what it sends through its SagaContext; the package-level Send, Query and Publish are refused with an error while a saga handler runs.

func HandleStream

func HandleStream[Q Message, T any](app *App, h func(context.Context, Q, *StreamWriter[T]) error, opts ...HandlerOption) error

HandleStream registers h as the handler of the streaming query type Q, by Q's MessageType: a request in mode STREAMING is answered by the items h sends with its StreamWriter, one ReplyPart each, numbered 1, 2, 3, ..., then one ReplyEnd when h returns (with h's error, as HandleQuery maps it, when it returns one). Q is registered in Register.query_types (with Shared, in Register.shared_query_types); a unary request of Q is answered INVALID_REQUEST.

The items go out under the caller's credit: StreamWriter.Send waits for credit, at most StreamCreditTimeout (10 minutes by default), after which the stream ends with TIMEOUT. When the hub cancels the stream (the caller stopped reading, a limit, the hub's idle timeout) or its hub stream is lost, h's context is cancelled, Send fails and nothing more is sent, whatever h returns. The request holds its handler slot and its permit until h returns.

Registration errors are those of HandleCommand. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Streaming).

func InvalidRequest

func InvalidRequest(msg string) error

InvalidRequest returns an error that a handler answers as INVALID_REQUEST.

func IsRetryable added in v0.7.0

func IsRetryable(err error) bool

IsRetryable reports whether err carries the retryable marker, locally (Retryable, a handler error whose details are the marker) or from a hub (an *Error's Details).

func IsUnknownOutcome added in v0.7.0

func IsUnknownOutcome(err error) bool

IsUnknownOutcome reports whether err carries the unknown-outcome marker, locally or from a hub.

func LetterID added in v0.2.0

func LetterID(processor, source, segment, position string) string

LetterID is a letter's id: "<processor>:<source>:<segment>:<position>" (on Kafka "<processor>:<topic>:<partition>:<offset>", as always).

func PermissionDenied

func PermissionDenied(msg string) error

PermissionDenied returns an error that a handler answers as PERMISSION_DENIED.

func ProcessorMarker added in v0.3.0

func ProcessorMarker(processor, eventID string) string

ProcessorMarker is the id of the stage-1 marker a processor records for the event with id eventID: "processor:<processor>:<eventId>". A marker recorded in the handler's transaction is what makes a redelivered event a duplicate.

func ProcessorSubscription added in v0.3.0

func ProcessorSubscription(service, processor string) string

ProcessorSubscription is the name a processor's subscription has on the event store: "<service>.<processor>". Every instance of the service joins it, so they share the processor's segments.

func Publish added in v0.3.0

func Publish[E Message](ctx context.Context, app *App, e E, opts ...PublishOption) error

Publish builds the event e and appends it to the service's outbox: the event type is E's MessageType, the id a fresh UUID, the key what Key set, the timestamp the creation time and the headers of messages.md: six headers plus traceparent when the work that publishes carries one (type, id, correlationId, timestamp, source and userId, and traceparent inside a trace). The append joins the transaction the context carries (the store's Begin or the add-on's own transaction helper), so the event commits with the service's writes or not at all. It returns once the entry is appended; the relay in every instance publishes it to the event store afterwards, at least once.

userId is the verified caller's subject for a command or a query; a token itself never crosses into an event. An event published while handling another message carries that message's correlation id and trace context, and the userId of the event being handled. Outside any handling the correlation id is a fresh UUID, the userId is empty and there is no traceparent.

Publishing needs the message store (WithStore) and the event store (WithEventStore): the first publish fails naming the missing add-on, since a service that only handles commands cannot be told apart from one that publishes at startup. See https://snodra.damoreira.com/docs/library-authors/messages/ (Event headers) and https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/ (The rule).

func Query

func Query[R any](ctx context.Context, app *App, q Message, opts ...SendOption) (R, error)

Query sends the query q through a hub to an instance that handles its type and returns the answer decoded as R. It fails as Send does; a query is also retried after an unknown outcome. A query of a type this instance handles itself, not Shared, is answered in-process as Send says; a shared one goes through a hub, which spreads it over every owner, this instance included.

func Retryable added in v0.7.0

func Retryable(err error) error

Retryable marks err as a failure a later attempt may cure: the answer is HANDLER_ERROR with details exactly `{"snodra":"retryable"}`. Use it in an idempotent adapter (or any handler whose failure the saga relay should retry) and do not retry inside the handler: the relay owns the backoff. A nil err still produces the marker with a generic message.

func SegmentOrder added in v0.2.0

func SegmentOrder(a, b string) int

SegmentOrder orders segment names as the hub lists them: names of ASCII digits only by their value (any length, no overflow; equal values by their text), before every other name, which go by their bytes. It returns a negative number when a comes first, zero when they are equal, and a positive number when b comes first.

func Send

func Send[R any](ctx context.Context, app *App, cmd Message, opts ...SendOption) (R, error)

Send sends the command cmd through a hub to the instance that handles its type and returns the handler's answer decoded as R (Empty for a command without a result).

A failed call is one of:

  • an *Error (test with errors.As): the hub's or the handler's answer, by its Code, or the library's own TIMEOUT when no answer came within the hub's bound for the request plus 1 s (a request still waiting in the library's buffer then is withdrawn and reported as TIMEOUT);
  • ErrNeverSent (test with errors.Is): no hub took the request within the call's timeout (5 s without one: a call made while no hub is acknowledged, or whose stream broke while the request was still in the library's buffer, waits for a hub and goes out on it), or the app is not started; the handler never saw it;
  • ErrOutcomeUnknown: the request was written, then its stream broke before the answer; the handler may or may not have run;
  • the context's error, when ctx ended first: with ErrOutcomeUnknown too once the request was written, else with ErrNeverSent;
  • ErrReservedHeader: a Header the library sets itself; nothing was sent;
  • another error for a local failure (the message cannot be encoded, the answer not decoded, an invalid option).

A deadline of ctx is the caller's timeout (see Timeout). Sent while handling a request (with the handler's ctx, or one derived from it), the request carries that request's correlation id, its authorization header (see ForwardJWT) and its valid traceparent; outside any handling it carries a new correlation id. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Requests).

A command of a type this instance handles itself is answered in-process, unless AlwaysRouteThroughHub is on: its handler runs on the caller's goroutine under ctx, with no hub, no permit and no handler slot (MaxConcurrent does not count it), also before App.Start and after App.Shutdown. The handler sees a request with a fresh id, the call's [Header]s and the correlation id (that of the request ctx is handling, else a new one); it acts for the caller the hub path would carry (that of the request ctx is handling when ForwardJWT is on; anonymous outside a handler or with it off), and its guards apply. RoutingKey, Timeout, Priority and retries do not apply, and the telemetry records nothing. Its error is the *Error the hub would have relayed (a panic is HANDLER_ERROR "handler panicked"); when ctx ended while the handler failed, ctx's error with ErrOutcomeUnknown, as for a written request.

func SendReply added in v0.10.0

func SendReply[R any](c *SagaContext, command Message, routingKey string) error

SendReply is SagaContext.Send for a command whose reply the caller names as R, so that the command is recorded with the response version of R, which routes it to the handlers that answer with that version. The response version is the one of the R of SendReply when given, else the one of this instance's handler of the command, else 1. The reply itself is never read: a saga learns the outcome from the events that follow.

// PlaceOrderReply is a message with MessageVersion() 3; another service handles PlaceOrder.
err := snodra.SendReply[PlaceOrderReply](saga, PlaceOrder{OrderID: id}, id)
// the command is recorded and later sent with snodra-response-schema-version: 3

func Stream

func Stream[T any](ctx context.Context, app *App, q Message, opts ...SendOption) iter.Seq2[T, error]

Stream streams the result of the streaming query q from one instance of its owner (HandleStream on the other side): ranging over the returned sequence sends one Request in mode STREAMING to one hub, unkeyed, and yields the handler's items, decoded as T, in the handler's order, until the hub's end. Nothing is sent until the range starts; each range sends the query anew.

for line, err := range snodra.Stream[OrderLine](ctx, app, ListOrders{}) {
	if err != nil {
		return err // the last thing the sequence yields
	}
	...
}

An error is the last thing the sequence yields: one of the errors of Query before the first item; after it, the hub's end with an error (an *Error by its code: the handler's error, the hub's idle timeout, HANDLER_DISCONNECTED, ...), ErrOutcomeUnknown when the hub stream was lost, ErrLostParts when the hub dropped items (a gap in the parts' numbers, or an end that counts more parts than arrived), the context's error (with ErrOutcomeUnknown), or an item that does not decode. Breaking out of the loop, an item that does not decode, lost parts and the local guard cancel the stream at the hub, which tells the handler.

The options are those of Query: Timeout (or DefaultTimeout, or ctx's deadline) is the idle timeout, the longest the hub waits for the next item, sent as Request.timeout_ms; the local guard waits the hub's bound plus 1 s between items and twice the bound plus 1 s for the first; InitialCredit is the credit window; MaxResults ends the stream after that many items; the retry policy applies until the first item (a retry is a new stream with a fresh id), never after it. RoutingKey is ignored: a stream goes to one hub, unkeyed. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Streaming).

func Supports added in v0.2.0

func Supports(store EventStore, capability Capability) bool

Supports reports whether store declares capability.

func Unauthenticated

func Unauthenticated(msg string) error

Unauthenticated returns an error that a handler answers as UNAUTHENTICATED.

func UnknownOutcome added in v0.7.0

func UnknownOutcome(err error) error

UnknownOutcome marks err as an external call whose outcome cannot be known: the answer is HANDLER_ERROR with details exactly `{"snodra":"unknown-outcome"}`, and a saga reports it as UNKNOWN_OUTCOME instead of retrying automatically. Use it when the request may or may not have reached the external system. A nil err still produces the marker with a generic message.

func VerifyWebhook added in v0.13.0

func VerifyWebhook(secret, previousSecret string, header http.Header, body []byte) bool

VerifyWebhook reports whether a partner's webhook request is signed with secret or, during a rotation, with previousSecret ("" is none). Either header verifies it:

The shared secret is checked first; when it does not match, the signature decides. Header names are case-insensitive, also in a header map built by hand. Every comparison is constant time. An empty secret is ignored: a service with none configured verifies nothing, not even an empty header or the HMAC under an empty key.

Verify the raw body bytes, before decoding them.

func WebhookHMACHex added in v0.13.0

func WebhookHMACHex(secret string, body []byte) (string, error)

WebhookHMACHex is the HMAC-SHA256 of body keyed by secret, in lower-case hex: what a partner sends in WebhookSignatureHeader. An empty secret is refused with an error wrapping ErrInvalid: it is no key, and VerifyWebhook never accepts a signature made with it.

func WithDetails

func WithDetails(err error, details any) error

WithDetails attaches details, marshalled with encoding/json, to err; the handler answers them as the error's details (sent only when the answer is HANDLER_ERROR: an error of InvalidRequest and the like keeps its code and loses the details). A nil err stays nil. Details that encoding/json cannot marshal are dropped: err is returned as it is.

Types

type AccessToken

type AccessToken struct {
	// Value is the token, as sent in Register.credentials.jwt.
	Value string
	// Expiry is when it stops being valid; the zero time is unknown, read as 60 s after the fetch.
	Expiry time.Time
}

AccessToken is a JWT the instance registers with, and when it expires. Printing it with %v, %+v, %#v or %s hides the token; %p and %w print the struct raw, and json.Marshal includes Value.

func (AccessToken) Format

func (t AccessToken) Format(f fmt.State, _ rune)

Format prints String for every verb that reaches a Formatter. %p and %w never reach it (fmt prints the struct raw for them, and go vet flags both), nor does encoding/json, which writes the exported fields.

func (AccessToken) LogValue

func (t AccessToken) LogValue() slog.Value

LogValue is String, for log/slog.

func (AccessToken) String

func (t AccessToken) String() string

String shows the expiry, never the token.

type App

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

App is one instance of a service on the hubs: it registers with every configured hub, keeps the streams alive and reconnects them until App.Shutdown.

func New

func New(opts ...Option) (*App, error)

New builds an App from opts; it connects to nothing before App.Start. It fails on missing or invalid settings (no service name, no hub, ...).

func (*App) HubIDs

func (a *App) HubIDs() []string

HubIDs are the RegisterAck.hub_id of every hub whose stream is acknowledged now, sorted (a second address of one hub, closed as a duplicate, is not among them; an empty hub_id reads as the hub's host:port).

func (*App) Ready

func (a *App) Ready(ctx context.Context) error

Ready waits until a hub has acknowledged the registration (its RegisterAck arrived). It returns ctx's error when ctx ends first, and an error when the app shuts down first.

func (*App) Rejection

func (a *App) Rejection() (Rejection, bool)

Rejection is the latest refusal of the Register by any hub, and false while none ever refused it. A later acceptance does not clear it.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run starts the app, waits for ctx to end, then shuts down within 15 s. It returns nil on a clean stop.

func (*App) Shutdown

func (a *App) Shutdown(ctx context.Context) error

Shutdown leaves the hubs in order: a Register with no types to every acknowledged hub (so it routes elsewhere at once), waiting at most 1 s for its acks; then every subscription served here completes with a ReplyEnd; then the handlers in flight finish (at most 5 s), the ends written meanwhile (waited for at most 2 s more); then each stream is half-closed and the hub gets at most 2 s to finish its side; then the relay, the event processors and the message store's background work stop (at most 5 s, and at most what is left of ctx's budget). Every wait is also bounded by ctx: when ctx ends first, the streams are dropped and ctx's error is returned, at most 50 ms after ctx's deadline (the time given to the dropped streams' goroutines to end). A second call waits for the first and returns its result. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Shutting down).

func (*App) Start

func (a *App) Start(ctx context.Context) error

Start opens a connection to every hub and returns at once; each connection registers and reconnects on its own until App.Shutdown. Handlers can no longer be registered after it. App.Ready waits for the first acknowledged hub. When a registration failed, Start returns every registration error, joined, and starts nothing.

ctx is checked on entry and bounds the message store's schema preparation when the store implements StoreLifecycle; it does not bound the app, and cancelling it later stops nothing. App.Shutdown stops the app; App.Run serves until its own context ends.

func (*App) SubscriptionsServed

func (a *App) SubscriptionsServed() int

SubscriptionsServed is how many subscriptions this instance serves now, those whose admission is still being decided included.

type Assigned added in v0.2.0

type Assigned struct {
	Segments []string
}

Assigned says these segments became this subscription's, in addition to the ones it has. A new subscription's first event is an Assigned, empty when it holds nothing.

type Caller

type Caller struct {
	// Subject is the token's sub claim.
	Subject string
	// Roles are read from the token's roles claim (see [RolesClaim]).
	Roles []string
}

Caller is who sent a request: the acting user of its forwarded token (the authorization header, "Bearer <JWT>"), verified against the issuer's keys (JWKS). Without a JWKS no token is an identity: every caller is anonymous. See https://snodra.damoreira.com/docs/library-authors/messages/ (Forwarded identity).

func CallerFrom

func CallerFrom(ctx context.Context) (Caller, bool)

CallerFrom returns who sent the request being handled, read from its forwarded token verified against the issuer's keys (JWKS), and false for an anonymous caller (no token, or no JWKS to verify it) and outside a handler. Do not change the returned Roles.

func (Caller) HasRole

func (c Caller) HasRole(role string) bool

HasRole reports whether the caller has role.

type Capability added in v0.2.0

type Capability string

Capability is what an event store offers beyond the required contract. It is reported to the hub as ProcessorStatus.capabilities.

const (
	// CapabilityReplay: reset to earliest, latest, a time or explicit positions, with reset
	// handlers and replay ranges (SubscriptionAdmin).
	CapabilityReplay Capability = "replay"
	// CapabilityBrowse: an event browser can read the store. The Go library has no event
	// browser, so its add-ons do not offer one; the capability still says another program
	// may read the store.
	CapabilityBrowse Capability = "browse"
	// CapabilityLag: how far a subscription is behind, per segment (SegmentStatus.Lag).
	CapabilityLag Capability = "lag"
	// CapabilityNativeDeadLetter: a dead-letter source (DeadLetterSource) for the
	// dead-letter mode that sends what a processor cannot handle to the event store.
	CapabilityNativeDeadLetter Capability = "native-dead-letter"
)

The capabilities the protocol names. An add-on may report others next to them.

func (Capability) String added in v0.2.0

func (c Capability) String() string

String returns the capability's protocol name ("replay", ...).

type ClientCredentials

type ClientCredentials struct {
	// TokenURL is the token endpoint, http:// or https:// (SNODRA_SERVER_OAUTH2_TOKEN_URI).
	TokenURL string
	// ClientID is the OAuth2 client; "" is the service name, which the hub requires as azp
	// (SNODRA_SERVER_OAUTH2_CLIENT_ID).
	ClientID string
	// ClientSecret is the client's secret (SNODRA_SERVER_OAUTH2_CLIENT_SECRET).
	ClientSecret string
	// ClientSecretFile is a file holding the secret, read at every fetch; it wins over
	// ClientSecret (SNODRA_SERVER_OAUTH2_CLIENT_SECRET_FILE).
	ClientSecretFile string
	// Scope is sent with the grant when set, space-separated (SNODRA_SERVER_OAUTH2_SCOPE).
	Scope string
	// CAFile is a PEM file of CA certificates trusted for the endpoint, beside the system's
	// (SNODRA_SERVER_OAUTH2_CA).
	CAFile string
}

ClientCredentials are the settings of an OAuth2 client-credentials grant (see NewClientCredentials). Printing it with %v, %+v, %#v or %s hides the secret; %p and %w print the struct raw, and json.Marshal includes ClientSecret.

func (ClientCredentials) Format

func (c ClientCredentials) Format(f fmt.State, _ rune)

Format prints String for every verb that reaches a Formatter. %p and %w never reach it (fmt prints the struct raw for them, and go vet flags both), nor does encoding/json, which writes the exported fields.

func (ClientCredentials) LogValue

func (c ClientCredentials) LogValue() slog.Value

LogValue is String, for log/slog.

func (ClientCredentials) String

func (c ClientCredentials) String() string

String shows the settings, never the secret.

type Code

type Code int32

Code is a protocol error code, with the numbers of the hub protocol. See https://snodra.damoreira.com/docs/library-authors/messages/.

const (
	CodeNoHandler           Code = 1
	CodeTimeout             Code = 2
	CodeHandlerDisconnected Code = 3
	CodeHandlerError        Code = 4
	CodeUnauthenticated     Code = 5
	CodeInvalidRequest      Code = 6
	CodePermissionDenied    Code = 7
	CodeResourceExhausted   Code = 8
	CodeCancelled           Code = 9
)

The error codes a call can fail with.

func (Code) String

func (c Code) String() string

String returns the protocol name of the code ("NO_HANDLER", ...).

type Config added in v0.3.0

type Config struct {
	// Service is the logical service name ([Service], SNODRA_SERVICE_NAME).
	Service string
	// EventsSource is the event store's source the service publishes to and its processors read
	// ([EventsSource], SNODRA_EVENTS_SOURCE).
	EventsSource string
}

Config is what a message store's StoreLifecycle sees of the application's configuration: the logical service name and the event source its processors read. It is read-only: a store copies what it needs and never changes it. Fields are added as settings a store uses appear (the retentions, for example); a store must not depend on the struct's size.

type ControlOperation added in v0.2.0

type ControlOperation struct {
	ID         string
	Kind       string
	LeaseUntil time.Time
	PreparedAt time.Time
}

ControlOperation is the lock of a reset: held until LeaseUntil unless renewed. PreparedAt is the first prepare's time; a renewal keeps it.

func (ControlOperation) HoldsAt added in v0.2.0

func (o ControlOperation) HoldsAt(now time.Time) bool

HoldsAt reports whether the lease has not passed at now.

type DeadLetter added in v0.2.0

type DeadLetter struct {
	ID        string
	Processor string
	// Source is the source the record was read from.
	Source string
	// Segment and Position are the record's place in it.
	Segment  string
	Position string
	// Key is the record's key as lossy UTF-8; nil when it had none.
	Key *string
	// EventID is the record's "id" header; empty when it had none or a blank one.
	EventID string
	// EventType is the record's "type" header; empty when it had none or a blank one.
	EventType string
	// Headers are every record header, lossy UTF-8.
	Headers map[string]string
	// Payload is the record's value, byte for byte.
	Payload []byte
	Reason  DeadLetterReason
	Error   DeadLetterError
	// BlockedBy is, for a SEQUENCED letter, the key's head letter when it was parked
	// (display only).
	BlockedBy string
	Attempts  int
	// ParkedAt and LastAttemptAt are the application's clock.
	ParkedAt      time.Time
	LastAttemptAt time.Time
	ExpireAt      time.Time
	Replay        bool
}

DeadLetter is one parked record. ID is "<processor>:<source>:<segment>:<position>" (LetterID), so parking a redelivered record finds the first letter. Segment and Position are the event store's opaque strings (decimal numbers for the stores shipped today).

An empty EventID, EventType, BlockedBy or Key means none; Payload is the record's value byte for byte, JSON or anything an INVALID record carried.

func (DeadLetter) DedupeID added in v0.2.0

func (l DeadLetter) DedupeID() string

DedupeID is the id the record's stage 1 is deduplicated by: its EventID, else (none or blank) "<source>-<segment>-<position>".

type DeadLetterError added in v0.2.0

type DeadLetterError struct {
	Type    string
	Message string
}

DeadLetterError is a letter's error: Type is the error variant's name and Message is cut to MaxDeadLetterErrorChars characters.

func InvalidDeadLetterError added in v0.2.0

func InvalidDeadLetterError(message string) DeadLetterError

InvalidDeadLetterError is an INVALID letter's error.

func NewDeadLetterError added in v0.2.0

func NewDeadLetterError(typeName, message string) DeadLetterError

NewDeadLetterError returns the error with message cut to MaxDeadLetterErrorChars characters.

func SequencedDeadLetterError added in v0.2.0

func SequencedDeadLetterError(headID string) DeadLetterError

SequencedDeadLetterError is a SEQUENCED letter's error, naming the key's head letter.

type DeadLetterReason added in v0.2.0

type DeadLetterReason string

DeadLetterReason is why a record was parked.

const (
	// DeadLetterHandlerFailed: stage 1 failed on every attempt.
	DeadLetterHandlerFailed DeadLetterReason = "HANDLER_FAILED"
	// DeadLetterSequenced: an earlier letter of the record's key was parked; stage 1 did not
	// run.
	DeadLetterSequenced DeadLetterReason = "SEQUENCED"
	// DeadLetterInvalid: the record cannot be handled (no type header, a value that is not a
	// JSON object); it blocks nothing and can only be discarded.
	DeadLetterInvalid DeadLetterReason = "INVALID"
)

The stored reasons.

func (DeadLetterReason) String added in v0.2.0

func (r DeadLetterReason) String() string

String returns the stored name ("HANDLER_FAILED", ...).

type DeadLetterStore added in v0.2.0

type DeadLetterStore interface {
	// Park inserts letter; ParkAlready when a letter of that id exists (a redelivery).
	Park(ctx context.Context, letter DeadLetter) (ParkResult, error)
	// Head is the id of the head letter of (processor, key): the earliest position among its
	// letters that are not INVALID (then the lowest id); ok is false when there is none.
	Head(ctx context.Context, processor, key string) (id string, ok bool, err error)
	// Earlier is the id of the earliest letter of (processor, key) at a position before
	// position that is not INVALID: what blocks a retry. ok is false when there is none.
	Earlier(ctx context.Context, processor, key, position string) (id string, ok bool, err error)
	// ParkedKeys is the keys with a letter (not INVALID) of processor on the given segments of
	// source; each key once, in no particular order, none for no segments.
	ParkedKeys(ctx context.Context, processor, source string, segments []string) ([]string, error)
	// Get returns the letter, or nil when there is none.
	Get(ctx context.Context, id string) (*DeadLetter, error)
	// List returns letters by ParkedAt, then id, every processor's when processor is empty, at
	// most limit when limit > 0.
	List(ctx context.Context, processor string, limit int) ([]DeadLetter, error)
	// Summaries returns every letter of processor, without its record, by position as Head
	// orders them, then id.
	Summaries(ctx context.Context, processor string) ([]DeadLetterSummary, error)
	// Count is how many letters there are; every processor's when processor is empty.
	Count(ctx context.Context, processor string) (int64, error)
	// Delete deletes the letter; false when there was none.
	Delete(ctx context.Context, id string) (bool, error)
	// DeleteIn deletes the letter in the transaction carried by ctx: a retry's, which commits
	// with the record's marker and its handlers' effects or not at all. False when there was
	// none.
	DeleteIn(ctx context.Context, id string) (bool, error)
	// RecordFailure records that a retry failed again: Attempts + 1, Error, LastAttemptAt =
	// now, reason HANDLER_FAILED, no BlockedBy any more. False when the letter is gone.
	RecordFailure(ctx context.Context, id string, failure DeadLetterError, now time.Time) (bool, error)
}

DeadLetterStore is the dead letters (mode collection). Every operation is a write of its own, outside any transaction, but a retry's DeleteIn.

type DeadLetterSummary added in v0.2.0

type DeadLetterSummary struct {
	ID       string
	Key      *string
	Position string
	Reason   DeadLetterReason
	ParkedAt time.Time
}

DeadLetterSummary is what DeadLetterStore.Summaries reads of a letter.

type DeadlineStatus added in v0.2.0

type DeadlineStatus string

DeadlineStatus is the lifecycle of a SagaDeadline; the values are the stored names.

const (
	// DeadlineScheduled: waiting for its due time.
	DeadlineScheduled DeadlineStatus = "SCHEDULED"
	// DeadlineFired: its handler ran.
	DeadlineFired DeadlineStatus = "FIRED"
	// DeadlineCancelled: it never fires.
	DeadlineCancelled DeadlineStatus = "CANCELLED"
)

type Delivery added in v0.2.0

type Delivery struct {
	// Segment is the segment of the source it was read from: a unit of order per key.
	Segment string
	// Position is its place in Segment; EventSubscription.Ack takes it.
	Position string
	// Key is the order key as published; nil for an event without one.
	Key *string
	// Headers are the headers as published, as UTF-8 text with one value per name.
	Headers map[string]string
	// Payload is the payload as published.
	Payload []byte
	// TimestampMs is when the event store appended it, epoch milliseconds (its own clock).
	TimestampMs int64
}

Delivery is one event a subscription delivers. Segment and Position are opaque strings of at most MaxSegmentBytes and MaxPositionBytes bytes that only the event store reads (decimal numbers on the stores shipped today); the core orders two positions of one segment only through EventStore.Compare.

type DispatchFailure added in v0.2.0

type DispatchFailure struct {
	Attempts *int
	Reason   FailureReason
	Message  string
	FailedAt time.Time
	NoticeAt *time.Time
}

DispatchFailure is how the dispatch relay gives an entry up: FailedAt, the reason and the message, with Attempts when non-nil (nil leaves the count unchanged), and a pending failure notice due at NoticeAt when non-nil (NoticePending true, NoticeAttempts 0): a command's failure has one, an event's none.

type DispatchKind added in v0.2.0

type DispatchKind string

DispatchKind says whether a saga dispatch entry is a command (through the hub or the service's own handler) or an event (through the outbox).

const (
	// DispatchCommand is a command.
	DispatchCommand DispatchKind = "COMMAND"
	// DispatchEvent is an event.
	DispatchEvent DispatchKind = "EVENT"
)

type Empty

type Empty struct{}

Empty is the result type of a command, which answers without a result. It encodes as {}.

type EnumValuer added in v0.8.0

type EnumValuer interface{ EnumValues() []string }

EnumValuer is the optional method of a string type that lists the values the type may hold, in declaration order, each once. The generated JSON Schema of a field of that type is a string enum. A type that is not a string type cannot have it, and a map cannot be keyed by such a type. See https://snodra.damoreira.com/docs/library-authors/contracts/.

type Error

type Error struct {
	Code    Code
	Message string
	Details json.RawMessage
	Detail  string
}

Error is an error answered by the hub or by a remote handler. Details holds the handler's machine-readable details (JSON), only for CodeHandlerError. Detail is the hub's own message of a CodeNoHandler that names the contracts that are live for the type ("no handler for orders.PlaceOrder (payload 1, response 1); live: (payload 2, response 2)"), else empty; Message stays the library's fixed text. See https://snodra.damoreira.com/docs/library-authors/messages/.

func (*Error) Error

func (e *Error) Error() string

Error returns "<CODE>: <Message>", and ": <Detail>" after it when there is one.

type EventOption added in v0.3.0

type EventOption func(*eventConfig)

An EventOption configures one event handler in HandleEvent: the processor it runs in (InProcessor).

func DisallowReplay added in v0.6.0

func DisallowReplay() EventOption

DisallowReplay keeps an event handler from running again when a reset replays the record: the handler runs for a live delivery, and not inside an open replay range. The stage-1 marker is still recorded and the record is still acknowledged, so the replay moves on. Every handler of the type but the ones marked this way runs; with every handler marked, the record is handled as a duplicate would be. A dead letter parked during a replay is retried as a replay too, so this handler stays out of that retry.

It is an EventOption of HandleEvent, like InProcessor:

snodra.HandleEvent[OrderPlaced](app, sendMail, snodra.InProcessor("mail"), snodra.DisallowReplay())

func InProcessor added in v0.3.0

func InProcessor(name string) EventOption

InProcessor runs the event handler in the named processor: its own subscription "<service>.<name>", its own stage-1 markers ("processor:<name>:<eventId>") and its own read of the events, so one event type handled in two processors reaches both and a failure in one does not affect the other. A name matches [a-z0-9][a-z0-9-]{0,47} (at most 48 characters) and is never "default", where handlers registered without this option run. Every instance of the service that runs the handler reads the processor's subscription; the instances share its segments.

type EventPublisher added in v0.2.0

type EventPublisher interface {
	// Name is the add-on's name ("kafka", "rabbitmq-streams", "memory" or a third party's),
	// reported to the hub as the processors' event store.
	Name() string
	// Publish appends event to event.Source and returns once the event store accepted it. Two
	// publishes of one key, the second called after the first returned, are delivered in that
	// order. It fails with ErrRejected when the event store will never take the event (the
	// relay gives it up at once), and with ErrFailed when another try may succeed. A context
	// that is done is returned as-is.
	Publish(ctx context.Context, event OutgoingEvent) error
}

EventPublisher is what an outbox relay needs of an event store: its name and the append of one event. EventStore embeds it.

type EventStore added in v0.2.0

type EventStore interface {
	EventPublisher
	// Capabilities is what the store offers beyond the required contract.
	Capabilities() []Capability
	// Subscribe joins spec as one more instance of its subscription. A context that is done is
	// returned as-is.
	Subscribe(ctx context.Context, spec SubscriptionSpec) (EventSubscription, error)
	// Admin is the reset side of spec, for a reset run while no instance reads it. It fails
	// with ErrUnsupported (an *UnsupportedError naming CapabilityReplay) when the store lacks
	// CapabilityReplay.
	Admin(spec SubscriptionSpec) (SubscriptionAdmin, error)
	// Compare orders two positions a and b of segment: a negative number when a comes first,
	// zero when they are equal, and a positive number when b comes first.
	Compare(segment, a, b string) int
}

EventStore is the event log a service publishes to and its event processors read from, one add-on per event store. The snodratest package checks the contract below; every operation keeps its meaning across the stores.

  • One subscription per processor: every SubscriptionSpec.Name receives every event of its source, whatever other processors and services do.
  • Competing instances: the EventSubscriptions of one name share its segments; adding one spreads them.
  • Order per key: events with the same key go to one segment and reach a processor in publish order.
  • At-least-once with acknowledgement: the core acknowledges after the handler and the processed-event marker committed; what was not acknowledged comes again, and the marker skips it.
  • Pause and resume: a subscription stops delivering without losing its place.
  • The headers: EventHeaders, and any other, travel as the event store's native metadata.

A new subscription name starts at the earliest position of every segment. Segments and positions are opaque strings of at most MaxSegmentBytes and MaxPositionBytes bytes; Compare is the only way the core orders two positions of one segment. Payloads are JSON bytes, carried as given.

type EventSubscription added in v0.2.0

type EventSubscription interface {
	// Next waits for the next assignment change or delivery. It returns when ctx is done
	// without losing anything: dropping a pending Next loses nothing.
	Next(ctx context.Context) (SubscriptionEvent, error)
	// Ack acknowledges the delivery at position of segment and every earlier one of that
	// segment: a later subscription of this name resumes after it. It may reach the event
	// store after the call returns; Close flushes it.
	Ack(segment, position string) error
	// Redeliver hands the delivery at position of segment out again, without leaving the
	// subscription; Next delivers it and that segment's later events again. Other segments are
	// unaffected.
	Redeliver(segment, position string) error
	// Pause stops delivering without losing the place: Next gives assignment changes only, and
	// a segment assigned while paused is paused at once. It is idempotent; called before the
	// first Next, nothing is ever delivered until Resume.
	Pause()
	// Resume delivers again from where the pause stopped. It is idempotent.
	Resume()
	// Segments is the segments assigned now, in SegmentOrder, with their positions and lag as
	// last known. It never blocks.
	Segments() []SegmentStatus
	// TakeError is the latest trouble the subscription recovered from by itself since the
	// last call, as text for the processor's status; it is empty when there was none. It never
	// blocks.
	TakeError() string
	// Close leaves the subscription after flushing the acknowledgements: its segments go to
	// the other subscriptions of the name. It is idempotent.
	Close(ctx context.Context) error
}

EventSubscription is one instance's subscription of a processor (EventStore.Subscribe). It is not the hub subscription query the root package's Subscription type represents.

  • Next drives it: nothing is delivered until Next is called, and the core keeps calling it while paused to keep the membership alive and report assignment changes.
  • Order per segment: a segment's events come in their order, each after the Assigned naming its segment and before any Revoked of it.
  • The first event is an Assigned (an empty one when the subscription holds no segment) within FirstAssignmentWithin of joining: an instance that joined and holds nothing is a member, idle, which the core reports running, never starting.
  • Every Revoked is followed by an Assigned (an empty one when nothing new comes): the assignment change is over only then.
  • At-least-once: an event is acknowledged with Ack after its handling committed; one not acknowledged comes again to the next subscription of the same name that gets its segment, or to this one after Redeliver.
  • A failure ends it: an error from Next means the subscription is broken; the caller closes it and subscribes again after a backoff.
  • The core serializes Pause, Resume, Segments and TakeError with Close: once Close returns, none of them is called again, and Close never runs beside one of them.

type ExternalCall added in v0.2.0

type ExternalCall struct {
	Key      string
	Status   ExternalCallStatus
	Reply    string
	Error    string
	Attempts int
	// UpdatedAt, LeaseUntil are the caller's clock; a zero LeaseUntil means none.
	UpdatedAt  time.Time
	LeaseUntil time.Time
	Owner      string
}

ExternalCall is the record of one idempotent external call. Reply is the JSON text of the handler's reply, Error the JSON text of a failed call's error ({"code","message"}); an empty string means none. An InProgress record holds Owner (the running call's random token) and a LeaseUntil; a settled one holds neither.

type ExternalCallStatus added in v0.2.0

type ExternalCallStatus string

ExternalCallStatus is where an external call stands; the values are the stored names.

const (
	// ExternalCallInProgress: the call is running under its owner's lease.
	ExternalCallInProgress ExternalCallStatus = "IN_PROGRESS"
	// ExternalCallSucceeded: the call returned Reply and is never repeated.
	ExternalCallSucceeded ExternalCallStatus = "SUCCEEDED"
	// ExternalCallFailed: the call failed permanently, with Error.
	ExternalCallFailed ExternalCallStatus = "FAILED"
	// ExternalCallUnknown: the call may or may not have happened.
	ExternalCallUnknown ExternalCallStatus = "UNKNOWN"
)

func (ExternalCallStatus) String added in v0.2.0

func (s ExternalCallStatus) String() string

String returns the stored name ("IN_PROGRESS", ...).

type ExternalCallStore added in v0.2.0

type ExternalCallStore interface {
	// Insert inserts call; false when a record of its key exists.
	Insert(ctx context.Context, call ExternalCall) (bool, error)
	// Find returns the record of key, or nil when there is none.
	Find(ctx context.Context, key string) (*ExternalCall, error)
	// TakeOver takes the lapsed call seen over for owner: Owner, LeaseUntil, UpdatedAt = now
	// and Attempts + 1, when the record is still seen; the record as written, nil when it is
	// not.
	TakeOver(ctx context.Context, seen ExternalCall, owner string, leaseUntil, now time.Time) (*ExternalCall, error)
	// Expire gives the lapsed call seen up as UNKNOWN (no owner, no lease), when the record is
	// still seen.
	Expire(ctx context.Context, seen ExternalCall, now time.Time) (bool, error)
	// Succeed settles the record owner owns as SUCCEEDED with reply (and no error, owner or
	// lease).
	Succeed(ctx context.Context, key, owner, reply string, now time.Time) (bool, error)
	// Fail settles the record owner owns as FAILED with errText (no owner or lease).
	Fail(ctx context.Context, key, owner, errText string, now time.Time) (bool, error)
	// MarkUnknown settles the record owner owns as UNKNOWN (no owner or lease).
	MarkUnknown(ctx context.Context, key, owner string, now time.Time) (bool, error)
	// Reset deletes the record owner owns (a retryable failure: the next call begins afresh).
	Reset(ctx context.Context, key, owner string) (bool, error)
}

ExternalCallStore is the records of idempotent external calls, keyed by their idempotency key. Every operation is a write of its own, outside any transaction (a rolled-back handler never forgets a call that happened); the times are the caller's clock.

Every write after Insert matches the record a call owns (its key, InProgress and its Owner) or the record a call read (its key, InProgress, Owner and LeaseUntil as read), so a call whose lease ran out never overwrites the record of the call that took it over; false (or nil) when nothing matched.

type FailureReason added in v0.2.0

type FailureReason string

FailureReason is why a saga command failed (the retry taxonomy), stored by name.

const (
	// FailureNoHandler: nobody handles the command type.
	FailureNoHandler FailureReason = "NO_HANDLER"
	// FailureDenied: the handler requires an authenticated caller and a saga command has none.
	FailureDenied FailureReason = "DENIED"
	// FailureInvalid: the handler could not read the payload.
	FailureInvalid FailureReason = "INVALID"
	// FailureFailed: the handler failed (any other error).
	FailureFailed FailureReason = "FAILED"
	// FailureUnknownOutcome: an idempotent adapter crashed mid-call and cannot tell whether the
	// call happened.
	FailureUnknownOutcome FailureReason = "UNKNOWN_OUTCOME"
	// FailureExhausted: a transient failure persisted through all the relay's attempts.
	FailureExhausted FailureReason = "EXHAUSTED"
)

func (FailureReason) String added in v0.2.0

func (r FailureReason) String() string

String returns the stored name ("NO_HANDLER", ...).

type Gathered

type Gathered[R any] struct {
	// Parts holds one entry per answer, in arrival order, failed ones included.
	Parts []Part[R]
	// Targets is the parts the hub sent plus TimedOut: how many targets the gather had when it
	// ended at its deadline or with every target answered. When [MaxResults] ended it, the hub
	// cancels the targets still working and counts them nowhere (TimedOut is 0): 5 targets and
	// MaxResults(2) give Targets 2.
	Targets int
	// Failed counts the Parts whose Err is set.
	Failed int
	// TimedOut counts the targets that had not answered by the deadline (no part for them).
	TimedOut int
}

Gathered is everything a Gather got by the hub's end.

func Gather

func Gather[R any](ctx context.Context, app *App, q Message, opts ...SendOption) (*Gathered[R], error)

Gather asks every live instance of every owner of the query type of q (a scatter-gather) and collects their answers until the hub's end. Partial answers are answers: a gather where some targets failed or timed out still succeeds, and Gathered says what was missing.

The options are those of Query: Timeout (or ctx's deadline, or DefaultTimeout) is the deadline of the whole gather, after which the targets that have not answered count as TimedOut; MaxResults ends it after that many successful parts; Retry applies to the whole gather (a retry sends a new gather and collects from scratch). RoutingKey is ignored: the gather goes to one hub, unkeyed.

A failed call is one of the errors of Send: an *Error for a failure of the whole gather (NO_HANDLER when the type has no live target, INVALID_REQUEST for a command type, an end that carries an error, whose parts are dropped, the library's own TIMEOUT when the hub's end did not come within the hub's bound plus 1 s), ErrNeverSent, ErrOutcomeUnknown (the hub stream broke before the end: the parts received are dropped), the context's error, or a local failure. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Scatter-gather).

type Gauges

type Gauges struct {
	// HandlersInFlight is the requests from the hubs whose handler runs now (or waits for a
	// handler slot).
	HandlersInFlight int64
	// ConnectedHubs is the hubs with an acknowledged stream.
	ConnectedHubs int64
}

Gauges are the library's gauges at one moment.

type GaugesStopper

type GaugesStopper interface {
	StopObservingGauges()
}

A GaugesStopper is an Instrumentation that wants to know when the gauges it was given by ObserveGauges end: App.Shutdown calls StopObservingGauges once, as it finishes, and the read function it was given reads zeros from then on. One Instrumentation serves one App.

type HandlerOption

type HandlerOption func(*handlerConfig)

A HandlerOption configures one handler in HandleCommand, HandleQuery, HandleStream or HandleSubscription: its guards (RequireAuthenticated, RequireRole, RequireCaller) and, for a query, a streaming query or a subscription query, Shared; ExternalIdempotent applies to an idempotent command.

func ExternalIdempotent added in v0.7.0

func ExternalIdempotent() HandlerOption

ExternalIdempotent says the external partner de-duplicates by the idempotency key. A lapsed IN_PROGRESS call (its lease ran out) is then taken over and its body retried; without it, the outcome is unknown and the body is not run again. It applies to HandleIdempotentCommand.

func RequireAuthenticated

func RequireAuthenticated() HandlerOption

RequireAuthenticated lets only a caller with a verified token run the handler: a request without one is answered UNAUTHENTICATED, decided before the payload is decoded. Every guard needs JWKS: registering a guarded handler without it is an error, and App.Start fails.

func RequireCaller

func RequireCaller(allow func(Caller) bool) HandlerOption

RequireCaller lets only a caller allow accepts run the handler: an anonymous caller is answered UNAUTHENTICATED before the payload is decoded, a caller allow refuses PERMISSION_DENIED once it decoded. When a handler has several of these options, every one must accept. The Caller is read from the token's verified claims; it needs JWKS.

func RequireRole

func RequireRole(role string) HandlerOption

RequireRole lets only a caller with role run the handler: an anonymous caller is answered UNAUTHENTICATED before the payload is decoded, a caller without the role PERMISSION_DENIED once it decoded (a payload that does not decode is INVALID_REQUEST for any caller with a token). The roles come from the token's verified claims (see RolesClaim); it needs JWKS.

func Shared

func Shared() HandlerOption

Shared registers a query type as shared (Register.shared_query_types): many services may own it, each answering point queries on it like any query, and a Gather asks every instance of every owner. Every owner must register it shared: the hub refuses a type one registrant lists as exclusive and another as shared. A streaming query (HandleStream) may be shared too, and so may a subscription query (HandleSubscription): a subscription then reaches every instance of every owner. Commands are never shared: HandleCommand with Shared returns an error. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Shared query types).

type Handling

type Handling struct {
	// Type is the message type, for example "orders.PlaceOrder".
	Type string
	// Kind is "command" or "query".
	Kind string
	// Traceparent is the request's traceparent header when it is a valid W3C one, else "".
	Traceparent string
	// Tracestate is the request's tracestate header, only with a valid Traceparent.
	Tracestate string
}

Handling describes a request a handler is about to handle.

type IngressOption added in v0.13.0

type IngressOption func(*ingressConfig)

IngressOption sets an optional part of one AcceptExternal call.

func IngressHeaders added in v0.13.0

func IngressHeaders(headers map[string]string) IngressOption

IngressHeaders are extra message headers the handlers and sagas see with the event (a saga's association may read them). A non-blank "correlationId" among them is the event's correlation id. The library's own headers (id, type, source, snodra-schema-version, and userId, always empty) replace any of the same name: an event from outside has no caller, so a partner's headers passed on here can never name the user the handlers' published events act for.

type IngressResult added in v0.13.0

type IngressResult int

IngressResult is what AcceptExternal did with an event from outside. Its zero value is neither result: it is what a call that failed returns with its error.

const (
	// IngressAccepted: the event was applied now, or this service will never apply it (nobody
	// handles it, or it is another version of its type). Answer the partner with a success.
	IngressAccepted IngressResult = iota + 1
	// IngressDuplicate: an earlier call with the same source and dedupe key already applied it.
	// Answer the partner with a success too.
	IngressDuplicate
)

func AcceptExternal added in v0.13.0

func AcceptExternal[E Message](ctx context.Context, app *App, source, dedupeKey string, event E, opts ...IngressOption) (IngressResult, error)

AcceptExternal applies event, taken in from outside the suite (a partner's webhook, for example), to this service once for source and dedupeKey: its event handlers, then its sagas, synchronously, each in the transactions of an ordinary event; when it returns they have committed. The event is never published to the event store. Verify the request first (see VerifyWebhook) and decode its body into event.

The event's id is the dedupe id "<source>:<dedupeKey>": use the partner's own delivery or event id, stable across its retries, as dedupeKey. The handlers see that id as the message id and in the "id" header, source in the "source" header, the event's type and the version of E's type, and as the correlation id the "correlationId" header of IngressHeaders, else the dedupe id. There is no caller: the "userId" header is empty, so an event a handler publishes acts for no user. The processors' and the sagas' markers are keyed by that id, so the same event is applied once however often the partner sends it.

It returns IngressDuplicate when an earlier call with the same source and dedupe key already returned (the marker "ingress:<source>:<dedupeKey>" in the processed-event store, recorded after the dispatch succeeded), else IngressAccepted. Two simultaneous deliveries of one key may both dispatch; the markers make the second a no-op and only one of them is told IngressAccepted (with a store that refuses the second marker while the first is written, the second gets a conflict error instead, which a retry turns into IngressDuplicate). An event is never applied twice and never marked without its effects. An event nobody handles is IngressAccepted, logged at warn, with no marker: the partner must not retry what this service will never use. An event of another version of its type than this service's handlers and sagas consume is skipped: IngressAccepted, logged at info at most once a minute per source, type and version.

A handler failure is returned after the other processors and the sagas ran, and leaves no marker: answer the partner with a server error, its retry is applied then. A blank source or dedupeKey, and the reserved source names "failed", "ingress", "processor" and "saga" (they would collide with the library's marker families), are refused with an error wrapping ErrIngressRefused before anything runs. It needs a message store (WithStore) and a started app. With an error, the result is the zero IngressResult, neither accepted nor duplicate.

func (IngressResult) String added in v0.13.0

func (r IngressResult) String() string

String returns "ACCEPTED" or "DUPLICATE".

type Instrumentation

type Instrumentation interface {
	// RequestDone records one Send or Query call of msgType through the hubs, from the call to
	// its result with every retry included; a call its caller cancels (context.Canceled), one its
	// options refuse and one answered in-process are not reported.
	// kind is "command" or "query"; outcome is "ok", "no_handler", "timeout",
	// "handler_disconnected", "resource_exhausted", "handler_error", "denied",
	// "invalid_request" (also an answer that does not decode),
	// "cancelled" (the hub's CANCELLED), "unavailable" (no hub took the request, or its
	// stream broke before the answer) or "error".
	RequestDone(kind, msgType, outcome string, took time.Duration)
	// TokenFetched records one fetch of an access token by [NewClientCredentials]: result is
	// "ok", "http_error" (a non-success status without an OAuth2 error body), "oauth_error" (an
	// OAuth2 error body), "io_error" (the request did not complete, or the secret could not be
	// read) or "bad_response" (a success answer that is no usable token response).
	TokenFetched(result string)
	// CertificateRotated records a client certificate pair presented to a hub after another one
	// before it.
	CertificateRotated()
	// CredentialsRefreshSent records a credentials refresh written to a hub stream.
	CredentialsRefreshSent()
	// ObserveGauges is called once, by [App.Start]: read returns the library's gauges as they
	// are now, from memory; call it whenever the gauges are collected. It is safe to call from
	// any goroutine. ObserveGauges itself must return without calling [App.Shutdown]: a
	// Shutdown waits for it to return, so it would never end.
	ObserveGauges(read func() Gauges)
	// StartHandling starts the handling of a request by a handler of this instance, before
	// the handler runs. The context it returns is the handler's (a span can live in it, and
	// the requests the handler sends carry it to Inject); the function it returns is called
	// once when the handler is done, with its error (nil on success).
	StartHandling(ctx context.Context, h Handling) (context.Context, func(err error))
	// Inject lets the implementation put the trace context of ctx on the headers of a request
	// about to be sent: it may set "traceparent" and "tracestate" in headers. Any other key,
	// and a "traceparent" that is not a valid W3C one, is ignored.
	Inject(ctx context.Context, headers map[string]string)
}

Instrumentation is where the library reports what it does: request timings, token fetches, certificate rotations, credential refreshes, two gauges and the handling of a request, for metrics and traces. The default is NopInstrumentation; the observability module of this repository implements it on OpenTelemetry (see Telemetry).

Every method runs on a hot path of the library: an implementation must return quickly and never block. A panic in one is recovered and logged once; the library goes on without it. Every label value comes from a bounded set (a kind, a registered type, an outcome), never an id. Embed NopInstrumentation in an implementation: it can then implement only some of the methods, and a method added to this interface later does not break it.

type LockOutcome added in v0.2.0

type LockOutcome struct {
	// Taken: the operation holds (or renewed) the lock.
	Taken bool
	// Holder is the other operation holding the lock when Taken is false.
	Holder ControlOperation
}

LockOutcome is what ProcessorControlStore.Lock reports.

type MemoryEventStore added in v0.2.0

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

MemoryEventStore is the in-memory event store: the whole event-store contract inside one process, for tests, local runs and single-process demos, with no infrastructure.

  • Every source is a log of a fixed number of segments (DefaultMemoryEventStoreSegments by default), named "0" to "n-1". An event's key goes to segment FNV-1a 64 of the key's UTF-8 bytes, unsigned, modulo the segments; an event without a key goes round the segments from "0". A position is the decimal index of a segment's event, from "0".
  • A subscription per name is shared by every Subscribe of that name in the process (competing instances): its segments are spread over its members, and a segment moves to another member only after the one holding it saw it revoked (its next Next) or closed. Close is the only way to give a segment up; Go has no drop notification. The committed positions are kept per name in memory.
  • Capabilities are CapabilityReplay and CapabilityLag; not CapabilityNativeDeadLetter (the dead letters stay in the message store) and not CapabilityBrowse (this library has no event browser).
  • It is not durable: it keeps every event it is given until the process ends, and loses them all then. Bounding what it holds is the caller's concern (a test, a demo); the service's builder warns at startup that it is not durable.
  • Every reference to one MemoryEventStore is that event store: hand the same one to each service instance of a test to make them compete. Use the pointer the constructor returns; do not copy the struct.

A MemoryEventStore is safe for concurrent use.

func NewMemoryEventStore added in v0.2.0

func NewMemoryEventStore() *MemoryEventStore

NewMemoryEventStore returns an in-memory event store with DefaultMemoryEventStoreSegments segments per source.

func NewMemoryEventStoreWithSegments added in v0.2.0

func NewMemoryEventStoreWithSegments(segments int) (*MemoryEventStore, error)

NewMemoryEventStoreWithSegments returns an in-memory event store with segments per source, from 1 to MaxMemoryEventStoreSegments. It fails with ErrInvalid for a number out of bounds.

func (*MemoryEventStore) Admin added in v0.2.0

Admin returns the reset side of spec. The in-memory store declares CapabilityReplay, so it always offers one.

func (*MemoryEventStore) Capabilities added in v0.2.0

func (s *MemoryEventStore) Capabilities() []Capability

Capabilities returns what the memory store offers: replay and lag. Like the reference in-memory event stores, it does not declare native-dead-letter, so the event-store dead-letter mode needs a durable event store (or a test store that declares the capability). A fresh slice is returned on every call.

func (*MemoryEventStore) Compare added in v0.2.0

func (s *MemoryEventStore) Compare(segment, a, b string) int

Compare orders two positions of one segment. Positions are decimal indexes; anything else is ordered as a segment name would be, so Compare is total and never panics.

func (*MemoryEventStore) Events added in v0.2.0

func (s *MemoryEventStore) Events(source string) []Delivery

Events returns every event of source so far, as a subscription would deliver it, in append order: what a test reads back. It is empty for a source nothing was published to. It is not part of the EventStore contract.

func (*MemoryEventStore) Name added in v0.2.0

func (s *MemoryEventStore) Name() string

Name returns "memory".

func (*MemoryEventStore) Publish added in v0.2.0

func (s *MemoryEventStore) Publish(ctx context.Context, event OutgoingEvent) error

Publish appends event at once. An event without a source fails with ErrRejected. The store keeps its own copies of the key, headers and payload.

func (*MemoryEventStore) Subscribe added in v0.2.0

Subscribe joins spec at once. It fails with ErrInvalid for an empty name or source.

type MemoryMessageStore added in v0.2.0

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

MemoryMessageStore is the in-memory message store: the whole message-store contract inside one process, for tests, local runs and single-process demos, with no database and no infrastructure. It implements the outbox, the processed-event markers, the dead letters, the processors' control state, the external calls and the saga ports.

  • Real transactions: Begin hands out a transaction that collects its writes; other readers see them only once it commits, and a rollback leaves nothing. Reads in the transaction see its own writes. A transaction reserves every record it writes: a second live transaction writing one of them fails at once with ErrConflict, and a commit fails with ErrConflict when a record it wrote changed meanwhile (a write outside any transaction). What runs outside a transaction commits at once. A transaction must always end with Commit or Rollback: one abandoned without either keeps its reservations until the process ends.
  • Claims and leases are atomic: of two claimers, one wins. The times the store stamps itself are the application's clock (UseClock); until it is set, the wall clock.
  • A committed outbox append calls every OnAppend waker, so the relay publishes at once rather than at its next poll.
  • It has no schema and nothing in the background: StoreLifecycle's InitSchema and CheckSchema do nothing, and Background waits for the app to end.
  • A dead letter whose ExpireAt passed is removed before any dead-letter call reads the letters, as a database's TTL would (the store's own clock, UseClock). Nothing else is ever deleted but what the explicit Purge and DeleteMarkers calls remove: it keeps everything else it is given until the process ends. It is not durable: one process, everything lost when it ends. A service builder warns at startup that it is not durable.

Every reference to one MemoryMessageStore is that store. Do not copy the struct; use the pointer the constructor returns.

A MemoryMessageStore is safe for concurrent use.

func NewMemoryMessageStore added in v0.2.0

func NewMemoryMessageStore() *MemoryMessageStore

NewMemoryMessageStore returns an empty in-memory message store.

func (*MemoryMessageStore) Background added in v0.3.0

func (s *MemoryMessageStore) Background(ctx context.Context) error

Background runs nothing: it waits until ctx is done, as the lifecycle's background work lives as long as the app.

func (*MemoryMessageStore) Begin added in v0.2.0

Begin starts a transaction and returns a context that carries it.

func (*MemoryMessageStore) CheckSchema added in v0.3.0

func (s *MemoryMessageStore) CheckSchema(context.Context) error

CheckSchema does nothing: the in-memory store needs no schema.

func (*MemoryMessageStore) Control added in v0.2.0

Control returns the processors' control state.

func (*MemoryMessageStore) DeadLetters added in v0.2.0

func (s *MemoryMessageStore) DeadLetters() DeadLetterStore

DeadLetters returns the dead letters.

func (*MemoryMessageStore) ExternalCalls added in v0.2.0

func (s *MemoryMessageStore) ExternalCalls() ExternalCallStore

ExternalCalls returns the external-call port.

func (*MemoryMessageStore) InitSchema added in v0.3.0

func (s *MemoryMessageStore) InitSchema(context.Context, *Config) error

InitSchema does nothing: the in-memory store needs no schema.

func (*MemoryMessageStore) Name added in v0.2.0

func (s *MemoryMessageStore) Name() string

Name returns "memory".

func (*MemoryMessageStore) Outbox added in v0.2.0

func (s *MemoryMessageStore) Outbox() OutboxStore

Outbox returns the outbox.

func (*MemoryMessageStore) Processed added in v0.2.0

func (s *MemoryMessageStore) Processed() ProcessedStore

Processed returns the processed-event markers.

func (*MemoryMessageStore) Sagas added in v0.2.0

func (s *MemoryMessageStore) Sagas() SagaStores

Sagas returns the saga ports.

func (*MemoryMessageStore) UseClock added in v0.2.0

func (s *MemoryMessageStore) UseClock(now func() time.Time)

UseClock sets the application's clock: what the store stamps the times it sets itself with (an outbox entry's sending, a claim's lease). A nil clock restores the wall clock. The clock must not call the store.

type Message

type Message interface{ MessageType() string }

Message is a typed message of the Snodra messaging suite. Its wire name (for example "orders.PlaceOrder") is the type every handler registers for and every sender addresses. The method may have a value or a pointer receiver. See https://snodra.damoreira.com/docs/library-authors/messages/.

type MessageInfo

type MessageInfo struct {
	// ID is the forwarded Request.id: the sender's id for a command or a point query, a
	// derived one ("<id>#<n>") for the multi-part modes. Never use it to detect a retried
	// command: a retry has a fresh id.
	ID string
	// Type is the message type, for example "orders.PlaceOrder".
	Type string
	// CorrelationID is the request's correlationId header, else (no such header) its ID. It is
	// empty when the header is present but empty; the requests sent while handling then carry a
	// new correlation id.
	CorrelationID string
	// Headers are the request's headers, as the hub forwarded them.
	Headers map[string]string
}

MessageInfo describes the request a handler is handling.

func MessageFrom

func MessageFrom(ctx context.Context) (MessageInfo, bool)

MessageFrom returns what the handler's context says of the request being handled, and false outside a handler.

type MessageStore added in v0.2.0

type MessageStore interface {
	// Name is the add-on's name ("mongo", "postgres", "mysql", "memory" or a third party's),
	// for logs and the startup report.
	Name() string
	// Begin starts a transaction. The returned context carries it: Outbox.Append and
	// Processed.Record called with it join the transaction, and so do the service's own writes
	// through the add-on's own transaction helper. Commit writes everything or nothing;
	// Rollback discards it. A context that carries no transaction (context.Background(), say) is
	// the plain case: the writes run in a short transaction of their own.
	Begin(ctx context.Context) (context.Context, Tx, error)
	// Outbox is the events appended in the service's transaction and relayed afterwards.
	Outbox() OutboxStore
	// Processed is the processed-event markers, the stage-1 marker included.
	Processed() ProcessedStore
	// DeadLetters is what exhausted its attempts (the collection mode).
	DeadLetters() DeadLetterStore
	// Control is the processors' pause, reset lock and replay ranges.
	Control() ProcessorControlStore
	// ExternalCalls is the idempotency records of external calls.
	ExternalCalls() ExternalCallStore
	// Sagas is the six saga ports.
	Sagas() SagaStores
}

MessageStore is the add-on: every store the library uses in the service's own database.

type NopInstrumentation

type NopInstrumentation struct{}

NopInstrumentation is the default Instrumentation: it does nothing, at no cost. Embed it to implement only some of the methods.

func (NopInstrumentation) CertificateRotated

func (NopInstrumentation) CertificateRotated()

func (NopInstrumentation) CredentialsRefreshSent

func (NopInstrumentation) CredentialsRefreshSent()

func (NopInstrumentation) Inject

func (NopInstrumentation) ObserveGauges

func (NopInstrumentation) ObserveGauges(func() Gauges)

func (NopInstrumentation) RequestDone

func (NopInstrumentation) StartHandling

func (NopInstrumentation) StartHandling(ctx context.Context, _ Handling) (context.Context, func(error))

func (NopInstrumentation) TokenFetched

func (NopInstrumentation) TokenFetched(string)

type Option

type Option func(*config) error

An Option configures an App in New. Options apply in order: a later one overrides an earlier one, FromEnv included.

func AlwaysRouteThroughHub

func AlwaysRouteThroughHub(on bool) Option

AlwaysRouteThroughHub, when on, sends every Send and Query through a hub, also those of a type this instance handles itself (SNODRA_SERVER_ALWAYS_ROUTE_THROUGH_HUB with FromEnv). Off, the default, a command, or a query that is not Shared, of a type registered here is answered in-process: its handler runs on the caller's goroutine, without a hub, a permit or a handler slot (see Send). Turn it on where every request must be seen by the hubs (routing-key affinity across instances, a conformance or an interoperability test). Gather, Stream and Subscribe always go through a hub. The library has no mode without hubs, so the option always applies.

func ClientCertificate

func ClientCertificate(certFile, keyFile string) Option

ClientCertificate makes the instance present a client certificate to the hubs (mutual TLS): certFile holds the chain, leaf first, keyFile its private key (PEM). It implies TLS (with the system's roots unless TLS is set). The leaf must carry exactly one URI SAN snodra://service/<name> naming the service; New checks the pair. The files are read at every connection and every 3 s: a renewed valid pair is rolled over to before the presented certificate's notAfter (when the hub closes the session), one hub at a time, after a random delay of at most a tenth of the presented certificate's remaining validity (at most 30 s). A pair that cannot be used keeps the one presented.

func Codec

func Codec(c PayloadCodec) Option

Codec is the payload codec of every handler and send; the default is JSON. Every library of the suite reads and writes JSON payloads (https://snodra.damoreira.com/docs/library-authors/messages/): change it only for a codec that writes the same JSON.

func ConsumerEnabled added in v0.3.0

func ConsumerEnabled(on bool) Option

ConsumerEnabled says whether the instances read their event processors' subscriptions (SNODRA_CONSUMER_ENABLED). On by default; a tool that only publishes turns it off.

func DeadLetterMode added in v0.6.0

func DeadLetterMode(mode string) Option

DeadLetterMode says where a record its processor cannot handle goes (SNODRA_DEAD_LETTER_MODE): DeadLetterModeCollection (the default: park it in the message store's dead letters), DeadLetterModeEventStore (publish it to the event store's dead-letter source, which needs an event store with CapabilityNativeDeadLetter) or DeadLetterModeLog (log it and skip it).

func DefaultRetry

func DefaultRetry(p RetryPolicy) Option

DefaultRetry is the retry policy of every call (Send, Query, Gather, Stream, Subscribe) that sets none with Retry or NoRetry. The default is no retry; RetryNeverRan is the usual policy.

func DefaultTimeout

func DefaultTimeout(d time.Duration) Option

DefaultTimeout is the timeout of every call (Send, Query, Gather, Stream, Subscribe) that sets none with Timeout (sent as Request.timeout_ms; for a Stream, the longest wait for its next part). The default is none (0): the hub applies its per-type override or its default request timeout, which is what the protocol asks for.

func EventsSource added in v0.3.0

func EventsSource(source string) Option

EventsSource is the event store's source the service publishes its events to and its processors read (SNODRA_EVENTS_SOURCE). The default is DefaultEventsSource, "snodra.events".

func ForwardJWT

func ForwardJWT(on bool) Option

ForwardJWT says whether a request sent while handling one carries the handled request's authorization header on, so that the downstream handler acts for the same user. The default is true.

func FromEnv

func FromEnv() Option

FromEnv reads the settings from the environment. A variable that is not set, or blank, changes nothing; a later option overrides what FromEnv set.

  • SNODRA_SERVICE_NAME: Service
  • SNODRA_INSTANCE_ID: Instance (default: a fresh random UUID)
  • SNODRA_SERVER_ADDRESS: Hubs, a comma-separated list of host:port ("static://" optional), or one dns:///name:port (default "static://snodra-server:7000" when no hub is configured yet)
  • SNODRA_SERVER_STATUS_INTERVAL_MS: StatusInterval in milliseconds, at least 1 (default 5000)
  • SNODRA_MAX_CONCURRENT_HANDLERS: MaxConcurrent (default 256)
  • SNODRA_RECONNECT_BACKOFF_MIN_MS, SNODRA_RECONNECT_BACKOFF_MAX_MS: ReconnectBackoff in milliseconds (default 500 and 5000)
  • SNODRA_SERVER_LOAD_FACTOR: LoadFactor (default 100)
  • SNODRA_SERVER_TAGS: Tags as "key=value,key=value"
  • SNODRA_SERVER_REQUEST_TIMEOUT_MS: DefaultTimeout in milliseconds (0, the default: none)
  • SNODRA_SERVER_PRIORITIES: Priorities as "type=n,type=n"
  • SNODRA_SERVER_STREAM_CREDIT_TIMEOUT_MS: StreamCreditTimeout in milliseconds, at least 1 (default 600000, 10 minutes)
  • SNODRA_SERVER_MAX_SUBSCRIPTIONS: MaxSubscriptions, at least 1 (default 1024)
  • SNODRA_SERVER_RETRY_ENABLED: true sets DefaultRetry to the policy of SNODRA_SERVER_RETRY_MAX_ATTEMPTS (default 3, at least 1), SNODRA_SERVER_RETRY_INITIAL_BACKOFF_MS (100), SNODRA_SERVER_RETRY_MULTIPLIER (2, a finite number of at least 1) and SNODRA_SERVER_RETRY_MAX_BACKOFF_MS (2000); default false. The policy variables are checked even when retry is off.
  • SNODRA_JWKS_URL, SNODRA_ISSUER: JWKS (the issuer is required with the URL; without a URL no token is an identity, and a guarded handler cannot be registered)
  • SNODRA_SECURITY_ROLES_CLAIM: RolesClaim (default "roles")
  • SNODRA_FORWARD_JWT: ForwardJWT, true or false (default true)
  • SNODRA_SERVER_ALWAYS_ROUTE_THROUGH_HUB: AlwaysRouteThroughHub, true or false (default false)
  • SNODRA_SERVER_TOKEN, SNODRA_SERVER_TOKEN_FILE: Token, TokenFile
  • SNODRA_SERVER_OAUTH2_TOKEN_URI: JWT with NewClientCredentials, from SNODRA_SERVER_OAUTH2_CLIENT_ID (default the service name), SNODRA_SERVER_OAUTH2_CLIENT_SECRET or SNODRA_SERVER_OAUTH2_CLIENT_SECRET_FILE, SNODRA_SERVER_OAUTH2_SCOPE and SNODRA_SERVER_OAUTH2_CA; the other SNODRA_SERVER_OAUTH2_* variables need the token URI
  • SNODRA_SERVER_TLS: true sets TLS with SNODRA_SERVER_TLS_CA and SNODRA_SERVER_TLS_SERVER_NAME (which need it); default false
  • SNODRA_SERVER_TLS_CLIENT_CERT, SNODRA_SERVER_TLS_CLIENT_KEY: ClientCertificate, which implies TLS (an error with SNODRA_SERVER_TLS=false)
  • SNODRA_EVENTS_SOURCE: EventsSource (default "snodra.events")
  • SNODRA_OUTBOX_ENABLED: OutboxEnabled, true or false (default true)
  • SNODRA_OUTBOX_POLL_INTERVAL_MS, SNODRA_OUTBOX_BATCH_SIZE, SNODRA_OUTBOX_MAX_ATTEMPTS, SNODRA_OUTBOX_LEASE_MS: the relay's poll interval (200), batch size (100), sends of one entry (10) and claim lease (120000); the lease must be longer than a send (40 s)
  • SNODRA_CONSUMER_ENABLED: ConsumerEnabled, true or false (default true)
  • SNODRA_CONSUMER_MAX_ATTEMPTS: the handler invocations per record, the first included (default 5)
  • SNODRA_DEAD_LETTER_MODE: DeadLetterMode, collection (the default), event-store or log
  • SNODRA_STORE_INIT_SCHEMA: whether Start prepares the message store's schema, true (the default) or false when the service applies it itself

The credential kinds (token, JWT, client certificate) exclude each other.

func Hubs

func Hubs(addresses ...string) Option

Hubs are the hubs to connect to: each "host:port" (a "static://", "http://" or "https://" prefix is accepted; an "https://" hub is reached over TLS with the system's roots even without TLS), or one "dns:///name:port" whose every address is a hub, resolved again every 30 s (an address that leaves the answer is drained and closed, a new one connected). The instance opens one stream to every hub, each with the identical registration, and knows a hub by its RegisterAck.hub_id: a second address answering an id already served is closed and parked until that hub has no other address. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Several hubs). Required (or SNODRA_SERVER_ADDRESS with FromEnv).

func Instance

func Instance(id string) Option

Instance is the instance id (Register.instance_id), unique per process, for example a pod name. The default is a fresh random UUID.

func JWKS

func JWKS(url, issuer string) Option

JWKS checks every forwarded token against the issuer's signing keys at url (RS256), its issuer (the iss claim must be issuer) and its expiry, before a handler runs; a token that fails is answered UNAUTHENTICATED, also when the keys cannot be fetched. It is required by every guard (RequireAuthenticated, RequireRole, RequireCaller). Without it a token is no identity: the caller is anonymous (the token still goes on with the requests the handler sends, see ForwardJWT), a token that is not a bearer token, not a JWS or unsigned is still answered UNAUTHENTICATED, and a warning is logged once (see SPEC-GAPS.md, SG-6).

func JWT

func JWT(src TokenSource) Option

JWT makes the instance register with an access token from src (Register.credentials.jwt), for a hub whose access control reads JWTs (its azp claim must be the service name). The token is kept while more than its renewal margin is left: a fifth of its lifetime, at least 5 s, at most half of it (so renewed at 80 % of a long lifetime, at half of a 10 s one). Before that point a new token is fetched and sent once on every registered stream as a credentials refresh; a failed renewal keeps the token and is retried after 1 s, doubling up to 30 s. A stream the hub closes with UNAUTHENTICATED drops the token it presented, so the next stream registers with a new one; PERMISSION_DENIED keeps it. When no token can be had, no stream is opened: the failure is the latest Rejection and the attempt is retried at the reconnect backoff.

func LoadFactor

func LoadFactor(n uint32) Option

LoadFactor is the instance's relative capacity (Register.load_factor); 0 reads as 100, the default.

func Logger

func Logger(l *slog.Logger) Option

Logger is where the library logs; the default is slog.Default.

func MaxConcurrent

func MaxConcurrent(n int) Option

MaxConcurrent is how many handlers the instance runs at once (the permits it offers the hubs). The default is 256.

func MaxSubscriptions

func MaxSubscriptions(n int) Option

MaxSubscriptions is how many subscriptions the instance serves at once: one more is refused with ReplyEnd{RESOURCE_EXHAUSTED "subscription limit (<n>) reached"}. The default is 1024; n must be at least 1.

func OutboxEnabled added in v0.3.0

func OutboxEnabled(on bool) Option

OutboxEnabled says whether every instance runs the outbox relay (SNODRA_OUTBOX_ENABLED). On by default. Turning it off on every instance stops the service's events being published; turning it off on all but one is how a service keeps the order per key of what one instance publishes (see https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/#the-rule).

func Priorities

func Priorities(p map[string]int32) Option

Priorities are the Request.priority of the sends of each type that set none with Priority (higher is served first while the target's queue at the hub is not empty); other types send 0.

func ReconnectBackoff

func ReconnectBackoff(min, max time.Duration) Option

ReconnectBackoff is the wait between two attempts to reach a hub: min, doubling up to max, each wait jittered by ±20 % (never above max). A refused Register waits 80 to 100 % of max. The default is 500 ms to 5 s. The specification caps max at 5 s and wants at least 1 s after a refusal, so keep max between 1.25 s and 5 s; values outside that range are accepted (see SPEC-GAPS.md, SG-16).

func RolesClaim

func RolesClaim(path string) Option

RolesClaim is where a token's roles are read: a dotted path to a list of strings ("realm_access.roles", "groups"), or "scope" for the space-separated scopes. The default is "roles".

func Service

func Service(name string) Option

Service is the logical service name the instance registers (Register.service_name), for example "orders-service". Required (or SNODRA_SERVICE_NAME with FromEnv).

func StatusInterval

func StatusInterval(d time.Duration) Option

StatusInterval is how often every hub with an acknowledged stream gets an InstanceStatus (the hubs it is connected to, its handlers in flight); one also goes out whenever the set of acknowledged hubs changes. The default is 5 s, which is what the protocol asks for at most; it must be at least 1 ms.

func StreamCreditTimeout

func StreamCreditTimeout(d time.Duration) Option

StreamCreditTimeout bounds how long a streaming handler's StreamWriter.Send waits for the caller's credit: then the stream ends with TIMEOUT "no credit within <ms> ms" and the handler's context is cancelled, so that a hub that forgot the stream (a lost Flow or Cancel) cannot hold the handler and its permit forever. The default is 10 minutes, the hub's default maximum stream duration; d must be at least 1 ms.

func TLS

func TLS(cfg TLSConfig) Option

TLS makes every hub connection TLS (1.2 or later), verifying the hub's certificate against cfg's CA and server name. A hub with TLS on accepts nothing else.

func Tags

func Tags(tags map[string]string) Option

Tags are free labels the instance registers (Register.tags); unkeyed requests prefer instances whose tags match more of the sender's.

func Telemetry

func Telemetry(i Instrumentation) Option

Telemetry reports what the library does to i, for example the one of the observability module of this repository. See Instrumentation. A nil i is the default, NopInstrumentation.

func Token

func Token(token string) Option

Token is the static token the instance presents to every hub (Register.credentials.token), for a hub whose access control asks for one. It is never logged. A blank token is none. An instance uses one kind of credential: Token or TokenFile, JWT, or ClientCertificate.

func TokenFile

func TokenFile(path string) Option

TokenFile is a file holding the static token (surrounding blanks ignored), for a mounted secret; it wins over Token. It is read again before every connection to a hub, and on every heartbeat of a registered stream, whose hub gets a changed token as a credentials refresh: a rotated secret applies without a restart. New fails when the file cannot be read or is empty; later, a file that cannot be read or is empty (a rotation caught half way) keeps the last token read.

func WithEventStore added in v0.3.0

func WithEventStore(store EventStore) Option

WithEventStore sets the event store: where the relay publishes the service's events and where its processors read them (EventStore). The in-memory one is NewMemoryEventStore. Events need it; commands, queries and subscription queries do not, and a service with only those starts without it. See https://snodra.damoreira.com/docs/library-authors/event-store-add-ons/.

func WithStore added in v0.3.0

func WithStore(store MessageStore) Option

WithStore sets the message store: the service's own database, where the outbox, the processed-event markers, the dead letters, the processors' control state, the idempotent calls and the sagas live. A store is the add-on of one database (MessageStore); the in-memory one is NewMemoryMessageStore. Events need it; commands, queries and subscription queries do not, and a service with only those starts without it. See https://snodra.damoreira.com/docs/library-authors/message-store-add-ons/.

type OutboxEntry added in v0.2.0

type OutboxEntry struct {
	// ID is the event's id (its "id" header).
	ID string
	// Type is the event's wire type name.
	Type string
	// Key is the event's order key; nil for none.
	Key *string
	// Headers are the headers the entry keeps in the outbox: the correlationId, the userId and,
	// when the work that published the event carried one, the traceparent. The relay adds type,
	// id, timestamp and source from the entry, so a store never holds a stale copy of them.
	Headers map[string]string
	// Payload is the event as JSON: a JSON object whose integers fit in a signed 64-bit
	// integer, at most MaxPayloadDepth deep. A store refuses every other payload with an error
	// wrapping ErrInvalid.
	Payload []byte
	// CreatedAt is when the publishing instance created the entry (the application's clock).
	CreatedAt time.Time
	// Seq is the appending instance's counter: it breaks CreatedAt ties, so per-key order
	// holds for what one instance publishes.
	Seq int64
	// Attempts counts the relay's failed sends so far.
	Attempts int
}

OutboxEntry is one event in the outbox.

type OutboxStore added in v0.2.0

type OutboxStore interface {
	// Append appends entry in the transaction carried by ctx, or on its own when ctx carries
	// none. An entry appended in a rolled-back transaction never reaches the relay. A payload
	// that is not a JSON object with integers that fit in a signed 64-bit integer is refused
	// (ErrInvalid) and nothing is appended; an id that exists is a conflict (ErrConflict).
	Append(ctx context.Context, entry OutboxEntry) error
	// Claim returns at most limit pending entries, now held by owner until lease from the
	// application's clock: those nobody holds, those whose holder's lease has passed, and those
	// owner holds already (its lease renewed); never an entry another owner holds. owner must
	// not be empty: an empty owner is the store's mark for "nobody holds this entry", so a
	// claimer cannot be told from it. The only order is (CreatedAt, Seq, ID): an entry owner
	// still holds comes back in its place, so an entry whose send failed is retried before the
	// later ones.
	Claim(ctx context.Context, owner string, lease time.Duration, limit int) ([]OutboxEntry, error)
	// MarkSent marks the entries sent: never claimed again, purged after the retention.
	MarkSent(ctx context.Context, ids []string) error
	// MarkAttemptFailed counts a failed send that will be retried: Attempts + 1; the entry
	// stays pending and held by its owner until the lease passes. cause is for diagnosis; a
	// store may keep it or not.
	MarkAttemptFailed(ctx context.Context, id, cause string) error
	// MarkFailed gives the entry up (out of attempts, or a failure no retry cures): Attempts +
	// 1, never claimed again, never purged. cause is for diagnosis; a store may keep it or not.
	MarkFailed(ctx context.Context, id, cause string) error
	// Purge removes the entries sent before sentBefore; how many.
	Purge(ctx context.Context, sentBefore time.Time) (int64, error)
	// Pending is how many entries are pending (neither sent nor failed), held or not.
	Pending(ctx context.Context) (int64, error)
	// OldestPending is the CreatedAt of the oldest pending entry (held or not); ok is false
	// when none is pending.
	OldestPending(ctx context.Context) (oldest time.Time, ok bool, err error)
	// OnAppend registers wake, called each time an append commits (on its own, or with its
	// transaction), so the relay publishes at once instead of at its next poll. The returned
	// function unregisters it and is safe to call more than once. A store that cannot tell
	// registers nothing and returns a function that does nothing; the relay then polls. wake
	// must return at once.
	OnAppend(wake func()) (cancel func())
}

OutboxStore is the outbox: events appended in the service's transaction, relayed by whichever instance claims them. An entry is pending until it is sent or failed. A claim holds the entries under a lease, so two instances relaying one outbox never both hold an entry, and a crashed instance's entries are claimed again once its lease has passed.

type OutgoingEvent added in v0.2.0

type OutgoingEvent struct {
	// Source is where the event goes: the service's events source, or its dead-letter source
	// (DeadLetterSource).
	Source string
	// ID is the event's id, also in header HeaderID.
	ID string
	// Type is the event's type name, also in header HeaderType.
	Type string
	// Key is the order key: events with one key reach a processor in publish order. An empty
	// key is a key; nil spreads the event as the event store does.
	Key *string
	// Headers travel as given, as the event store's native metadata: the seven
	// EventHeaders and any other (for example a dead letter's snodra-dlt-* headers).
	// Headers are UTF-8 text, one value per name.
	Headers map[string]string
	// Payload is JSON bytes, carried as given.
	Payload []byte
}

OutgoingEvent is one event an outbox relay hands an event store (EventPublisher.Publish).

type ParkResult added in v0.2.0

type ParkResult int

ParkResult says whether DeadLetterStore.Park inserted the letter or found it parked already.

const (
	// ParkNew: the letter was inserted.
	ParkNew ParkResult = iota
	// ParkAlready: a letter of that id exists (a redelivery).
	ParkAlready
)

type Part

type Part[R any] struct {
	Service, Instance string
	Value             R
	Err               error
}

Part is one target's answer to a Gather: the service and instance that answered, and the answer decoded as R, or the target's failure. Err is an *Error with the target's code and message (its handler's error, or a failure the hub saw for that target, such as HANDLER_DISCONNECTED or RESOURCE_EXHAUSTED). A payload that does not decode as R is a plain error, not an *Error: the target answered, the caller could not read it.

type PayloadCodec

type PayloadCodec interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

PayloadCodec turns message values into payload bytes and back.

var JSON PayloadCodec = jsonCodec{}

JSON is the default payload codec: encoding/json, with unknown fields ignored on read. See https://snodra.damoreira.com/docs/library-authors/messages/.

type ProcessedEvents added in v0.2.0

type ProcessedEvents interface {
	Record(ctx context.Context, marker ProcessedMarker) (bool, error)
}

ProcessedEvents records processed-event markers. It is the processed-event port of a message store, frozen at level 2 because the event-store kit records a marker in its at-least-once check; the rest of the message-store interface comes with the message store.

Record records marker in the caller's transaction and reports whether it was new: false means the id is recorded already (a duplicate), and the caller skips the handlers. A message store whose transaction is bound through the context records it in that transaction; with no transaction in the context, the store records it in a transaction of its own.

type ProcessedMarker added in v0.2.0

type ProcessedMarker struct {
	ID          string
	Type        string
	ProcessedAt time.Time
	Processor   string
	Source      string
	Segment     string
	Position    string
}

ProcessedMarker is the idempotency marker of a handled event: its id ("processor:<name>:<eventId>", "saga:<type>:<eventId>", ...), the event's type and when it was handled. The stage-1 marker of a delivered event also carries its processor, source, segment and position, so a reset deletes exactly the markers of its replay range; every other marker leaves them empty. An empty Processor, Source, Segment or Position means none.

type ProcessedStore added in v0.2.0

type ProcessedStore interface {
	ProcessedEvents
	// Exists reports whether a marker with id is committed. A marker recorded in the
	// transaction carried by ctx is not visible yet.
	Exists(ctx context.Context, id string) (bool, error)
	// DeleteMarkers deletes the stage-1 markers of processor in ranges (a range's source and
	// segment, a position in [From, Until) in the event store's order) and nothing else; how
	// many. Markers without a position are never deleted. It runs outside any transaction.
	//
	// TODO(spec-gap): SG-30 (the opaque positions are ordered as document stores keep them:
	// canonical decimals by value, other text by bytes, and never across the two).
	DeleteMarkers(ctx context.Context, processor string, ranges []ReplayRange) (int64, error)
	// Purge removes the markers processed before before; how many.
	Purge(ctx context.Context, before time.Time) (int64, error)
}

ProcessedStore is the processed-event markers: the ids of the events a handler has handled, recorded in its transaction, so a redelivered event is skipped (at-least-once delivery, exactly-once effects). A marker also records when it was handled (the retention counts from it); a stage-1 marker of a delivered event carries its processor, source, segment and position, so a reset deletes exactly the markers of its replay range, while every other marker leaves them empty and is never deleted by a reset.

ProcessedStore satisfies ProcessedEvents: the event-store kit records its marker through it.

type ProcessorControlState added in v0.2.0

type ProcessorControlState struct {
	Processor string
	Paused    bool
	PausedAt  time.Time
	// PausedBy is the control id of the request that paused it, or "local".
	PausedBy string
	// Operation is the reset holding the processor's lock.
	Operation *ControlOperation
	// Replay is the open replay ranges.
	Replay    []ReplayRange
	UpdatedAt time.Time
}

ProcessorControlState is one processor's control state; a processor the store knows nothing of is not paused, not locked and not replaying. A zero time means none.

type ProcessorControlStore added in v0.2.0

type ProcessorControlStore interface {
	// Get is the state of processor; the zero state (not paused, nothing held) when the store
	// has none.
	Get(ctx context.Context, processor string) (ProcessorControlState, error)
	// SetPaused pauses (by the control id, or "local") or resumes processor, idempotently. A
	// resume clears PausedAt and PausedBy.
	SetPaused(ctx context.Context, processor string, paused bool, by string, now time.Time) error
	// Lock takes the lock of processor for operation until leaseUntil, atomically: when nothing
	// holds it or the holder's lease has passed (leaseUntil <= now); a renewal (the operation
	// holds it already) moves the lease only. The outcome names the holder when another holds
	// it.
	Lock(ctx context.Context, processor, operation string, leaseUntil, now time.Time) (LockOutcome, error)
	// Extend moves the lease of operation; false when it does not hold the lock.
	Extend(ctx context.Context, processor, operation string, leaseUntil, now time.Time) (bool, error)
	// Release clears the lock when operation holds it (never another operation's); false when
	// it did not.
	Release(ctx context.Context, processor, operation string, now time.Time) (bool, error)
	// Expire clears the lock when operation holds it and its lease has passed at now (a renewal
	// that came meanwhile keeps it); false otherwise.
	Expire(ctx context.Context, processor, operation string, now time.Time) (bool, error)
	// SetReplay replaces the replay ranges of processor. A store that keeps a range's segment
	// and positions as numbers refuses one that is not decimal with ErrInvalid.
	SetReplay(ctx context.Context, processor string, ranges []ReplayRange, now time.Time) error
	// RemoveRange removes that exact range from the replay ranges of processor; false when it
	// was not there.
	RemoveRange(ctx context.Context, processor string, replay ReplayRange, now time.Time) (bool, error)
}

ProcessorControlStore is the processors' control state: per processor its pause, its reset lock and its replay ranges, the source of truth of all three. Every operation is a write of its own, outside any transaction; the times are the caller's clock.

type PublishOption added in v0.3.0

type PublishOption func(*publishConfig)

A PublishOption configures one Publish call.

func Key added in v0.3.0

func Key(key string) PublishOption

Key gives a published event its order key, typically an aggregate id: events with one key reach a processor in publish order. An empty key is a key; without Key the event has none and spreads over the event store's segments. See https://snodra.damoreira.com/docs/library-authors/messages/ (Event headers).

type Rejection

type Rejection struct {
	// Hub is the hub's address (host:port); a refused Register carries no hub id.
	Hub string
	// Code is the gRPC status in upper snake case: "ALREADY_EXISTS", "INVALID_ARGUMENT",
	// "FAILED_PRECONDITION", "UNAUTHENTICATED" or "PERMISSION_DENIED".
	Code string
	// Message is the hub's reason, for example "type orders.PlaceOrder is owned by billing-service".
	Message string
	// At is when the refusal arrived.
	At time.Time
}

Rejection is a hub's refusal of the instance's Register: the hub closed the stream with ALREADY_EXISTS (a type another service owns), INVALID_ARGUMENT, FAILED_PRECONDITION (a contract that is live with a different schema), UNAUTHENTICATED or PERMISSION_DENIED instead of acknowledging it. The instance keeps running and retries at its backoff cap. With JWT, a failure to get an access token, when no stream could be opened, is kept too (Code UNAUTHENTICATED, a Message that names the access token); it is retried at the ordinary backoff. Like any kept refusal it is not cleared when a hub accepts the Register later: a token endpoint that failed once at startup leaves it here while the instance runs registered, and it replaces an earlier refusal by a hub.

type ReplayRange added in v0.2.0

type ReplayRange struct {
	Source  string
	Segment string
	From    string
	Until   string
}

ReplayRange says events of Source's Segment at positions from From (inclusive) to Until (exclusive) are a replay. Until is the subscription's committed position before the plan, empty when it had none; only a range with Until set and From before it, by EventStore.Compare, replays anything. The others are moves without a replay.

type ResetContext added in v0.6.0

type ResetContext struct {
	Processor   string
	OperationID string
	Target      ResetTarget
	Ranges      []ReplayRange
}

ResetContext is what a reset handler is told: the processor, the reset's operation id, its target and the replay ranges it will delete markers in (never empty). A handler runs before any marker or position moves; a failure stops the reset with ControlRefusal.CONTROL_REFUSAL_RESET_HANDLER_FAILED.

type ResetEarliest added in v0.2.0

type ResetEarliest struct{}

ResetEarliest moves every segment to its first position: everything the event store still has is a replay.

type ResetLatest added in v0.2.0

type ResetLatest struct{}

ResetLatest moves every segment to its head: nothing is replayed.

type ResetPositions added in v0.2.0

type ResetPositions struct {
	Positions []SegmentPosition
}

ResetPositions moves the listed segments to their positions. A segment not listed keeps its committed position.

type ResetTarget added in v0.2.0

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

ResetTarget is where SubscriptionAdmin.Plan moves a subscription. The set is closed; an add-on switches on ResetEarliest, ResetLatest, ResetTimestamp and ResetPositions.

type ResetTimestamp added in v0.2.0

type ResetTimestamp struct {
	TimestampMs int64
}

ResetTimestamp moves every segment to the first position whose event was appended at or after TimestampMs (epoch milliseconds, the event store's append time), else its head.

type ResponseSchemaOverride added in v0.8.1

type ResponseSchemaOverride interface{ ResponseJSONSchema() []byte }

ResponseSchemaOverride is the optional method of a request type that replaces the generated JSON Schema of the whole response with a checked-in one. It applies to every request whose response document is titled "<request type>.Response": a reply without content (Empty), a reply type that is not a Message (a list, a plain structure), and the initial and update pair of a subscription query. A reply type that is a Message is described by its own SchemaOverride, and a request that has this method with such a reply type is a registration error. ResponseJSONSchema returns the whole document, validated and sent as written like any override.

It belongs on a handled command or query type only. On an event type, a reply or stream item type, or the initial or update type of a subscription it would never be read, so registering a handler with such a type is an error. A type the instance only sends is not checked: its method is ignored. See https://snodra.damoreira.com/docs/library-authors/contracts/.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts    int
	InitialBackoff time.Duration
	Multiplier     float64
	MaxBackoff     time.Duration
}

RetryPolicy is how a failed call is sent again (Send, Query, Gather; a Stream only before its first part, a Subscribe only before its initial result): at most MaxAttempts attempts in all (1: no retry), the first wait InitialBackoff, each next one Multiplier times longer, at most MaxBackoff; every wait is jittered by ±20 % (never above MaxBackoff).

Only failures where the handler never ran are retried for a command (ErrNeverSent, NO_HANDLER, RESOURCE_EXHAUSTED); a query is also retried after an unknown outcome (ErrOutcomeUnknown, TIMEOUT, HANDLER_DISCONNECTED). Every attempt has a fresh request id, and all attempts share one time budget: the caller's timeout, else the hub's timeout for the type, else 5 s. A retry starts only with at least max(InitialBackoff, 250 ms) of it left, and sends what is left as the request's timeout. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Never sent or outcome unknown).

type Revoked added in v0.2.0

type Revoked struct {
	Segments []string
}

Revoked says these segments are this subscription's no longer. What it delivered of them and did not acknowledge comes again to whichever subscription gets them. A Revoked is always followed by an Assigned (possibly empty), which ends the change.

type Saga added in v0.2.0

type Saga struct {
	ID           string
	Type         string
	State        string
	Associations []SagaAssociation
	StartKey     *string
	Ended        bool
	EndedAt      time.Time
	Version      int64
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

Saga is one saga instance. State is the saga object as JSON text; Version is the optimistic version every write checks (0 at creation, +1 per write). While Ended is false the instance is live: its Associations route events to it and its StartKey ("<type>|<key>=<value>", nil for forceNew instances) is unique. An empty StartKey means none; a zero EndedAt means none.

type SagaAssociation added in v0.2.0

type SagaAssociation struct {
	Key   string
	Value string
}

SagaAssociation is an association "Key = Value" of a saga instance: events whose association value is Value for Key are routed to it.

type SagaCommandFailed added in v0.7.0

type SagaCommandFailed struct {
	// SagaID is the id of the saga that sent the command.
	SagaID string `json:"sagaId"`
	// CommandType is the command's wire type name.
	CommandType string `json:"commandType"`
	// IdempotencyKey is the failed command's entry id, "<sagaId>:<seq>".
	IdempotencyKey string `json:"idempotencyKey"`
	// Reason is why the command was given up.
	Reason SagaCommandFailedReason `json:"reason"`
	// Message is why, for people.
	Message string `json:"message"`
}

SagaCommandFailed is the local event a saga receives when a command it recorded was given up on. It is never published to the event store. Its message id is "failed:<sagaId>:<seq>", from which its processed-event markers are built; it reaches the instance that sent the command by SagaID, without an association.

func (SagaCommandFailed) MessageType added in v0.7.0

func (SagaCommandFailed) MessageType() string

MessageType is the event's wire type name.

type SagaCommandFailedHandler added in v0.7.0

type SagaCommandFailedHandler[S any] struct {
	// contains filtered or unexported fields
}

SagaCommandFailedHandler is the handler of the local SagaCommandFailed event.

func CommandFailed added in v0.7.0

func CommandFailed[S any](handler func(context.Context, *SagaContext, *S, SagaCommandFailed) error) SagaCommandFailedHandler[S]

CommandFailed registers a handler of the local SagaCommandFailed event. The runtime also routes the event to the instance that sent the command, by its id; no association is needed.

type SagaCommandFailedReason added in v0.7.0

type SagaCommandFailedReason string

SagaCommandFailedReason says why a command a saga sent was given up on.

const (
	// SagaCommandFailedNoHandler: nobody handles the command type (a service without a hub).
	SagaCommandFailedNoHandler SagaCommandFailedReason = "NO_HANDLER"
	// SagaCommandFailedDenied: the handler requires an authenticated caller, and a saga command
	// has none.
	SagaCommandFailedDenied SagaCommandFailedReason = "DENIED"
	// SagaCommandFailedInvalid: the handler could not read the payload.
	SagaCommandFailedInvalid SagaCommandFailedReason = "INVALID"
	// SagaCommandFailedFailed: the handler failed (any other error).
	SagaCommandFailedFailed SagaCommandFailedReason = "FAILED"
	// SagaCommandFailedUnknownOutcome: an idempotent adapter cannot tell whether its external
	// call happened.
	SagaCommandFailedUnknownOutcome SagaCommandFailedReason = "UNKNOWN_OUTCOME"
	// SagaCommandFailedExhausted: a transient failure lasted through all the relay's attempts.
	SagaCommandFailedExhausted SagaCommandFailedReason = "EXHAUSTED"
)

func (SagaCommandFailedReason) String added in v0.7.0

func (r SagaCommandFailedReason) String() string

String returns the stored reason.

type SagaContext added in v0.7.0

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

SagaContext is what a saga handler records: associations, commands, events, deadlines and the end of its instance. Nothing is sent or published while the handler runs; the runtime applies what was recorded in the saga's transaction and the relay sends it afterwards. Use Send and Publish (and Schedule) here: the package-level Send, Query and Publish are refused inside a saga handler, because they would bypass the saga's transaction and its ordering. A nil *SagaContext is never passed to a handler.

func (*SagaContext) Associate added in v0.7.0

func (c *SagaContext) Associate(key, value string)

Associate adds key = value to the instance's associations. The same pair twice is recorded once.

func (*SagaContext) CancelDeadline added in v0.7.0

func (c *SagaContext) CancelDeadline(id string)

CancelDeadline cancels the deadline id. It has no effect when the deadline already fired or was cancelled.

func (*SagaContext) CancelDeadlines added in v0.7.0

func (c *SagaContext) CancelDeadlines(name string)

CancelDeadlines cancels every scheduled deadline of the instance named name.

func (*SagaContext) CorrelationID added in v0.7.0

func (c *SagaContext) CorrelationID() string

CorrelationID is the correlation id of the message whose handling recorded the effects.

func (*SagaContext) End added in v0.7.0

func (c *SagaContext) End()

End ends the instance after the handler returns. The runtime then cancels its scheduled deadlines; an ended instance receives no more events.

func (*SagaContext) Publish added in v0.7.0

func (c *SagaContext) Publish(event Message, key string) error

Publish records event, to be appended to the outbox after the transaction commits, with key (empty for none). The same limits as SagaContext.Send apply.

func (*SagaContext) RemoveAssociation added in v0.7.0

func (c *SagaContext) RemoveAssociation(key, value string)

RemoveAssociation removes key = value from the instance's associations.

func (*SagaContext) SagaID added in v0.7.0

func (c *SagaContext) SagaID() string

SagaID is the instance's id.

func (*SagaContext) Schedule added in v0.7.0

func (c *SagaContext) Schedule(after time.Duration, name string, payload any) (string, error)

Schedule records a deadline named name to fire after d, with payload (nil for none). It returns the deadline id, which SagaContext.CancelDeadline cancels.

func (*SagaContext) ScheduleAt added in v0.7.0

func (c *SagaContext) ScheduleAt(at time.Time, name string, payload any) (string, error)

ScheduleAt records a deadline named name to fire at at.

func (*SagaContext) Send added in v0.7.0

func (c *SagaContext) Send(command Message, routingKey string) error

Send records command, to be sent after the transaction commits with routingKey (empty for none). It returns why the command cannot be recorded (a nil message, an unencodable payload, or more than 999 messages in one handling); the handler decides whether to return the error, which fails the handling and retries or parks the event.

The command is recorded with the two schema versions it will be sent with: the version of its type, and the response version of its handler when this instance handles it (1 when it does not, or when the handler's reply is not a versioned message). For a command another service handles, whose reply is a versioned message, use SendReply, which takes precedence.

type SagaDeadline added in v0.2.0

type SagaDeadline struct {
	ID            string
	SagaType      string
	SagaID        string
	Name          string
	Payload       *string
	PayloadType   *string
	DueAt         time.Time
	Status        DeadlineStatus
	ClaimedBy     string
	ClaimedUntil  time.Time
	FinishedAt    time.Time
	CorrelationID string
}

SagaDeadline is a deadline of a saga instance. Payload is the JSON text of the payload (any JSON value) and PayloadType its type name, both nil when there is none. A scheduler claims a due deadline with ClaimedBy and ClaimedUntil (a lease: an expired one lets it fire again); FinishedAt is set when it is FIRED or CANCELLED; CorrelationID is the correlation id of the message that scheduled it (empty means none).

type SagaDeadlineHandler added in v0.7.0

type SagaDeadlineHandler[S any] struct {
	// contains filtered or unexported fields
}

SagaDeadlineHandler is one deadline handler of a saga definition.

func Deadline added in v0.7.0

func Deadline[S any, P any](name string, handler func(context.Context, *SagaContext, *S, P) error) SagaDeadlineHandler[S]

Deadline registers a handler of deadlines named name, receiving the payload as P. A deadline without a payload calls it with P's zero value.

func (SagaDeadlineHandler[S]) Ending added in v0.7.0

func (d SagaDeadlineHandler[S]) Ending() SagaDeadlineHandler[S]

Ending makes the deadline handler end the instance.

type SagaDeadlineStore added in v0.2.0

type SagaDeadlineStore interface {
	// Insert inserts deadline.
	Insert(ctx context.Context, deadline SagaDeadline) error
	// FindScheduled returns the deadline when it is still SCHEDULED, else nil.
	FindScheduled(ctx context.Context, id string) (*SagaDeadline, error)
	// Cancel cancels the SCHEDULED deadline deadlineID of sagaID; no effect on any other.
	Cancel(ctx context.Context, sagaID, deadlineID string, now time.Time) error
	// CancelByName cancels the SCHEDULED deadlines of sagaID named name.
	CancelByName(ctx context.Context, sagaID, name string, now time.Time) error
	// CancelAll cancels every SCHEDULED deadline of sagaID.
	CancelAll(ctx context.Context, sagaID string, now time.Time) error
	// MarkFired sets the SCHEDULED deadline id to FIRED; false when it was not SCHEDULED.
	MarkFired(ctx context.Context, id string, now time.Time) (bool, error)
	// ClaimDue claims the SCHEDULED deadline due first (DueAt <= now) that nobody holds or whose
	// claim has passed (ClaimedUntil < now), for owner until claimedUntil, atomically: of two
	// schedulers asking at once, one gets it. It runs outside any transaction; nil when nothing
	// is due.
	ClaimDue(ctx context.Context, owner string, now, claimedUntil time.Time) (*SagaDeadline, error)
	// CountOverdueByName is how many SCHEDULED deadlines are due (DueAt <= now) per name,
	// claimed or not; a name without one is absent.
	CountOverdueByName(ctx context.Context, now time.Time) (map[string]int64, error)
}

SagaDeadlineStore is the deadlines, as far as the runtime writes them.

type SagaDefinition added in v0.7.0

type SagaDefinition[S any] struct {
	// contains filtered or unexported fields
}

SagaDefinition collects a saga's handlers. Build it inside HandleSaga, with StartedOn, HandledOn, Deadline and CommandFailed, adding each with StartOn, On, OnDeadline or OnCommandFailed.

func (*SagaDefinition[S]) On added in v0.7.0

func (d *SagaDefinition[S]) On(event SagaEvent[S])

On adds an event handler of a live instance.

func (*SagaDefinition[S]) OnCommandFailed added in v0.7.0

func (d *SagaDefinition[S]) OnCommandFailed(handler SagaCommandFailedHandler[S])

OnCommandFailed adds the handler of the local SagaCommandFailed event.

func (*SagaDefinition[S]) OnDeadline added in v0.7.0

func (d *SagaDefinition[S]) OnDeadline(handler SagaDeadlineHandler[S])

OnDeadline adds a deadline handler. A name may be registered once.

func (*SagaDefinition[S]) StartOn added in v0.7.0

func (d *SagaDefinition[S]) StartOn(event SagaEvent[S])

StartOn adds a start handler.

type SagaDispatch added in v0.2.0

type SagaDispatch struct {
	ID             string
	SagaID         string
	Seq            int64
	Kind           DispatchKind
	Type           string
	Payload        string
	Headers        map[string]string
	RoutingKey     *string
	CreatedAt      time.Time
	DispatchedAt   time.Time
	Attempts       int
	NextAttemptAt  time.Time
	FailedAt       time.Time
	FailureReason  FailureReason
	FailureMessage string
	NoticePending  bool
	NoticeAttempts int
	NoticeNextAt   time.Time
}

SagaDispatch is one command or event a saga recorded in its transaction, waiting in the saga-side outbox. Seq orders the entries of one saga (Version*1000 + index); the id "<sagaID>:<seq>" is the command's idempotency key. A command given up on carries its outcome (FailureReason, FailureMessage, FailedAt); NoticePending is true until the snodra.SagaCommandFailed notice was delivered locally. Zero times mean none.

type SagaDispatchStore added in v0.2.0

type SagaDispatchStore interface {
	// Record records entries in the transaction carried by ctx. An EVENT entry whose payload
	// the outbox would refuse (not a JSON object, or an integer above the signed 64-bit range)
	// is refused with ErrInvalid: the saga's attempt fails and nothing of it commits.
	Record(ctx context.Context, entries []SagaDispatch) error
	// DueSagas returns the ids of the sagas whose first pending entry (lowest Seq) is due
	// (NextAttemptAt zero or <= now), oldest first pending entry first (its CreatedAt, then the
	// saga id), at most limit, leaving out the sagas in except (in flight on this instance).
	DueSagas(ctx context.Context, now time.Time, except []string, limit int) ([]string, error)
	// NextPending returns the first pending entry of sagaID (lowest Seq), due or not; nil when
	// there is none.
	NextPending(ctx context.Context, sagaID string) (*SagaDispatch, error)
	// MarkDispatched records the entry dispatched at now, in the transaction carried by ctx (an
	// event: with its outbox append).
	MarkDispatched(ctx context.Context, id string, now time.Time) error
	// ScheduleRetry records a transient failure: Attempts and the next attempt at nextAttempt.
	ScheduleRetry(ctx context.Context, id string, attempts int, nextAttempt time.Time) error
	// MarkFailed gives the entry up: see DispatchFailure.
	MarkFailed(ctx context.Context, id string, failure DispatchFailure) error
	// ClaimDueNotice claims the pending failure notice due first (NoticeNextAt zero or <= now),
	// moving its NoticeNextAt to reserveUntil (which reserves it for the caller), atomically;
	// the entry as claimed, nil when no notice is due.
	ClaimDueNotice(ctx context.Context, now, reserveUntil time.Time) (*SagaDispatch, error)
	// ClearNotice records that the failure notice was delivered (or given up): no notice is
	// pending any more.
	ClearNotice(ctx context.Context, id string) error
	// ScheduleNoticeRetry records that a delivery of the notice failed: NoticeAttempts and its
	// next try at next.
	ScheduleNoticeRetry(ctx context.Context, id string, noticeAttempts int, next time.Time) error
	// ClaimLease takes the dispatch lease of sagaID for owner until until, when nobody holds it
	// or its lease has passed (< now), atomically; false when another holder's lease runs.
	ClaimLease(ctx context.Context, sagaID, owner string, now, until time.Time) (bool, error)
	// RenewLease moves the lease owner holds to until; false when it holds it no longer.
	RenewLease(ctx context.Context, sagaID, owner string, until time.Time) (bool, error)
	// ReleaseLease lets go of the lease when owner holds it.
	ReleaseLease(ctx context.Context, sagaID, owner string) error
	// Pending is how many entries are pending.
	Pending(ctx context.Context) (int64, error)
}

SagaDispatchStore is the saga-side outbox and its per-saga dispatch leases. The runtime records what a saga sends in the saga's transaction; the dispatch relay works through it. An entry is pending until it is dispatched or failed. Every relay operation is a write of its own, outside any transaction, but MarkDispatched, which joins the transaction the relay appends the event to the outbox in. A call naming an entry that no longer exists changes nothing.

type SagaEvent added in v0.7.0

type SagaEvent[S any] struct {
	// contains filtered or unexported fields
}

SagaEvent is one event handler of a saga definition, built by StartedOn or HandledOn.

func HandledOn added in v0.7.0

func HandledOn[S any, E Message](association SagaRoute[E], handler func(context.Context, *SagaContext, *S, E) error) SagaEvent[S]

HandledOn registers a handler of an event of a live instance.

func StartedOn added in v0.7.0

func StartedOn[S any, E Message](association SagaRoute[E], handler func(context.Context, *SagaContext, *S, E) error) SagaEvent[S]

StartedOn registers a start handler: an event matching no live instance starts one. A live instance with the same start association keeps the event instead of starting another; add SagaEvent.ForceNew to start one anyway.

func (SagaEvent[S]) Ending added in v0.7.0

func (e SagaEvent[S]) Ending() SagaEvent[S]

Ending makes the event's handler end the instance when it returns. Later handlers of the same event do not run.

func (SagaEvent[S]) ForceNew added in v0.7.0

func (e SagaEvent[S]) ForceNew() SagaEvent[S]

ForceNew makes a start handler start a new instance even when instances already match. The new instance keeps no start key, so it never blocks another one.

type SagaFailure added in v0.2.0

type SagaFailure struct {
	ID            string
	SagaType      string
	EventID       string
	EventType     string
	Payload       string
	Headers       map[string]string
	Error         string
	Attempts      int
	FirstFailedAt time.Time
	LastFailedAt  time.Time
}

SagaFailure is a saga event that failed all its attempts, parked in saga_failures (ID "<sagaType>:<eventId>"): the event as received, the last error and how many attempts were made.

type SagaFailureStore added in v0.2.0

type SagaFailureStore interface {
	// Find returns the failure, or nil when there is none.
	Find(ctx context.Context, id string) (*SagaFailure, error)
	// Save inserts or replaces the failure with that id.
	Save(ctx context.Context, failure SagaFailure) error
	// Delete deletes the failure; false when there was none.
	Delete(ctx context.Context, id string) (bool, error)
	// FailedAgain records that a retry of failure id failed again: Attempts grows by attempts,
	// Error and LastFailedAt are replaced. It never inserts: false when the failure no longer
	// exists, so the bookkeeping of a failed retry cannot bring a discarded failure back.
	FailedAgain(ctx context.Context, id, errText string, attempts int, now time.Time) (bool, error)
	// List returns the failures of sagaType (every type when sagaType is empty), oldest
	// LastFailedAt first.
	List(ctx context.Context, sagaType string) ([]SagaFailure, error)
}

SagaFailureStore is the parked saga events.

type SagaMarkerStore added in v0.2.0

type SagaMarkerStore interface {
	// Exists reports whether the marker is recorded.
	Exists(ctx context.Context, id string) (bool, error)
	// Insert inserts the marker; ErrConflict when it exists.
	Insert(ctx context.Context, id, typeName string, now time.Time) error
}

SagaMarkerStore is the exactly-once markers of the saga stage: processed-event ids "saga:<sagaType>:<eventId>".

type SagaRepository added in v0.2.0

type SagaRepository interface {
	// FindByID returns the instance, or nil when there is none.
	FindByID(ctx context.Context, id string) (*Saga, error)
	// FindLive returns the live (not ended) instances of typeName associated with key = value.
	FindLive(ctx context.Context, typeName, key, value string) ([]Saga, error)
	// Insert inserts a new instance; ErrConflict when its StartKey is held by a live instance.
	Insert(ctx context.Context, saga Saga) error
	// Update replaces the stored instance by saga when the stored Version is
	// expectedVersion; false when it is not.
	Update(ctx context.Context, saga Saga, expectedVersion int64) (bool, error)
	// CountLiveByType is how many live instances there are per saga type, outside any
	// transaction; a type without one is absent.
	CountLiveByType(ctx context.Context) (map[string]int64, error)
}

SagaRepository is the sagas.

type SagaRoute added in v0.7.0

type SagaRoute[E Message] struct {
	Key   string
	Value func(E) string
}

SagaRoute is how an event reaches a saga instance: the event's value for Key. A nil Value, or a blank value, means the event has no such association and matches no instance.

func Associate added in v0.7.0

func Associate[E Message](key string, value func(E) string) SagaRoute[E]

Associate builds a route for the saga event type E. The value is usually one field of the event, for example the order id; events whose value is blank match no instance.

type SagaStores added in v0.2.0

type SagaStores struct {
	// Sagas is the sagas themselves.
	Sagas SagaRepository
	// Dispatch is the saga-side outbox and its leases.
	Dispatch SagaDispatchStore
	// Deadlines is the deadlines and their scheduler.
	Deadlines SagaDeadlineStore
	// Failures is the parked saga events.
	Failures SagaFailureStore
	// Markers is the exactly-once markers of the saga stage.
	Markers SagaMarkerStore
}

SagaStores is the saga ports, all in the store's transactions (the context's).

type SchemaOverride added in v0.8.0

type SchemaOverride interface{ JSONSchema() []byte }

SchemaOverride is the optional method of a type that replaces the generated JSON Schema with a checked-in one, for example for a recursive type or a custom wire format. JSONSchema returns the whole document, which is sent exactly as written: a UTF-8 JSON object of at most 64 KiB, nested at most 100 levels, without duplicate keys. The method may be on a message type, which overrides its own document, or on the reply or item type of a handler. Only those apply: a JSONSchema on the type of a nested field or element is not used, because the schema of a type that is generated is generated whole. An override is never ignored: a reply type with JSONSchema on a request that has ResponseSchemaOverride is a registration error, and so is JSONSchema on the initial or update type of a subscription query, whose response is one document: describe that with ResponseSchemaOverride and leave the types without it. See https://snodra.damoreira.com/docs/library-authors/contracts/.

type SegmentPosition added in v0.2.0

type SegmentPosition struct {
	Segment  string
	Position string
}

SegmentPosition is one segment and one position of it, for ResetPositions.

type SegmentStatus added in v0.2.0

type SegmentStatus struct {
	// Segment is the segment's name.
	Segment string
	// Position is the next position this subscription delivers.
	Position string
	// Committed is the subscription's committed position, the one after its last
	// acknowledgement.
	Committed string
	// Head is the position of the next event appended to the segment.
	Head string
	// Lag is how many events lie between Committed and Head (between Position and Head when
	// nothing is committed): what is not acknowledged yet. It is -1 when unknown, and always
	// -1 without CapabilityLag.
	Lag int64
}

SegmentStatus is one segment assigned to a subscription, as EventSubscription.Segments reports it. Positions are as in Delivery; an empty Position, Committed or Head means unknown or none. Lag is -1 when unknown, never negative otherwise.

type SendOption

type SendOption func(*sendConfig)

A SendOption configures one Send, Query, Gather, Stream or Subscribe.

func Header(name, value string) SendOption

Header adds the header name with value to this call's request; the handler sees it in MessageInfo.Headers. The names the library sets itself (authorization, traceparent, tracestate, correlationId, correlation-id, and the schema version headers snodra-schema-version and snodra-response-schema-version, in any letter case) are refused: the call fails with ErrReservedHeader before anything is sent, never silently overwritten. A later Header of the same name wins.

func InitialCredit

func InitialCredit(n uint32) SendOption

InitialCredit is the credit window of a Stream or a Subscribe (Request.initial_credit): the parts the hub may relay before the first refill (a subscription's initial result included). The caller gives back half of it every time half of it was read, so the hub never relays more than a window ahead of the caller. 0, the default, reads as 64. The other calls ignore it.

func MaxResults

func MaxResults(n uint32) SendOption

MaxResults ends a Gather after n successful parts, a Stream after n items, or a Subscribe after n updates, the initial result not counted (Request.max_results): the hub sends the end then and cancels the targets or the handler still working. 0, the default, is no limit. Send and Query ignore it.

func NoRetry

func NoRetry() SendOption

NoRetry sends this call once, whatever DefaultRetry says.

func Priority

func Priority(p int32) SendOption

Priority is this call's Request.priority (higher is served first while the target's queue at the hub is not empty); it wins over Priorities. The default is 0.

func Retry

func Retry(p RetryPolicy) SendOption

Retry is this call's retry policy; it wins over DefaultRetry. An invalid policy fails the call before anything is sent.

func RoutingKey

func RoutingKey(key string) SendOption

RoutingKey sends the request with key (Request.routing_key): commands of one type with the same key go to the same instance of the owning service, typically the aggregate id. Queries ignore it at the hub.

func Timeout

func Timeout(d time.Duration) SendOption

Timeout is this call's timeout, sent as Request.timeout_ms; it wins over DefaultTimeout. A deadline of the call's context that comes sooner is the timeout instead. Without one the hub applies its per-type override or its default request timeout. A negative d fails the call.

type StoreLifecycle added in v0.3.0

type StoreLifecycle interface {
	// UseClock sets the application's clock: what the store stamps the times it sets itself
	// with (an outbox entry's sending, a claim's lease). The clock must not call the store.
	UseClock(now func() time.Time)
	// InitSchema prepares what the store needs in its database, idempotently: indexes (MongoDB,
	// with its retentions or TTLs), tables (SQL), nothing (memory). config is the application's
	// read-only settings. It runs when the service builds the store with schema initialization
	// on (the default).
	InitSchema(ctx context.Context, config *Config) error
	// CheckSchema fails unless the database has what the store needs, for example an SQL schema
	// at the version it reads or later. It runs instead of InitSchema when the service applies
	// the schema itself.
	CheckSchema(ctx context.Context) error
	// Background is what the store runs on its own while the app runs (for example the SQL
	// add-on's purge of what the retentions let go), until ctx is done. A store with nothing to
	// run may return at once or wait for ctx.
	Background(ctx context.Context) error
}

StoreLifecycle is what a message store may implement besides MessageStore: the builder calls these methods around the store's life, and the six store ports stay as they are, so a third-party add-on compiles against MessageStore alone. A store that does not implement it is simply used as it is.

App.Start hands the store the application's clock (UseClock), prepares its schema (InitSchema, with the application's Config), or checks a schema the service applies itself (CheckSchema), and then starts what the store runs in the background (Background), if it implements this interface. A failing InitSchema or CheckSchema fails Start; an error from Background while the app runs is logged.

type StreamWriter

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

StreamWriter sends the items of one streaming request (HandleStream). It is safe for concurrent use; the items go out in the order Send is called.

func (*StreamWriter[T]) Send

func (w *StreamWriter[T]) Send(ctx context.Context, item T) error

Send encodes item with the app's codec and sends it as the stream's next part, once the caller granted credit for it. It returns an error, and sends nothing, when ctx ends first, when the hub cancelled the stream or its hub stream is gone, when no credit came within StreamCreditTimeout (the stream then ended with TIMEOUT), or once the handler returned.

type SubscribersActiveError added in v0.2.0

type SubscribersActiveError struct {
	Members []string
}

SubscribersActiveError is the ErrSubscribersActive a reset returns while instances read the subscription. It names the members, and errors.Is finds ErrSubscribersActive.

func (*SubscribersActiveError) Error added in v0.2.0

func (e *SubscribersActiveError) Error() string

Error returns the subscribers-active message, naming the members when there are some.

func (*SubscribersActiveError) Is added in v0.2.0

func (e *SubscribersActiveError) Is(target error) bool

Is reports the error as ErrSubscribersActive.

type Subscription

type Subscription[I, U any] struct {
	// Initial is the initial result, answered by one instance of an owner.
	Initial I
	// contains filtered or unexported fields
}

Subscription is an open subscription query (Subscribe): its initial result, and the updates that follow until every owner completed, the hub ended it or it is closed.

func Subscribe

func Subscribe[I, U any](ctx context.Context, app *App, q Message, opts ...SendOption) (*Subscription[I, U], error)

Subscribe subscribes to the subscription query q (HandleSubscription on the other side): one Request in mode SUBSCRIPTION to one hub, unkeyed. The hub subscribes every live instance of every owner of q's type, as they are now (an instance that registers later is not added, one that leaves is not replaced: the updates arrive at most once, and neither the hub nor the library subscribes again), and asks one of them for the initial result.

sub, err := snodra.Subscribe[OrderView, OrderUpdate](ctx, app, WatchOrders{ID: "o-42"})
if err != nil {
	return err
}
defer sub.Close()
render(sub.Initial)
for u, err := range sub.Updates() {
	if err != nil {
		return err // the last thing the sequence yields
	}
	...
}

Subscribe returns once the initial result arrived, so its errors are those of Query: an *Error (NO_HANDLER without an owner, INVALID_REQUEST for a type no owner declared a subscription query type, which the hub refuses itself, or one served in another mode, TIMEOUT when the initial result is not in time, the handler's error, RESOURCE_EXHAUSTED, ...), ErrNeverSent, ErrOutcomeUnknown, the context's error, or a local failure (an initial result that does not decode, a hub that ended the subscription without one). The retry policy applies until then, as for a query: a retry is a new subscription with a fresh id, sending what is left of the call's time budget.

The updates are hot: the hub relays them from the open on, up to the credit window (InitialCredit, the initial result taking one credit), and buffers up to its own limit beyond it, ending the subscription with RESOURCE_EXHAUSTED when the caller falls further behind; reading them gives credit back. ctx bounds the whole subscription: when it ends (cancelled, or its deadline passed), the subscription is cancelled at the hub at once, ranging or not, and Subscription.Updates yields ctx's error (with ErrOutcomeUnknown) once.

The options are those of Query: Timeout (or DefaultTimeout) is sent as Request.timeout_ms and bounds the initial result only (the local guard waits the hub's bound plus 1 s for it; the updates have no timeout and no guard). A deadline of ctx does both: until the initial result it counts as the timeout when it comes sooner, and when it passes it ends the subscription, as above. InitialCredit is the credit window; MaxResults ends the subscription after that many updates. RoutingKey is ignored. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Subscription).

func (*Subscription[I, U]) Close

func (sub *Subscription[I, U]) Close()

Close cancels the subscription at the hub at once, which tells every owner instance, unless it ended already. It is safe to call more than once, from any goroutine, also from the loop body of a range over Subscription.Updates: that range ends once its loop body returns.

func (*Subscription[I, U]) Updates

func (sub *Subscription[I, U]) Updates() iter.Seq2[U, error]

Updates is the sequence of the subscription's updates, decoded as U, in the hub's arrival order (from every owner instance), until every owner completed (or MaxResults updates came). It can be ranged over once; a later range yields nothing more.

An error is the last thing the sequence yields: the hub's end with an error (an *Error by its code: an owner's failure, RESOURCE_EXHAUSTED when the hub's buffer for the caller overflowed, HANDLER_DISCONNECTED when the last owner left, CANCELLED at the hub's maximum duration, ...), ErrOutcomeUnknown when the hub stream was lost, ErrLostParts when the hub dropped updates, ctx's error (with ErrOutcomeUnknown, yielded once: by the range under way when ctx ends, else by the next range), or an update that does not decode. Breaking out of the loop cancels the subscription at the hub, as Subscription.Close does; a Close during the range (also from the loop body) ends it without an error once the loop body returns; the buffered updates may not be yielded (one that arrives with the Close can still be yielded once).

type SubscriptionAdmin added in v0.2.0

type SubscriptionAdmin interface {
	// Members is the instances reading the subscription now, the event store's ids for them;
	// empty when none does.
	Members(ctx context.Context) ([]string, error)
	// Plan says where target moves each segment, from the event store's current positions;
	// nothing moves yet. It returns one range per segment the target addresses, sorted by
	// segment. A target position the segment does not have (a segment the source lacks, a
	// position past the head) fails with ErrInvalid.
	Plan(ctx context.Context, target ResetTarget) ([]ReplayRange, error)
	// Apply moves the committed position of each range's segment to its From (Until is not
	// read), all or nothing. It fails with ErrSubscribersActive while an instance reads the
	// subscription.
	Apply(ctx context.Context, ranges []ReplayRange) error
}

SubscriptionAdmin is the reset side of one subscription (EventStore.Admin). Every call blocks (it talks to the event store); callers run them off their event loop, and they return when ctx is done.

type SubscriptionEvent added in v0.2.0

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

SubscriptionEvent is what EventSubscription.Next gives: an Assigned, a Revoked or a Delivery. The set is closed; an add-on constructs one of the three types and never implements the interface itself.

type SubscriptionSpec added in v0.2.0

type SubscriptionSpec struct {
	// Name is "<service>.<processor>": the name the event store knows the subscription by.
	Name string
	// Source is the source read.
	Source string
}

SubscriptionSpec names a processor's subscription. Every subscription of one Name shares the events of Source (competing instances), and each Name receives every event (one subscription per processor).

type TLSConfig

type TLSConfig struct {
	// CAFile is a PEM file of the CA certificates that sign the hubs' certificates, read again
	// at every connection (a rotated CA applies at the next one); "" trusts the system's roots
	// (SNODRA_SERVER_TLS_CA).
	CAFile string
	// ServerName is the name the hubs' certificates must carry, also sent as SNI; "" is the host
	// of each hub address (SNODRA_SERVER_TLS_SERVER_NAME).
	ServerName string
}

TLSConfig is TLS towards the hubs (see TLS).

type TokenSource

type TokenSource interface {
	Token(ctx context.Context) (AccessToken, error)
}

A TokenSource gives the instance a JWT to register with. The library asks for one before a stream opens when it holds none still fresh, and again ahead of its expiry (see JWT); one call at a time, bounded by a 10 s context. NewClientCredentials is the usual source.

func NewClientCredentials

func NewClientCredentials(c ClientCredentials) TokenSource

NewClientCredentials is a TokenSource fetching tokens with the OAuth2 client-credentials grant: a POST of grant_type=client_credentials (and scope) to TokenURL, the client authenticated with HTTP Basic (id and secret form-urlencoded first, RFC 6749 2.3.1), 10 s at most, no redirect followed. The answer's access_token is required, its token_type must be Bearer when present, and expires_in gives the expiry (unknown without it). Each call fetches; JWT keeps the token. The secret and the tokens never appear in an error. New checks the settings.

type Tx added in v0.2.0

type Tx interface {
	Commit(ctx context.Context) error
	Rollback(ctx context.Context) error
}

Tx is one transaction of the service's own database. A transaction must end with Commit or Rollback; an operation that fails with ErrConflict is retried as a whole, in a new transaction.

Commit writes what the transaction collected, all or nothing. It fails with ErrConflict when another writer got to one of its records first, and with the store's own error when the database failed; after a commit returns, the transaction has ended either way. Rollback abandons everything and never fails; a transaction that ended already is a no-op.

TODO(spec-gap): SG-31 (a transaction abandoned without Commit or Rollback keeps its write reservations until the process ends: Go has no destructor to release them; the reference's in-memory store reserves a row the same way until its transaction ends, snodra-messaging@64dde1e:snodra-messaging/src/main/kotlin/com/damoreira/snodra/messaging/store/memory/MemoryTables.kt:77).

type UnsupportedError added in v0.2.0

type UnsupportedError struct {
	Capability Capability
}

UnsupportedError is the ErrUnsupported an add-on returns for a missing capability. It names the capability, and errors.Is finds ErrUnsupported.

func (*UnsupportedError) Error added in v0.2.0

func (e *UnsupportedError) Error() string

Error returns the unsupported message, naming the capability when there is one.

func (*UnsupportedError) Is added in v0.2.0

func (e *UnsupportedError) Is(target error) bool

Is reports the error as ErrUnsupported.

type Updates

type Updates[Q Message, U any] struct {
	// contains filtered or unexported fields
}

Updates pushes the updates, of type U, of the subscription query type Q to the subscriptions this instance serves (HandleSubscription). Each call reaches every open subscription of Q whose query match accepts (a nil match accepts every one), in call order per subscription; a call never waits for a hub stream. It is safe for concurrent use, also from a match.

A subscription is reached from the moment its request is read: what is emitted before its admission is decided is held, then sent first (or dropped when it is refused). Its query is decoded off the hub stream, so a call waits for the decoding of the queries of the subscriptions read before it, to run match on them.

func HandleSubscription

func HandleSubscription[Q Message, I, U any](app *App, initial func(context.Context, Q) (I, error), opts ...HandlerOption) (*Updates[Q, U], error)

HandleSubscription registers the subscription query type Q, by Q's MessageType: initial answers a subscription's initial result (an I), and the returned Updates pushes the updates (each a U) to the subscriptions this instance serves, until they complete or fail. I and U are what a subscriber reads with Subscribe[I, U]. U cannot be inferred: give the three types, HandleSubscription[Q, I, U](app, initial). Q is registered in Register.query_types (with Shared, in Register.shared_query_types), and declared in Register.subscription_query_types: the hub serves it in mode SUBSCRIPTION only, so a Query, Stream or Gather of Q is answered INVALID_REQUEST by the hub before any instance sees it (this instance answers one that reaches it, through another hub or in-process, the same way).

The hub subscribes every live instance of every owner of Q: each gets the subscription (a request <id>#n, which this instance registers at once, before its admission: the caller's token, the guards, the decoding of the query and the limit, MaxSubscriptions), and one of them also gets the initial request <id>#0, which initial answers like a HandleQuery handler. Any other unary request of Q is answered INVALID_REQUEST. A subscription takes no permit and no handler slot: it is passive, fed by Updates.Emit from anywhere in the application, and ends with Updates.Complete or Updates.Fail, when the hub cancels it (the caller closed it, another owner failed, a limit), when its hub stream is lost, or at App.Shutdown, which completes every one of them.

Registration errors are those of HandleCommand; the Updates is nil then. See https://snodra.damoreira.com/docs/library-authors/protocol/ (Subscription).

func (*Updates[Q, U]) Complete

func (u *Updates[Q, U]) Complete(match func(Q) bool)

Complete ends every open subscription of Q that match accepts with a clean ReplyEnd; each is removed. At the hub a clean end removes this instance from the subscription; the last owner's clean end completes it for the caller.

func (*Updates[Q, U]) Emit

func (u *Updates[Q, U]) Emit(match func(Q) bool, update U) int

Emit sends update, encoded with the app's codec, as the next part of every open subscription of Q that match accepts, and returns how many it reached. An update that does not encode reaches none (logged); a match that panics skips its subscription (logged).

func (*Updates[Q, U]) Fail

func (u *Updates[Q, U]) Fail(match func(Q) bool, err error)

Fail ends every open subscription of Q that match accepts with ReplyEnd{HANDLER_ERROR}, err's message on one line and the details attached with WithDetails (always HANDLER_ERROR, also for an error of Unauthenticated and the like); each is removed. At the hub it ends the whole subscription with that error for the caller and cancels its other owners.

type Versioned added in v0.8.0

type Versioned interface{ MessageVersion() uint32 }

Versioned is the optional method of a message type that declares its version, a positive integer: the version is a promise about the type's JSON Schema, so a changed schema needs a new version. A type without the method is version 1; a version of 0 is a registration error. See https://snodra.damoreira.com/docs/library-authors/contracts/.

Directories

Path Synopsis
examples
conformance-service command
Command conformance-service is the service the Snodra conformance runner drives to check this library (https://github.com/snodra/snodra-conformance/blob/main/docs/contract.md), written with the library's public API as an application would write it.
Command conformance-service is the service the Snodra conformance runner drives to check this library (https://github.com/snodra/snodra-conformance/blob/main/docs/contract.md), written with the library's public API as an application would write it.
events-service command
The events service example: a command appends an event to the service's outbox, the relay publishes it to the event store, and the service's own event processor handles it.
The events service example: a command appends an event to the service's outbox, the relay publishes it to the event store, and the service's own event processor handles it.
quickstart command
internal
backoff
Package backoff computes the jittered exponential waits of reconnects, retries and token refreshes: a wait doubles from a floor up to a cap, and each wait is spread by ±20 % without ever exceeding the cap.
Package backoff computes the jittered exponential waits of reconnects, retries and token refreshes: a wait doubles from a floor up to a cap, and each wait is spread by ±20 % without ever exceeding the cap.
fakehub
Package fakehub is an in-process gRPC server implementing Hub.Connect, scripted frame by frame by unit tests, so the library's suite runs without a real hub.
Package fakehub is an in-process gRPC server implementing Hub.Connect, scripted frame by frame by unit tests, so the library's suite runs without a real hub.
jwt
Package jwt checks the callers' forwarded tokens: RS256 signatures against a JWKS, the issuer and the expiry.
Package jwt checks the callers' forwarded tokens: RS256 signatures against a JWKS, the issuer and the expiry.
rendezvous
Package rendezvous is the hub choice of a keyed request: the rendezvous score of a hub id and a routing key, and the ranking of hubs by it.
Package rendezvous is the hub choice of a keyed request: the rendezvous score of a hub id and a routing key, and the ranking of hubs by it.
traceparent
Package traceparent reads W3C trace context headers.
Package traceparent reads W3C trace context headers.
uuid
Package uuid generates random version 4 UUIDs.
Package uuid generates random version 4 UUIDs.
kafka module
mongo module
rabbitmq module
Package snodratest is the conformance kit for Snodra add-ons: the event-store kit (EventStore) and the message-store kit (MessageStore).
Package snodratest is the conformance kit for Snodra add-ons: the event-store kit (EventStore) and the message-store kit (MessageStore).
sql module

Jump to

Keyboard shortcuts

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