circuitbreaker

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: None detected not legal advice Imports: 0 Imported by: 0

Documentation

Overview

Package circuitbreaker provides a classic three-state breaker (Closed / Open / HalfOpen) that consumes success/failure signals and gates a caller's attempts. Designed to consume validator.Verdict signals via VerdictSink (a ValidatedTool decorator fires on every pre-commit Verdict).

Decision flow:

Closed:   every Allow() returns nil; RecordFailure() increments a
          counter; threshold breaches trip the breaker to Open.
Open:     Allow() returns ErrOpen until cooldown elapses, then the
          breaker transitions to HalfOpen on the next Allow() call.
HalfOpen: the first Allow() returns nil (probe); subsequent Allow()
          return ErrOpen until the probe reports back. Probe
          RecordSuccess resets to Closed (failure counter zero);
          RecordFailure trips back to Open (cooldown restarts).

Deliberate omissions:

  • No automatic retry / backoff: callers (the Agent) should observe ErrOpen and replan, matching SQLCAS's maxRetries=0 default.
  • No percentage-based threshold: a raw consecutive-failure count is simpler to reason about and debug; platforms that want rate windows wrap or replace this breaker.

Package circuitbreaker 提供经典三态熔断器 (Closed / Open / HalfOpen), 消费成功 / 失败信号对调用方施加 gate. 设计上消费 validator.Verdict 信号经 VerdictSink (ValidatedTool decorator 每次 pre-commit Verdict 触发).

决策流:

Closed:   每次 Allow() 返 nil; RecordFailure() 累计计数; 破阈值
          跳 Open.
Open:     Allow() 返 ErrOpen 直到 cooldown 过去; 下一次 Allow()
          转 HalfOpen.
HalfOpen: 首次 Allow() 返 nil (试探), 后续 Allow() 返 ErrOpen 直到
          试探回报. 试探 RecordSuccess 清零回 Closed; RecordFailure
          回 Open (cooldown 重启).

刻意不做:

  • 自动重试 / backoff: 调用方 (Agent) 应当看到 ErrOpen 重新 plan, 对齐 SQLCAS maxRetries=0 默认.
  • 百分比阈值: 纯连续失败计数更易推理与调试; 要 rate 窗口的 platform 包装或替换本实现.

Index

Constants

View Source
const (
	DefaultThreshold = 5
	DefaultCooldown  = 60 * time.Second
)

Defaults used when Config fields are left zero.

Config 字段为零时使用的默认值.

Variables

View Source
var ErrOpen = errors.New("circuitbreaker: circuit is open")

ErrOpen is returned by Allow when the breaker is rejecting calls.

ErrOpen 是 Open 态 Allow() 的返回值.

Functions

This section is empty.

Types

type CircuitBreaker

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

CircuitBreaker is a thread-safe three-state circuit breaker.

CircuitBreaker 是线程安全的三态熔断器.

func New

func New(cfg Config) *CircuitBreaker

New constructs a CircuitBreaker. Zero / negative values in cfg are replaced by defaults (DefaultThreshold / DefaultCooldown / realClock).

New 构造 CircuitBreaker. cfg 中的零或负值用默认值替换 (DefaultThreshold / DefaultCooldown / realClock).

func (*CircuitBreaker) Allow

func (b *CircuitBreaker) Allow() error

Allow returns nil if the caller may proceed, or ErrOpen if the breaker is currently rejecting. Closed always allows; Open allows only after the cooldown elapses (the breaker transitions to HalfOpen on the granting Allow call); HalfOpen allows a single probe call per cycle.

Allow 返回 nil 表示可通过, 或 ErrOpen. Closed 放行; Open cooldown 过后下一次 Allow 转 HalfOpen; HalfOpen 每周期只允许 1 次试探.

func (*CircuitBreaker) FailureCount

func (b *CircuitBreaker) FailureCount() int

FailureCount returns the current failure counter (0 outside Closed).

