Repository navigation
Conversation
…he-billing fix: 修复 Anthropic 渠道缓存计费错误
fix: revert model ratio
feat: pyroscope integrate
fix: ensure overwrite works correctly when no missing models
…rwrite updates working - Only short-circuit when there are no missing models AND no overwrite fields requested - Preserve overwrite behavior even when the missing-model list is empty - Always return empty arrays (not null) for list fields to keep API responses stable - Clarify SyncUpstreamModels behavior in comments (create missing models + optional overwrite updates)
…ions i18next uses ':' as namespace separator by default, causing URLs like 'https://api.openai.com' to be incorrectly parsed as namespace 'https' with key '//api.openai.com', resulting in truncated display. Setting nsSeparator to false fixes this issue since the project doesn't use multiple namespaces.
…verwrite-empty-missing
fix: 支持小写bearer和Bearer后带多个空格 && 修复 WSS预扣费错误提取key的问题
…rough-body fix: add warning for pass through body
…rompt fix: 支持传入system_instruction和systemInstruction两种风格系统提示词参数名
…h-minial fix(gemini): handle minimal reasoning effort budget
…ous#2433) * fix: Refine openrouter error * fix: Refine openrouter error * fix: openrouter test max_output_token * fix: optimize messages * fix: maxToken unified to 16 * fix: codex系列模型使用 responses接口 * fix: codex系列模型使用 responses接口 * fix: 状态码非200打印错误信息 * fix: 日志里没有报错的响应体
* wip ionet integrate * wip ionet integrate * wip ionet integrate * ollama wip * wip * feat: ionet integration & ollama manage * fix merge conflict * wip * fix: test conn cors * wip * fix ionet * fix ionet * wip * fix model select * refactor: Remove `pkg/ionet` test files and update related Go source and web UI model deployment components. * feat: Enhance model deployment UI with styling improvements, updated text, and a new description component. * Revert "feat: Enhance model deployment UI with styling improvements, updated text, and a new description component." This reverts commit 8b75cb5.
…bfe886b93606003f6753fcb4e9d feat: task log show username
…management across multiple languages
…ference - Add go-i18n library for internationalization - Create i18n package with translation keys and YAML locale files (zh/en) - Implement i18n middleware for language detection from user settings and Accept-Language header - Add Language field to UserSetting DTO - Update API response helpers with i18n support (ApiErrorI18n, ApiSuccessI18n) - Migrate hardcoded messages in token, redemption, and user controllers - Add frontend language preference settings component - Sync language preference across header selector and user settings - Auto-restore user language preference on login
fix: default summary = detailed fix ReasoningContent fix ReasoningContent fix ReasoningContent fix ReasoningContent Revert "fix ReasoningContent" This reverts commit 45a88f7. fix ReasoningContent fix ReasoningContent
- Change default language fallback to English instead of Chinese - Add ErrRedeemFailed typed error for model layer translation - Migrate remaining hardcoded messages in controller/user.go - Add translation keys: redeem.failed, user.create_default_token_error, common.uuid_duplicate, common.invalid_input
The i18n middleware runs before UserAuth, so user settings weren't available when language was detected. Now GetLangFromContext checks user settings first (set by UserAuth) before falling back to the language set by middleware or Accept-Language header.
Unify Epay subscription response format with top-up flow, and harden frontend error handling to avoid object-to-string issues. Refine subscription plan cards layout to be wider, left-aligned, and visually consistent across breakpoints.
Use dynamic viewport height to prevent sidebar scroll lock in mobile browsers Harden sidebar scroll container with min-height and momentum scrolling
…-epay ✨ fix: Improve subscription payment handling and card layout consistency
…ll-dvh 🐛 fix: sidebar scroll on mobile dynamic viewport
…reasoning fix: map Responses reasoning stream to chat completion deltas
…x-override feat: 支持基于Go Regex规则和全量的请求体透传
feat: backend i18n
fix: optimize Codex relay
…sponses-local-usage fix: charge local input tokens when Gemini returns empty response
- Remove claude-instant-1.2, claude-2, claude-2.0, claude-2.1 from model lists - Remove /v1/complete endpoint support (legacy completion API) - Remove RequestModeCompletion and related code paths - Simplify handler functions by removing requestMode parameter - Update all channel adaptors that referenced claude handlers
…gacy-models remove: drop support for claude-2 and claude-1 series models
WalkthroughA sliding-window rate limiting mechanism using atomic Lua scripts has been introduced to resolve race conditions in the rate limiter. The implementation includes automatic script loading, error recovery with retry logic, and comprehensive test coverage for concurrent scenarios. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
middleware/model-rate-limit.go (2)
26-63:⚠️ Potential issue | 🟠 MajorRace condition persists in
checkRedisRateLimit— the same issue this PR aims to fix.This function uses a non-atomic sequence:
LLen(line 33) followed byLIndex(line 44). Under high concurrency, multiple requests can read the same list length and all proceed, exactly matching the race condition described in issue#2841.The PR fixed the race condition in
middleware/rate-limit.goby switching to Lua-basedAllowSlidingWindow, but this file still uses the vulnerable pattern. Consider refactoring to use the newAllowSlidingWindowmethod or a similar atomic Lua script approach here as well.
66-76:⚠️ Potential issue | 🟠 MajorRace condition in
recordRedisRequest— non-atomicLPush/LTrim/Expiresequence.The
LPush,LTrim, andExpireoperations at lines 73-75 are executed as separate commands. Under concurrency, this can lead to inconsistent list state. If this function is called concurrently (e.g., multiple successful requests finishing simultaneously), the list may grow beyondmaxCountbeforeLTrimexecutes.Consider combining these operations into an atomic Lua script, similar to the sliding window implementation.
middleware/rate-limit.go (1)
40-47:⚠️ Potential issue | 🔴 CriticalSame issue:
memoryRateLimiteralso missingc.Next()for allowed requests.When the rate limit check passes (doesn't enter the
ifblock), the function returns without callingc.Next().🐛 Proposed fix
func memoryRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark string) { key := mark + c.ClientIP() if !inMemoryRateLimiter.Request(key, maxRequestNum, duration) { c.Status(http.StatusTooManyRequests) c.Abort() return } + c.Next() }
🤖 Fix all issues with AI agents
In `@middleware/rate-limit.go`:
- Around line 19-37: The middleware redisRateLimiter currently aborts on errors
or when !allowed but never calls c.Next() when a request is permitted, which
breaks the Gin middleware chain; update redisRateLimiter to call c.Next() after
the allowed check (i.e., when allowed == true) so that normal requests proceed
to subsequent handlers, while preserving the existing behavior on err (c.Status
+ c.Abort) and when !allowed (c.Status + c.Abort).
🧹 Nitpick comments (4)
common/limiter/limiter.go (2)
43-56: Script load failures are logged but execution will fail later with unclear errors.If
ScriptLoadfails (e.g., Redis connection issues), the SHA fields remain empty strings. SubsequentEvalShacalls will fail with a confusing error rather than a clear "script not loaded" message. Consider either:
- Returning an error from
loadScriptsand handling it inNew()- Adding a check before
EvalShacalls to verify SHAs are non-empty🛠️ Suggested improvement
-// loadScripts 加载 Lua 脚本到 Redis,返回是否全部成功 -func (rl *RedisLimiter) loadScripts(ctx context.Context) { +// loadScripts 加载 Lua 脚本到 Redis +func (rl *RedisLimiter) loadScripts(ctx context.Context) error { + var errs []error if sha, err := rl.client.ScriptLoad(ctx, rateLimitScript).Result(); err != nil { common.SysLog(fmt.Sprintf("Failed to load token bucket script: %v", err)) + errs = append(errs, err) } else { rl.limitScriptSHA = sha } if sha, err := rl.client.ScriptLoad(ctx, slidingWindowScript).Result(); err != nil { common.SysLog(fmt.Sprintf("Failed to load sliding window script: %v", err)) + errs = append(errs, err) } else { rl.slidingWindowSHA = sha } + if len(errs) > 0 { + return fmt.Errorf("failed to load %d script(s)", len(errs)) + } + return nil }
63-73: Good NOSCRIPT recovery pattern, but consider double-check-locking for efficiency.The retry logic correctly handles Redis restarts and failovers. However, under high concurrency with a NOSCRIPT error, multiple goroutines may queue up on the mutex and each reload scripts sequentially. Consider checking if scripts are already reloaded after acquiring the lock:
♻️ Optional: Double-check to avoid redundant reloads
func (rl *RedisLimiter) evalWithRetry(ctx context.Context, evalFn func() (int, error)) (int, error) { result, err := evalFn() if isNoScriptErr(err) { rl.mutex.Lock() - rl.loadScripts(ctx) + // Re-check after acquiring lock - another goroutine may have reloaded + result, err = evalFn() + if isNoScriptErr(err) { + rl.loadScripts(ctx) + result, err = evalFn() + } rl.mutex.Unlock() - result, err = evalFn() } return result, err }common/limiter/limiter_test.go (2)
17-22: Hardcoded Redis address may cause CI failures.The test requires a running Redis instance at
localhost:6379. Consider:
- Documenting the Redis requirement in the test file header (partially done at lines 14-15)
- Using environment variables or build tags to skip tests when Redis is unavailable
This is acceptable for local development but may need adjustment for CI pipelines.
84-87: Minor: Ignoring errors fromAllowSlidingWindowcalls.While consuming quota, errors are silently ignored. Although this is unlikely to cause test issues, capturing and logging errors would make debugging easier if tests fail unexpectedly.
♻️ Optional fix
// 消耗完配额 for i := 0; i < maxReq; i++ { - rl.AllowSlidingWindow(ctx, key, maxReq, duration, expiration) + if _, err := rl.AllowSlidingWindow(ctx, key, maxReq, duration, expiration); err != nil { + t.Logf("Warning: error during quota consumption: %v", err) + } }
| func redisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark string) { | ||
| ctx := context.Background() | ||
| rdb := common.RDB | ||
| key := "rateLimit:" + mark + c.ClientIP() | ||
| listLength, err := rdb.LLen(ctx, key).Result() | ||
| key := "rate_limit:" + mark + c.ClientIP() | ||
| expiration := int64(common.RateLimitKeyExpirationDuration.Seconds()) | ||
|
|
||
| redisLimiter := limiter.New(ctx, common.RDB) | ||
| allowed, err := redisLimiter.AllowSlidingWindow(ctx, key, maxRequestNum, duration, expiration) | ||
|
|
||
| if err != nil { | ||
| fmt.Println(err.Error()) | ||
| c.Status(http.StatusInternalServerError) | ||
| c.Abort() | ||
| return | ||
| } | ||
| if listLength < int64(maxRequestNum) { | ||
| rdb.LPush(ctx, key, time.Now().Format(timeFormat)) | ||
| rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration) | ||
| } else { | ||
| oldTimeStr, _ := rdb.LIndex(ctx, key, -1).Result() | ||
| oldTime, err := time.Parse(timeFormat, oldTimeStr) | ||
| if err != nil { | ||
| fmt.Println(err) | ||
| c.Status(http.StatusInternalServerError) | ||
| c.Abort() | ||
| return | ||
| } | ||
| nowTimeStr := time.Now().Format(timeFormat) | ||
| nowTime, err := time.Parse(timeFormat, nowTimeStr) | ||
| if err != nil { | ||
| fmt.Println(err) | ||
| c.Status(http.StatusInternalServerError) | ||
| c.Abort() | ||
| return | ||
| } | ||
| // time.Since will return negative number! | ||
| // See: https://stackoverflow.com/questions/50970900/why-is-time-since-returning-negative-durations-on-windows | ||
| if int64(nowTime.Sub(oldTime).Seconds()) < duration { | ||
| rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration) | ||
| c.Status(http.StatusTooManyRequests) | ||
| c.Abort() | ||
| return | ||
| } else { | ||
| rdb.LPush(ctx, key, time.Now().Format(timeFormat)) | ||
| rdb.LTrim(ctx, key, 0, int64(maxRequestNum-1)) | ||
| rdb.Expire(ctx, key, common.RateLimitKeyExpirationDuration) | ||
| } | ||
|
|
||
| if !allowed { | ||
| c.Status(http.StatusTooManyRequests) | ||
| c.Abort() | ||
| } |
There was a problem hiding this comment.
Missing c.Next() for allowed requests — middleware chain broken.
When allowed is true, the function returns without calling c.Next(), breaking the middleware chain. Subsequent handlers in the Gin chain won't execute.
🐛 Proposed fix
func redisRateLimiter(c *gin.Context, maxRequestNum int, duration int64, mark string) {
ctx := context.Background()
key := "rate_limit:" + mark + c.ClientIP()
expiration := int64(common.RateLimitKeyExpirationDuration.Seconds())
redisLimiter := limiter.New(ctx, common.RDB)
allowed, err := redisLimiter.AllowSlidingWindow(ctx, key, maxRequestNum, duration, expiration)
if err != nil {
fmt.Println(err.Error())
c.Status(http.StatusInternalServerError)
c.Abort()
return
}
if !allowed {
c.Status(http.StatusTooManyRequests)
c.Abort()
+ return
}
+ c.Next()
}🤖 Prompt for AI Agents
In `@middleware/rate-limit.go` around lines 19 - 37, The middleware
redisRateLimiter currently aborts on errors or when !allowed but never calls
c.Next() when a request is permitted, which breaks the Gin middleware chain;
update redisRateLimiter to call c.Next() after the allowed check (i.e., when
allowed == true) so that normal requests proceed to subsequent handlers, while
preserving the existing behavior on err (c.Status + c.Abort) and when !allowed
(c.Status + c.Abort).
fix #2841
大致逻辑,复用common/ 下的lua调用,lua实现之前的逻辑。
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes