resiliency

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package resiliency provides declarative, configuration-driven resilience policies (timeouts, retries and circuit breakers) bound to service endpoints, modeled after Dapr's resiliency policy model. It composes with the primitive middleware in pkg/resilience but adds named-policy templates, target binding, status-code-range matching and per-endpoint breaker state.

Relationship to pkg/resilience: pkg/resilience is the imperative layer of client-side primitives (circuit breaker, retry, timeout, hedge, shedder, deadline, bulkhead) written as func(Handler) Handler middleware. This package is the declarative layer above it: a YAML-driven Provider resolves a PolicyDefinition per app endpoint at call time. Note that the circuit breaker implemented in breaker.go is a "consecutive-failure threshold" breaker, which differs in semantics from the Google SRE sliding-window breaker in pkg/resilience — the two are intentionally distinct algorithms, not a duplicated implementation.

Index

Constants

This section is empty.

Variables

View Source
var ErrCircuitOpen = errno.ErrCircuitOpen

ErrCircuitOpen is returned when the breaker rejects a request while open.

Functions

func ParseStatusRanges

func ParseStatusRanges(s string) (func(int) bool, error)

ParseStatusRanges parses a comma-separated list of status codes and inclusive ranges (e.g. "500,502-504") into a predicate. An empty string yields a predicate that matches nothing.

func Runner

func Runner[T any](ctx context.Context, def *PolicyDefinition, op func(ctx context.Context) (T, error)) (T, error)

Runner executes op under def's resilience policies, applying timeout outermost, then the circuit breaker, then retries innermost (each attempt passes through the breaker). When def is nil, op runs unmodified.

Types

type CircuitBreaker

type CircuitBreaker struct {
	// MaxRequests is the number of requests allowed in the half-open state.
	MaxRequests int `json:"maxRequests,omitempty" yaml:"maxRequests,omitempty"`
	// Interval is reserved for a future sliding-window breaker. The current
	// breaker trips on a consecutive-failure threshold (see Trip), so this
	// field is parsed for compatibility but not yet applied.
	Interval string `json:"interval,omitempty" yaml:"interval,omitempty"`
	// Timeout is how long the breaker stays open before half-open.
	Timeout string `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	// Trip is a predicate describing when to open. A CEL expression is reserved
	// for future use; when empty, a default consecutive-failure threshold is
	// used.
	Trip string `json:"trip,omitempty" yaml:"trip,omitempty"`
}

CircuitBreaker is a named circuit breaker policy template.

type CircuitBreakerState

type CircuitBreakerState interface {
	// Execute runs req under the breaker, classifying results via acceptable
	// (nil acceptable treats any non-nil error as a failure).
	Execute(req func() error, acceptable func(error) bool) error
	// State reports the current breaker state.
	State() State
}

CircuitBreakerState protects requests with a closed/open/half-open breaker.

type EndpointPolicyNames

type EndpointPolicyNames struct {
	Timeout                 string `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	Retry                   string `json:"retry,omitempty" yaml:"retry,omitempty"`
	CircuitBreaker          string `json:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty"`
	CircuitBreakerCacheSize int    `json:"circuitBreakerCacheSize,omitempty" yaml:"circuitBreakerCacheSize,omitempty"`
}

EndpointPolicyNames references named policies for a single endpoint.

type Policies

type Policies struct {
	Timeouts        map[string]string         `json:"timeouts,omitempty" yaml:"timeouts,omitempty"`
	Retries         map[string]Retry          `json:"retries,omitempty" yaml:"retries,omitempty"`
	CircuitBreakers map[string]CircuitBreaker `json:"circuitBreakers,omitempty" yaml:"circuitBreakers,omitempty"`
}

Policies holds named policy templates.

type PolicyDefinition

type PolicyDefinition struct {
	Name           string
	Timeout        time.Duration
	Retry          *RetryPolicy
	CircuitBreaker CircuitBreakerState
}

PolicyDefinition is a compiled set of resilience policies for an endpoint.

type Provider

type Provider interface {
	// EndpointPolicy returns the compiled policy for an app's endpoint, or nil
	// when no policy is defined for it.
	EndpointPolicy(app, endpoint string) *PolicyDefinition
	// PolicyDefined reports whether the app has any resilience configuration.
	PolicyDefined(app string) bool
}

Provider resolves resilience policies for service endpoints.

func FromConfigurations

func FromConfigurations(cfgs ...*Resiliency) (Provider, error)

FromConfigurations builds a Provider from parsed Resiliency configurations.

func Load

func Load(paths ...string) (Provider, error)

Load reads resiliency YAML files and builds a Provider. Each file is a single Resiliency document.

type Resiliency

type Resiliency struct {
	Name   string   `json:"name" yaml:"name"`
	Spec   Spec     `json:"spec" yaml:"spec"`
	Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
}

Resiliency is a named resiliency configuration.

type Retry

type Retry struct {
	// Policy is the backoff strategy: "constant" or "exponential".
	Policy string `json:"policy,omitempty" yaml:"policy,omitempty"`
	// Duration is the initial backoff duration, e.g. "100ms".
	Duration string `json:"duration,omitempty" yaml:"duration,omitempty"`
	// MaxInterval caps the backoff duration.
	MaxInterval string `json:"maxInterval,omitempty" yaml:"maxInterval,omitempty"`
	// MaxRetries is the number of retries after the first attempt.
	MaxRetries *int `json:"maxRetries,omitempty" yaml:"maxRetries,omitempty"`
	// Matching restricts which errors are retried by status code.
	Matching *RetryMatching `json:"matching,omitempty" yaml:"matching,omitempty"`
}

Retry is a named retry policy template.

type RetryMatching

type RetryMatching struct {
	// HTTPStatusCodes is a comma/range list, e.g. "500,502-504".
	HTTPStatusCodes string `json:"httpStatusCodes,omitempty" yaml:"httpStatusCodes,omitempty"`
	// GRPCStatusCodes is a comma/range list of gRPC status codes, e.g. "14,8".
	GRPCStatusCodes string `json:"gRPCStatusCodes,omitempty" yaml:"gRPCStatusCodes,omitempty"`
}

RetryMatching selects retryable errors by status code range.

type RetryPolicy

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

RetryPolicy is a compiled retry policy.

type Spec

type Spec struct {
	Policies Policies `json:"policies" yaml:"policies"`
	Targets  Targets  `json:"targets" yaml:"targets"`
}

Spec holds the policy templates and their target bindings.

type State

type State int32

State is a circuit breaker state.

const (
	// StateClosed lets requests through normally.
	StateClosed State = iota
	// StateOpen rejects requests until the cooldown elapses.
	StateOpen
	// StateHalfOpen lets a bounded number of probe requests through.
	StateHalfOpen
)

func (State) String

func (s State) String() string

type Targets

type Targets struct {
	Apps map[string]EndpointPolicyNames `json:"apps,omitempty" yaml:"apps,omitempty"`
}

Targets binds named policies to endpoints.

Jump to

Keyboard shortcuts

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