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
}
Output:
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
}
Output:
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
}
Output:
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
}
Output:
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
}
Output:
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
}
Output:
Index ¶
- Constants
- Variables
- func CheckOutboxPayload(typeName string, payload []byte) error
- func DeadLetterSource(source string) string
- func HandleCommand[C Message, R any](app *App, h func(context.Context, C) (R, error), opts ...HandlerOption) error
- func HandleEvent[E Message](app *App, h func(context.Context, E) error, opts ...EventOption) error
- func HandleQuery[Q Message, R any](app *App, h func(context.Context, Q) (R, error), opts ...HandlerOption) error
- func HandleStream[Q Message, T any](app *App, h func(context.Context, Q, *StreamWriter[T]) error, ...) error
- func InvalidRequest(msg string) error
- func LetterID(processor, source, segment, position string) string
- func PermissionDenied(msg string) error
- func ProcessorMarker(processor, eventID string) string
- func ProcessorSubscription(service, processor string) string
- func Publish[E Message](ctx context.Context, app *App, e E, opts ...PublishOption) error
- func Query[R any](ctx context.Context, app *App, q Message, opts ...SendOption) (R, error)
- func SegmentOrder(a, b string) int
- func Send[R any](ctx context.Context, app *App, cmd Message, opts ...SendOption) (R, error)
- func Stream[T any](ctx context.Context, app *App, q Message, opts ...SendOption) iter.Seq2[T, error]
- func Supports(store EventStore, capability Capability) bool
- func Unauthenticated(msg string) error
- func WithDetails(err error, details any) error
- type AccessToken
- type App
- func (a *App) HubIDs() []string
- func (a *App) Ready(ctx context.Context) error
- func (a *App) Rejection() (Rejection, bool)
- func (a *App) Run(ctx context.Context) error
- func (a *App) Shutdown(ctx context.Context) error
- func (a *App) Start(ctx context.Context) error
- func (a *App) SubscriptionsServed() int
- type Assigned
- type Caller
- type Capability
- type ClientCredentials
- type Code
- type Config
- type ControlOperation
- type DeadLetter
- type DeadLetterError
- type DeadLetterReason
- type DeadLetterStore
- type DeadLetterSummary
- type DeadlineStatus
- type Delivery
- type DispatchFailure
- type DispatchKind
- type Empty
- type Error
- type EventOption
- type EventPublisher
- type EventStore
- type EventSubscription
- type ExternalCall
- type ExternalCallStatus
- type ExternalCallStore
- type FailureReason
- type Gathered
- type Gauges
- type GaugesStopper
- type HandlerOption
- type Handling
- type Instrumentation
- type LockOutcome
- type MemoryEventStore
- func (s *MemoryEventStore) Admin(spec SubscriptionSpec) (SubscriptionAdmin, error)
- func (s *MemoryEventStore) Capabilities() []Capability
- func (s *MemoryEventStore) Compare(segment, a, b string) int
- func (s *MemoryEventStore) Events(source string) []Delivery
- func (s *MemoryEventStore) Name() string
- func (s *MemoryEventStore) Publish(ctx context.Context, event OutgoingEvent) error
- func (s *MemoryEventStore) Subscribe(ctx context.Context, spec SubscriptionSpec) (EventSubscription, error)
- type MemoryMessageStore
- func (s *MemoryMessageStore) Background(ctx context.Context) error
- func (s *MemoryMessageStore) Begin(ctx context.Context) (context.Context, Tx, error)
- func (s *MemoryMessageStore) CheckSchema(context.Context) error
- func (s *MemoryMessageStore) Control() ProcessorControlStore
- func (s *MemoryMessageStore) DeadLetters() DeadLetterStore
- func (s *MemoryMessageStore) ExternalCalls() ExternalCallStore
- func (s *MemoryMessageStore) InitSchema(context.Context, *Config) error
- func (s *MemoryMessageStore) Name() string
- func (s *MemoryMessageStore) Outbox() OutboxStore
- func (s *MemoryMessageStore) Processed() ProcessedStore
- func (s *MemoryMessageStore) Sagas() SagaStores
- func (s *MemoryMessageStore) UseClock(now func() time.Time)
- type Message
- type MessageInfo
- type MessageStore
- type NopInstrumentation
- func (NopInstrumentation) CertificateRotated()
- func (NopInstrumentation) CredentialsRefreshSent()
- func (NopInstrumentation) Inject(context.Context, map[string]string)
- func (NopInstrumentation) ObserveGauges(func() Gauges)
- func (NopInstrumentation) RequestDone(string, string, string, time.Duration)
- func (NopInstrumentation) StartHandling(ctx context.Context, _ Handling) (context.Context, func(error))
- func (NopInstrumentation) TokenFetched(string)
- type Option
- func AlwaysRouteThroughHub(on bool) Option
- func ClientCertificate(certFile, keyFile string) Option
- func Codec(c PayloadCodec) Option
- func ConsumerEnabled(on bool) Option
- func DefaultRetry(p RetryPolicy) Option
- func DefaultTimeout(d time.Duration) Option
- func EventsSource(source string) Option
- func ForwardJWT(on bool) Option
- func FromEnv() Option
- func Hubs(addresses ...string) Option
- func Instance(id string) Option
- func JWKS(url, issuer string) Option
- func JWT(src TokenSource) Option
- func LoadFactor(n uint32) Option
- func Logger(l *slog.Logger) Option
- func MaxConcurrent(n int) Option
- func MaxSubscriptions(n int) Option
- func OutboxEnabled(on bool) Option
- func Priorities(p map[string]int32) Option
- func ReconnectBackoff(min, max time.Duration) Option
- func RolesClaim(path string) Option
- func Service(name string) Option
- func StatusInterval(d time.Duration) Option
- func StreamCreditTimeout(d time.Duration) Option
- func TLS(cfg TLSConfig) Option
- func Tags(tags map[string]string) Option
- func Telemetry(i Instrumentation) Option
- func Token(token string) Option
- func TokenFile(path string) Option
- func WithEventStore(store EventStore) Option
- func WithStore(store MessageStore) Option
- type OutboxEntry
- type OutboxStore
- type OutgoingEvent
- type ParkResult
- type Part
- type PayloadCodec
- type ProcessedEvents
- type ProcessedMarker
- type ProcessedStore
- type ProcessorControlState
- type ProcessorControlStore
- type PublishOption
- type Rejection
- type ReplayRange
- type ResetEarliest
- type ResetLatest
- type ResetPositions
- type ResetTarget
- type ResetTimestamp
- type RetryPolicy
- type Revoked
- type Saga
- type SagaAssociation
- type SagaDeadline
- type SagaDeadlineStore
- type SagaDispatch
- type SagaDispatchStore
- type SagaFailure
- type SagaFailureStore
- type SagaMarkerStore
- type SagaRepository
- type SagaStores
- type SegmentPosition
- type SegmentStatus
- type SendOption
- type StoreLifecycle
- type StreamWriter
- type SubscribersActiveError
- type Subscription
- type SubscriptionAdmin
- type SubscriptionEvent
- type SubscriptionSpec
- type TLSConfig
- type TokenSource
- type Tx
- type UnsupportedError
- type Updates
Examples ¶
Constants ¶
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" )
The headers every event carries, as the event store's native metadata.
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 )
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 )
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.
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>".
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).
const MaxDeadLetterErrorChars = 2000
The most characters of a dead letter's error message.
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).
const (
// MemoryMessageStoreName is the in-memory message store's name (MessageStore.Name).
MemoryMessageStoreName = "memory"
)
const ResetKind = "reset"
ResetKind is ControlOperation.Kind of a reset, the only kind there is.
const Version = "0.5.0"
Version is the version of this library.
Variables ¶
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.
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.
var AllCapabilities = [...]Capability{ CapabilityReplay, CapabilityBrowse, CapabilityLag, CapabilityNativeDeadLetter, }
AllCapabilities lists the capabilities the protocol names, in protocol order.
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.
var EventHeaders = [...]string{ HeaderType, HeaderID, HeaderCorrelationID, HeaderTimestamp, HeaderSource, HeaderUserID, HeaderTraceparent, }
EventHeaders lists the seven headers, in the order the specification gives them.
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
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
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
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 logged and skipped (level 3 parks it as a dead letter instead).
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 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/docs/library-authors/protocol/ (Streaming).
func InvalidRequest ¶
InvalidRequest returns an error that a handler answers as INVALID_REQUEST.
func LetterID ¶ added in v0.2.0
LetterID is a letter's id: "<processor>:<source>:<segment>:<position>" (on Kafka "<processor>:<topic>:<partition>:<offset>", as always).
func PermissionDenied ¶
PermissionDenied returns an error that a handler answers as PERMISSION_DENIED.
func ProcessorMarker ¶ added in v0.3.0
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
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
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 ¶
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 SegmentOrder ¶ added in v0.2.0
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 ¶
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 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 ¶
Unauthenticated returns an error that a handler answers as UNAUTHENTICATED.
func WithDetails ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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/.
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
ControlOperation is the lock of a reset: held until LeaseUntil unless renewed. PreparedAt is the first prepare's time; a renewal keeps it.
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
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 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/docs/library-authors/messages/.
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 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.
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.
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 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
func (s *MemoryEventStore) Admin(spec SubscriptionSpec) (SubscriptionAdmin, error)
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 the capabilities the store declares: CapabilityReplay and CapabilityLag. 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
func (s *MemoryEventStore) Subscribe(ctx context.Context, spec SubscriptionSpec) (EventSubscription, error)
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 and the processed-event markers; the dead letters, processor control, external calls and saga ports of this release return ErrUnsupported (the official add-ons implement every store by level 4, and this store follows).
- 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.
- Nothing 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
func (s *MemoryMessageStore) Control() ProcessorControlStore
Control returns the processor-control port, which this store does not implement yet: every operation fails with ErrUnsupported.
func (*MemoryMessageStore) DeadLetters ¶ added in v0.2.0
func (s *MemoryMessageStore) DeadLetters() DeadLetterStore
DeadLetters returns the dead-letter port, which this store does not implement yet: every operation fails with ErrUnsupported.
func (*MemoryMessageStore) ExternalCalls ¶ added in v0.2.0
func (s *MemoryMessageStore) ExternalCalls() ExternalCallStore
ExternalCalls returns the external-call port, which this store does not implement yet: every operation fails with ErrUnsupported.
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, which this store does not implement yet: every operation fails with ErrUnsupported.
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) Inject(context.Context, map[string]string)
func (NopInstrumentation) ObserveGauges ¶
func (NopInstrumentation) ObserveGauges(func() Gauges)
func (NopInstrumentation) RequestDone ¶
func (NopInstrumentation) StartHandling ¶
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 ¶
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 ¶
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
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 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 ¶
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
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 ¶
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_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 ¶
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 ¶
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 ¶
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 ¶
LoadFactor is the instance's relative capacity (Register.load_factor); 0 reads as 100, the default.
func Logger ¶
Logger is where the library logs; the default is slog.Default.
func MaxConcurrent ¶
MaxConcurrent is how many handlers the instance runs at once (the permits it offers the hubs). The default is 256.
func MaxSubscriptions ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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",
// "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 ReplayRange ¶ added in v0.2.0
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 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 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
SagaAssociation is an association "Key = Value" of a saga instance: events whose association value is Value for Key are routed to it.
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 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 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.
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 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 SegmentPosition ¶ added in v0.2.0
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 ¶
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 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
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 ¶
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 ¶
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 ¶
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 ¶
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.
Source Files
¶
- app.go
- connection.go
- consumer.go
- context.go
- credentials.go
- dispatch.go
- doc.go
- env.go
- errors.go
- events.go
- eventstore.go
- eventstore_memory.go
- gather.go
- identity.go
- local.go
- message.go
- options.go
- outbox.go
- permits.go
- pool.go
- processor.go
- propagation.go
- register.go
- retry.go
- send.go
- store.go
- store_memory.go
- stream_client.go
- stream_handler.go
- subscribe.go
- subscription_handler.go
- targets.go
- telemetry.go
- timings.go
- tls.go
- version.go
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
|
|
|
observability
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
|