feat: 流式首包缓冲容错(hold)与失败分类冷却

流式请求在首个内容事件到达前由网关缓冲(借鉴 magpie 的 holdWriter):上游的错误
事件、空流、断连、协议形态不符(要流给了整包)都在放行前换渠道消化,客户端无感知。
扣住期间照常发 SSE 注释心跳;缓冲超过 1MB 直接放行退化为普通转发,判定失效不吞正文。

- 新增 proxy/hold.go:streamHold(缓冲/放行/心跳/首 token 计时与放行互斥)、
  sseEventHasContent(chat/messages/responses 三种协议的内容判定)、
  sseUpstreamError(200+流式形式的错误事件识别)、classifyUpstreamError +
  quotaSignals(余额/配额特征识别)
- 非流式改为先读完整响应再写头:读失败(网络错误/超时)发生在写出之前,可换渠道
  重试;此前先写 200 头再读,超时只能给客户端留一个 200 空响应
- 协议形态校验:要流却给了整包(didNotStream)按失败换渠道,反复如此的渠道会被
  健康计数剔除
- 记账:每次尝试独立 trySink,只有成功走到 EOF 才并入请求级 sink——失败渠道的
  message_start 用量不计入账单
- 冷却按原因分类(channel.FailKind):余额/配额类第一次失败即冷却 30 分钟(429 不
  一定是限流,智谱 429「余额不足」也在此列);其余按连续进冷却次数指数退避
  30s→60s→120s,封顶 10 分钟;短于退避值的 Retry-After 不再缩短冷却
- 新增 OT_PROXY_FIRST_TOKEN_WAIT(默认 0=不限):放行前等内容的最长时间,超时即
  取消本次尝试换下一个渠道
- 渠道列表接口返回 cooldown_reason,后台可区分「限流」与「余额耗尽」
- 测试:hold 缓冲/放行/心跳、内容与错误事件判定、失败分类与指数退避、容量热生效
- docs/magpie-plugin-mechanism.md:参考实现的插件机制调研
This commit is contained in:
Sakurasan committed 2026-10-30 02:43:23 +08:00
1 parent d357134e97
commit 979973ddde
12 files changed
+1377 -168

No files matched your search

+7 -7
View File
@@ -30,28 +30,28 @@ func (h *Handler) AdminChannels(c *gin.Context) {
} else if err == nil {
masked = "****"
}
fails, cooldownSec := h.channelRuntime(ch.ID)
fails, cooldownSec, reason := h.channelRuntime(ch.ID)
out = append(out, gin.H{
"id": ch.ID, "name": ch.Name, "provider": ch.Provider, "formats": ch.FormatsEffective(),
"base_url": ch.BaseURL, "base_urls": ch.BaseURLs,
"api_key_masked": masked, "weight": ch.Weight, "priority": ch.Priority,
"timeout_ms": ch.TimeoutMS, "max_concurrency": ch.MaxConcurrency,
"health_status": ch.HealthStatus, "enabled": ch.Enabled,
"runtime_fails": fails, "cooldown_seconds": cooldownSec,
"runtime_fails": fails, "cooldown_seconds": cooldownSec, "cooldown_reason": reason,
"created_at": ch.CreatedAt,
})
}
resp.OK(c, gin.H{"items": out})
}
// channelRuntime 渠道运行期健康:连续失败次数与冷却剩余秒数(0 表示无冷却)。
// channelRuntime 渠道运行期健康:连续失败次数、冷却剩余秒数(0 表示无冷却)与最近失败原因。
// 运行期冷却只存在于进程内存,DB 的 health_status 看不到它,故列表单独返回。
func (h *Handler) channelRuntime(id uint64) (fails int, cooldownSeconds int64) {
func (h *Handler) channelRuntime(id uint64) (fails int, cooldownSeconds int64, reason string) {
if h.gw == nil {
return 0, 0
return 0, 0, ""
}
fails, remaining := h.gw.ChannelRuntime(id)
return fails, int64((remaining + time.Second - time.Nanosecond) / time.Second) // 向上取整
fails, remaining, reason := h.gw.ChannelRuntime(id)
return fails, int64((remaining + time.Second - time.Nanosecond) / time.Second), reason // 向上取整
}
type channelBody struct {