Help us shape the future of Go! Take the 2026 Go Developer Survey

http

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 28 Imported by: 0

README

HTTP Retry Governance Client

基于 Go net/http 的客户端治理组件,提供有限重试、超时预算、请求分类、Consul 动态配置、链路约束传播和请求结果观测能力。

环境要求

  • Go 版本以 go.mod 为准
  • Gin 中间件是可选能力;仅使用标准 net/http 时无需注册
  • Consul 是可选配置源;也可以直接加载 YAML 或自定义 RetryConfigProvider

核心能力

  • 内部读、内部写、外部读、外部写四类请求策略
  • 单次超时、整体预算、指数退避和随机抖动
  • 可选的按 downstream 隔离的本地重试预算,用于限制持续故障时的额外重试
  • 基于 caller / downstream / operation / class 的动态规则
  • Consul blocking query 热更新
  • 跨服务传播 X-No-More-Retry 和 X-Request-Deadline
  • 单跳维护 X-Retry-Attempt 和 X-Retry-Reason
  • slog 日志及 RetryObserver / RetryResultObserver
  • 可选的 Prometheus 请求量、重试、预算抑制、失败、超时和耗时指标

安装

go get github.com/duanyubin/http-governance-client

包名为 http,建议使用别名导入,避免与标准库冲突:

import httpclient "github.com/duanyubin/http-governance-client"

快速开始

1. 初始化

服务启动时显式传入服务名和 Consul 地址:

func initHTTP(consulAddress string) error {
	return httpclient.SetupWithOptions(httpclient.SetupOptions{
		Name:   "orders-api",
		Consul: consulAddress,
	})
}

初始化会读取以下 Consul KV,并启动热更新:

  1. config/go/application/retry
  2. config/go/orders-api/retry

服务级配置在应用级配置之后合并。没有 Consul 时,可通过 SetRetryConfigProviderFromYAML(...) 加载静态配置。

Setup() 是读取 --env/-e、--name/-n、--consul/-c 进程参数的便捷入口。长短参数均支持空格分隔和 = 写法。库代码和测试通常优先使用显式的 SetupWithOptions(...)。

2. Gin 链路约束
import ginmiddleware "github.com/duanyubin/http-governance-client/ginmiddleware"

router.Use(ginmiddleware.GovernanceMiddleware())

Handler 调用下游时传递标准请求 Context:

ctx := c.Request.Context()
err := httpclient.Post(
	ctx,
	"http://payments.svc.cluster.local/v1/payments",
	"application/json",
	body,
	&response,
)

需要从入站请求读取 Token 或设置其他业务 Header 时,使用对应的 *WithHeaders 方法:

err := httpclient.GetWithHeaders(
	c.Request.Context(),
	targetURL,
	&response,
	func(req *http.Request) error {
		req.Header.Set("Authorization", c.GetHeader("Authorization"))
		return nil
	},
)

辅助函数不是必选项。也可以用 http.NewRequestWithContext(...) 创建请求,再通过 httpclient.Do(...) 或 httpclient.Instance().Do(...) 发送;不要改用 http.DefaultClient,具体见接入与使用。

不要传递 *gin.Context,也不要用 context.Background() 替换入站请求 Context。

3. 处理 HTTP 状态码

辅助函数不会把 HTTP 4xx/5xx 自动转换为 Go error。需要同时检查返回的 error 和状态码:

var body PaymentResponse
result := httpclient.ResponsePtr{ExpectedPtr: &body}

if err := httpclient.Get(ctx, targetURL, &result); err != nil {
	return err // 传输、超时或解码错误
}
if result.StatusCode < 200 || result.StatusCode >= 300 {
	return fmt.Errorf("payments returned HTTP %d", result.StatusCode)
}
4. Prometheus 指标(可选)

需要直接采集指标时,在服务启动时注册内置适配器:

