Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1107 lines (1042 loc) · 39.4 KB
/
Copy pathmain.go
File metadata and controls
1107 lines (1042 loc) · 39.4 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
// qoder2api: OpenAI-compatible API bridge for QoderWork.
package main
import (
"context"
"encoding/json"
"fmt"
"hash/fnv"
"log"
"net/http"
"os"
"os/signal"
"sort"
"strconv"
"strings"
"syscall"
"qoder2api/admin"
"qoder2api/auth"
"qoder2api/bridge"
"qoder2api/logs"
"qoder2api/models"
"qoder2api/stats"
"qoder2api/store"
"qoder2api/transform"
"qoder2api/web"
"sync"
"time"
)
// Version is the build version, overridden at build time via
// -ldflags "-X main.Version=v1.2.3". It is only used for display (login page).
var Version = "dev"
// bridgeProvider owns the per-account bridges and routes requests across them.
// It keeps one OpenAiBridge per account (lazily built and invalidated when the
// account's PAT/region changes) so switching accounts no longer discards a
// warmed-up session and model catalog.
type bridgeProvider struct {
mu sync.Mutex
bridges map[string]*bridge.OpenAiBridge // accountID -> bridge
bridgeSig map[string]string // accountID -> "pat|region" the bridge was built for
store *store.Store
router *router
// lastPAT tracks the PAT currentBridge last observed, so a PAT change can
// fire the recorder-clearing hook (the panel's account snapshot belongs to
// the previous account).
lastPAT string
// snapshots are the in-memory quota snapshots maintained by passive
// deduction and authoritative correction; flushed to disk periodically.
snapMu sync.Mutex
snapshots map[string]*store.AccountSnapshot
// onPatChange is fired after a different non-empty PAT was replaced or the
// PAT was cleared. It runs without the provider lock held: the callback
// takes the recorder lock, and nesting the two risks a lock-order stall.
onPatChange func()
// reqMu guards reqCounts: per-account cumulative request counts since
// process start, shown in the panel so the spread is observable.
reqMu sync.Mutex
reqCounts map[string]int64
// checkinMu guards checkinRunning: accounts with an in-flight check-in, so
// the scheduler and a manual trigger cannot run the same account twice.
checkinMu sync.Mutex
checkinRunning map[string]bool
}
func newBridgeProvider(st *store.Store) *bridgeProvider {
p := &bridgeProvider{
store: st,
bridges: map[string]*bridge.OpenAiBridge{},
bridgeSig: map[string]string{},
snapshots: map[string]*store.AccountSnapshot{},
reqCounts: map[string]int64{},
checkinRunning: map[string]bool{},
}
p.router = newRouter(routerDeps{
accounts: func() []store.Account { return st.ListAccounts() },
snapshot: p.snapshotFor,
bridge: p.bridgeForAccount,
config: func() store.AutoSwitch { return st.GetAutoSwitch() },
markFailure: p.markAccountFailure,
})
return p
}
// snapshotFor returns the freshest snapshot for an account: the in-memory one
// (updated by passive deduction / authoritative correction) or the persisted
// one when no in-memory entry exists yet.
func (p *bridgeProvider) snapshotFor(id string) *store.AccountSnapshot {
p.snapMu.Lock()
snap := p.snapshots[id]
p.snapMu.Unlock()
if snap != nil {
return snap
}
if acc, ok := p.store.GetAccount(id); ok {
return acc.Snapshot
}
return nil
}
// markAccountFailure writes a cooldown onto an account's in-memory snapshot so
// the router skips it for a while. Memory-only; flushed by the 30s loop.
func (p *bridgeProvider) markAccountFailure(accountID string, cooldownUntil int64) {
p.snapMu.Lock()
snap := p.snapshots[accountID]
if snap == nil {
if acc, ok := p.store.GetAccount(accountID); ok && acc.Snapshot != nil {
cp := *acc.Snapshot
snap = &cp
} else {
snap = &store.AccountSnapshot{}
}
}
snap.CooldownUntil = cooldownUntil
p.snapshots[accountID] = snap
p.snapMu.Unlock()
}
// AccountIDByPAT resolves a PAT to its pool entry ID ("" when absent).
func AccountIDByPAT(s *store.Store, pat string) string {
for _, acc := range s.ListAccounts() {
if acc.PAT == pat {
return acc.ID
}
}
return ""
}
// setOnPatChange installs the callback fired when the configured PAT changes.
// Wiring happens before the provider is used by any goroutine.
func (p *bridgeProvider) setOnPatChange(fn func()) {
p.mu.Lock()
p.onPatChange = fn
p.mu.Unlock()
}
// bridgeForAccount returns the bridge for one account, building it on first use
// or rebuilding it when the account's PAT or region changed. The note is not
// part of the signature: it is display-only, and a label edit must not reset a
// warmed-up session and machine fingerprint. Safe for concurrent use; never
// holds the lock across upstream work.
func (p *bridgeProvider) bridgeForAccount(acc store.Account) *bridge.OpenAiBridge {
sig := acc.PAT + "|" + acc.Region
p.mu.Lock()
defer p.mu.Unlock()
if b, ok := p.bridges[acc.ID]; ok && p.bridgeSig[acc.ID] == sig {
b.SetLabel(accountLabel(acc))
return b
}
b := bridge.NewOpenAiBridge(acc.PAT, auth.RegionByName(acc.Region))
b.SetLabel(accountLabel(acc))
p.bridges[acc.ID] = b
p.bridgeSig[acc.ID] = sig
return b
}
// accountLabel renders the account's log label: its note when set, otherwise a
// masked PAT, always tagged with the region.
func accountLabel(acc store.Account) string {
name := acc.Note
if name == "" {
if len(acc.PAT) > 8 {
name = acc.PAT[:4] + "****" + acc.PAT[len(acc.PAT)-4:]
} else if acc.PAT != "" {
name = "pt-****"
} else {
name = "账号"
}
}
region := "cn"
if acc.Region == "global" {
region = "global"
}
return name + "(" + region + ")"
}
// pruneBridges drops bridges for accounts that no longer exist (or whose
// signature changed) so a deleted/replaced account cannot leak a stale session.
func (p *bridgeProvider) pruneBridges(accounts []store.Account) {
live := make(map[string]struct{}, len(accounts))
for _, acc := range accounts {
live[acc.ID] = struct{}{}
}
p.mu.Lock()
for id := range p.bridges {
if _, ok := live[id]; !ok {
delete(p.bridges, id)
delete(p.bridgeSig, id)
}
}
p.mu.Unlock()
}
// resolveBridge validates the API key and routes the request to an account,
// returning that account's bridge plus the key's metadata for request logging.
// Returns nil if the key is invalid or no account can serve the request.
func (p *bridgeProvider) resolveBridge(req bridge.ResolveRequest) *bridge.ResolvedBridge {
key, ok := p.store.LookupKey(req.APIKey)
if !ok {
return nil
}
acc, stickyKey, ok := p.router.pick(key.ID, req.Model, req.StickySeed, req.Region, req.Exclude)
if !ok {
return nil
}
b := p.bridgeForAccount(acc)
if b == nil {
return nil
}
p.bumpRequestCount(acc.ID)
rb := &bridge.ResolvedBridge{Bridge: b, KeyID: key.ID, KeyNote: key.Note,
AccountID: acc.ID, AccountNote: acc.Note, Region: auth.RegionByName(acc.Region).Name}
if stickyKey != "" {
accountID := acc.ID
rb.OnSuccess = func() { p.router.bind(stickyKey, accountID) }
}
return rb
}
// bumpRequestCount increments one account's cumulative request counter (shown
// in the panel). Memory-only: it resets on restart, which is the intended
// "since this process started" semantic.
func (p *bridgeProvider) bumpRequestCount(accountID string) {
if accountID == "" {
return
}
p.reqMu.Lock()
p.reqCounts[accountID]++
p.reqMu.Unlock()
}
// RequestCount returns the cumulative request count for an account.
func (p *bridgeProvider) RequestCount(accountID string) int64 {
p.reqMu.Lock()
defer p.reqMu.Unlock()
return p.reqCounts[accountID]
}
// --- Daily check-in ---
// tryAcquireCheckin marks an account's check-in as running. Returns false when
// one is already in flight (manual trigger racing the scheduler, etc.).
func (p *bridgeProvider) tryAcquireCheckin(accountID string) bool {
p.checkinMu.Lock()
defer p.checkinMu.Unlock()
if p.checkinRunning[accountID] {
return false
}
p.checkinRunning[accountID] = true
return true
}
func (p *bridgeProvider) releaseCheckin(accountID string) {
p.checkinMu.Lock()
delete(p.checkinRunning, accountID)
p.checkinMu.Unlock()
}
// CheckinAccount runs one manual or scheduled check-in for an account, records
// the outcome on the account, and returns it. Failures are recorded with status
// "error" and the reason in LastCheckinMsg (shown in the panel's recent-result
// tooltip).
//
// Both regions are supported: the campaigns endpoint requires the jt- OpenAPI
// bearer in either region (minted via jobToken/exchange; the bridge picks the
// right bearer per endpoint). The genuine desktop fingerprint from the
// installed Qoder app is optional — without it no machine headers are sent and
// the generic daily-credit activity is still returned.
func (p *bridgeProvider) CheckinAccount(ctx context.Context, accountID string) (auth.CheckinResult, error) {
acc, ok := p.store.GetAccount(accountID)
if !ok {
return auth.CheckinResult{}, fmt.Errorf("账号不存在: %s", accountID)
}
b := p.bridgeForAccount(acc)
if b == nil {
return auth.CheckinResult{}, fmt.Errorf("无法创建账号会话")
}
result, err := b.Checkin(ctx)
if err != nil {
_ = p.store.RecordCheckin(accountID, "error", err.Error(), time.Now())
return auth.CheckinResult{}, err
}
_ = p.store.RecordCheckin(accountID, result.Status, result.Message, time.Now())
return result, nil
}
// CheckinRegionSupported reports whether daily check-in is available for the
// account's region. Both CN and global are supported (global needs the OpenAPI
// bearer, handled in the bridge).
func CheckinRegionSupported(region string) bool {
return true
}
// checkinDue reports whether an account is due for its daily automatic
// check-in at now. Accounts that already succeeded/already/skipped today are
// not re-run (a "skipped" day is deliberately not retried, to avoid hammering
// the endpoint while no campaign is open); a previous "error" is retried after
// a 30-minute gap.
func checkinDue(acc store.Account, configuredTime string, now time.Time) bool {
if !acc.AutoCheckin || acc.PAT == "" {
return false
}
due, ok := checkinSlot(configuredTime, acc.ID, now)
if !ok || now.Before(due) {
return false
}
if acc.LastCheckinAt > 0 {
last := time.Unix(acc.LastCheckinAt, 0).In(now.Location())
sameDay := last.Year() == now.Year() && last.YearDay() == now.YearDay()
if sameDay {
if acc.LastCheckinStatus != "error" {
return false // already done today
}
if now.Sub(last) < 30*time.Minute {
return false // retry cooldown after a failure
}
}
}
return true
}
// checkinSlot resolves a configured "HH:MM" into today's instant, adding a
// per-account sub-minute jitter so a pool does not stampede the endpoint at the
// same second. ok is false when the configured time cannot be parsed.
func checkinSlot(value, accountID string, now time.Time) (time.Time, bool) {
parsed, err := time.Parse("15:04", strings.TrimSpace(value))
if err != nil {
return time.Time{}, false
}
h := fnv.New32a()
_, _ = h.Write([]byte(accountID))
return time.Date(now.Year(), now.Month(), now.Day(),
parsed.Hour(), parsed.Minute(), int(h.Sum32()%60), 0, now.Location()), true
}
// runScheduledCheckins launches check-ins for every auto-enabled account whose
// daily slot has passed. Each run is guarded by checkinRunning and performed in
// its own goroutine so a slow account does not block the others or the caller.
func (p *bridgeProvider) runScheduledCheckins(now time.Time) {
defaultTime := p.store.GetCheckinTime()
for _, acc := range p.store.ListAccounts() {
configured := acc.CheckinTime
if strings.TrimSpace(configured) == "" {
configured = defaultTime
}
if !checkinDue(acc, configured, now) {
continue
}
if !p.tryAcquireCheckin(acc.ID) {
continue
}
accountID := acc.ID
go func() {
defer p.releaseCheckin(accountID)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
res, err := p.CheckinAccount(ctx, accountID)
if err != nil {
log.Printf("[checkin] %s failed: %v", accountID, err)
return
}
log.Printf("[checkin] %s: %s (%s)", accountID, res.Status, res.Message)
}()
}
}
// currentBridge returns the bridge for the active account (used by the account
// loop, model fetcher, and legacy paths). Returns nil when no PAT is set. A PAT
// change fires onPatChange so the panel drops the previous account's snapshot.
func (p *bridgeProvider) currentBridge() *bridge.OpenAiBridge {
pat := p.store.GetPAT()
p.mu.Lock()
changed := p.lastPAT != "" && p.lastPAT != pat
p.lastPAT = pat
hook := p.onPatChange
p.mu.Unlock()
if changed && hook != nil {
hook()
}
activeID := p.store.GetActiveAccountID()
if activeID != "" {
if acc, ok := p.store.GetAccount(activeID); ok && acc.PAT != "" {
return p.bridgeForAccount(acc)
}
}
// Legacy: a bare PAT with no pool entry.
if pat == "" {
return nil
}
acc := store.Account{PAT: pat, Region: p.store.AccountRegionByPAT(pat)}
return p.bridgeForAccount(acc)
}
// accountRefreshCadence keeps the authoritative allowance reasonably fresh
// without coupling the admin panel's 15-second poll to an upstream request.
const accountRefreshCadence = time.Minute
// patWriteMu serializes the recorder writes of the account loop against the
// PAT-change clear. Without it, an in-flight refresh could pass its PAT
// re-check, be preempted by an admin PAT change, and then write the previous
// account's snapshot after the hook had already cleared it. The lock is never
// held across the upstream fetch.
var patWriteMu sync.Mutex
// applyAccountWrite persists one account snapshot under patWriteMu, re-checking
// the PAT inside the lock so a snapshot belonging to a replaced or cleared PAT
// can never be written. It returns false when the snapshot was dropped.
func applyAccountWrite(rec *stats.Recorder, provider *bridgeProvider, pat string, nextResetMs int64, account *stats.Account) bool {
patWriteMu.Lock()
defer patWriteMu.Unlock()
if provider.store.GetPAT() != pat {
return false // the PAT changed while the fetch was in flight
}
rec.SetBillingCycle(nextResetMs)
rec.SetAccount(account)
return true
}
// clearAccountOnPatChange drops the cached account snapshot when the configured
// PAT changed. It shares patWriteMu with applyAccountWrite so the clear and the
// writes are mutually exclusive.
func clearAccountOnPatChange(rec *stats.Recorder) {
patWriteMu.Lock()
defer patWriteMu.Unlock()
rec.ClearAccount()
}
// ═══ Account health signals ═══
//
// Routing itself lives in routing.go (the router spreads requests across the
// pool). These helpers keep the per-account snapshots the router reads fresh:
//
// 1. authoritative correction — the account loop fetches each account's quota
// in rotation; the result is written back into the snapshot and hard
// exhaustion arms a cooldown until the next reset;
// 2. failure fallback — a chat request dying on an upstream 401/403 before any
// byte reached the client marks that account cooling and retries on another;
// 3. passive deduction — the usage frame of every billed request carries
// credits, which are subtracted from the serving account's snapshot. The
// threshold is enforced by the router (low-credit accounts stop receiving
// new requests), not by switching the single active account.
// handleChatFailover implements bridge.FailoverFunc: mark the failed account
// cooling, exclude it, and route the request to another account. Returns nil
// when no other account can serve it (the original error surfaces).
func (p *bridgeProvider) handleChatFailover(failedAccountID string, req bridge.ResolveRequest, excluded map[string]bool) *bridge.ResolvedBridge {
p.router.markFailure(failedAccountID)
if excluded == nil {
excluded = map[string]bool{}
}
excluded[failedAccountID] = true
// excluded holds every account this request already tried, so the configured
// retry budget caps how many accounts one chat request may consume.
if len(excluded) >= p.store.GetAutoSwitch().MaxRetryAccounts {
return nil
}
key, ok := p.store.LookupKey(req.APIKey)
if !ok {
return nil
}
acc, stickyKey, ok := p.router.pick(key.ID, req.Model, req.StickySeed, req.Region, excluded)
if !ok {
return nil
}
b := p.bridgeForAccount(acc)
if b == nil {
return nil
}
p.bumpRequestCount(acc.ID)
rb := &bridge.ResolvedBridge{Bridge: b, KeyID: key.ID, KeyNote: key.Note,
AccountID: acc.ID, AccountNote: acc.Note, Region: auth.RegionByName(acc.Region).Name}
if stickyKey != "" {
accountID := acc.ID
rb.OnSuccess = func() { p.router.bind(stickyKey, accountID) }
}
return rb
}
// modelsUnion merges the model names from every account's catalog so the admin
// panel (and /v1/models via the default account) reflects models available in
// any region. Falls back to the built-in catalog when no bridge exists.
func (p *bridgeProvider) modelsUnion(ctx context.Context) []string {
accounts := p.store.ListAccounts()
if len(accounts) == 0 {
b := p.currentBridge()
if b == nil {
return models.DefaultCatalog().Keys()
}
return b.GetCatalog(ctx).Keys()
}
seen := map[string]struct{}{}
var out []string
for _, acc := range accounts {
b := p.bridgeForAccount(acc)
if b == nil {
continue
}
for _, name := range b.GetCatalog(ctx).Keys() {
if _, ok := seen[name]; ok {
continue
}
seen[name] = struct{}{}
out = append(out, name)
}
}
if len(out) == 0 {
return models.DefaultCatalog().Keys()
}
sort.Strings(out)
return out
}
// deductCredits passively applies one usage frame to the current account's
// snapshot and evaluates the threshold. Memory-only: the snapshot is flushed
// to disk by the 30s stats loop (flushAccountSnapshots).
func (p *bridgeProvider) deductCredits(accountID string, credits float64) {
if accountID == "" || credits <= 0 {
return
}
p.snapMu.Lock()
snap := p.snapshots[accountID]
if snap == nil {
// Seed from the persisted snapshot so passive deduction continues
// where the last check left off.
for _, acc := range p.store.ListAccounts() {
if acc.ID == accountID {
if acc.Snapshot != nil {
cp := *acc.Snapshot
snap = &cp
}
break
}
}
}
if snap == nil || snap.Total <= 0 {
p.snapMu.Unlock()
return // no authoritative baseline: passive deduction would guess
}
snap.Remaining -= credits
if snap.Remaining < 0 {
snap.Remaining = 0
}
p.snapshots[accountID] = snap
p.snapMu.Unlock()
// The router excludes low-credit accounts on its own (see routing.go), so
// no explicit switch is needed here — the next request simply routes away.
}
// flushAccountSnapshots persists the passively deducted snapshots. Runs on the
// existing 30s stats flush loop; a single save covers every touched account.
func (p *bridgeProvider) flushAccountSnapshots() {
p.snapMu.Lock()
if len(p.snapshots) == 0 {
p.snapMu.Unlock()
return
}
batch := make(map[string]*store.AccountSnapshot, len(p.snapshots))
for id, snap := range p.snapshots {
cp := *snap
batch[id] = &cp
}
p.snapMu.Unlock()
if err := p.store.SaveSnapshots(batch); err != nil {
log.Printf("[stats] WARN account snapshot flush failed: %v", err)
}
}
// sumSpendablePools sums the spendable quota pools (personal + add-on +
// available org package) with the same policy as the panel's quota list:
// zero-total pools are absent; the org pool counts only when it is available
// to this member. Org-only accounts (Teams) report a 0/0 userQuota upstream,
// so adopting it verbatim would zero the snapshot. The totals are clamped at
// zero: an over-drawn pool (remaining < 0) must never poison the snapshot.
// NOTE: the cooldown/reset model assumes a single billing cycle; if add-on or
// org pools ever reset on a different cadence than the subscription, that
// assumption needs revisiting.
func sumSpendablePools(st *auth.AccountStatus) (total, remaining float64) {
if st.UserQuota != nil && st.UserQuota.Total > 0 {
total += st.UserQuota.Total
remaining += st.UserQuota.Remaining
}
if st.AddOnQuota != nil && st.AddOnQuota.Total > 0 {
total += st.AddOnQuota.Total
remaining += st.AddOnQuota.Remaining
}
if st.OrgResourcePackage != nil && st.OrgResourcePackage.Cap > 0 && st.OrgResourcePackage.Available {
total += st.OrgResourcePackage.Cap
remaining += st.OrgResourcePackage.Remaining
}
return total, max(remaining, 0)
}
// applyQuotaToSnapshot merges an authoritative OpenAPI result into the pool
// snapshot of the given account: it repairs drift from passive deduction and
// records hard exhaustion (cooldown until the next reset).
func (p *bridgeProvider) applyQuotaToSnapshot(accountID string, st *auth.AccountStatus) {
if accountID == "" || st == nil {
return
}
p.snapMu.Lock()
snap := p.snapshots[accountID]
if snap == nil {
snap = &store.AccountSnapshot{}
}
snap.Total, snap.Remaining = sumSpendablePools(st)
snap.Plan = st.UserTag
snap.IsExceeded = st.IsQuotaExceeded
snap.NextResetAtMs = st.NextResetAtMs
snap.CheckedAt = time.Now().Unix()
snap.LastError = ""
if st.IsQuotaExceeded {
if st.NextResetAtMs > time.Now().UnixMilli() {
snap.CooldownUntil = st.NextResetAtMs / 1000
} else {
snap.CooldownUntil = time.Now().Add(routerFailureCooldown).Unix()
}
} else {
snap.CooldownUntil = 0
}
p.snapshots[accountID] = snap
p.snapMu.Unlock()
}
// healthHandler serves an unauthenticated liveness/readiness probe. It is
// deliberately cheap (no upstream calls, no session bootstrap): the body
// carries readiness details (PAT configured, effective stream timeouts)
// while the status stays 200 as long as the process is serving.
func healthHandler(st *store.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
timeouts := auth.CurrentStreamTimeouts()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "ok",
"has_pat": st.GetPAT() != "",
"chat_timeout_seconds": int(timeouts.Header.Seconds()),
"idle_timeout_seconds": int(timeouts.Idle.Seconds()),
})
}
}
func main() {
// Initialize store
dataPath := os.Getenv("QODER_DATA_PATH")
if dataPath == "" {
dataPath = "data.json"
}
st, err := store.New(dataPath)
if err != nil {
log.Fatalf("[store] failed to init: %v", err)
}
// Host/port: env vars override config file; config file overrides defaults
host := os.Getenv("QODER_HOST")
if host == "" {
host = st.GetHost()
}
port := st.GetPort()
if envPort := os.Getenv("QODER_PORT"); envPort != "" {
if p, err := strconv.Atoi(envPort); err == nil {
port = p
} else {
log.Printf("[bridge] WARN invalid QODER_PORT=%q; using %d", envPort, port)
}
}
// Chat stream timeouts: env vars override the persisted config, the
// config file overrides the built-in defaults (same precedence as
// host/port). Applied to new requests immediately.
chatTimeout := st.GetChatTimeoutSeconds()
if v := os.Getenv("QODER_CHAT_TIMEOUT_SECONDS"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= store.MaxChatTimeoutSeconds {
chatTimeout = n
} else {
log.Printf("[bridge] WARN invalid QODER_CHAT_TIMEOUT_SECONDS=%q; using %d", v, chatTimeout)
}
}
idleTimeout := st.GetIdleTimeoutSeconds()
if v := os.Getenv("QODER_IDLE_TIMEOUT_SECONDS"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= store.MaxIdleTimeoutSeconds {
idleTimeout = n
} else {
log.Printf("[bridge] WARN invalid QODER_IDLE_TIMEOUT_SECONDS=%q; using %d", v, idleTimeout)
}
}
auth.SetStreamTimeouts(time.Duration(chatTimeout)*time.Second, time.Duration(idleTimeout)*time.Second)
// Request-log limits: env vars override the persisted config, which
// overrides the built-in defaults (same precedence as the timeouts above).
logRetention := st.GetLogRetentionDays()
if v := os.Getenv("QODER_LOG_RETENTION_DAYS"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= store.MaxLogRetentionDays {
logRetention = n
} else {
log.Printf("[logs] WARN invalid QODER_LOG_RETENTION_DAYS=%q; using %d", v, logRetention)
}
}
logMaxEntries := st.GetLogMaxEntries()
if v := os.Getenv("QODER_LOG_MAX_ENTRIES"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= store.MinLogMaxEntries && n <= store.MaxLogEntriesHardCap {
logMaxEntries = n
} else {
log.Printf("[logs] WARN invalid QODER_LOG_MAX_ENTRIES=%q; using %d", v, logMaxEntries)
}
}
// CORS: warn once if the env override defines nothing that can match,
// mirroring how the other env knobs report bad input. A whitespace-only or
// unparseable override is then treated as "unset" everywhere (here, in
// corsSpec below, and in the admin panel) so the panel cannot advertise a
// policy the request path never applies.
if v := os.Getenv("QODER_CORS_ORIGINS"); v != "" && store.UsableCORSSpec(v) == "" {
log.Printf("[cors] WARN QODER_CORS_ORIGINS=%q defines no usable origin; using panel setting", v)
}
provider := newBridgeProvider(st)
// Request statistics recorder with periodic persistence (30s cadence).
// The loop also drains a stop channel so graceful shutdown can trigger a
// final flush, avoiding loss of the last <=30s of stats.
rec := stats.NewRecorder(st)
// Request-log recorder: same persistence model as stats (in-memory on the
// request path, flushed out of band). Entries are metadata only.
logRec := logs.NewRecorder(st, logRetention, logMaxEntries)
// A PAT change invalidates the previous account's plan and allowance; drop
// the cached snapshot so the panel cannot keep showing it. The clear shares
// patWriteMu with the account loop's writes.
provider.setOnPatChange(func() { clearAccountOnPatChange(rec) })
// The snapshot is persisted, so a restart with a different or cleared PAT
// would otherwise keep showing the previous account (the hook only fires on
// an in-process change). Drop it once here; the account loop repopulates the
// panel from the first successful refresh.
rec.ClearAccount()
statsStop := make(chan struct{})
statsDone := make(chan struct{})
go func() {
defer close(statsDone)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
flushAll := func(final bool) {
if err := rec.Flush(); err != nil {
log.Printf("[stats] WARN %sflush failed: %v", finalStr(final), err)
}
if err := logRec.Flush(); err != nil {
log.Printf("[logs] WARN %sflush failed: %v", finalStr(final), err)
}
// Passively deducted account snapshots ride the same cadence (a
// single batched save; a no-op when nothing was touched).
provider.flushAccountSnapshots()
}
for {
select {
case <-ticker.C:
flushAll(false)
case <-statsStop:
flushAll(true)
return
}
}
}()
// Model fetcher for admin UI: union of every account's catalog so the panel
// shows models available across all regions/accounts.
modelFetcher := func(ctx context.Context) []string {
return provider.modelsUnion(ctx)
}
// Subscription account loop: refreshes each account's identity metadata
// (/user/status) and authoritative allowance (OpenAPI quota/usage) out of
// band. It probes ONE account per tick in rotation, so N accounts are all
// refreshed within N minutes while upstream load stays at ~1 call/minute.
// The stats recorder (panel headline) is only updated when the probed
// account is the active one.
//
// The loop has its own stop/done pair so shutdown can join it before the
// final stats flush: its last SetAccount/SetBillingCycle would otherwise
// land after that flush and be lost on exit.
accountStop := make(chan struct{})
accountDone := make(chan struct{})
// applyAccountFor probes one account and folds the result into its pool
// snapshot. When it is the active account, the panel recorder is updated
// too. Returns true when a status was obtained.
applyAccountFor := func(ctx context.Context, acc store.Account, activeID string) bool {
b := provider.bridgeForAccount(acc)
if b == nil {
return false
}
st := b.EnsureAccountStatus(ctx)
if st == nil {
return false // upstream unreachable: keep the last known state
}
// Authoritative correction: merge into that account's snapshot and arm
// the hard-exhaustion cooldown.
provider.applyQuotaToSnapshot(acc.ID, st)
if acc.ID != activeID {
return true
}
account := &stats.Account{
Plan: st.Plan,
Tag: st.UserTag,
OrgName: st.OrgName,
IsQuotaExceeded: st.IsQuotaExceeded,
TotalUsagePercentage: st.TotalUsagePercentage,
}
if st.UserQuota != nil {
account.UserQuota = &stats.Quota{
Total: st.UserQuota.Total, Used: st.UserQuota.Used,
Remaining: st.UserQuota.Remaining, Percentage: st.UserQuota.Percentage,
Unit: st.UserQuota.Unit, DetailURL: st.UserQuota.DetailURL,
}
}
if st.AddOnQuota != nil {
account.AddOnQuota = &stats.Quota{
Total: st.AddOnQuota.Total, Used: st.AddOnQuota.Used,
Remaining: st.AddOnQuota.Remaining, Percentage: st.AddOnQuota.Percentage,
Unit: st.AddOnQuota.Unit, DetailURL: st.AddOnQuota.DetailURL,
}
}
if st.OrgResourcePackage != nil {
account.OrgResourcePackage = &stats.OrgResourcePackage{
Used: st.OrgResourcePackage.Used, Cap: st.OrgResourcePackage.Cap,
Remaining: st.OrgResourcePackage.Remaining, Percentage: st.OrgResourcePackage.Percentage,
Available: st.OrgResourcePackage.Available, Unit: st.OrgResourcePackage.Unit,
}
}
// The write section runs under patWriteMu and re-checks the PAT inside
// it: the PAT-change hook clears the recorder under the same lock, so a
// snapshot fetched for the previous PAT can no longer land after that
// clear. The fetch above stays outside the lock (it can take 30s).
applyAccountWrite(rec, provider, provider.store.GetPAT(), st.NextResetAtMs, account)
return true
}
// probeAccounts returns the rotation order: the active account first, then
// the rest by ID. Empty pool (legacy bare PAT) yields a synthetic account.
probeAccounts := func() []store.Account {
accounts := provider.store.ListAccounts()
if len(accounts) == 0 {
pat := provider.store.GetPAT()
if pat == "" {
return nil
}
return []store.Account{{ID: "", PAT: pat, Region: provider.store.AccountRegionByPAT(pat)}}
}
activeID := provider.store.GetActiveAccountID()
out := make([]store.Account, 0, len(accounts))
for _, acc := range accounts {
if acc.ID == activeID {
out = append(out, acc)
}
}
for _, acc := range accounts {
if acc.ID != activeID {
out = append(out, acc)
}
}
return out
}
go func() {
defer close(accountDone)
// Fetch the active account once immediately so the panel is populated
// from the start rather than after the first tick.
activeID := provider.store.GetActiveAccountID()
for _, acc := range probeAccounts() {
if acc.ID == activeID || activeID == "" {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
applyAccountFor(ctx, acc, activeID)
cancel()
break
}
}
// Kick off any auto check-in that is already due on startup.
provider.runScheduledCheckins(time.Now())
ticker := time.NewTicker(accountRefreshCadence)
defer ticker.Stop()
cursor := 0
for {
select {
case <-ticker.C:
// Daily automatic check-ins ride the same once-a-minute cadence;
// due accounts run in their own goroutines (see runScheduledCheckins).
provider.runScheduledCheckins(time.Now())
list := probeAccounts()
if len(list) == 0 {
continue
}
provider.pruneBridges(provider.store.ListAccounts())
acc := list[cursor%len(list)]
cursor++
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
applyAccountFor(ctx, acc, provider.store.GetActiveAccountID())
cancel()
case <-accountStop:
return
}
}
}()
// Initialize admin
adminInst := admin.New(st, modelFetcher, rec, logRec)
// Per-account runtime for the panel: in-flight, capacity and cumulative
// request count (shows how the router spreads load).
adminInst.SetAccountRuntime(func(accountID string) (int, int, int64) {
inflight, capacity := 0, 0
if acc, ok := st.GetAccount(accountID); ok {
if b := provider.bridgeForAccount(acc); b != nil {
inflight, capacity = b.InFlight(), b.Capacity()
}
}
return inflight, capacity, provider.RequestCount(accountID)
})
// Account「签到」runs a single check-in for one account (manual trigger from
// the panel) and records the result on the account.
adminInst.SetAccountCheckiner(func(ctx context.Context, accountID string) (auth.CheckinResult, error) {
if !provider.tryAcquireCheckin(accountID) {
return auth.CheckinResult{}, fmt.Errorf("该账号正在签到中,请稍候")
}
defer provider.releaseCheckin(accountID)
return provider.CheckinAccount(ctx, accountID)
})
// Account「检测」runs a throwaway bridge through a full session bootstrap
// and returns the authoritative quota snapshot; the admin layer only owns
// the endpoint. On-demand only — every check costs a session round-trip.
// The result also seeds the auto-switch snapshot for that account.
adminInst.SetAccountChecker(func(ctx context.Context, pat, regionName string) (*store.AccountSnapshot, error) {
region := auth.RegionByName(regionName)
b := bridge.NewOpenAiBridge(pat, region)
acct := b.EnsureAccountStatus(ctx)
if acct == nil {
return nil, fmt.Errorf("无法获取账号状态(会话建立失败)")
}
snap := &store.AccountSnapshot{
Plan: acct.UserTag,
IsExceeded: acct.IsQuotaExceeded,
NextResetAtMs: acct.NextResetAtMs,
CheckedAt: time.Now().Unix(),
}
// Same spendable-pool summation as applyQuotaToSnapshot (see
// sumSpendablePools): numbers must stay comparable across accounts and
// consistent with the stats page.
snap.Total, snap.Remaining = sumSpendablePools(acct)
// Seed the pool snapshot so passive deduction and candidate picking
// have an authoritative baseline even before the loop reaches it.
if id := AccountIDByPAT(st, pat); id != "" {
cp := *snap
provider.snapMu.Lock()
provider.snapshots[id] = &cp
provider.snapMu.Unlock()
}
return snap, nil
})
// WebUI: pre-render all pages at startup (multi-page Alpine.js frontend,
// no build step, no external dependencies).
webHandler, err := web.New(Version)
if err != nil {
log.Fatalf("[web] failed to init: %v", err)
}
mux := http.NewServeMux()
// failover routes a chat-path auth failure to another account (excluding
// every account already tried) and returns its bridge for the retry.
failover := func(failedAccountID string, req bridge.ResolveRequest, excluded map[string]bool) *bridge.ResolvedBridge {
return provider.handleChatFailover(failedAccountID, req, excluded)
}
// usageHook feeds the usage sink with the serving account: billed credits
// passively deduct that account's snapshot (the router then avoids it once
// it drops below the threshold).
usageHook := func(accountID string, u *transform.Usage) {
if u != nil && u.Billable {
provider.deductCredits(accountID, u.Credits)
}
}
mux.HandleFunc("/v1/chat/completions", bridge.MakeChatHandler(provider.resolveBridge, rec, logRec, failover, usageHook))
mux.HandleFunc("/v1/models", bridge.MakeModelsHandler(provider.resolveBridge))
mux.HandleFunc("/health", healthHandler(st))
// Root redirect to admin UI
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.Redirect(w, r, "/admin", http.StatusFound)
return
}
http.NotFound(w, r)
})
// Register admin API routes (/admin/api/*) and WebUI routes
// (/admin, /admin/<page>, /admin/assets/*)