retry

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DoWithResultTyped

func DoWithResultTyped[T any](r Retryer, ctx context.Context, fn func() (T, error)) (T, error)

DoWithResultTyped is a type-safe generic wrapper around Retryer.DoWithResult. It eliminates the need for type assertions on the return value.

Usage:

val, err := retry.DoWithResultTyped[int](r, ctx, func() (int, error) {
    return 42, nil
})

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError 检查错误是否被 WrapRetryable 包装为可重试错误。 注意:这与 types.IsRetryable 语义不同 —— 本函数检查 *RetryableError 包装类型, 而 types.IsRetryable 检查 *types.Error 的 Retryable 字段。

func WrapRetryable

func WrapRetryable(err error) error

WrapRetryable 将错误包装为可重试错误

Types

type RetryPolicy

type RetryPolicy struct {
	MaxRetries      int                                               // 最大重试次数(0 表示不重试)
	InitialDelay    time.Duration                                     // 初始延迟时间
	MaxDelay        time.Duration                                     // 最大延迟时间
	Multiplier      float64                                           // 延迟时间倍增因子(指数退避)
	Jitter          bool                                              // 是否添加随机抖动(防止雪崩)
	RetryableErrors []error                                           // 可重试的错误类型(为空则重试所有错误)
	OnRetry         func(attempt int, err error, delay time.Duration) // 重试回调
}

RetryPolicy 定义重试策略配置 遵循 KISS 原则:简单但功能完整的重试策略

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy 返回默认的重试策略 适用于大部分 LLM API 调用场景

type RetryableError

type RetryableError struct {
	Err error
}

RetryableError 可重试的错误类型 用于标记哪些错误应该触发重试

func (*RetryableError) Error

func (e *RetryableError) Error() string

func (*RetryableError) Unwrap

func (e *RetryableError) Unwrap() error

type Retryer

type Retryer interface {
	// Do 执行函数,失败时根据策略重试
	Do(ctx context.Context, fn func() error) error

	// DoWithResult 执行函数并返回结果,失败时根据策略重试
	DoWithResult(ctx context.Context, fn func() (any, error)) (any, error)
}

Retryer 重试器接口 提供统一的重试能力

func NewBackoffRetryer

func NewBackoffRetryer(policy *RetryPolicy, logger *zap.Logger) Retryer

NewBackoffRetryer 创建指数退避重试器

Jump to

Keyboard shortcuts

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