core

package
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package resiliencex 提供服务治理组件: 令牌桶限流、熔断器与舱壁隔离, 拒绝语义统一 errx,观测外部注入,零第三方依赖。

Index

Constants

View Source
const (
	// CodeInvalidConfig 配置非法。
	CodeInvalidConfig errx.Code = "RESX_INVALID_CONFIG"
	// CodeRateLimited 限流拒绝。
	CodeRateLimited errx.Code = "RESX_RATE_LIMITED"
	// CodeCircuitOpen 熔断拒绝。
	CodeCircuitOpen errx.Code = "RESX_CIRCUIT_OPEN"
	// CodeBulkheadFull 舱壁拒绝。
	CodeBulkheadFull errx.Code = "RESX_BULKHEAD_FULL"
	// CodeWaitCanceled 等待限流许可被取消。
	CodeWaitCanceled errx.Code = "RESX_WAIT_CANCELED"
)

错误码定义:resiliencex 各失败场景的错误码。

View Source
const Version = "v1.5.1"

Version 是当前库版本,与 git tag 保持一致。

Variables

This section is empty.

Functions

func ErrCircuitOpen

func ErrCircuitOpen() error

ErrCircuitOpen 返回熔断拒绝错误(便于调用方统一比较)。

func ErrRateLimited

func ErrRateLimited() error

ErrRateLimited 返回限流拒绝错误(便于调用方统一比较)。

Types

type Bulkhead

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

Bulkhead 是信号量舱壁:限制并发在途请求数。

func NewBulkhead

func NewBulkhead(maxConcurrent int, opts ...Option) (*Bulkhead, error)

NewBulkhead 创建舱壁,限制 maxConcurrent 个并发。

func (*Bulkhead) Acquire

func (b *Bulkhead) Acquire(ctx context.Context) (func(), error)

Acquire 阻塞获取许可,ctx 取消立即返回。

func (*Bulkhead) Available

func (b *Bulkhead) Available() int

Available 返回当前可用许可数。

func (*Bulkhead) TryAcquire

func (b *Bulkhead) TryAcquire() (release func(), ok bool)

TryAcquire 非阻塞获取许可;成功返回 release 函数(幂等), 失败返回 ok=false。

type CircuitBreaker

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

CircuitBreaker 是三态熔断器:Closed / Open / HalfOpen。

func NewCircuitBreaker

func NewCircuitBreaker(opts ...Option) (*CircuitBreaker, error)

NewCircuitBreaker 创建熔断器。配置非法返回 RESX_INVALID_CONFIG。

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() error

Allow 检查请求是否可放行。 Closed 放行;Open 拒绝并在超时后转入 HalfOpen;HalfOpen 限量放行探测。

func (*CircuitBreaker) Counts

func (cb *CircuitBreaker) Counts() Counts

Counts 返回窗口统计快照。

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(fn func() error) error

Execute 执行并自动上报成功/失败。

func (*CircuitBreaker) ExecuteContext

func (cb *CircuitBreaker) ExecuteContext(ctx context.Context, fn func(context.Context) error) error

ExecuteContext 以受保护方式执行 fn,自动熔断并记录链路 span。

func (*CircuitBreaker) Failure

func (cb *CircuitBreaker) Failure()

Failure 上报一次失败。 Closed 计入窗口,失败率达标后转入 Open;HalfOpen 任一失败立即 Open。

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() State

State 返回当前状态。

func (*CircuitBreaker) Success

func (cb *CircuitBreaker) Success()

Success 上报一次成功。 Closed 计入窗口;HalfOpen 累计探测成功,达到阈值后回到 Closed。

type Counts

type Counts struct {
	// Requests 窗口内请求总数。
	Requests uint64
	// Successes 窗口内成功数。
	Successes uint64
	// Failures 窗口内失败数。
	Failures uint64
}

Counts 是熔断器窗口统计快照。

type KeyedWindow added in v1.5.1

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

KeyedWindow 是按任意 key 维护固定窗口的限流器: 每个 key 独立计数,带容量上限与空闲 TTL 清理,防止 key 膨胀。

func NewKeyedFixedWindow added in v1.5.1

func NewKeyedFixedWindow(limit int, window time.Duration, opts ...KeyedWindowOption) (*KeyedWindow, error)

NewKeyedFixedWindow 创建按 key 固定窗口限流器。 每个 key 在 window 内最多 limit 次;空闲超过 TTL 或容量超限时淘汰。

func (*KeyedWindow) Allow added in v1.5.1

func (k *KeyedWindow) Allow(key string) bool

Allow 尝试通过指定 key 的窗口;超限返回 false。

func (*KeyedWindow) Len added in v1.5.1

func (k *KeyedWindow) Len() int

Len 返回当前维护的 key 数量。

func (*KeyedWindow) Reset added in v1.5.1

func (k *KeyedWindow) Reset()

Reset 清空全部 key 窗口。

func (*KeyedWindow) Wait added in v1.5.1

func (k *KeyedWindow) Wait(ctx context.Context, key string) error

Wait 阻塞等待指定 key 的许可,ctx 取消立即返回;ctx 必须非 nil。

type KeyedWindowOption added in v1.5.1

type KeyedWindowOption func(*keyedWindowConfig)

KeyedWindowOption 修改按 key 窗口限流器配置。

func WithKeyedWindowClock added in v1.5.1

func WithKeyedWindowClock(now func() time.Time) KeyedWindowOption

WithKeyedWindowClock 注入时间源(测试用)。

func WithKeyedWindowLogger added in v1.5.1

func WithKeyedWindowLogger(l logx.Logger) KeyedWindowOption

WithKeyedWindowLogger 注入结构化日志实现。

