dispatch

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package dispatch is the "dispatcher" role: it leases due deliveries, sends them through their sink, retries failures with full-jitter exponential backoff, and sets them dead after a permanent error or the last attempt (ADR 0017). Delivery is at least once.

Index

Constants

View Source
const (
	DefaultWorkers     = 8
	DefaultMaxAttempts = 8
	DefaultRetryBase   = 12 * time.Minute
	DefaultRetryMax    = 12 * time.Hour
	DefaultLeaseTTL    = 2 * time.Minute
	// DefaultDeliverTimeout bounds one attempt (rendering and the sink
	// call). It stays well below DefaultLeaseTTL, so a holder gives up
	// before its lease can expire, and DefaultDeliverTimeout + writeTimeout
	// stays below supervisor.DefaultDrainTimeout (25 s), so an attempt in
	// progress at shutdown is still recorded.
	DefaultDeliverTimeout = 15 * time.Second
	DefaultPollInterval   = time.Second
)

Defaults for zero Options fields.

View Source
const (
	ReasonSubscriptionDeleted = "subscription deleted"
	ReasonSinkDeleted         = "sink deleted"
)

Reasons a delivery is set dead without calling a sink (maintainer decision on #107: a deleted subscription or sink fails its deliveries).

View Source
const (
	OutcomeDelivered = store.DeliveryDelivered
	OutcomeRetry     = "retry" // failed, due again later
	OutcomeDead      = store.DeliveryDead
)

Outcomes of an attempt, as reported to Metrics.

View Source
const WriteTimeout = writeTimeout

WriteTimeout bounds the store write that ends an attempt, after the attempt's DeliverTimeout. An attempt in progress at shutdown is recorded only when the drain timeout exceeds DeliverTimeout + WriteTimeout.

Variables

This section is empty.

Functions

func ResolveSecrets

func ResolveSecrets(ctx context.Context, cfg []byte, src SecretSources) (map[string]secrets.Value, error)

ResolveSecrets resolves the secret references of a sink configuration into the map of sink.Request.Secrets (ADR 0023 section 4, ADR 0024 §6):

  • every key ending in "_env", at any depth, names an environment variable read with src.LookupEnv;
  • every key ending in "_ref" names a stored secret, resolved with src.Stored for src.Destination.

The map key is the RFC 6901 JSON Pointer of the reference key, such as "/secret_env" or "/secret_ref". A configuration without references gives a nil map; one that is not JSON is left to the sink to reject.

A reference that is not a valid name, an unset or empty variable, a missing secret, a host the secret is not bound to or a secret that cannot be opened, or a variable starting with ANGELIA_, is an error naming the pointer and the variable or secret, never a value. The dispatcher retries it: the operator fixes it by setting the variable, storing the secret or changing its binding.

func RetryCeiling

func RetryCeiling(failed int64, base, maxDelay time.Duration) time.Duration

RetryCeiling is the upper bound of the wait after the failed-th failed attempt (failed >= 1): base·2^(failed−1), capped at maxDelay. failed <= 0 returns base.

func RetryDelay

func RetryDelay(failed int64, base, maxDelay time.Duration, r float64) time.Duration

RetryDelay is the wait before the next attempt after the failed-th failed attempt, with full jitter: r in [0, 1) maps linearly onto [0, RetryCeiling). Full jitter spreads the retries of deliveries that failed together (a sink outage) over the whole window instead of sending them back in waves. r is clamped to [0, 1].

With the defaults (base 12 min, cap 12 h, 8 attempts) the seven waits have ceilings of 12 min, 24 min, 48 min, 1 h 36, 3 h 12, 6 h 24 and 12 h: the last attempt comes at most 24 h 36 min after the first, about 12 h on average.

Types

type Clock

type Clock interface {
	Now() time.Time
	// Timer returns a channel that receives once d has elapsed, and a
	// function that stops the timer.
	Timer(d time.Duration) (<-chan time.Time, func())
}

Clock is the dispatcher's time source. Tests replace it with a fake so that retry times and lease expiry are deterministic without sleeps.

type DefaultRenderer

type DefaultRenderer struct{}

DefaultRenderer sends the CloudEvents JSON of the event, which is the default payload (architecture.md 3.5). It rejects a non-empty template as permanent until templating exists.

func (DefaultRenderer) Render

func (DefaultRenderer) Render(_ context.Context, template string, envelope []byte) (sink.Rendered, error)

Render implements Renderer.

type Dispatcher

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

Dispatcher is the "dispatcher" role: it leases due deliveries from the store, sends each through the sink of its subscription on a bounded worker pool, and records the outcome: delivered, retried with backoff, or dead after a permanent error or the last attempt.

Delivery is at least once. A delivery is sent by one holder at a time (its lease, ADR 0017); a holder that crashes mid-send leaves it in flight and another holder sends it again once the lease expires. Consumers drop duplicates by the event id or the idempotency key.

func New

func New(st Store, sinks Sinks, opts Options) (*Dispatcher, error)

New returns a Dispatcher. It does not start anything; call Run.

func (*Dispatcher) Name

func (d *Dispatcher) Name() string

Name implements supervisor.Role.

func (*Dispatcher) Run

func (d *Dispatcher) Run(ctx context.Context) error

Run implements supervisor.Role. It polls for due deliveries until ctx is cancelled, then waits for the attempts already started: they are not cancelled (that would turn a send into a likely duplicate) but end within DeliverTimeout. It returns nil.

type Metrics

type Metrics interface {
	// AttemptFinished is called once an attempt's outcome (OutcomeDelivered,
	// OutcomeRetry or OutcomeDead) is recorded in the store. An attempt that
	// lost its lease, or whose result could not be written, is not reported.
	AttemptFinished(outcome string)
}

Metrics receives dispatcher observations. Phase 1 exports them to Prometheus (internal/metrics); a nil Metrics discards them.

type Options

type Options struct {
	// Workers is the number of deliveries sent at the same time.
	Workers int
	// MaxAttempts is the number of attempts before a delivery is dead.
	MaxAttempts int64
	// RetryBase and RetryMax shape the wait between attempts: after the
	// n-th failure it is drawn uniformly from [0, min(RetryBase·2^(n−1),
	// RetryMax)) (full jitter, see RetryDelay).
	RetryBase, RetryMax time.Duration
	// LeaseTTL is how long a delivery lease lasts; a crashed holder's
	// deliveries are sent again after it.
	LeaseTTL time.Duration
	// DeliverTimeout bounds one attempt (rendering and the sink call). It
	// must be at most LeaseTTL − max(30 s, LeaseTTL/4); that margin is the
	// clock skew tolerated between dispatchers. Zero means
	// DefaultDeliverTimeout, or that bound when it is lower. Keep
	// DeliverTimeout + writeTimeout (8 s) below the supervisor's drain timeout, so that
	// attempts in progress at shutdown are recorded.
	DeliverTimeout time.Duration
	// PollInterval is how often the store is asked for due deliveries.
	PollInterval time.Duration
	// Holder identifies this dispatcher in the lease table. Empty means the
	// host name plus a random suffix; two dispatchers must never share one.
	Holder string
	Clock  Clock
	// Rand returns a number in [0, 1); nil means math/rand/v2. Workers call
	// it concurrently, so it must be safe for concurrent use.
	Rand   func() float64
	Logger *slog.Logger
	// TracerProvider starts the root span of every delivery attempt. Nil
	// records nothing.
	TracerProvider trace.TracerProvider
	// Renderer builds messages; nil means DefaultRenderer.
	Renderer Renderer
	// Metrics receives attempt outcomes; nil discards them.
	Metrics Metrics
	// LookupEnv reads the environment variable named by each *_env key of a
	// sink's configuration, for sink.Request.Secrets (ADR 0023 section 4).
	// Nil means os.LookupEnv. It is called on every attempt: values are not
	// cached.
	LookupEnv func(string) (string, bool)
	// Secrets resolves the stored secret named by each *_ref key of a sink's
	// configuration, for sink.Request.Secrets (ADR 0024 §6), on every
	// attempt. Nil: a sink with a *_ref key fails before Deliver, retried.
	Secrets SecretResolver
	// Destinations maps a sink kind to the JSON Pointer of the key its
	// config_schema marks x-angelia-destination (api.SinkDestinations): a
	// secret bound to hosts is resolved only for that URL. A kind with
	// none gets only unbound secrets.
	Destinations map[string]string
	// SecretDestinations maps a sink kind to the JSON Pointers of the
	// reference keys its config_schema marks x-angelia-secret-destination
	// (api.SinkSecretDestinations; ADR 0026): the resolved value is the
	// destination. For such a kind the sink derives the origins
	// (sink.SecretDestinations) and the dispatcher checks each against
	// AllowHTTPHosts, URLCheck and the secret's hosts before Deliver.
	SecretDestinations map[string][]string
	// URLCheck is the SSRF guard's URL check of those origins: the netguard
	// client the sinks send through. Nil fails every delivery of a kind
	// with secret destinations (retried).
	URLCheck URLChecker
	// AllowHTTPHosts is http.allow_http_hosts: the only hosts a derived
	// origin may use over plain http (decision D12).
	AllowHTTPHosts []string
}

Options configures a Dispatcher. Zero fields take the Default* values.

type Renderer

type Renderer interface {
	Render(ctx context.Context, template string, envelope []byte) (sink.Rendered, error)
}

Renderer builds the message of a delivery from its subscription's template and the event's stored CloudEvents JSON (envelope). The templating story (#114) provides the real one; a permanent error (sink.Permanent) sets the delivery dead. Render must not keep or modify envelope.

type SecretResolver

type SecretResolver interface {
	Resolve(ctx context.Context, name string, dest *url.URL) (secrets.Bound, error)
	ResolveSelfAddressed(ctx context.Context, name string) (secrets.Bound, error)
}

SecretResolver resolves a stored secret: *secrets.Resolver. Resolve resolves it for one destination: a secret bound to hosts is resolved only when dest's host and port equal one of them (ADR 0024 §2). ResolveSelfAddressed resolves a secret whose value is the destination, with its hosts, for the dispatcher to check against the origins derived from it (ADR 0026 §2).

type SecretSources

type SecretSources struct {
	// LookupEnv reads the variable named by each *_env key.
	LookupEnv func(string) (string, bool)
	// Stored resolves each *_ref key; nil fails every *_ref key.
	Stored SecretResolver
	// Destination is the URL the sink sends to: the configuration value the
	// kind's config_schema marks x-angelia-destination. A bound secret is
	// resolved only for it; nil refuses every bound secret.
	Destination *url.URL
	// SelfAddressed are the pointers of the keys the kind's config_schema
	// marks x-angelia-secret-destination (ADR 0026 §2). A *_ref key at one
	// of them is resolved with Stored.ResolveSelfAddressed, without the
	// host check, and comes back with its hosts for the caller to check.
	SelfAddressed []string
}

SecretSources are where ResolveSecrets reads values from.

type Sinks

type Sinks interface {
	Get(kind string) (sink.Sink, error)
}

Sinks finds the Sink of a kind; *sink.Registry implements it.

type Store

type Store interface {
	LeaseDueDeliveries(ctx context.Context, holder string, now, until time.Time, limit int) ([]store.LeasedDelivery, error)
	HasDueDeliveries(ctx context.Context, now time.Time) (bool, error)
	FinishDelivery(ctx context.Context, f store.DeliveryFinish, holder string) (bool, error)
}

Store is the part of store.Store the dispatcher uses.

type URLChecker

type URLChecker interface {
	CheckURL(ctx context.Context, u *url.URL) error
}

URLChecker is the SSRF guard's URL check: *netguard.Client.

Jump to

Keyboard shortcuts

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