Skip to content

Commit 869952d

Browse files
StarryKiraclaude
andcommitted
fix(review): address Copilot PR feedback
- Add compile-time interface assertion for sessionWindowMockRepo - Fix flaky fallback test by capturing time.Now() before calling UpdateSessionWindow - Replace stale hardcoded timestamps with dynamic future values - Add millisecond detection and bounds validation for reset header timestamp - Use pause/resume pattern for interval in UsageProgressBar to avoid idle timers on large lists - Fix gofmt comment alignment Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 668e164 commit 869952d

3 files changed

Lines changed: 46 additions & 13 deletions

File tree

backend/internal/service/ratelimit_service.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,14 +1054,26 @@ func (s *RateLimitService) UpdateSessionWindow(ctx context.Context, account *Acc
10541054
// 优先使用响应头中的真实重置时间(比预测更准确)
10551055
if resetStr := headers.Get("anthropic-ratelimit-unified-5h-reset"); resetStr != "" {
10561056
if ts, err := strconv.ParseInt(resetStr, 10, 64); err == nil {
1057+
// 检测可能的毫秒时间戳(秒级约为 1e9,毫秒约为 1e12)
1058+
if ts > 1e11 {
1059+
slog.Warn("account_session_window_header_millis_detected", "account_id", account.ID, "raw_reset", resetStr)
1060+
ts = ts / 1000
1061+
}
10571062
end := time.Unix(ts, 0)
1058-
// 窗口需要初始化,或者真实重置时间与已存储的不同,则更新
1059-
if needInitWindow || account.SessionWindowEnd == nil || !end.Equal(*account.SessionWindowEnd) {
1063+
// 校验时间戳是否在合理范围内(不早于 5h 前,不晚于 7 天后)
1064+
minAllowed := time.Now().Add(-5 * time.Hour)
1065+
maxAllowed := time.Now().Add(7 * 24 * time.Hour)
1066+
if end.Before(minAllowed) || end.After(maxAllowed) {
1067+
slog.Warn("account_session_window_header_out_of_range", "account_id", account.ID, "raw_reset", resetStr, "parsed_end", end)
1068+
} else if needInitWindow || account.SessionWindowEnd == nil || !end.Equal(*account.SessionWindowEnd) {
1069+
// 窗口需要初始化,或者真实重置时间与已存储的不同,则更新
10601070
start := end.Add(-5 * time.Hour)
10611071
windowStart = &start
10621072
windowEnd = &end
10631073
slog.Info("account_session_window_from_header", "account_id", account.ID, "window_start", start, "window_end", end, "status", status)
10641074
}
1075+
} else {
1076+
slog.Warn("account_session_window_header_parse_failed", "account_id", account.ID, "raw_reset", resetStr, "error", err)
10651077
}
10661078
}
10671079

backend/internal/service/ratelimit_session_window_test.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ type sessionWindowMockRepo struct {
1919
clearRateLimitIDs []int64
2020
}
2121

22+
var _ AccountRepository = (*sessionWindowMockRepo)(nil)
23+
2224
type swCall struct {
2325
ID int64
2426
Start *time.Time
@@ -160,7 +162,7 @@ func newRateLimitServiceForTest(repo AccountRepository) *RateLimitService {
160162
func TestUpdateSessionWindow_UsesResetHeader(t *testing.T) {
161163
// The reset header provides the real window end as a Unix timestamp.
162164
// UpdateSessionWindow should use it instead of the hour-truncated prediction.
163-
resetUnix := int64(1771020000) // 2026-02-14T10:00:00Z
165+
resetUnix := time.Now().Add(3 * time.Hour).Unix()
164166
wantEnd := time.Unix(resetUnix, 0)
165167
wantStart := wantEnd.Add(-5 * time.Hour)
166168

@@ -203,6 +205,11 @@ func TestUpdateSessionWindow_FallbackPredictionWhenNoResetHeader(t *testing.T) {
203205
headers.Set("anthropic-ratelimit-unified-5h-status", "allowed_warning")
204206
// No anthropic-ratelimit-unified-5h-reset header
205207

208+
// Capture now before the call to avoid hour-boundary races
209+
now := time.Now()
210+
expectedStart := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
211+
expectedEnd := expectedStart.Add(5 * time.Hour)
212+
206213
svc.UpdateSessionWindow(context.Background(), account, headers)
207214

208215
if len(repo.sessionWindowCalls) != 1 {
@@ -214,9 +221,6 @@ func TestUpdateSessionWindow_FallbackPredictionWhenNoResetHeader(t *testing.T) {
214221
t.Fatal("expected window end to be set (fallback prediction)")
215222
}
216223
// Fallback: start = current hour truncated, end = start + 5h
217-
now := time.Now()
218-
expectedStart := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
219-
expectedEnd := expectedStart.Add(5 * time.Hour)
220224

221225
if !call.End.Equal(expectedEnd) {
222226
t.Errorf("expected fallback end %v, got %v", expectedEnd, *call.End)
@@ -229,7 +233,7 @@ func TestUpdateSessionWindow_FallbackPredictionWhenNoResetHeader(t *testing.T) {
229233
func TestUpdateSessionWindow_CorrectsStalePrediction(t *testing.T) {
230234
// When the stored SessionWindowEnd is wrong (from a previous prediction),
231235
// and the reset header provides the real time, it should update the window.
232-
staleEnd := time.Now().Add(2 * time.Hour) // existing prediction: 2h from now
236+
staleEnd := time.Now().Add(2 * time.Hour) // existing prediction: 2h from now
233237
realResetUnix := time.Now().Add(4 * time.Hour).Unix() // real reset: 4h from now
234238
wantEnd := time.Unix(realResetUnix, 0)
235239

@@ -291,7 +295,7 @@ func TestUpdateSessionWindow_NoUpdateWhenHeaderMatchesStored(t *testing.T) {
291295

292296
func TestUpdateSessionWindow_ClearsUtilizationOnWindowReset(t *testing.T) {
293297
// When needInitWindow=true and window is set, utilization should be cleared.
294-
resetUnix := int64(1771020000)
298+
resetUnix := time.Now().Add(3 * time.Hour).Unix()
295299

296300
repo := &sessionWindowMockRepo{}
297301
svc := newRateLimitServiceForTest(repo)

frontend/src/components/account/UsageProgressBar.vue

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
</template>
5757

5858
<script setup lang="ts">
59-
import { computed, ref } from 'vue'
59+
import { computed, ref, watch } from 'vue'
6060
import { useIntervalFn } from '@vueuse/core'
6161
import { useI18n } from 'vue-i18n'
6262
import type { WindowStats } from '@/types'
@@ -72,11 +72,28 @@ const props = defineProps<{
7272
7373
const { t } = useI18n()
7474
75-
// Reactive clock for countdown (updates every 60s)
75+
// Reactive clock for countdown — only runs when a reset time is shown,
76+
// to avoid creating many idle timers across large account lists.
7677
const now = ref(new Date())
77-
useIntervalFn(() => {
78-
now.value = new Date()
79-
}, 60_000)
78+
const { pause: pauseClock, resume: resumeClock } = useIntervalFn(
79+
() => {
80+
now.value = new Date()
81+
},
82+
60_000,
83+
{ immediate: false },
84+
)
85+
if (props.resetsAt) resumeClock()
86+
watch(
87+
() => props.resetsAt,
88+
(val) => {
89+
if (val) {
90+
now.value = new Date()
91+
resumeClock()
92+
} else {
93+
pauseClock()
94+
}
95+
},
96+
)
8097
8198
// Label background colors
8299
const labelClass = computed(() => {

0 commit comments

Comments
 (0)