func WithKeyedWindowMaxKeys added in v1.5.1

func WithKeyedWindowMaxKeys(n int) KeyedWindowOption

WithKeyedWindowMaxKeys 设置 key 容量上限;达到上限后按最近使用淘汰。

func WithKeyedWindowMetrics added in v1.5.1

func WithKeyedWindowMetrics(m Metrics) KeyedWindowOption

WithKeyedWindowMetrics 注入指标钩子。

func WithKeyedWindowTTL added in v1.5.1

func WithKeyedWindowTTL(d time.Duration) KeyedWindowOption

WithKeyedWindowTTL 设置 key 空闲过期时长;0 表示仅按容量淘汰。

type Limiter

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

Limiter 是令牌桶限流器: 以 rate 匀速补充令牌,burst 允许瞬时突发,惰性计算零后台任务。

func NewTokenBucket

func NewTokenBucket(rate float64, burst int, opts ...Option) (*Limiter, error)

NewTokenBucket 创建令牌桶限流器。 rate 为每秒补充令牌数(>0),burst 为桶容量(>=1)。

func (*Limiter) Allow

func (l *Limiter) Allow() bool

Allow 等价于 AllowN(1)。

func (*Limiter) AllowN

func (l *Limiter) AllowN(n int) bool

AllowN 非阻塞地尝试消耗 n 个令牌;桶余量不足时返回 false。

func (*Limiter) Burst

func (l *Limiter) Burst() int

Burst 返回桶容量(不可变)。

func (*Limiter) Rate

func (l *Limiter) Rate() float64

Rate 返回每秒补充速率(不可变)。

func (*Limiter) RetryAfter

func (l *Limiter) RetryAfter() time.Duration

RetryAfter 返回补满 1 枚令牌所需的等待时间;当前余量足够时返回 0。 用于生成 HTTP 429 响应头 Retry-After 等场景。

func (*Limiter) SetRate

func (l *Limiter) SetRate(rate float64) error

SetRate 动态调整补充速率(支持运行期基于下游健康度调整)。 rate 必须为正数,非法返回 RESX_INVALID_CONFIG 且不改变原值。

func (*Limiter) Wait

func (l *Limiter) Wait(ctx context.Context) error

Wait 等价于 WaitN(ctx, 1)。

func (*Limiter) WaitN

func (l *Limiter) WaitN(ctx context.Context, n int) error

WaitN 阻塞地等待 n 个令牌;ctx 取消时立即返回并归还预定。 单次请求超过桶容量时返回参数错误。

type Metrics

type Metrics = metricsx.Sink

Metrics 是最小指标协议(家族统一契约,定义见 metricsx.Sink)。 调用方按 Sink 签名传入标签切片;无标签时传 nil。

type Option

type Option func(configApplier)

Option 修改组件配置,在组件 New 时按顺序应用。 组件专属选项对不匹配的组件无效(文档说明)。

func WithFailureThreshold

func WithFailureThreshold(ratio float64) Option

WithFailureThreshold 设置失败率阈值(0,1],默认 0.5。

func WithHalfOpenMax

func WithHalfOpenMax(n int) Option

WithHalfOpenMax 设置半开状态允许的探测请求数,默认 1。

func WithLogger

func WithLogger(l logx.Logger) Option

WithLogger 注入结构化日志实现,空表示关闭日志(默认)。

func WithMetrics

func WithMetrics(m Metrics) Option

WithMetrics 注入指标钩子,空表示关闭指标(默认)。

func WithMinRequests

func WithMinRequests(n int) Option

WithMinRequests 设置触发熔断的最小请求数,默认 5。

func WithOnStateChange

func WithOnStateChange(fn func(from, to State)) Option

WithOnStateChange 设置状态切换回调(锁外调用)。

func WithOpenTimeout

func WithOpenTimeout(d time.Duration) Option

WithOpenTimeout 设置熔断打开后的探测等待时长,默认 10s。

func WithTraceHook

func WithTraceHook(h TraceHook) Option

WithTraceHook 设置受保护调用链路追踪钩子。

func WithWindow

func WithWindow(slot time.Duration, size int) Option

WithWindow 设置滑动窗口时间片与数量(默认 1s × 10)。

type State

type State uint8

State 是熔断器状态。

const (
	// StateClosed 关闭:请求放行,统计失败率。
	StateClosed State = iota
	// StateOpen 打开:拒绝全部请求,等待探测超时。
	StateOpen
	// StateHalfOpen 半开:允许少量探测请求。
	StateHalfOpen
)

func (State) String

func (s State) String() string

String 返回状态的稳定名称。

type TraceAttr

type TraceAttr = contract.TraceAttr

TraceAttr 链路追踪属性(家族统一契约,定义见 tracex/contract)。

type TraceHook

type TraceHook = contract.TraceHook

TraceHook 链路追踪钩子(家族统一契约,定义见 tracex/contract)。

type Window

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

Window 是固定或滑动窗口限流器。

func NewFixedWindow

func NewFixedWindow(limit int, window time.Duration, opts ...Option) (*Window, error)

NewFixedWindow 创建固定窗口限流:每 window 内最多 limit 次。

func NewSlidingWindow

func NewSlidingWindow(limit int, window time.Duration, opts ...Option) (*Window, error)

NewSlidingWindow 创建滑动窗口限流:任意连续 window 内最多 limit 次。

func (*Window) Allow

func (w *Window) Allow() bool

Allow 尝试通过;窗口内超限返回 false。

func (*Window) Wait

func (w *Window) Wait(ctx context.Context) error

Wait 阻塞等待许可,ctx 取消立即返回。 采用轮询实现(间隔为窗口的 1/10,10-100ms)。

Jump to

Keyboard shortcuts

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