-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathusage.go
More file actions
176 lines (153 loc) · 3.84 KB
/
Copy pathusage.go
File metadata and controls
176 lines (153 loc) · 3.84 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
package instance
import (
"sync"
"time"
)
const usageWindowDuration = 1 * time.Hour
// UsageRecord holds a single timestamped request event.
type usageRecord struct {
At time.Time
Failed bool
Is429 bool
}
// AccountUsage tracks per-account request statistics within a sliding window.
type AccountUsage struct {
mu sync.Mutex
records []usageRecord
last429 time.Time
}
// AccountUsageSnapshot is a point-in-time view of an account's usage stats.
type AccountUsageSnapshot struct {
TotalRequests int64 `json:"totalRequests"`
FailedRequests int64 `json:"failedRequests"`
Last429At string `json:"last429At,omitempty"` // RFC3339 or empty
WindowSeconds int `json:"windowSeconds"`
}
var (
usageMap = make(map[string]*AccountUsage)
usageMapMu sync.RWMutex
)
func getOrCreateUsage(accountID string) *AccountUsage {
usageMapMu.RLock()
u, ok := usageMap[accountID]
usageMapMu.RUnlock()
if ok {
return u
}
usageMapMu.Lock()
defer usageMapMu.Unlock()
// Double-check after acquiring write lock.
if u, ok = usageMap[accountID]; ok {
return u
}
u = &AccountUsage{}
usageMap[accountID] = u
return u
}
// RecordRequest records a request for the given account.
func RecordRequest(accountID string, failed bool, is429 bool) {
u := getOrCreateUsage(accountID)
now := time.Now()
u.mu.Lock()
defer u.mu.Unlock()
u.records = append(u.records, usageRecord{At: now, Failed: failed, Is429: is429})
if is429 {
u.last429 = now
}
// Trim old records outside the sliding window.
u.trimLocked(now)
}
// GetUsageSnapshot returns current usage stats for a single account.
func GetUsageSnapshot(accountID string) AccountUsageSnapshot {
usageMapMu.RLock()
u, ok := usageMap[accountID]
usageMapMu.RUnlock()
if !ok {
return AccountUsageSnapshot{WindowSeconds: int(usageWindowDuration.Seconds())}
}
u.mu.Lock()
defer u.mu.Unlock()
u.trimLocked(time.Now())
var total, failed int64
for _, r := range u.records {
total++
if r.Failed {
failed++
}
}
snap := AccountUsageSnapshot{
TotalRequests: total,
FailedRequests: failed,
WindowSeconds: int(usageWindowDuration.Seconds()),
}
if !u.last429.IsZero() {
snap.Last429At = u.last429.Format(time.RFC3339)
}
return snap
}
// GetAllUsageSnapshots returns usage stats for all tracked accounts.
func GetAllUsageSnapshots() map[string]AccountUsageSnapshot {
usageMapMu.RLock()
defer usageMapMu.RUnlock()
result := make(map[string]AccountUsageSnapshot, len(usageMap))
now := time.Now()
for id, u := range usageMap {
u.mu.Lock()
u.trimLocked(now)
var total, failed int64
for _, r := range u.records {
total++
if r.Failed {
failed++
}
}
snap := AccountUsageSnapshot{
TotalRequests: total,
FailedRequests: failed,
WindowSeconds: int(usageWindowDuration.Seconds()),
}
if !u.last429.IsZero() {
snap.Last429At = u.last429.Format(time.RFC3339)
}
u.mu.Unlock()
result[id] = snap
}
return result
}
// GetWindowRequestCount returns the number of requests in the current window for an account.
// Used by load balancer strategies.
func GetWindowRequestCount(accountID string) int64 {
usageMapMu.RLock()
u, ok := usageMap[accountID]
usageMapMu.RUnlock()
if !ok {
return 0
}
u.mu.Lock()
defer u.mu.Unlock()
u.trimLocked(time.Now())
return int64(len(u.records))
}
// GetLast429Time returns the last time a 429 was recorded for the account.
func GetLast429Time(accountID string) time.Time {
usageMapMu.RLock()
u, ok := usageMap[accountID]
usageMapMu.RUnlock()
if !ok {
return time.Time{}
}
u.mu.Lock()
defer u.mu.Unlock()
return u.last429
}
// trimLocked removes records outside the sliding window. Must be called with u.mu held.
func (u *AccountUsage) trimLocked(now time.Time) {
cutoff := now.Add(-usageWindowDuration)
i := 0
for i < len(u.records) && u.records[i].At.Before(cutoff) {
i++
}
if i > 0 {
u.records = u.records[i:]
}
}