gateway

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 10 Imported by: 0

README

gateway

A generic orchestration framework for routing one standard request format across multiple external providers.

Use this package to build gateways for notifications, storage, search, or any system that needs:

  • A unified application-facing interface.
  • Bidirectional payload translation.
  • Transport-independent custom providers.
  • Built-in routing strategies.
  • Retry and cross-provider fallback.
  • Request timeouts and structured logging.

It is reasonable for:

  • A prototype or separate generic orchestration service.
  • Routing safe, idempotent reads among interchangeable upstreams.
  • Routing between redundant upstream endpoints inside one provider adapter.

Installation

  • Go 1.23 or later.
  • No third-party runtime dependencies.
go get github.com/henryhale/gateway

Example

A quotes gateway that routes one standard request across two quote APIs:

quoteGateway, err := gw.New(
	gw.WithProviders(
		gw.UseProvider("zenquotes", zenQuotes, gw.WithOperations("quote.random")),
		gw.UseProvider("motivational-spark", motivationalSpark, gw.WithOperations("quote.random")),
	),
	gw.WithRouting(gw.RoundRobin()),
)
if err != nil {
	log.Fatal(err)
}

A runnable version of this gateway is in _examples/quotes.

Documentation

See _docs/README.md for the full guide.

Development

Run all release checks:

make check

Individual commands:

go fmt ./...
go vet ./...
go test -race ./...

License

Released under MIT License. See LICENSE.txt for details.

© 2026-present Henry Hale

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValueAs added in v1.0.0

func ValueAs[T any](result Result) (T, bool)

ValueAs extracts a typed value from a Result.

Types

type Backoff added in v1.0.0

type Backoff interface {
	Delay(attempt int) time.Duration
}

Backoff computes a delay before another provider attempt.

func FixedBackoff added in v1.0.0

func FixedBackoff(delay time.Duration) Backoff

FixedBackoff returns a policy that always waits the same duration.

func NoBackoff added in v1.0.0

func NoBackoff() Backoff

NoBackoff returns a backoff policy that never delays.

type BackoffFunc added in v1.0.0

type BackoffFunc func(int) time.Duration

BackoffFunc adapts a function to the Backoff interface.

func (BackoffFunc) Delay added in v1.0.0

func (f BackoffFunc) Delay(attempt int) time.Duration

Delay returns the delay produced by the adapted function.

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

func (c Candidate) Cost() float64

Cost returns the provider's application-defined normalized cost.

func (Candidate) FailureRate added in v1.0.0

func (c Candidate) FailureRate() float64

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

func (c Candidate) InFlight() int64

InFlight returns the number of locally active calls at selection time.

func (Candidate) ObservedLatency added in v1.0.0

func (c Candidate) ObservedLatency() time.Duration

ObservedLatency returns the provider's locally observed EWMA latency.

func (Candidate) Priority added in v1.0.0

func (c Candidate) Priority() int

Priority returns the provider's configured priority.

func (Candidate) Weight added in v1.0.0

func (c Candidate) Weight() uint32

Weight returns the provider's configured routing weight.

type CooldownConfig added in v1.0.0

type CooldownConfig struct {
	Failures int
	Duration time.Duration
	When     func(error) bool
}

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.

func AsError

func AsError(err error) (*Error, bool)

AsError extracts a gateway Error from an error chain.

func (*Error) Error added in v1.0.0

func (e *Error) Error() string

Error returns a compact human-readable error description.

func (*Error) Unwrap added in v1.0.0

func (e *Error) Unwrap() error

Unwrap returns the underlying provider, routing, or context error.

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

type ExponentialBackoff struct {
	Initial time.Duration
	Maximum time.Duration
}

ExponentialBackoff computes bounded exponential retry delays.

func (ExponentialBackoff) Delay

func (b ExponentialBackoff) Delay(attempt int) time.Duration

Delay returns the bounded exponential delay for an attempt number.

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

type Filter interface {
	Allow(context.Context, Request, Candidate) (bool, error)
}

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

type FilterFunc func(context.Context, Request, Candidate) (bool, error)

FilterFunc adapts a function to the Filter interface.

func (FilterFunc) Allow added in v1.0.0

func (f FilterFunc) Allow(ctx context.Context, request Request, candidate Candidate) (bool, error)

Allow evaluates the adapted eligibility function.

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 New

func New(options ...Option) (*Gateway, error)

New constructs an immutable, concurrency-safe Gateway.

func (*Gateway) HandleRequest

func (g *Gateway) HandleRequest(ctx context.Context, request Request) (Result, error)

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

type Observer interface {
	Observe(context.Context, Event)
}

Observer receives optional gateway events.

Implementations must be concurrency-safe and should return quickly.

type ObserverFunc added in v1.0.0

type ObserverFunc func(context.Context, Event)

ObserverFunc adapts a function to the Observer interface.

func (ObserverFunc) Observe added in v1.0.0

func (f ObserverFunc) Observe(ctx context.Context, event Event)

Observe dispatches an event to the adapted function.

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

func WithMaxAttempts(maxAttempts int) Option

WithMaxAttempts sets the hard total provider-attempt budget per request.

func WithObserver added in v1.0.0

func WithObserver(observer Observer) Option

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

func WithRequestTimeout(timeout time.Duration) Option

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

type Provider interface {
	Handle(context.Context, Request) (any, error)
}

Provider executes opaque gateway requests.

Implementations must be safe for concurrent use by multiple goroutines.

type ProviderFunc added in v1.0.0

type ProviderFunc func(context.Context, Request) (any, error)

ProviderFunc adapts a function to the Provider interface.

func (ProviderFunc) Handle added in v1.0.0

func (f ProviderFunc) Handle(ctx context.Context, request Request) (any, error)

Handle executes the adapted provider function.

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) ID

func (r Request) ID() string

ID returns the optional request identifier.

func (Request) Key added in v1.0.0

func (r Request) Key() string

Key returns the optional affinity key.

func (Request) Operation

func (r Request) Operation() Operation

Operation returns the logical operation being routed.

func (Request) ProviderHint

func (r Request) ProviderHint() ProviderID

ProviderHint returns the optional first-choice provider.

func (Request) Value added in v1.0.0

func (r Request) Value() any

Value returns the opaque application payload.

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.

func (Result) Value added in v1.0.0

func (r Result) Value() any

Value returns the opaque application response.

type RoutingFunc added in v1.0.0

type RoutingFunc func(context.Context, Request, []Candidate) (int, error)

RoutingFunc adapts a function to the RoutingStrategy interface.

func (RoutingFunc) Select added in v1.0.0

func (f RoutingFunc) Select(ctx context.Context, request Request, candidates []Candidate) (int, error)

Select delegates provider selection to the adapted function.

type RoutingStrategy

type RoutingStrategy interface {
	Select(context.Context, Request, []Candidate) (int, error)
}

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 ScoreFunc added in v1.0.0

type ScoreFunc func(Request, Candidate) float64

ScoreFunc adapts a function to the Scorer interface.

func (ScoreFunc) Score added in v1.0.0

func (f ScoreFunc) Score(request Request, candidate Candidate) float64

Score delegates scoring to the adapted function.

type Scorer added in v1.0.0

type Scorer interface {
	Score(Request, Candidate) float64
}

Scorer assigns a lower-is-better score to a routing candidate.

func ByCost

func ByCost() Scorer

ByCost scores lower configured cost as better.

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.

Directories

Path Synopsis
_examples
catalog command
http 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.

Jump to

Keyboard shortcuts

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