snodra

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 44 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 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 the Kotlin and Rust libraries: 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.
  • 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.
  • Feature level 1, proved by the 33 checks of the conformance runner. Events, stores, event processors and sagas (levels 2 to 4) are not in it yet: the Kotlin and Rust libraries have them.

Install

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

Both modules are on the Go module proxy and need Go 1.26 or later; the core depends only on gRPC and protobuf. Both modules of a release have the same version.

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 same SNODRA_* variables as the Rust library; options given after it win.

Documentation

Quick start, the settings map, the API and testing: https://snodra.damoreira.com/messaging/go/, and go doc -all for the package. A complete service is examples/quickstart. The counterparts are snodra-messaging (Kotlin, the reference) and snodra-messaging-rs (Rust); all three speak the same protocol (snodra.hub.v1). Where the specification was silent, this library does what the Kotlin library does: SPEC-GAPS.md records each case.

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 two 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 for github.com/snodra/snodra-messaging-go/observability. CI commits release: X.Y.Z (Version in version.go, the requirement of observability/go.mod on the root module with its hashes in observability/go.sum, and the go.work replacement) and tags that commit twice. Before anything is pushed, both modules are built and tested as a consumer gets them, from the new tag. A last job, which builds nothing, pushes the commit and both tags together or not at all. The release workflow then has the Go proxy fetch both versions 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/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
}

Index

Examples

Constants

View Source
const Version = "0.1.1"

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 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 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/library-authors/protocol/ (Handling a request).

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 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/library-authors/protocol/ (Streaming).

func InvalidRequest

func InvalidRequest(msg string) error

InvalidRequest returns an error that a handler answers as INVALID_REQUEST.

func PermissionDenied

func PermissionDenied(msg string) error

PermissionDenied returns an error that a handler answers as PERMISSION_DENIED.

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 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/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 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/library-authors/protocol/ (Streaming).

func Unauthenticated

func Unauthenticated(msg string) error

Unauthenticated returns an error that a handler answers as UNAUTHENTICATED.

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. 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/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 only checked on entry (Start returns its error when it is already done): 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 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/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 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/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 Empty

type Empty struct{}

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

type Error

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

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. See https://snodra.damoreira.com/library-authors/messages/.

func (*Error) Error

func (e *Error) Error() string

Error returns "<CODE>: <Message>".

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/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.

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, as in the reference library. 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/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 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 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/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 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/library-authors/messages/): change it only for a codec that writes the same JSON.

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 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, the same variables the Rust library reads (the Kotlin library is configured with Spring properties). 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); the Rust library reads it too, the Kotlin library has the Spring property snodra.messaging.hub.always-route-through-hub instead
  • 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)

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/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 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; as in the reference libraries, 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.

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/library-authors/messages/.

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",
	// "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, 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 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/library-authors/protocol/ (Never sent or outcome unknown).

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, in any letter case) are refused: the call fails with ErrReservedHeader before anything is sent. 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 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 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/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 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 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/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.

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.
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
sql module

Jump to

Keyboard shortcuts

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