Documentation
¶
Overview ¶
Package gateway provides a transport-independent, data-independent routing kernel.
A Gateway selects an eligible provider, executes it, applies an explicit failure policy, and returns the provider's response. The package does not interpret, serialize, persist, or otherwise own application payloads.
Gateway configuration is immutable after construction and Gateway is safe for concurrent use. Providers, filters, routing strategies, failure policies, and observers supplied by callers may be invoked concurrently and must therefore be concurrency-safe.
Index ¶
- func ValueAs[T any](result Result) (T, bool)
- type Backoff
- type BackoffFunc
- type Candidate
- type CooldownConfig
- type Error
- type ErrorCode
- type Event
- type EventType
- type ExponentialBackoff
- type Failure
- type FailureAction
- type FailureDecision
- type FailurePolicy
- type FailurePolicyFunc
- type Filter
- type FilterFunc
- type Gateway
- type Observer
- type ObserverFunc
- type Operation
- type Option
- func WithFailurePolicy(policy FailurePolicy) Option
- func WithMaxAttempts(maxAttempts int) Option
- func WithObserver(observer Observer) Option
- func WithProviders(providers ...ProviderRegistration) Option
- func WithRequestTimeout(timeout time.Duration) Option
- func WithRouting(strategy RoutingStrategy) Option
- type Provider
- type ProviderFunc
- type ProviderID
- type ProviderOption
- func WithCooldown(config CooldownConfig) ProviderOption
- func WithFilter(filter Filter) ProviderOption
- func WithMaxInFlight(limit int64) ProviderOption
- func WithOperations(operations ...Operation) ProviderOption
- func WithProviderCost(cost float64) ProviderOption
- func WithProviderPriority(priority int) ProviderOption
- func WithProviderWeight(weight uint32) ProviderOption
- type ProviderRegistration
- type ProviderStats
- type Request
- type RequestOption
- type Result
- type RoutingFunc
- type RoutingStrategy
- func Least(scorer Scorer) RoutingStrategy
- func LeastBusy() RoutingStrategy
- func LowestCost() RoutingStrategy
- func LowestLatency() RoutingStrategy
- func PowerOfTwo(scorer Scorer) RoutingStrategy
- func Priority(ids ...ProviderID) RoutingStrategy
- func Random() RoutingStrategy
- func RoundRobin() RoutingStrategy
- func Sticky() RoutingStrategy
- func Weighted() RoutingStrategy
- type ScoreFunc
- type Scorer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Backoff ¶ added in v1.0.0
Backoff computes a delay before another provider attempt.
func FixedBackoff ¶ added in v1.0.0
FixedBackoff returns a policy that always waits the same duration.
type BackoffFunc ¶ added in v1.0.0
BackoffFunc adapts a function to the Backoff interface.
type Candidate ¶ added in v1.0.0
type Candidate struct {
// contains filtered or unexported fields
}
Candidate is an immutable snapshot of an eligible provider used for routing.
func (Candidate) Cost ¶ added in v1.0.0
Cost returns the provider's application-defined normalized cost.
func (Candidate) FailureRate ¶ added in v1.0.0
FailureRate returns the provider's observed local failure ratio.
func (Candidate) ID ¶ added in v1.0.0
func (c Candidate) ID() ProviderID
ID returns the provider identifier.
func (Candidate) InFlight ¶ added in v1.0.0
InFlight returns the number of locally active calls at selection time.
func (Candidate) ObservedLatency ¶ added in v1.0.0
ObservedLatency returns the provider's locally observed EWMA latency.
type CooldownConfig ¶ added in v1.0.0
CooldownConfig configures local provider cooldown after repeated failures.
type Error ¶ added in v1.0.0
type Error struct {
Code ErrorCode
Operation Operation
Provider ProviderID
Attempt int
Cause error
}
Error describes a failure surfaced by Gateway.HandleRequest.
type ErrorCode ¶
type ErrorCode string
ErrorCode classifies errors produced by the gateway kernel itself.
const ( // CodeInvalidRequest indicates an invalid routing request. CodeInvalidRequest ErrorCode = "invalid_request" // CodeNoProvider indicates that no provider is currently eligible. CodeNoProvider ErrorCode = "no_provider" // CodeRoutingFailed indicates that a routing strategy could not select a candidate. CodeRoutingFailed ErrorCode = "routing_failed" // CodeProviderFailed indicates that a provider returned an error. CodeProviderFailed ErrorCode = "provider_failed" // CodeAttemptsExhausted indicates that the configured attempt budget was exhausted. CodeAttemptsExhausted ErrorCode = "attempts_exhausted" // CodeDeadlineExceeded indicates that the request deadline elapsed. CodeDeadlineExceeded ErrorCode = "deadline_exceeded" // CodeCanceled indicates that the request context was canceled. CodeCanceled ErrorCode = "canceled" )
type Event ¶ added in v1.0.0
type Event struct {
Type EventType
RequestID string
Operation Operation
Provider ProviderID
Attempt int
Duration time.Duration
Error error
}
Event contains low-cardinality routing telemetry and never contains payloads.
type EventType ¶ added in v1.0.0
type EventType uint8
EventType identifies an observability event emitted by the gateway.
const ( // EventRequestStarted is emitted before routing starts. EventRequestStarted EventType = iota + 1 // EventProviderSelected is emitted after a provider is selected. EventProviderSelected // EventAttemptFinished is emitted after each provider invocation. EventAttemptFinished // EventRequestFinished is emitted after a successful request. EventRequestFinished )
type ExponentialBackoff ¶
ExponentialBackoff computes bounded exponential retry delays.
type Failure ¶ added in v1.0.0
type Failure struct {
Request Request
Provider ProviderID
Error error
Attempt int
ProviderAttempt int
}
Failure describes one unsuccessful provider invocation.
type FailureAction ¶ added in v1.0.0
type FailureAction uint8
FailureAction determines how execution continues after a provider error.
const ( // Stop terminates the request immediately. Stop FailureAction = iota // RetryProvider retries the same provider. RetryProvider // NextProvider excludes the failed provider and routes to another candidate. NextProvider )
type FailureDecision ¶ added in v1.0.0
type FailureDecision struct {
Action FailureAction
Delay time.Duration
}
FailureDecision is the bounded action selected by a FailurePolicy.
type FailurePolicy ¶ added in v1.0.0
type FailurePolicy interface {
Decide(context.Context, Failure) FailureDecision
}
FailurePolicy decides what the gateway should do after a provider error.
Implementations must be safe for concurrent use.
func FailoverWhen ¶ added in v1.0.0
func FailoverWhen(predicate func(error) bool) FailurePolicy
FailoverWhen moves to another provider when predicate accepts the error.
func RetryThenFailover ¶ added in v1.0.0
func RetryThenFailover(maxRetries int, backoff Backoff, predicate func(error) bool) FailurePolicy
RetryThenFailover retries each provider before moving to another provider.
func StopOnFailure ¶ added in v1.0.0
func StopOnFailure() FailurePolicy
StopOnFailure returns the safe default policy that never replays requests.
type FailurePolicyFunc ¶ added in v1.0.0
type FailurePolicyFunc func(context.Context, Failure) FailureDecision
FailurePolicyFunc adapts a function to the FailurePolicy interface.
func (FailurePolicyFunc) Decide ¶ added in v1.0.0
func (f FailurePolicyFunc) Decide(ctx context.Context, failure Failure) FailureDecision
Decide returns the decision produced by the adapted function.
type Filter ¶ added in v1.0.0
Filter performs a pre-call eligibility check for a provider.
Implementations must be concurrency-safe and should avoid blocking whenever possible because filters run on the request path.
type FilterFunc ¶ added in v1.0.0
FilterFunc adapts a function to the Filter interface.
type Gateway ¶
type Gateway struct {
// contains filtered or unexported fields
}
Gateway routes opaque requests across immutable provider registrations.
Gateway is safe for concurrent use after construction.
func (*Gateway) HandleRequest ¶
HandleRequest selects providers, executes the configured failure policy, and returns the first success.
func (*Gateway) Stats ¶ added in v1.0.0
func (g *Gateway) Stats() []ProviderStats
Stats returns a point-in-time copy of local provider runtime statistics.
type Observer ¶ added in v1.0.0
Observer receives optional gateway events.
Implementations must be concurrency-safe and should return quickly.
type ObserverFunc ¶ added in v1.0.0
ObserverFunc adapts a function to the Observer interface.
type Operation ¶
type Operation string
Operation identifies a logical action that providers may handle.
type Option ¶
type Option func(*config) error
Option configures a Gateway at construction time.
func WithFailurePolicy ¶ added in v1.0.0
func WithFailurePolicy(policy FailurePolicy) Option
WithFailurePolicy installs the explicit retry and failover policy.
func WithMaxAttempts ¶ added in v1.0.0
WithMaxAttempts sets the hard total provider-attempt budget per request.
func WithObserver ¶ added in v1.0.0
WithObserver enables optional synchronous gateway event observation.
func WithProviders ¶
func WithProviders(providers ...ProviderRegistration) Option
WithProviders registers one or more providers with the gateway.
func WithRequestTimeout ¶
WithRequestTimeout applies a gateway-wide upper bound; zero disables it.
func WithRouting ¶
func WithRouting(strategy RoutingStrategy) Option
WithRouting installs the routing strategy used for eligible providers.
type Provider ¶
Provider executes opaque gateway requests.
Implementations must be safe for concurrent use by multiple goroutines.
type ProviderFunc ¶ added in v1.0.0
ProviderFunc adapts a function to the Provider interface.
type ProviderID ¶ added in v1.0.0
type ProviderID string
ProviderID identifies one registered provider instance.
type ProviderOption ¶
type ProviderOption func(*ProviderRegistration) error
ProviderOption configures a ProviderRegistration.
func WithCooldown ¶ added in v1.0.0
func WithCooldown(config CooldownConfig) ProviderOption
WithCooldown enables local cooldown after matching consecutive failures.
func WithFilter ¶ added in v1.0.0
func WithFilter(filter Filter) ProviderOption
WithFilter adds a dynamic pre-call eligibility filter.
func WithMaxInFlight ¶ added in v1.0.0
func WithMaxInFlight(limit int64) ProviderOption
WithMaxInFlight sets a hard local concurrency limit for a provider.
func WithOperations ¶ added in v1.0.0
func WithOperations(operations ...Operation) ProviderOption
WithOperations limits a provider to the supplied operations.
func WithProviderCost ¶
func WithProviderCost(cost float64) ProviderOption
WithProviderCost sets an application-defined normalized provider cost.
func WithProviderPriority ¶
func WithProviderPriority(priority int) ProviderOption
WithProviderPriority sets the provider's static priority; lower values win.
func WithProviderWeight ¶
func WithProviderWeight(weight uint32) ProviderOption
WithProviderWeight sets the provider's relative weighted-routing share.
type ProviderRegistration ¶
type ProviderRegistration struct {
// contains filtered or unexported fields
}
ProviderRegistration describes one provider instance and its static routing data.
func UseProvider ¶
func UseProvider(id ProviderID, provider Provider, options ...ProviderOption) ProviderRegistration
UseProvider registers a provider under a stable gateway-local identifier.
type ProviderStats ¶ added in v1.0.0
type ProviderStats struct {
Provider ProviderID
InFlight int64
ObservedLatency time.Duration
Total uint64
Failures uint64
CooldownUntil time.Time
}
ProviderStats is a point-in-time snapshot of one provider's local runtime state.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request is an immutable routing envelope around an opaque application value.
Gateway never modifies Value. If Value contains mutable data, the caller and provider are responsible for coordinating access to that data.
func NewRequest ¶ added in v1.0.0
func NewRequest(operation Operation, value any, options ...RequestOption) Request
NewRequest creates a routing request for an operation and opaque value.
func (Request) ProviderHint ¶
func (r Request) ProviderHint() ProviderID
ProviderHint returns the optional first-choice provider.
type RequestOption ¶ added in v1.0.0
type RequestOption func(*Request)
RequestOption configures a Request created by NewRequest.
func WithKey ¶ added in v1.0.0
func WithKey(key string) RequestOption
WithKey sets an optional affinity key used by routing strategies.
func WithProviderHint ¶ added in v1.0.0
func WithProviderHint(id ProviderID) RequestOption
WithProviderHint requests a specific provider for the first attempt.
func WithRequestID ¶ added in v1.0.0
func WithRequestID(id string) RequestOption
WithRequestID sets an optional request identifier for observability.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result contains the successful provider and opaque application response.
func (Result) Provider ¶
func (r Result) Provider() ProviderID
Provider returns the provider that produced the successful result.
type RoutingFunc ¶ added in v1.0.0
RoutingFunc adapts a function to the RoutingStrategy interface.
type RoutingStrategy ¶
RoutingStrategy selects one index from the provided candidate slice.
Implementations must be concurrency-safe and must not retain candidates after Select returns because the gateway may reuse the backing storage.
func Least ¶ added in v1.0.0
func Least(scorer Scorer) RoutingStrategy
Least selects the candidate with the smallest scorer value.
func LeastBusy ¶ added in v1.0.0
func LeastBusy() RoutingStrategy
LeastBusy selects the provider with the fewest in-flight requests.
func LowestCost ¶
func LowestCost() RoutingStrategy
LowestCost selects the provider with the lowest configured cost.
func LowestLatency ¶ added in v1.0.0
func LowestLatency() RoutingStrategy
LowestLatency selects the provider with the lowest observed latency.
func PowerOfTwo ¶
func PowerOfTwo(scorer Scorer) RoutingStrategy
PowerOfTwo samples two candidates and selects the lower-scoring one.
func Priority ¶
func Priority(ids ...ProviderID) RoutingStrategy
Priority selects the lowest configured priority, optionally honoring an explicit ID order.
func Random ¶ added in v1.0.0
func Random() RoutingStrategy
Random selects an eligible provider uniformly at random.
func RoundRobin ¶
func RoundRobin() RoutingStrategy
RoundRobin selects eligible providers in a concurrency-safe rotating order.
func Sticky ¶ added in v1.0.0
func Sticky() RoutingStrategy
Sticky uses rendezvous hashing over Request.Key and provider IDs for affinity.
func Weighted ¶
func Weighted() RoutingStrategy
Weighted selects a provider in proportion to Candidate.Weight.
type Scorer ¶ added in v1.0.0
Scorer assigns a lower-is-better score to a routing candidate.
func ByFailureRate ¶ added in v1.0.0
func ByFailureRate() Scorer
ByFailureRate scores lower observed local failure ratio as better.
func ByInFlight ¶ added in v1.0.0
func ByInFlight() Scorer
ByInFlight scores fewer concurrent provider calls as better.
func ByObservedLatency ¶
func ByObservedLatency() Scorer
ByObservedLatency scores lower observed latency as better.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
http
command
|
|
|
payment
command
|
|
|
quotes
command
Command qoutes is a random quote generator that fans out across three unrelated third-party quote APIs through a single gw.Gateway.
|
Command qoutes is a random quote generator that fans out across three unrelated third-party quote APIs through a single gw.Gateway. |
|
sms
command
|
|
|
Package httpgw provides optional net/http provider adapters for gateway.
|
Package httpgw provides optional net/http provider adapters for gateway. |