FailureCount 返回当前失败计数 (Closed 之外为 0).

func (*CircuitBreaker) RecordFailure

func (b *CircuitBreaker) RecordFailure()

RecordFailure records a failed call. In Closed state increments the counter; on reaching Threshold trips to Open. In HalfOpen, any failure immediately trips back to Open with the cooldown restarted (prevents short-cycle flapping). Failures in Open state are a no-op (already tripped).

RecordFailure 记录失败调用. Closed 态累计计数, 达 Threshold 跳 Open. HalfOpen 态任一失败立即回 Open 并重置 cooldown (防短周期 flapping). Open 态记录 no-op.

func (*CircuitBreaker) RecordSuccess

func (b *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful call. Resets the breaker to Closed (clearing the failure counter) regardless of prior state.

RecordSuccess 记录成功调用. 不管之前何态, 清零失败计数回 Closed.

func (*CircuitBreaker) State

func (b *CircuitBreaker) State() State

State returns the current breaker state (for observation; use Allow for gate decisions, not State).

State 返回当前状态 (供观测; gate 决策用 Allow 不用 State).

func (*CircuitBreaker) VerdictSink

func (b *CircuitBreaker) VerdictSink() func(toolName string, v validator.Verdict)

VerdictSink returns a function matching ValidatedTool's VerdictSink signature (func(toolName string, v validator.Verdict)). It maps Verdicts to RecordSuccess / RecordFailure according to Severity:

  • SeverityBlock -> RecordFailure (the write was rejected)
  • other (Warn, empty) -> RecordSuccess (write proceeded)

The toolName argument is intentionally ignored by this baseline implementation -- a single breaker protects all tools uniformly. Platforms wanting per-tool breakers wrap multiple CircuitBreakers and route in their own sink.

VerdictSink 返回一个与 ValidatedTool VerdictSink 签名匹配的函数 (func(toolName string, v validator.Verdict)). 按 Severity 把 Verdict 映射到 RecordSuccess / RecordFailure:

  • SeverityBlock -> RecordFailure (写被明确拒)
  • 其他 (Warn / empty) -> RecordSuccess (写放行)

toolName 本基础实现刻意忽略 -- 单个 breaker 统一保护所有工具. 需要 per-tool breaker 的 platform 包装多个 CircuitBreaker 在自己 的 sink 中路由.

type Clock

type Clock interface {
	Now() time.Time
}

Clock abstracts time for tests. Production callers use the default realClock; tests inject a fake to drive cooldown without sleeping.

Clock 为测试抽象时间. 生产走默认 realClock; 测试注入 fake 让 cooldown 推进不需要真 sleep.

type Config

type Config struct {
	// Threshold is the number of consecutive RecordFailure calls in
	// Closed state that trip the breaker to Open.
	//
	// Threshold 是 Closed 态连续 RecordFailure 跳 Open 所需的次数.
	Threshold int

	// Cooldown is how long the breaker stays Open before the next
	// Allow call flips it to HalfOpen.
	//
	// Cooldown 是 Open 态持续多久后下一次 Allow 转 HalfOpen.
	Cooldown time.Duration

	// Clock is the time source. nil uses a real wall clock.
	//
	// Clock 是时间源. nil 用真 wall clock.
	Clock Clock
}

Config constructs a CircuitBreaker. Zero or negative values are replaced by the Default* constants; a nil Clock uses a wall clock.

Config 构造 CircuitBreaker. 零或负值用 Default* 常量替换; nil Clock 用真 wall clock.

type State

type State int

State enumerates the three breaker states.

State 是三态熔断器的状态枚举.

const (
	StateClosed State = iota
	StateOpen
	StateHalfOpen
)

Breaker states.

熔断器状态.

func (State) String

func (s State) String() string

String returns a human-readable state name for logs / events.

String 返回人类可读的状态名, 供日志 / 事件使用.

Jump to

Keyboard shortcuts

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