Skip to content

Commit c5fa3fa

Browse files
committed
feat(pool): multi-account rotation with cooldown and failover
Minimal account pool for the bridge: - Pool/Slot with round-robin pick, per-account cooldown, exclusion set - CallQoderWithOpts now tries each healthy account in turn: on quota (401/403), rate-limit (429) or transient (418/5xx/transport) failure it cools the account and fails over to the next; content-policy and client-param errors do not fail over - streamWithSlot extracted from CallQoderWithOpts and reports whether any delta was emitted, so failover only happens before bytes reach the client - ListAvailableModels picks a healthy account - Service builds the pool from every account that has a secret (single-account path preserved when no pool is set) - tests: pick/cooldown/exclude, error classification, end-to-end failover
1 parent ae3d42f commit c5fa3fa

5 files changed

Lines changed: 598 additions & 44 deletions

File tree

‎internal/bridge/bridge.go‎

Lines changed: 74 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ type Bridge struct {
7676
client *BearerClient
7777
region account.Region
7878
templateBase map[string]interface{}
79+
// pool 非空时启用多账号轮询 + 失败换号;为空则退化为单账号(sess/client/region)。
80+
pool *Pool
7981
// chatStreamURL 测试注入用:非空时覆盖 region 对应的上游 chat 流地址
8082
chatStreamURL string
8183
}
@@ -174,8 +176,12 @@ func NewBridge(pat string, region account.Region, templateBase map[string]interf
174176
// ListAvailableModels 通过 cosy 签名调用 /algo/api/v2/model/list 拉取上游模型清单。
175177
// 返回顶层 assistant 数组中 enable=true 的模型,按 is_default desc + display_name asc 排序。
176178
func (b *Bridge) ListAvailableModels() ([]QoderModel, error) {
177-
modelListURL := qoderModelListURL(b.region)
178-
resp, err := b.client.callGet(modelListURL)
179+
slot, ok := b.pickSlot(nil)
180+
if !ok {
181+
return nil, ErrNoAccount
182+
}
183+
modelListURL := qoderModelListURL(slot.Region)
184+
resp, err := slot.client.callGet(modelListURL)
179185
if err != nil {
180186
return nil, err
181187
}
@@ -184,7 +190,7 @@ func (b *Bridge) ListAvailableModels() ([]QoderModel, error) {
184190
for k := range resp {
185191
keys = append(keys, k)
186192
}
187-
logger.Info("model list response keys: %v (region=%s)", keys, b.region)
193+
logger.Info("model list response keys: %v (region=%s)", keys, slot.Region)
188194
models := parseQoderModels(resp)
189195
if len(models) == 0 {
190196
return nil, fmt.Errorf("%s -> empty model list, keys=%v", modelListURL, keys)
@@ -322,13 +328,7 @@ func (b *Bridge) CallQoderWithOpts(ctx context.Context, agent string, messages [
322328
}
323329
body := DeepCopyMap(b.templateBase)
324330

325-
nid := cosy.NewUUID()
326-
body["request_id"] = nid
327-
body["chat_record_id"] = nid
328-
body["request_set_id"] = cosy.NewUUID()
329-
body["session_id"] = cosy.NewUUID()
330331
body["stream"] = true
331-
body["aliyun_user_type"] = b.sess.Identity.UserType
332332

333333
if mc, ok := body["model_config"].(map[string]interface{}); ok {
334334
mc["key"] = model
@@ -397,38 +397,77 @@ func (b *Bridge) CallQoderWithOpts(ctx context.Context, agent string, messages [
397397
}
398398
}
399399

400-
qurl := qoderChatStreamURL(b.region)
401-
if b.chatStreamURL != "" {
402-
qurl = b.chatStreamURL
403-
}
404400
extra := map[string]string{
405401
"x-model-key": model,
406402
"x-model-source": mcSource,
407403
}
408404

409405
preview := prompt
410-
if len(preview) > 80 {
406+
if len(prompt) > 80 {
411407
preview = preview[:80] + "..."
412408
}
413409
logger.Info("callQoder model=%s prompt=%s", model, preview)
414-
logger.Debug("callQoder request body: %s", func() string { d, _ := json.Marshal(body); return string(d) }())
415-
416-
// ---- SSE 信封重试闸门(第 3 步,参照 hub should_retry_envelope /
417-
// aggregate_with_envelope_retry)------------------------------------------
418-
// 关键形态:上游 HTTP200 建流后才在信封里投 418/5xx,连接层重试覆盖不到。
419-
// 闸门规则:只要「尚未向 onDelta 发出任何非空 delta」且错误属瞬时类
420-
// (信封 418/5xx/provider_error、传输层 TLS EOF 等),就重开上游重试,
421-
// 对调用方无感;已发出内容则直接上抛,避免客户端收到重复内容。
422-
// 客户端参数错 / 内容审核 / 401/429 经 IsTransientUpstream 判定为
423-
// 不可重试,快速失败。闸门做在此处,chat/claude/codex 三协议的
424-
// 流式与非流式路径全部自动覆盖。
425-
// 说明:连接阶段错误已在 openStreamLines 内部重试过;此处重开是
426-
// 第二层防护(有界:最多 TransientMaxRetries 次),主要覆盖流内信封错误。
410+
411+
// ---- 账号池选号 + 失败换号 -------------------------------------------
412+
// 逐个尝试池内账号:某账号失败且「尚未向客户端发出任何内容」、且错误属于
413+
// 可换号类(额度/频控/瞬时),就冷却该账号并换下一个;已发出内容或
414+
// 客户端参数错/内容审核则立即上抛——避免重复内容、避免无意义换号。
415+
tried := make(map[string]struct{})
427416
var lastErr error
417+
for {
418+
slot, ok := b.pickSlot(tried)
419+
if !ok {
420+
break
421+
}
422+
// 每个账号用全新的请求 id / session,避免跨账号复用同一标识
423+
nid := cosy.NewUUID()
424+
body["request_id"] = nid
425+
body["chat_record_id"] = nid
426+
body["request_set_id"] = cosy.NewUUID()
427+
body["session_id"] = cosy.NewUUID()
428+
body["aliyun_user_type"] = slot.sess.Identity.UserType
429+
if biz, ok := body["business"].(map[string]interface{}); ok {
430+
biz["id"] = cosy.NewUUID()
431+
biz["begin_at"] = cosy.UnixMs()
432+
}
433+
434+
qurl := b.chatStreamURL
435+
if qurl == "" {
436+
qurl = qoderChatStreamURL(slot.Region)
437+
}
438+
logger.Debug("callQoder request body: %s", func() string { d, _ := json.Marshal(body); return string(d) }())
439+
440+
emitted, err := b.streamWithSlot(ctx, slot, qurl, body, extra, onDelta)
441+
if err == nil {
442+
b.noteSlotSuccess(slot.ID)
443+
return nil
444+
}
445+
lastErr = err
446+
if emitted || !ShouldFailover(err) {
447+
return err
448+
}
449+
b.coolSlot(slot.ID, CooldownFor(err), err.Error())
450+
tried[slot.ID] = struct{}{}
451+
logger.Info("callQoder: account %s failed, failing over to next account: %v", slot.ID, err)
452+
}
453+
if lastErr == nil {
454+
lastErr = ErrNoAccount
455+
}
456+
return lastErr
457+
}
458+
459+
// streamWithSlot 在单个账号上执行「SSE 信封重试闸门」。
460+
// 连接阶段错误已由 openStreamLines 内部重试;此处是第二层防护(有界:
461+
// 最多 TransientMaxRetries 次),主要覆盖上游 HTTP200 建流后才在信封里
462+
// 投递 418/5xx 的形态。返回是否已向 onDelta 发出过内容——上层据此决定
463+
// 能否换号(已发出内容则不能,否则客户端会收到重复内容)。
464+
func (b *Bridge) streamWithSlot(ctx context.Context, slot *Slot, qurl string, body map[string]interface{}, extra map[string]string, onDelta func(Delta)) (bool, error) {
465+
var lastErr error
466+
emittedAny := false
428467
for attempt := 0; attempt <= TransientMaxRetries; attempt++ {
429468
if attempt > 0 {
430469
if serr := sleepCtx(ctx, RetryBackoff(attempt)); serr != nil {
431-
return lastErr
470+
return emittedAny, lastErr
432471
}
433472
logger.Info("reopen upstream after in-stream error (try %d/%d): %v",
434473
attempt+1, TransientMaxRetries+1, lastErr)
@@ -438,30 +477,30 @@ func (b *Bridge) CallQoderWithOpts(ctx context.Context, agent string, messages [
438477
onDeltaWrapped := func(d Delta) {
439478
if !d.isEmpty() {
440479
emitted = true
480+
emittedAny = true
441481
}
442482
onDelta(d)
443483
}
444-
streamErr := b.client.openStreamLines(ctx, qurl, body, extra,
484+
streamErr := slot.client.openStreamLines(ctx, qurl, body, extra,
445485
deltaDispatcher(onDeltaWrapped, &upstreamErr))
446486
if upstreamErr == nil && streamErr == nil {
447487
// 上游正常关流但未发出任何有效 delta/usage 帧:对齐 hub
448-
// "empty upstream stream" 显式报错(不纳入重开闸门——
449-
// isRetryableStreamError 对哨兵错误自然返回 false,不重试)
488+
// "empty upstream stream" 显式报错(不纳入重开闸门)。
450489
if !emitted {
451-
return ErrEmptyStream
490+
return emittedAny, ErrEmptyStream
452491
}
453-
return nil
492+
return emittedAny, nil
454493
}
455494
if upstreamErr != nil {
456495
lastErr = upstreamErr
457496
} else {
458497
lastErr = streamErr
459498
}
460499
if emitted || attempt >= TransientMaxRetries || !isRetryableStreamError(lastErr) {
461-
return lastErr
500+
return emittedAny, lastErr
462501
}
463502
}
464-
return lastErr
503+
return emittedAny, lastErr
465504
}
466505

467506
// isRetryableStreamError 判定流内/连接错误是否值得重开上游:

‎internal/bridge/bridge_pool.go‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package bridge
2+
3+
import (
4+
"time"
5+
6+
"qoder2api/account"
7+
)
8+
9+
// NewSlotFromSecret 用账号凭证构建一个可入池的 Slot(复用 NewBridge 的
10+
// 会话构建逻辑:OAuth 直接 userinfo,PAT 走 jobToken 交换 + 稳定指纹)。
11+
func NewSlotFromSecret(id, name string, region account.Region, secret string) (*Slot, error) {
12+
b, err := NewBridge(secret, region, nil)
13+
if err != nil {
14+
return nil, err
15+
}
16+
return NewSlot(id, name, region, b.sess, b.client), nil
17+
}
18+
19+
// NewPoolBridge 用账号池创建桥接(多账号轮询 + 失败换号)。
20+
func NewPoolBridge(pool *Pool, templateBase map[string]interface{}) *Bridge {
21+
return &Bridge{pool: pool, templateBase: templateBase}
22+
}
23+
24+
// candidateSlots 返回当前可参与选号的账号:池优先;无池时退化为单账号
25+
// (保持既有单账号构造方式与测试兼容)。
26+
func (b *Bridge) candidateSlots() []*Slot {
27+
if b.pool != nil {
28+
return b.pool.snapshot()
29+
}
30+
if b.sess == nil || b.client == nil {
31+
return nil
32+
}
33+
return []*Slot{{ID: "default", Name: "default", Region: b.region, sess: b.sess, client: b.client}}
34+
}
35+
36+
// pickSlot 选一个账号,跳过 exclude 与冷却中的账号。
37+
func (b *Bridge) pickSlot(exclude map[string]struct{}) (*Slot, bool) {
38+
if b.pool != nil {
39+
return b.pool.Pick(exclude)
40+
}
41+
slots := b.candidateSlots()
42+
if len(slots) == 0 {
43+
return nil, false
44+
}
45+
if _, skip := exclude[slots[0].ID]; skip {
46+
return nil, false
47+
}
48+
return slots[0], true
49+
}
50+
51+
// coolSlot 冷却账号(仅池模式下生效;单账号模式为 no-op)。
52+
func (b *Bridge) coolSlot(id string, d time.Duration, reason string) {
53+
if b.pool != nil {
54+
b.pool.Cool(id, d, reason)
55+
}
56+
}
57+
58+
// noteSlotSuccess 记录成功(仅池模式下生效)。
59+
func (b *Bridge) noteSlotSuccess(id string) {
60+
if b.pool != nil {
61+
b.pool.NoteSuccess(id)
62+
}
63+
}

0 commit comments

Comments
 (0)