-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
Expand file tree
/
Copy pathconductor.go
More file actions
5970 lines (5576 loc) · 169 KB
/
Copy pathconductor.go
File metadata and controls
5970 lines (5576 loc) · 169 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package auth
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
internalconfig "github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/home"
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v7/internal/thinking"
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/executor"
coreusage "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/usage"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/pluginapi"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v7/sdk/translator"
log "github.com/sirupsen/logrus"
"github.com/tidwall/sjson"
)
// ProviderExecutor defines the contract required by Manager to execute provider calls.
type ProviderExecutor interface {
// Identifier returns the provider key handled by this executor.
Identifier() string
// Execute handles non-streaming execution and returns the provider response payload.
Execute(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error)
// ExecuteStream handles streaming execution and returns a StreamResult containing
// upstream headers and a channel of provider chunks.
ExecuteStream(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error)
// Refresh attempts to refresh provider credentials and returns the updated auth state.
Refresh(ctx context.Context, auth *Auth) (*Auth, error)
// CountTokens returns the token count for the given request.
CountTokens(ctx context.Context, auth *Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (cliproxyexecutor.Response, error)
// HttpRequest injects provider credentials into the supplied HTTP request and executes it.
// Callers must close the response body when non-nil.
HttpRequest(ctx context.Context, auth *Auth, req *http.Request) (*http.Response, error)
}
// RequestAuthPreparer lets an executor update missing auth metadata immediately
// before a request. Manager serializes and persists returned updates.
type RequestAuthPreparer interface {
ShouldPrepareRequestAuth(auth *Auth) bool
PrepareRequestAuth(ctx context.Context, auth *Auth) (*Auth, error)
}
// ExecutionSessionCloser allows executors to release per-session runtime resources.
type ExecutionSessionCloser interface {
CloseExecutionSession(sessionID string)
}
const (
homeAuthCountMetadataKey = "__cliproxy_home_auth_count"
// CloseAllExecutionSessionsID asks an executor to release all active execution sessions.
// Executors that do not support this marker may ignore it.
CloseAllExecutionSessionsID = "__all_execution_sessions__"
)
// RefreshEvaluator allows runtime state to override refresh decisions.
type RefreshEvaluator interface {
ShouldRefresh(now time.Time, auth *Auth) bool
}
const (
refreshCheckInterval = 5 * time.Second
refreshMaxConcurrency = 16
refreshPendingBackoff = time.Minute
refreshFailureBackoff = 5 * time.Minute
// refreshIneffectiveBackoff throttles refresh attempts when an executor returns
// success but the auth still evaluates as needing refresh (e.g. token expiry
// wasn't updated). Without this guard, the auto-refresh loop can tight-loop and
// burn CPU at idle.
refreshIneffectiveBackoff = 30 * time.Second
quotaBackoffBase = time.Second
quotaBackoffMax = 30 * time.Minute
transientErrorCooldown = time.Minute
)
var quotaCooldownDisabled atomic.Bool
var transientErrorCooldownSeconds atomic.Int64
// SetQuotaCooldownDisabled toggles quota cooldown scheduling globally.
func SetQuotaCooldownDisabled(disable bool) {
quotaCooldownDisabled.Store(disable)
}
// SetTransientErrorCooldownSeconds configures cooldowns for 408/500/502/503/504.
// 0 keeps the legacy default; negative values disable transient error cooldowns.
func SetTransientErrorCooldownSeconds(seconds int) {
transientErrorCooldownSeconds.Store(int64(seconds))
}
func quotaCooldownDisabledForAuth(auth *Auth) bool {
return quotaCooldownDisabledForAuthWithConfig(auth, nil)
}
func quotaCooldownDisabledForAuthWithConfig(auth *Auth, cfg *internalconfig.Config) bool {
if auth != nil {
if override, ok := auth.DisableCoolingOverride(); ok {
return override
}
if providerCoolingDisabledForAuth(auth, cfg) {
return true
}
}
if cfg != nil && cfg.DisableCooling {
return true
}
return quotaCooldownDisabled.Load()
}
func providerCoolingDisabledForAuth(auth *Auth, cfg *internalconfig.Config) bool {
if auth == nil || cfg == nil {
return false
}
provider := strings.ToLower(strings.TrimSpace(auth.Provider))
if provider == "" {
return false
}
providerKey := ""
compatName := ""
if auth.Attributes != nil {
providerKey = strings.TrimSpace(auth.Attributes["provider_key"])
compatName = strings.TrimSpace(auth.Attributes["compat_name"])
}
if providerKey == "" && compatName == "" && provider != "openai-compatibility" {
return false
}
if providerKey == "" {
providerKey = provider
}
entry := resolveOpenAICompatConfig(cfg, providerKey, compatName, provider)
return entry != nil && entry.DisableCooling
}
func nextTransientErrorRetryAfter(now time.Time) time.Time {
seconds := transientErrorCooldownSeconds.Load()
if seconds < 0 {
return time.Time{}
}
if seconds == 0 {
return now.Add(transientErrorCooldown)
}
return now.Add(time.Duration(seconds) * time.Second)
}
// Result captures execution outcome used to adjust auth state.
type Result struct {
// AuthID references the auth that produced this result.
AuthID string
// Provider is copied for convenience when emitting hooks.
Provider string
// Model is the upstream model identifier used for the request.
Model string
// Success marks whether the execution succeeded.
Success bool
// RetryAfter carries a provider supplied retry hint (e.g. 429 retryDelay).
RetryAfter *time.Duration
// Error describes the failure when Success is false.
Error *Error
}
// Selector chooses an auth candidate for execution.
type Selector interface {
Pick(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth) (*Auth, error)
}
type PluginScheduler interface {
PickAuth(context.Context, pluginapi.SchedulerPickRequest) (pluginapi.SchedulerPickResponse, bool, error)
}
type pluginSchedulerState interface {
HasScheduler() bool
}
// StoppableSelector is an optional interface for selectors that hold resources.
// Selectors that implement this interface will have Stop called during shutdown.
type StoppableSelector interface {
Selector
Stop()
}
// Hook captures lifecycle callbacks for observing auth changes.
type Hook interface {
// OnAuthRegistered fires when a new auth is registered.
OnAuthRegistered(ctx context.Context, auth *Auth)
// OnAuthUpdated fires when an existing auth changes state.
OnAuthUpdated(ctx context.Context, auth *Auth)
// OnResult fires when execution result is recorded.
OnResult(ctx context.Context, result Result)
}
// NoopHook provides optional hook defaults.
type NoopHook struct{}
// OnAuthRegistered implements Hook.
func (NoopHook) OnAuthRegistered(context.Context, *Auth) {}
// OnAuthUpdated implements Hook.
func (NoopHook) OnAuthUpdated(context.Context, *Auth) {}
// OnResult implements Hook.
func (NoopHook) OnResult(context.Context, Result) {}
// Manager orchestrates auth lifecycle, selection, execution, and persistence.
type Manager struct {
store Store
cooldownStore CooldownStateStore
executors map[string]ProviderExecutor
selector Selector
hook Hook
mu sync.RWMutex
auths map[string]*Auth
scheduler *authScheduler
// pluginScheduler runs outside m.mu before falling back to native selection.
pluginScheduler PluginScheduler
// homeRuntimeAuths caches auths returned by Home so websocket sessions can
// reuse an established upstream credential without dispatching every turn.
homeRuntimeAuths map[string]map[string]*Auth
// providerOffsets tracks per-model provider rotation state for multi-provider routing.
providerOffsets map[string]int
// Retry controls request retry behavior.
requestRetry atomic.Int32
maxRetryCredentials atomic.Int32
maxRetryInterval atomic.Int64
// oauthModelAlias stores global OAuth model alias mappings (alias -> upstream name) keyed by channel.
oauthModelAlias atomic.Value
// apiKeyModelAlias caches resolved model alias mappings for API-key auths.
// Keyed by auth.ID, value is alias(lower) -> upstream model (including suffix).
apiKeyModelAlias atomic.Value
// modelPoolOffsets tracks per-auth alias pool rotation state.
modelPoolOffsets map[string]int
// runtimeConfig stores the latest application config for request-time decisions.
// It is initialized in NewManager; never Load() before first Store().
runtimeConfig atomic.Value
// Optional HTTP RoundTripper provider injected by host.
rtProvider RoundTripperProvider
// Auto refresh state
refreshCancel context.CancelFunc
refreshLoop *authAutoRefreshLoop
requestPrepareLocks sync.Map
}
// NewManager constructs a manager with optional custom selector and hook.
func NewManager(store Store, selector Selector, hook Hook) *Manager {
if selector == nil {
selector = &RoundRobinSelector{}
}
if hook == nil {
hook = NoopHook{}
}
manager := &Manager{
store: store,
executors: make(map[string]ProviderExecutor),
selector: selector,
hook: hook,
auths: make(map[string]*Auth),
homeRuntimeAuths: make(map[string]map[string]*Auth),
providerOffsets: make(map[string]int),
modelPoolOffsets: make(map[string]int),
}
// atomic.Value requires non-nil initial value.
manager.runtimeConfig.Store(&internalconfig.Config{})
manager.apiKeyModelAlias.Store(apiKeyModelAliasTable(nil))
manager.scheduler = newAuthScheduler(selector)
return manager
}
func (m *Manager) SetPluginScheduler(scheduler PluginScheduler) {
if m == nil {
return
}
m.mu.Lock()
m.pluginScheduler = scheduler
m.mu.Unlock()
}
func (m *Manager) hasPluginScheduler() bool {
if m == nil {
return false
}
m.mu.RLock()
scheduler := m.pluginScheduler
m.mu.RUnlock()
if scheduler == nil {
return false
}
if state, ok := scheduler.(pluginSchedulerState); ok {
return state.HasScheduler()
}
return true
}
func isBuiltInSelector(selector Selector) bool {
switch selector.(type) {
case *RoundRobinSelector, *FillFirstSelector:
return true
default:
return false
}
}
func (m *Manager) syncSchedulerFromSnapshot(auths []*Auth) {
if m == nil || m.scheduler == nil {
return
}
m.scheduler.rebuild(auths)
}
func (m *Manager) syncScheduler() {
if m == nil || m.scheduler == nil {
return
}
m.syncSchedulerFromSnapshot(m.snapshotAuths())
}
func (m *Manager) snapshotAuths() []*Auth {
m.mu.RLock()
defer m.mu.RUnlock()
out := make([]*Auth, 0, len(m.auths))
for _, a := range m.auths {
out = append(out, a.Clone())
}
return out
}
// RefreshSchedulerEntry re-upserts a single auth into the scheduler so that its
// supportedModelSet is rebuilt from the current global model registry state.
// This must be called after models have been registered for a newly added auth,
// because the initial scheduler.upsertAuth during Register/Update runs before
// registerModelsForAuth and therefore snapshots an empty model set.
func (m *Manager) RefreshSchedulerEntry(authID string) {
if m == nil || m.scheduler == nil || authID == "" {
return
}
m.mu.RLock()
auth, ok := m.auths[authID]
if !ok || auth == nil {
m.mu.RUnlock()
return
}
snapshot := auth.Clone()
m.mu.RUnlock()
m.scheduler.upsertAuth(snapshot)
}
// RefreshSchedulerAll rebuilds scheduler entries for every known auth.
func (m *Manager) RefreshSchedulerAll() {
if m == nil {
return
}
m.mu.RLock()
ids := make([]string, 0, len(m.auths))
for id := range m.auths {
ids = append(ids, id)
}
m.mu.RUnlock()
for _, id := range ids {
m.RefreshSchedulerEntry(id)
}
}
// ReconcileRegistryModelStates aligns per-model runtime state with the current
// registry snapshot for one auth.
//
// Supported models are reset to a clean state because re-registration already
// cleared the registry-side cooldown/suspension snapshot. ModelStates for
// models that are no longer present in the registry are pruned entirely so
// renamed/removed models cannot keep auth-level status stale.
func (m *Manager) ReconcileRegistryModelStates(ctx context.Context, authID string) {
if m == nil || authID == "" {
return
}
supportedModels := registry.GetGlobalRegistry().GetModelsForClient(authID)
supported := make(map[string]struct{}, len(supportedModels))
for _, model := range supportedModels {
if model == nil {
continue
}
modelKey := canonicalModelKey(model.ID)
if modelKey == "" {
continue
}
supported[modelKey] = struct{}{}
}
var snapshot *Auth
now := time.Now()
m.mu.Lock()
auth, ok := m.auths[authID]
if ok && auth != nil && len(auth.ModelStates) > 0 {
changed := false
for modelKey, state := range auth.ModelStates {
baseModel := canonicalModelKey(modelKey)
if baseModel == "" {
baseModel = strings.TrimSpace(modelKey)
}
if _, supportedModel := supported[baseModel]; !supportedModel {
// Drop state for models that disappeared from the current registry
// snapshot. Keeping them around leaks stale errors into auth-level
// status, management output, and websocket fallback checks.
delete(auth.ModelStates, modelKey)
changed = true
continue
}
if state == nil {
continue
}
if modelStateIsClean(state) {
continue
}
resetModelState(state, now)
changed = true
}
if len(auth.ModelStates) == 0 {
auth.ModelStates = nil
}
if changed {
updateAggregatedAvailability(auth, now)
if !hasModelError(auth, now) {
auth.LastError = nil
auth.StatusMessage = ""
auth.Status = StatusActive
}
auth.UpdatedAt = now
if errPersist := m.persist(ctx, auth); errPersist != nil {
logEntryWithRequestID(ctx).WithField("auth_id", auth.ID).Warnf("failed to persist auth changes during model state reconciliation: %v", errPersist)
}
snapshot = auth.Clone()
}
}
m.mu.Unlock()
if m.scheduler != nil && snapshot != nil {
m.scheduler.upsertAuth(snapshot)
}
}
func (m *Manager) SetSelector(selector Selector) {
if m == nil {
return
}
if selector == nil {
selector = &RoundRobinSelector{}
}
m.mu.Lock()
m.selector = selector
m.mu.Unlock()
if m.scheduler != nil {
m.scheduler.setSelector(selector)
m.syncScheduler()
}
}
// SetStore swaps the underlying persistence store.
func (m *Manager) SetStore(store Store) {
m.mu.Lock()
defer m.mu.Unlock()
m.store = store
}
// SetCooldownStateStore swaps the independent runtime cooldown state store.
func (m *Manager) SetCooldownStateStore(store CooldownStateStore) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
m.cooldownStore = store
}
// SetRoundTripperProvider register a provider that returns a per-auth RoundTripper.
func (m *Manager) SetRoundTripperProvider(p RoundTripperProvider) {
m.mu.Lock()
m.rtProvider = p
m.mu.Unlock()
}
// SetConfig updates the runtime config snapshot used by request-time helpers.
// Callers should provide the latest config on reload so per-credential alias mapping stays in sync.
func (m *Manager) SetConfig(cfg *internalconfig.Config) {
if m == nil {
return
}
if cfg == nil {
cfg = &internalconfig.Config{}
}
m.runtimeConfig.Store(cfg)
clearedCooldowns := m.clearDisabledCooldownStates(cfg)
if !cfg.Home.Enabled {
m.clearHomeRuntimeAuths()
}
m.rebuildAPIKeyModelAliasFromRuntimeConfig()
if clearedCooldowns {
m.persistCooldownStates(context.Background())
}
}
func (m *Manager) cooldownDisabledForAuth(auth *Auth) bool {
if m == nil {
return quotaCooldownDisabledForAuth(auth)
}
cfg, _ := m.runtimeConfig.Load().(*internalconfig.Config)
return quotaCooldownDisabledForAuthWithConfig(auth, cfg)
}
func (m *Manager) clearDisabledCooldownStates(cfg *internalconfig.Config) bool {
if m == nil {
return false
}
now := time.Now()
snapshots := make([]*Auth, 0)
m.mu.Lock()
for _, auth := range m.auths {
if auth == nil {
continue
}
if !quotaCooldownDisabledForAuthWithConfig(auth, cfg) && !auth.Disabled && auth.Status != StatusDisabled {
continue
}
if clearCooldownStateForAuth(auth, now) {
snapshots = append(snapshots, auth.Clone())
}
}
m.mu.Unlock()
if m.scheduler != nil {
for _, snapshot := range snapshots {
m.scheduler.upsertAuth(snapshot)
}
}
return len(snapshots) > 0
}
// RestoreCooldownStates restores unexpired persisted cooldown records into registered auths.
func (m *Manager) RestoreCooldownStates(ctx context.Context) error {
if m == nil {
return nil
}
if ctx == nil {
ctx = context.Background()
}
m.mu.RLock()
store := m.cooldownStore
m.mu.RUnlock()
if store == nil {
return nil
}
records, errLoad := store.Load(ctx)
if errLoad != nil {
return errLoad
}
if len(records) == 0 {
return nil
}
now := time.Now()
authLevelRecords := make([]CooldownStateRecord, 0)
snapshotsByID := make(map[string]*Auth)
m.mu.Lock()
for _, record := range records {
if strings.TrimSpace(record.Model) == "" {
authLevelRecords = append(authLevelRecords, record)
continue
}
if m.restoreCooldownRecordLocked(record, now) {
if auth := m.auths[strings.TrimSpace(record.AuthID)]; auth != nil {
snapshotsByID[auth.ID] = auth.Clone()
}
}
}
for _, record := range authLevelRecords {
if m.restoreCooldownRecordLocked(record, now) {
if auth := m.auths[strings.TrimSpace(record.AuthID)]; auth != nil {
snapshotsByID[auth.ID] = auth.Clone()
}
}
}
m.mu.Unlock()
if m.scheduler != nil {
for _, snapshot := range snapshotsByID {
m.scheduler.upsertAuth(snapshot)
}
}
m.persistCooldownStates(ctx)
return nil
}
func (m *Manager) restoreCooldownRecordLocked(record CooldownStateRecord, now time.Time) bool {
authID := strings.TrimSpace(record.AuthID)
if authID == "" || record.NextRetryAfter.IsZero() || !record.NextRetryAfter.After(now) {
return false
}
auth := m.auths[authID]
if auth == nil || auth.Disabled || auth.Status == StatusDisabled || m.cooldownDisabledForAuth(auth) {
return false
}
updatedAt := record.UpdatedAt
if updatedAt.IsZero() {
updatedAt = now
}
reason := strings.TrimSpace(record.Reason)
model := strings.TrimSpace(record.Model)
quota := record.Quota
if quota.Exceeded && quota.NextRecoverAt.IsZero() {
quota.NextRecoverAt = record.NextRetryAfter
}
if model == "" {
auth.Unavailable = true
auth.Status = StatusError
auth.NextRetryAfter = record.NextRetryAfter
auth.Quota = quota
auth.UpdatedAt = updatedAt
if reason != "" {
auth.StatusMessage = reason
}
auth.LastError = cloneError(record.LastError)
return true
}
state := ensureModelState(auth, model)
state.Unavailable = true
state.Status = StatusError
state.NextRetryAfter = record.NextRetryAfter
state.Quota = quota
state.UpdatedAt = updatedAt
if reason != "" {
state.StatusMessage = reason
}
state.LastError = cloneError(record.LastError)
updateAggregatedAvailability(auth, now)
return true
}
func clearCooldownStateForAuth(auth *Auth, now time.Time) bool {
if auth == nil {
return false
}
changed := false
if auth.Unavailable || !auth.NextRetryAfter.IsZero() || auth.Quota.Exceeded || !auth.Quota.NextRecoverAt.IsZero() {
auth.Unavailable = false
auth.NextRetryAfter = time.Time{}
auth.Quota = QuotaState{}
auth.UpdatedAt = now
changed = true
}
for _, state := range auth.ModelStates {
if state == nil {
continue
}
if state.Unavailable || !state.NextRetryAfter.IsZero() || state.Quota.Exceeded || !state.Quota.NextRecoverAt.IsZero() {
state.Unavailable = false
state.NextRetryAfter = time.Time{}
state.Quota = QuotaState{}
state.UpdatedAt = now
changed = true
}
}
if len(auth.ModelStates) > 0 {
updateAggregatedAvailability(auth, now)
}
return changed
}
func dedupeStrings(values []string) []string {
if len(values) < 2 {
return values
}
seen := make(map[string]struct{}, len(values))
out := values[:0]
for _, value := range values {
value = strings.TrimSpace(value)
if value == "" {
continue
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
out = append(out, value)
}
return out
}
// ResetQuota clears quota/cooldown state for an auth and resumes registry routing.
func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []string, error) {
if m == nil {
return nil, nil, nil
}
authID = strings.TrimSpace(authID)
if authID == "" {
return nil, nil, fmt.Errorf("auth id is required")
}
now := time.Now()
var snapshot *Auth
models := make([]string, 0)
registeredModels := modelsForRegisteredAuth(authID)
cooldownStateChanged := false
m.mu.Lock()
auth, ok := m.auths[authID]
if !ok || auth == nil {
m.mu.Unlock()
return nil, nil, nil
}
var cooldownRecordsBefore []CooldownStateRecord
trackCooldownState := m.cooldownStore != nil
if trackCooldownState {
cooldownRecordsBefore = m.cooldownStateRecordsForAuthLocked(auth, now)
}
for modelKey, state := range auth.ModelStates {
if strings.TrimSpace(modelKey) == "" {
continue
}
models = append(models, modelKey)
if state != nil {
resetModelState(state, now)
}
}
if clearCooldownStateForAuth(auth, now) {
if len(models) == 0 {
models = append(models, registeredModels...)
}
} else if len(auth.ModelStates) > 0 {
updateAggregatedAvailability(auth, now)
}
if len(models) == 0 {
models = append(models, registeredModels...)
}
models = dedupeStrings(models)
if !auth.Disabled && auth.Status != StatusDisabled && !hasModelError(auth, now) {
auth.LastError = nil
auth.StatusMessage = ""
auth.Status = StatusActive
}
auth.UpdatedAt = now
if errPersist := m.persist(ctx, auth); errPersist != nil {
m.mu.Unlock()
return nil, nil, errPersist
}
snapshot = auth.Clone()
if trackCooldownState {
cooldownRecordsAfter := m.cooldownStateRecordsForAuthLocked(auth, now)
cooldownStateChanged = !cooldownStateRecordsEqual(cooldownRecordsBefore, cooldownRecordsAfter)
}
m.mu.Unlock()
for _, modelKey := range models {
registry.GetGlobalRegistry().ClearModelQuotaExceeded(authID, modelKey)
registry.GetGlobalRegistry().ResumeClientModel(authID, modelKey)
}
if m.scheduler != nil && snapshot != nil {
m.scheduler.upsertAuth(snapshot)
}
if snapshot != nil && cooldownStateChanged {
m.persistCooldownStates(ctx)
}
return snapshot, models, nil
}
func modelsForRegisteredAuth(authID string) []string {
supportedModels := registry.GetGlobalRegistry().GetModelsForClient(authID)
models := make([]string, 0, len(supportedModels))
for _, supportedModel := range supportedModels {
if supportedModel == nil || strings.TrimSpace(supportedModel.ID) == "" {
continue
}
models = append(models, supportedModel.ID)
}
return models
}
func (m *Manager) persistCooldownStates(ctx context.Context) {
if m == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
records, store := m.cooldownStateSnapshot()
if store == nil {
return
}
if errSave := store.Save(ctx, records); errSave != nil {
logEntryWithRequestID(ctx).Warnf("failed to persist cooldown state: %v", errSave)
}
}
func (m *Manager) cooldownStateSnapshot() ([]CooldownStateRecord, CooldownStateStore) {
now := time.Now()
records := make([]CooldownStateRecord, 0)
m.mu.RLock()
store := m.cooldownStore
if store == nil {
m.mu.RUnlock()
return nil, nil
}
for _, auth := range m.auths {
records = append(records, m.cooldownStateRecordsForAuthLocked(auth, now)...)
}
m.mu.RUnlock()
sort.Slice(records, func(i, j int) bool {
if records[i].Provider != records[j].Provider {
return records[i].Provider < records[j].Provider
}
if records[i].AuthID != records[j].AuthID {
return records[i].AuthID < records[j].AuthID
}
return records[i].Model < records[j].Model
})
return records, store
}
func (m *Manager) cooldownStateRecordsForAuthLocked(auth *Auth, now time.Time) []CooldownStateRecord {
if auth == nil || auth.ID == "" || auth.Disabled || auth.Status == StatusDisabled || m.cooldownDisabledForAuth(auth) {
return nil
}
records := make([]CooldownStateRecord, 0, 1+len(auth.ModelStates))
if record, ok := authCooldownStateRecord(auth, now); ok {
records = append(records, record)
}
for model, state := range auth.ModelStates {
if record, ok := modelCooldownStateRecord(auth, model, state, now); ok {
records = append(records, record)
}
}
sort.Slice(records, func(i, j int) bool {
return records[i].Model < records[j].Model
})
return records
}
func cooldownStateRecordsEqual(a, b []CooldownStateRecord) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !cooldownStateRecordEqual(a[i], b[i]) {
return false
}
}
return true
}
func cooldownStateRecordEqual(a, b CooldownStateRecord) bool {
if a.Provider != b.Provider ||
a.AuthID != b.AuthID ||
a.AuthFile != b.AuthFile ||
a.Model != b.Model ||
a.Status != b.Status ||
a.Reason != b.Reason ||
!a.NextRetryAfter.Equal(b.NextRetryAfter) ||
!a.UpdatedAt.Equal(b.UpdatedAt) ||
!cooldownQuotaEqual(a.Quota, b.Quota) {
return false
}
return cooldownErrorEqual(a.LastError, b.LastError)
}
func cooldownQuotaEqual(a, b QuotaState) bool {
return a.Exceeded == b.Exceeded &&
a.Reason == b.Reason &&
a.BackoffLevel == b.BackoffLevel &&
a.NextRecoverAt.Equal(b.NextRecoverAt)
}
func cooldownErrorEqual(a, b *Error) bool {
if a == nil || b == nil {
return a == b
}
return a.Code == b.Code &&
a.Message == b.Message &&
a.Retryable == b.Retryable &&
a.HTTPStatus == b.HTTPStatus
}
func authCooldownStateRecord(auth *Auth, now time.Time) (CooldownStateRecord, bool) {
if auth == nil || !auth.Unavailable || auth.NextRetryAfter.IsZero() || !auth.NextRetryAfter.After(now) {
return CooldownStateRecord{}, false
}
return CooldownStateRecord{
Provider: strings.TrimSpace(auth.Provider),
AuthID: auth.ID,
AuthFile: cooldownAuthFile(auth),
Status: "cooling",
NextRetryAfter: auth.NextRetryAfter,
Reason: cooldownReason(auth.StatusMessage, auth.Quota, auth.LastError),
Quota: auth.Quota,
LastError: cloneError(auth.LastError),
UpdatedAt: auth.UpdatedAt,
}, true
}
func modelCooldownStateRecord(auth *Auth, model string, state *ModelState, now time.Time) (CooldownStateRecord, bool) {
model = strings.TrimSpace(model)
if auth == nil || state == nil || model == "" || !state.Unavailable || state.NextRetryAfter.IsZero() || !state.NextRetryAfter.After(now) {
return CooldownStateRecord{}, false
}
return CooldownStateRecord{
Provider: strings.TrimSpace(auth.Provider),
AuthID: auth.ID,
AuthFile: cooldownAuthFile(auth),
Model: model,
Status: "cooling",
NextRetryAfter: state.NextRetryAfter,
Reason: cooldownReason(state.StatusMessage, state.Quota, state.LastError),
Quota: state.Quota,
LastError: cloneError(state.LastError),
UpdatedAt: state.UpdatedAt,
}, true
}
func cooldownReason(statusMessage string, quota QuotaState, lastErr *Error) string {
if reason := strings.TrimSpace(quota.Reason); reason != "" {
return reason
}
if statusMessage = strings.TrimSpace(statusMessage); statusMessage != "" {
return statusMessage
}
if lastErr != nil {
if code := strings.TrimSpace(lastErr.Code); code != "" {
return code
}
if message := strings.TrimSpace(lastErr.Message); message != "" {
return message
}
}
return ""
}
// HomeEnabled reports whether the home control plane integration is enabled in the runtime config.
func (m *Manager) HomeEnabled() bool {
if m == nil {
return false
}
cfg, _ := m.runtimeConfig.Load().(*internalconfig.Config)
return cfg != nil && cfg.Home.Enabled
}
func (m *Manager) lookupAPIKeyUpstreamModel(authID, requestedModel string) string {
if m == nil {
return ""
}
authID = strings.TrimSpace(authID)
if authID == "" {
return ""
}
requestedModel = strings.TrimSpace(requestedModel)
if requestedModel == "" {
return ""
}
table, _ := m.apiKeyModelAlias.Load().(apiKeyModelAliasTable)
if table == nil {
return ""
}
byAlias := table[authID]
if len(byAlias) == 0 {
return ""
}
key := strings.ToLower(thinking.ParseSuffix(requestedModel).ModelName)
if key == "" {
key = strings.ToLower(requestedModel)
}
resolved := strings.TrimSpace(byAlias[key])
if resolved == "" {
return ""
}