Repository navigation
fix(rate-limit): retry_after 不再超过窗口长度 - #27
Merged
Merged
Conversation
剩余时间用 window - (now - oldest) 计算,一旦 now 早于最旧记录(时钟回拨、跨进程共享记录、注入时间),结果会超过整个窗口,Retry-After 就要求客户端等一段比窗口还长的时间。现在夹到 [1, window]。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
问题
SlidingWindowRateLimiter.allow里剩余时间是这样算的:只有「
now一定不早于所有记录」时这个式子才成立。一旦now早于最旧记录(时钟回拨、跨进程/多 worker 共享记录、测试注入时间),current - oldest为负,结果会超过整个窗口,Retry-After就要求客户端等一段比窗口还长的时间。另外
timestamps[0]假设列表有序;记录被外部/并发改动时并不保证。做法
min(timestamps)取最早记录,不再依赖列表顺序;[1, window]:min(self.window, max(1, int(remaining) + 1))。正常路径(
0 < remaining < window)的输出与原来完全一致,既有测试全部不受影响。测试
backend/tests/unit/test_rate_limit.py新增两条:test_retry_after_never_exceeds_the_window:记录来自「未来」(now=100写入,now=0请求),断言1 <= retry_after <= 30;test_retry_after_is_always_a_strictly_positive_int_within_window:多个时间点(含负数时间)下retry_after恒为正整数且不超过窗口。验证
cd backend && python -m pytest tests/unit/test_rate_limit.py tests/integration/test_rate_limit_middleware.py→ 29 passedcd backend && python -m pytest -q→ 仅有 2 个与本次无关的既有失败(tests/unit/test_verify_setup.py),在未改动的main上复现同样失败