Fuse - Circuit breaker with half-open state, exponential backoff, and event hooks for MoonBit
moon add fuselet fuse = @fuse.new_builder()
.failure_threshold(5) // 连续 5 次失败 → 熔断
.cooldown_secs(30) // 30 秒冷却后进入半开
.half_open_limit(3) // 半开状态 3 次成功后恢复
.on_trip(fn(fails) { alert("CIRCUIT OPEN: " + fails.to_string()) })
.on_restore(fn() { alert("CIRCUIT CLOSED") })
.build()
match fuse.try_acquire() {
Ok(_) => {
// 获得许可,执行业务
if call_service() {
fuse.record_success()
} else {
fuse.record_failure()
}
}
Err(e) => println(e) // "FUSE OPEN: cooldown 25s remaining"
} 连续 N 次失败 冷却期满
Closed ──────────────► Open ─────────────► HalfOpen
▲ │
│ 半开成功 × M 次 │
└───────────────────────────────────────────┘
│
└── 半开失败 ──► Open(重新熔断)let dev = @fuse.permissive_fuse() // threshold=10 cooldown=10s half_open=1
let prod = @fuse.default_fuse() // threshold=5 cooldown=30s half_open=3
let strict = @fuse.strict_fuse() // threshold=2 cooldown=60s half_open=5| 方法 | 说明 |
|---|---|
| new_builder() | 创建 Builder |
| .failure_threshold(n) | 连续失败 N 次熔断 |
| .cooldown_secs(n) | 熔断后冷却 tick 数 |
| .half_open_limit(n) | 半开恢复所需成功次数 |
| .on_trip(fn) | 熔断触发回调 |
| .on_restore(fn) | 恢复回调 |
| .on_half_open(fn) | 进入半开回调 |
| .build() | 构建 Fuse |
| fuse.try_acquire() | 获取许可 → Ok / Err |
| fuse.record_success() | 上报成功 |
| fuse.record_failure() | 上报失败 |
| fuse.tick() | 手动推进时间 |
| fuse.current_state() | 当前状态(Closed/Open/HalfOpen) |
| fuse.is_open() | 是否熔断中 |
| fuse.stats() | 统计字符串 |
Fuse - Circuit breaker with half-open state, exponential backoff, and event hooks for MoonBit