import (
	httpclient "github.com/duanyubin/http-governance-client"
	prometheusmetrics "github.com/duanyubin/http-governance-client/metrics/prometheus"
	"github.com/gin-gonic/gin"
	stdprometheus "github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

observer, err := prometheusmetrics.New(stdprometheus.DefaultRegisterer)
if err != nil {
	return err
}
httpclient.SetRetryResultObserver(observer)
router.GET("/metrics", gin.WrapH(promhttp.Handler()))

/metrics 端点由应用暴露。指标明细、独立 Registry 和 PromQL 示例见接入与使用。

重试安全约束

  • 读请求默认最多额外重试一次
  • 写请求默认不自动重试
  • 写请求只有在具备幂等保障后,才应通过精确规则开启重试
  • 带 Body 的请求只有在请求体可重放时才会自动重试
    • 使用 Post、PostWithHeaders 等辅助函数时,组件已生成可重放的请求体,无需额外处理
    • 直接创建 http.Request 时,bytes.Buffer、bytes.Reader 和 strings.Reader 由标准库自动设置 GetBody
    • 使用其他自定义或流式 Body 时,需要自行设置 GetBody;未设置时组件会关闭该请求的自动重试,只发送一次
  • HTTP 尝试与退避受 max_elapsed_time、请求 Context deadline 和 X-Request-Deadline 中最早的截止时间约束
  • 上游 X-No-More-Retry=true 不能被下游配置重新放宽
  • 可通过 retry_budget 限制每个 downstream 的额外重试;该预算不限制首次请求,也不替代幂等、限流或服务端过载保护

文档

开发

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

协作约定见 CONTRIBUTING.md,安全问题报告方式见 SECURITY.md,版本记录见 CHANGELOG.md,开源协议见 LICENSE。

Documentation

Overview

Package http provides an HTTP client governance component built on top of Go net/http.

It focuses on timeout control, bounded retries, request classification, Consul-based dynamic configuration, and request-level observability.

The package is designed to preserve existing business calling patterns as much as possible while adding governance capabilities through the transport layer.

Index

Constants

View Source
const (
	// HeaderRetryAttempt carries the zero-based attempt number for the current request.
	HeaderRetryAttempt = "X-Retry-Attempt"
	// HeaderNoMoreRetry tells downstream callers not to relax the current retry budget.
	HeaderNoMoreRetry = "X-No-More-Retry"
	// HeaderRequestDeadline carries the overall request deadline as a Unix millisecond timestamp.
	HeaderRequestDeadline = "X-Request-Deadline"
	// HeaderRetryReason records the reason for the latest retry decision.
	HeaderRetryReason = "X-Retry-Reason"
)
View Source
const (
	// RetrySuppressedReasonBudgetExhausted reports a retry denied by the local downstream budget.
	RetrySuppressedReasonBudgetExhausted = "budget_exhausted"
)

Variables

View Source
var (
	// ErrUrlNotFound reports an outgoing request without a URL.
	ErrUrlNotFound = errors.New("request URL not found")
)
View Source
var HealthcheckSkipper = SkipperFunc(func(req *http.Request) bool {
	if req == nil || req.URL == nil {
		return false
	}
	return strings.Contains(req.URL.Path, "/healthcheck")
})

HealthcheckSkipper bypasses retry governance for health-check paths.

Functions

func CallerServiceName

func CallerServiceName() string

CallerServiceName returns the process-level caller service name that is used as the default caller identity for outgoing requests.

func ClearRequestClassResolver

func ClearRequestClassResolver()

ClearRequestClassResolver removes the currently registered request class resolver.

func ContextWithRetryConstraints

func ContextWithRetryConstraints(ctx context.Context, headers stdhttp.Header) (context.Context, context.CancelFunc)

ContextWithRetryConstraints imports chain-wide retry constraints from headers.

func Delete

func Delete(ctx context.Context, url, contentType string, body any, expectedPtr any) error

Delete sends a DELETE request through the shared client.

func DeleteWithHeaders added in v0.5.0

func DeleteWithHeaders(ctx context.Context, url, contentType string, body any, expectedPtr any, setHeaders RequestHeaderSetter) error

DeleteWithHeaders sends a DELETE request after applying setHeaders.

func Do

func Do(req *http.Request, expectedPtr any) error

Do sends req through the shared client and decodes its response.

func Get

func Get(ctx context.Context, url string, expectedPtr any) error

Get sends a GET request through the shared client.

func GetInstance

func GetInstance() *http.Client

GetInstance returns the shared HTTP client instance. Deprecated: use Instance instead.

func GetWithHeaders added in v0.5.0

func GetWithHeaders(ctx context.Context, url string, expectedPtr any, setHeaders RequestHeaderSetter) error

GetWithHeaders sends a GET request after applying setHeaders.

func Head(ctx context.Context, url string, expectedPtr any) error

Head sends a HEAD request through the shared client.

func Instance

func Instance() *http.Client

Instance returns the shared HTTP client used by the helper functions in this package.

func InternalDelete

func InternalDelete(ctx context.Context, url, contentType string, body any, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalDelete sends a DELETE request with an optional authorization-header setter through the shared client.

func InternalGet

func InternalGet(ctx context.Context, url string, expectedPtr any, setAuthorizationInHeader func(request *http.Request) error) error

InternalGet sends a GET request with an optional authorization-header setter through the shared client.

func InternalMultipartForm

func InternalMultipartForm(ctx context.Context, method, url string, mf MultipartFormData, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalMultipartForm sends a multipart request with an optional authorization-header setter through the shared client.

func InternalPost

func InternalPost(ctx context.Context, url, contentType string, body any, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalPost sends a POST request with an optional authorization-header setter through the shared client.

func InternalPostMultipartForm

func InternalPostMultipartForm(ctx context.Context, url string, mf MultipartFormData, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalPostMultipartForm sends a multipart POST request with an optional authorization-header setter through the shared client.

func InternalPut

func InternalPut(ctx context.Context, url, contentType string, body any, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalPut sends a PUT request with an optional authorization-header setter through the shared client.

func InternalPutMultipartForm

func InternalPutMultipartForm(ctx context.Context, url string, mf MultipartFormData, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalPutMultipartForm sends a multipart PUT request with an optional authorization-header setter through the shared client.

func InternalWithMethod

func InternalWithMethod(ctx context.Context, url, method, contentType string, body any, expectedPtr any, authorizationInHeaderSetter AuthorizationInHeaderSetter) error

InternalWithMethod sends a request with the supplied HTTP method and an optional authorization-header setter through the shared client.

func MultipartFormWithHeaders added in v0.5.0

func MultipartFormWithHeaders(ctx context.Context, method, url string, mf MultipartFormData, expectedPtr any, setHeaders RequestHeaderSetter) error

MultipartFormWithHeaders sends a multipart request after applying setHeaders.

func NewClient

func NewClient() *http.Client

NewClient returns an independently instantiated HTTP client with the package defaults.

func NewClientWithOptions

func NewClientWithOptions(options ClientOptions) *http.Client

NewClientWithOptions returns an independently configured HTTP client without mutating the package-level shared client.

func NoMoreRetryFromContext

func NoMoreRetryFromContext(ctx context.Context) bool

NoMoreRetryFromContext reports whether an upstream caller disabled retries.

func Post

func Post(ctx context.Context, url, contentType string, body any, expectedPtr any) error

Post sends a POST request through the shared client.

func PostMultipartForm

func PostMultipartForm(ctx context.Context, url string, mf MultipartFormData, expectedPtr any) error

PostMultipartForm sends a multipart POST request through the shared client.

func PostMultipartFormWithHeaders added in v0.5.0

func PostMultipartFormWithHeaders(ctx context.Context, url string, mf MultipartFormData, expectedPtr any, setHeaders RequestHeaderSetter) error

PostMultipartFormWithHeaders sends a multipart POST request after applying setHeaders.

func PostWithHeaders added in v0.5.0

func PostWithHeaders(ctx context.Context, url, contentType string, body any, expectedPtr any, setHeaders RequestHeaderSetter) error

PostWithHeaders sends a POST request after applying setHeaders.

func Put

func Put(ctx context.Context, url, contentType string, body any, expectedPtr any) error

Put sends a PUT request through the shared client.

func PutMultipartForm

func PutMultipartForm(ctx context.Context, url string, mf MultipartFormData, expectedPtr any) error

PutMultipartForm sends a multipart PUT request through the shared client.

func PutMultipartFormWithHeaders added in v0.5.0

func PutMultipartFormWithHeaders(ctx context.Context, url string, mf MultipartFormData, expectedPtr any, setHeaders RequestHeaderSetter) error

PutMultipartFormWithHeaders sends a multipart PUT request after applying setHeaders.

func PutWithHeaders added in v0.5.0

func PutWithHeaders(ctx context.Context, url, contentType string, body any, expectedPtr any, setHeaders RequestHeaderSetter) error

PutWithHeaders sends a PUT request after applying setHeaders.

func RespHandler

func RespHandler(resp *http.Response, expectedPtr any) error

RespHandler closes the response body and decodes it into expectedPtr.

func RetryConfigAutoReloadInterval

func RetryConfigAutoReloadInterval() time.Duration

RetryConfigAutoReloadInterval returns the current retry config auto reload interval.

func SendWithHeaders added in v0.5.0

func SendWithHeaders(ctx context.Context, method, url, contentType string, body any, expectedPtr any, setHeaders RequestHeaderSetter) error

SendWithHeaders sends a request with the supplied method after applying setHeaders.

func SetBodyLogLevel

func SetBodyLogLevel(level slog.Level)

SetBodyLogLevel configures the log level used for request/response body logging. The default level is slog.LevelDebug.

func SetBodyLogLimit added in v0.3.0

func SetBodyLogLimit(limit int64) error

SetBodyLogLimit configures, in bytes, the maximum request or response body size that can be captured for logging. The default is 64 KiB.

func SetCallerServiceName

func SetCallerServiceName(name string)

SetCallerServiceName sets the process-level caller service name used to fill RetryConfigScope.Caller when business code does not provide it explicitly.

In normal startup flow this value is injected by Setup() from the `--name` or `-n` command-line flag.

func SetHealthcheckSkipper

func SetHealthcheckSkipper()

SetHealthcheckSkipper skips requests whose URL path contains `/healthcheck`.

func SetRequestClassResolver

func SetRequestClassResolver(resolver RequestClassResolver)

SetRequestClassResolver registers a resolver that can classify requests as internal/external read/write before method-based defaults are applied.

func SetRetryConfigAutoReloadInterval

func SetRetryConfigAutoReloadInterval(interval time.Duration)

SetRetryConfigAutoReloadInterval sets the wait interval used by retry config auto reload. For blocking-query mode, it is the maximum wait time for each Consul watch request. For fallback/polling mode, it is the reload interval.

Call this before Setup() or before StartRetryConfigAutoReloadFromConsul() if you want the current process to use the new value immediately.

If interval <= 0, auto reload will be disabled for newly started watchers.

func SetRetryConfigProvider

func SetRetryConfigProvider(provider RetryConfigProvider)

SetRetryConfigProvider installs a dynamic retry-config provider on the shared transport.

func SetRetryObserver

func SetRetryObserver(observer RetryObserver)

SetRetryObserver registers a retry observer on the shared transport.

func SetRetryPolicyResolver

func SetRetryPolicyResolver(resolver RetryPolicyResolver)

SetRetryPolicyResolver configures the baseline retry policy resolver for the shared transport.

func SetRetryResultObserver

func SetRetryResultObserver(observer RetryResultObserver)

SetRetryResultObserver registers a transport-result observer on the shared transport.

func SetSkipper

func SetSkipper(skipper SkipperFunc)

SetSkipper configures a request skipper on the shared transport.

func Setup

func Setup() error

Setup initializes caller identity and retry configuration from the current process arguments. It recognizes `--env`/`-e`, `--name`/`-n` and `--consul`/`-c`.

func SetupWithOptions

func SetupWithOptions(options SetupOptions) error

SetupWithOptions initializes caller identity and retry configuration from the provided options instead of reading os.Args.

func StartRetryConfigAutoReloadFromConsul

func StartRetryConfigAutoReloadFromConsul(provider *ManagedRetryConfigProvider, env, appName, endpoint string) error

StartRetryConfigAutoReloadFromConsul starts a background task that watches Consul and refreshes the provider when retry configuration changes.

func StopRetryConfigAutoReload

func StopRetryConfigAutoReload()

StopRetryConfigAutoReload stops the background retry-config reload task if it is currently running.

func WithExternalRead

func WithExternalRead(ctx context.Context) context.Context

WithExternalRead forces the current request context to use the external read classification.

func WithExternalWrite

func WithExternalWrite(ctx context.Context) context.Context

WithExternalWrite forces the current request context to use the external write classification.

func WithInternalRead

func WithInternalRead(ctx context.Context) context.Context

WithInternalRead forces the current request context to use the internal read classification.

func WithInternalWrite

func WithInternalWrite(ctx context.Context) context.Context

WithInternalWrite forces the current request context to use the internal write classification.

func WithNoMoreRetry

func WithNoMoreRetry(ctx context.Context) context.Context

WithNoMoreRetry marks all downstream calls derived from ctx as non-retryable.

func WithRequestClass

func WithRequestClass(ctx context.Context, class RequestClass) context.Context

WithRequestClass stores an explicit request class in context.

func WithRetryConfigScope

func WithRetryConfigScope(ctx context.Context, scope RetryConfigScope) context.Context

WithRetryConfigScope stores explicit scope values in the request context. Callers can use it as an escape hatch when automatic scope inference is not precise enough for a particular request.

func WithRetryPolicy

func WithRetryPolicy(ctx context.Context, policy RetryPolicy) context.Context

WithRetryPolicy stores an explicit baseline retry policy in context.

Types

type AuthorizationInHeaderSetter

type AuthorizationInHeaderSetter interface {
	SetAuthorizationInHeader(request *http.Request) error
}

AuthorizationInHeaderSetter adds authorization data to an outgoing request.

type AuthorizationInHeaderSetterFunc

type AuthorizationInHeaderSetterFunc func(request *http.Request) error

AuthorizationInHeaderSetterFunc adapts a function to AuthorizationInHeaderSetter.

func (AuthorizationInHeaderSetterFunc) SetAuthorizationInHeader

func (fn AuthorizationInHeaderSetterFunc) SetAuthorizationInHeader(request *http.Request) error

SetAuthorizationInHeader calls fn when it is non-nil.

type ClientOptions

type ClientOptions struct {
	RoundTripper   http.RoundTripper
	Skipper        SkipperFunc
	ResolvePolicy  RetryPolicyResolver
	ConfigProvider RetryConfigProvider
	Observer       RetryObserver
	ResultObserver RetryResultObserver
	RequestTimeout time.Duration
	CheckRedirect  func(req *http.Request, via []*http.Request) error
	Jar            http.CookieJar
}

ClientOptions configures independently instantiated clients and transports.

type ManagedRetryConfigProvider

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

ManagedRetryConfigProvider atomically serves validated retry configuration.

func NewManagedRetryConfigProvider

func NewManagedRetryConfigProvider() *ManagedRetryConfigProvider

NewManagedRetryConfigProvider returns an empty managed provider.

func NewManagedRetryConfigProviderFromConsul

func NewManagedRetryConfigProviderFromConsul(env, appName, endpoint string) (*ManagedRetryConfigProvider, error)

NewManagedRetryConfigProviderFromConsul creates a managed provider from Consul without installing it into the shared HTTP client.

func NewManagedRetryConfigProviderFromYAML

func NewManagedRetryConfigProviderFromYAML(data []byte) (*ManagedRetryConfigProvider, error)

NewManagedRetryConfigProviderFromYAML validates YAML and creates a provider.

func SetRetryConfigProviderFromConsul

func SetRetryConfigProviderFromConsul(env, appName, endpoint string) (*ManagedRetryConfigProvider, error)

SetRetryConfigProviderFromConsul loads retry configuration from Consul, installs the provider into the shared HTTP client and starts background reload for subsequent configuration changes.

func SetRetryConfigProviderFromYAML

func SetRetryConfigProviderFromYAML(data []byte) (*ManagedRetryConfigProvider, error)

SetRetryConfigProviderFromYAML loads retry configuration from YAML and installs the resulting provider into the shared transport.

func (*ManagedRetryConfigProvider) ResolveRequestClass

func (p *ManagedRetryConfigProvider) ResolveRequestClass(req *http.Request) (RequestClass, bool)

ResolveRequestClass classifies a request using the configured internal hosts.

func (*ManagedRetryConfigProvider) ResolveRetryConfigScope

func (p *ManagedRetryConfigProvider) ResolveRetryConfigScope(req *http.Request, scope RetryConfigScope) RetryConfigScope

ResolveRetryConfigScope fills missing caller, downstream and operation values.

func (*ManagedRetryConfigProvider) ResolveRetryPolicy

func (p *ManagedRetryConfigProvider) ResolveRetryPolicy(ctx context.Context, scope RetryConfigScope, base RetryPolicy) RetryPolicy

ResolveRetryPolicy applies the first matching rule to the class-adjusted policy.

func (*ManagedRetryConfigProvider) Update

Update validates and atomically replaces the current configuration.

func (*ManagedRetryConfigProvider) UpdateFromConsul

func (p *ManagedRetryConfigProvider) UpdateFromConsul(env, appName, endpoint string) error

UpdateFromConsul reloads the provider from Consul immediately.

func (*ManagedRetryConfigProvider) UpdateFromYAML

func (p *ManagedRetryConfigProvider) UpdateFromYAML(data []byte) error

UpdateFromYAML validates and atomically replaces the current configuration.

type MultipartFormData

type MultipartFormData struct {
	FileName string
	File     *multipart.FileHeader
	Form     interface{}
}

MultipartFormData describes a multipart form with an optional file.

type RequestClass

type RequestClass string

RequestClass describes whether a request is internal/external and read/write.

const (
	RequestClassInternalRead  RequestClass = "internal_read"
	RequestClassInternalWrite RequestClass = "internal_write"
	RequestClassExternalRead  RequestClass = "external_read"
	RequestClassExternalWrite RequestClass = "external_write"
)

type RequestClassResolver

type RequestClassResolver interface {
	ResolveRequestClass(req *http.Request) (RequestClass, bool)
}

RequestClassResolver classifies outgoing requests for policy selection.

type RequestHeaderSetter added in v0.5.0

type RequestHeaderSetter func(request *http.Request) error

RequestHeaderSetter adds or overrides headers before a request is sent.

type RequestResultEvent

type RequestResultEvent struct {
	Method                string
	URL                   string
	Caller                string
	Downstream            string
	Operation             string
	Class                 RequestClass
	AttemptCount          int
	RetryCount            int
	MaxRetries            int
	StatusCode            int
	FinalReason           string
	FinalError            string
	RetrySuppressedReason string
	Retried               bool
	RetrySucceeded        bool
	FinalFailed           bool
	TimedOut              bool
	Duration              time.Duration
}

RequestResultEvent records the transport-level outcome after all retries. It does not include response-body decoding performed by helper functions.

type ResponsePtr

type ResponsePtr struct {
	// ExpectedPtr receives the decoded response body.
	ExpectedPtr any
	// Deprecated: use ExpectedPtr. ExceptPtr is retained for compatibility.
	ExceptPtr any
	// StatusCode receives the HTTP response status code.
	StatusCode int
}

ResponsePtr captures both a decoded response body and its HTTP status code.

type RetryBudgetFile added in v0.8.0

type RetryBudgetFile struct {
	Enabled          *bool `yaml:"enabled" json:"enabled"`
	Capacity         *int  `yaml:"capacity" json:"capacity"`
	RetryCost        *int  `yaml:"retry_cost" json:"retry_cost"`
	SuccessIncrement *int  `yaml:"success_increment" json:"success_increment"`
}

RetryBudgetFile configures the local retry budget shared by one Transport.

type RetryClassPolicyFile

type RetryClassPolicyFile struct {
	InternalRead  *RetryPolicyPatchFile `yaml:"internal_read" json:"internal_read"`
	InternalWrite *RetryPolicyPatchFile `yaml:"internal_write" json:"internal_write"`
	ExternalRead  *RetryPolicyPatchFile `yaml:"external_read" json:"external_read"`
	ExternalWrite *RetryPolicyPatchFile `yaml:"external_write" json:"external_write"`
}

RetryClassPolicyFile defines policy patches for the four request classes.

type RetryConfigFile

type RetryConfigFile struct {
	Version       string                   `yaml:"version" json:"version"`
	RetryBudget   *RetryBudgetFile         `yaml:"retry_budget" json:"retry_budget"`
	InternalHosts []string                 `yaml:"internal_hosts" json:"internal_hosts"`
	Downstreams   []RetryDownstreamFile    `yaml:"downstreams" json:"downstreams"`
	Operations    []RetryOperationRuleFile `yaml:"operations" json:"operations"`
	Policies      RetryClassPolicyFile     `yaml:"policies" json:"policies"`
	Rules         []RetryConfigRuleFile    `yaml:"rules" json:"rules"`
}

RetryConfigFile is the versioned YAML/JSON model for retry governance.

type RetryConfigMatchFile

type RetryConfigMatchFile struct {
	Callers     []string `yaml:"callers" json:"callers"`
	Downstreams []string `yaml:"downstreams" json:"downstreams"`
	Operations  []string `yaml:"operations" json:"operations"`
	Methods     []string `yaml:"methods" json:"methods"`
	Hosts       []string `yaml:"hosts" json:"hosts"`
	Paths       []string `yaml:"paths" json:"paths"`
	Classes     []string `yaml:"classes" json:"classes"`
}

RetryConfigMatchFile contains the match dimensions for a configuration rule.

type RetryConfigProvider

type RetryConfigProvider interface {
	ResolveRetryPolicy(ctx context.Context, scope RetryConfigScope, base RetryPolicy) RetryPolicy
}

RetryConfigProvider resolves the effective retry policy for the current request scope after combining defaults and dynamic configuration.

type RetryConfigProviderFunc

type RetryConfigProviderFunc func(ctx context.Context, scope RetryConfigScope, base RetryPolicy) RetryPolicy

RetryConfigProviderFunc adapts a function to RetryConfigProvider.

func (RetryConfigProviderFunc) ResolveRetryPolicy

func (fn RetryConfigProviderFunc) ResolveRetryPolicy(ctx context.Context, scope RetryConfigScope, base RetryPolicy) RetryPolicy

ResolveRetryPolicy calls fn.

type RetryConfigRuleFile

type RetryConfigRuleFile struct {
	Name     string               `yaml:"name" json:"name"`
	Priority int                  `yaml:"priority" json:"priority"`
	Disabled bool                 `yaml:"disabled" json:"disabled"`
	Match    RetryConfigMatchFile `yaml:"match" json:"match"`
	Policy   RetryPolicyPatchFile `yaml:"policy" json:"policy"`
}

RetryConfigRuleFile defines a named conditional policy override.

type RetryConfigScope

type RetryConfigScope struct {
	Caller     string
	Downstream string
	Operation  string
	Method     string
	Host       string
	Path       string
	Class      RequestClass
}

RetryConfigScope describes the dimensions used to resolve retry policies for an outgoing request.

type RetryConfigScopeDefaultsResolver

type RetryConfigScopeDefaultsResolver interface {
	ResolveRetryConfigScope(req *http.Request, scope RetryConfigScope) RetryConfigScope
}

RetryConfigScopeDefaultsResolver fills missing scope fields such as caller, downstream and operation before policy matching runs.

type RetryDownstreamFile

type RetryDownstreamFile struct {
	Name  string   `yaml:"name" json:"name"`
	Hosts []string `yaml:"hosts" json:"hosts"`
}

RetryDownstreamFile maps one logical downstream name to host patterns.

type RetryEvent

type RetryEvent struct {
	Method     string
	URL        string
	Class      RequestClass
	Attempt    int
	MaxRetries int
	Delay      time.Duration
	StatusCode int
	Reason     string
	WillRetry  bool
}

RetryEvent records a scheduled retry attempt.

type RetryObserver

type RetryObserver interface {
	ObserveRetry(ctx context.Context, event RetryEvent)
}

RetryObserver receives retry scheduling events.

type RetryOperationRuleFile

type RetryOperationRuleFile struct {
	Name        string   `yaml:"name" json:"name"`
	Priority    int      `yaml:"priority" json:"priority"`
	Methods     []string `yaml:"methods" json:"methods"`
	Hosts       []string `yaml:"hosts" json:"hosts"`
	Paths       []string `yaml:"paths" json:"paths"`
	Downstreams []string `yaml:"downstreams" json:"downstreams"`
}

RetryOperationRuleFile maps request attributes to a logical operation name.

type RetryPolicy

type RetryPolicy struct {
	MaxRetries        int
	PerAttemptTimeout time.Duration
	MaxElapsedTime    time.Duration
	InitialBackoff    time.Duration
	MaxBackoff        time.Duration
	RetryOnStatuses   map[int]struct{}
	RetryOn429        bool
}

RetryPolicy describes retry, timeout and backoff controls for a request.

func DefaultRetryPolicyResolver

func DefaultRetryPolicyResolver(req *http.Request) RetryPolicy

DefaultRetryPolicyResolver returns the built-in baseline policy: read requests retry once by default while write requests do not retry automatically.

type RetryPolicyPatch

type RetryPolicyPatch struct {
	DisableRetry      *bool
	MaxRetries        *int
	PerAttemptTimeout *time.Duration
	MaxElapsedTime    *time.Duration
	InitialBackoff    *time.Duration
	MaxBackoff        *time.Duration
	RetryOnStatuses   []int
	RetryOn429        *bool
}

RetryPolicyPatch describes the fields that should override a base retry policy. Nil values keep the base policy unchanged.

func (RetryPolicyPatch) Apply

Apply merges the patch into the provided base policy and returns the normalized result.

type RetryPolicyPatchFile

type RetryPolicyPatchFile struct {
	DisableRetry      *bool  `yaml:"disable_retry" json:"disable_retry"`
	MaxRetries        *int   `yaml:"max_retries" json:"max_retries"`
	PerAttemptTimeout string `yaml:"per_attempt_timeout" json:"per_attempt_timeout"`
	MaxElapsedTime    string `yaml:"max_elapsed_time" json:"max_elapsed_time"`
	InitialBackoff    string `yaml:"initial_backoff" json:"initial_backoff"`
	MaxBackoff        string `yaml:"max_backoff" json:"max_backoff"`
	RetryOnStatuses   []int  `yaml:"retry_on_statuses" json:"retry_on_statuses"`
	RetryOn429        *bool  `yaml:"retry_on_429" json:"retry_on_429"`
}

RetryPolicyPatchFile is the serialized form of a partial retry policy.

type RetryPolicyResolver

type RetryPolicyResolver func(req *http.Request) RetryPolicy

RetryPolicyResolver resolves the baseline retry policy before dynamic configuration is applied.

type RetryResultObserver

type RetryResultObserver interface {
	ObserveRequestResult(ctx context.Context, event RequestResultEvent)
}

RetryResultObserver receives the final transport-level request outcome event.

type SetupOptions

type SetupOptions struct {
	Env    string
	Name   string
	Consul string
}

SetupOptions contains the explicit initialization parameters used by SetupWithOptions.

type SkipperFunc

type SkipperFunc func(req *http.Request) bool

SkipperFunc reports whether retry governance should be bypassed for a request.

type Transport

type Transport struct {
	http.RoundTripper
	Skipper        SkipperFunc
	ResolvePolicy  RetryPolicyResolver
	ConfigProvider RetryConfigProvider
	Observer       RetryObserver
	ResultObserver RetryResultObserver
	// contains filtered or unexported fields
}

Transport is the retry-aware RoundTripper used by the shared HTTP client.

func NewTransport

func NewTransport() *Transport

NewTransport returns a retry-aware transport with the package defaults.

func NewTransportWithOptions

func NewTransportWithOptions(options ClientOptions) *Transport

NewTransportWithOptions returns an independently configured retry-aware transport without mutating the package-level shared client.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip applies request classification, policy resolution, retry budgeting and retry headers before delegating the request to the wrapped RoundTripper.

Directories

Path Synopsis
Package ginmiddleware imports retry-governance chain constraints from Gin requests into the standard request context.
Package ginmiddleware imports retry-governance chain constraints from Gin requests into the standard request context.
metrics
prometheus
Package prometheus exposes HTTP governance client metrics to Prometheus.
Package prometheus exposes HTTP governance client metrics to Prometheus.

Jump to

Keyboard shortcuts

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