Repository navigation
Conversation
WalkthroughThe changes enhance channel distribution middleware with structured logging and affinity management capabilities. A new channel affinity clearing function enables cache invalidation when preferred channels become unavailable or disabled. Configuration updates adjust retry behavior for Claude CLI trace rules, accompanied by corresponding tests and UI enhancements for cache management. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 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: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@middleware/distributor.go`:
- Around line 456-474: service.AppendChannelAffinityAdminInfo mutates adminInfo
but the mutated map is never recorded; include the enriched adminInfo in the
fallback path so the rule/key context is preserved—after calling
service.AppendChannelAffinityAdminInfo(c, adminInfo) pass the mutated adminInfo
into the logger.LogWarn call (e.g., add admin_info=%v to the formatted message)
so the enriched map is logged, or alternatively call the existing
persistence/attach function that records adminInfo for the request before
emitting the warning; reference AppendChannelAffinityAdminInfo, adminInfo and
logger.LogWarn.
In `@service/channel_affinity.go`:
- Around line 238-255: ClearCurrentChannelAffinity currently leaves
ginKeyChannelAffinitySkipRetry unchanged when cache.DeleteMany fails, allowing
ShouldSkipRetryAfterChannelAffinityFailure to see an old SkipRetry=true; ensure
the retry gate is always reset by setting c.Set(ginKeyChannelAffinitySkipRetry,
false) regardless of delete outcome (either move that c.Set before calling
getChannelAffinityCache/DeleteMany or use a defer to set it immediately in
ClearCurrentChannelAffinity), keep error logging of
getChannelAffinityCache().DeleteMany and still return false on error but do not
leave the retry flag intact.
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx`:
- Around line 287-299: claudeCliRule and claudeCliCacheCount currently match and
index cache by the mutable display name; change claudeCliRule to locate the
Claude rule by a stable identifier (e.g., rule.id or rule.rule_type) instead of
rule.name (update the useMemo that defines claudeCliRule), and then compute
claudeCliCacheCount by looking up cacheStats using that stable id (e.g.,
cacheStats.by_rule_id[stableId]) with a fallback to the name if needed; update
the useMemo dependencies (claudeCliRule, cacheStats) accordingly so the cache
count no longer drops when admins rename the rule.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2440eebc-180f-43bf-9673-04b6b1d3fda2
📒 Files selected for processing (6)
middleware/distributor.goservice/channel_affinity.goservice/channel_affinity_template_test.gosetting/operation_setting/channel_affinity_setting.gosetting/operation_setting/channel_affinity_setting_test.goweb/src/pages/Setting/Operation/SettingsChannelAffinity.jsx
| adminInfo := map[string]interface{}{ | ||
| "cache_cleared": cacheCleared, | ||
| } | ||
| service.AppendChannelAffinityAdminInfo(c, adminInfo) | ||
|
|
||
| logger.LogWarn( | ||
| c.Request.Context(), | ||
| fmt.Sprintf( | ||
| "event=fallback_triggered status=affinity_channel_unavailable decision_reason=%s model=%s channel_id=%d channel_name=%q channel_status=%d using_group=%s request_path=%s cache_cleared=%t", | ||
| decisionReason, | ||
| modelName, | ||
| channelID, | ||
| channelName, | ||
| channelStatus, | ||
| usingGroup, | ||
| c.Request.URL.Path, | ||
| cacheCleared, | ||
| ), | ||
| ) |
There was a problem hiding this comment.
The enriched affinity context is dropped on this warning path.
service.AppendChannelAffinityAdminInfo mutates adminInfo, but nothing logs or stores that map afterward. The fallback warning therefore still loses the rule/key context this call was meant to attach.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@middleware/distributor.go` around lines 456 - 474,
service.AppendChannelAffinityAdminInfo mutates adminInfo but the mutated map is
never recorded; include the enriched adminInfo in the fallback path so the
rule/key context is preserved—after calling
service.AppendChannelAffinityAdminInfo(c, adminInfo) pass the mutated adminInfo
into the logger.LogWarn call (e.g., add admin_info=%v to the formatted message)
so the enriched map is logged, or alternatively call the existing
persistence/attach function that records adminInfo for the request before
emitting the warning; reference AppendChannelAffinityAdminInfo, adminInfo and
logger.LogWarn.
| func ClearCurrentChannelAffinity(c *gin.Context) bool { | ||
| if c == nil { | ||
| return false | ||
| } | ||
| cacheKey, _, ok := getChannelAffinityContext(c) | ||
| if !ok || strings.TrimSpace(cacheKey) == "" { | ||
| return false | ||
| } | ||
|
|
||
| cache := getChannelAffinityCache() | ||
| if _, err := cache.DeleteMany([]string{cacheKey}); err != nil { | ||
| common.SysError(fmt.Sprintf("channel affinity cache delete failed: key=%s, err=%v", cacheKey, err)) | ||
| return false | ||
| } | ||
|
|
||
| c.Set(ginKeyChannelAffinitySkipRetry, false) | ||
| return true | ||
| } |
There was a problem hiding this comment.
Always reset the current-request retry gate, even when cache eviction fails.
middleware.Distribute keeps routing after this helper returns false. On the error path here, ginKeyChannelAffinitySkipRetry stays untouched, so ShouldSkipRetryAfterChannelAffinityFailure() can still read the old rule’s SkipRetry=true and suppress retries for the fallback channel.
Proposed fix
func ClearCurrentChannelAffinity(c *gin.Context) bool {
if c == nil {
return false
}
+ c.Set(ginKeyChannelAffinitySkipRetry, false)
cacheKey, _, ok := getChannelAffinityContext(c)
if !ok || strings.TrimSpace(cacheKey) == "" {
return false
}
cache := getChannelAffinityCache()
if _, err := cache.DeleteMany([]string{cacheKey}); err != nil {
common.SysError(fmt.Sprintf("channel affinity cache delete failed: key=%s, err=%v", cacheKey, err))
return false
}
-
- c.Set(ginKeyChannelAffinitySkipRetry, false)
return true
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@service/channel_affinity.go` around lines 238 - 255,
ClearCurrentChannelAffinity currently leaves ginKeyChannelAffinitySkipRetry
unchanged when cache.DeleteMany fails, allowing
ShouldSkipRetryAfterChannelAffinityFailure to see an old SkipRetry=true; ensure
the retry gate is always reset by setting c.Set(ginKeyChannelAffinitySkipRetry,
false) regardless of delete outcome (either move that c.Set before calling
getChannelAffinityCache/DeleteMany or use a defer to set it immediately in
ClearCurrentChannelAffinity), keep error logging of
getChannelAffinityCache().DeleteMany and still return false on error but do not
leave the retry flag intact.
| const claudeCliRule = useMemo( | ||
| () => | ||
| (rules || []).find( | ||
| (rule) => (rule?.name || '').trim().toLowerCase() === 'claude cli trace', | ||
| ) || null, | ||
| [rules], | ||
| ); | ||
|
|
||
| const claudeCliCacheCount = useMemo(() => { | ||
| const name = (claudeCliRule?.name || '').trim(); | ||
| if (!name) return 0; | ||
| return Number(cacheStats?.by_rule_name?.[name] || 0); | ||
| }, [cacheStats, claudeCliRule]); |
There was a problem hiding this comment.
The Claude shortcut is tied to a mutable display name.
claudeCliRule only resolves when rule.name === 'claude cli trace', but this screen lets admins rename rules. After a rename, the count drops to 0 and the “清空 Claude Code 缓存” shortcut stops working even though the Claude rule still exists.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@web/src/pages/Setting/Operation/SettingsChannelAffinity.jsx` around lines 287
- 299, claudeCliRule and claudeCliCacheCount currently match and index cache by
the mutable display name; change claudeCliRule to locate the Claude rule by a
stable identifier (e.g., rule.id or rule.rule_type) instead of rule.name (update
the useMemo that defines claudeCliRule), and then compute claudeCliCacheCount by
looking up cacheStats using that stable id (e.g.,
cacheStats.by_rule_id[stableId]) with a fallback to the name if needed; update
the useMemo dependencies (claudeCliRule, cacheStats) accordingly so the cache
count no longer drops when admins rename the rule.
51fdfc5 to
2b6f1df
Compare
Summary
Why
This fixes a high-impact connectivity issue where Claude Code and other affinity-bound traffic could get pinned to disabled historical channels and return opaque 403 errors. The new behavior degrades gracefully, preserves routing continuity, and adds enough observability to identify the bad channel quickly when something does go wrong.
Testing
Notes
Summary by CodeRabbit
New Features
Improvements
Tests