Skip to content

feat: 支持配置渠道被禁用后是否清空渠道粘性 - #5306

Merged
seefs001 merged 2 commits into
QuantumNous:mainfrom
GuangYiDing:fix/stale-channel-affinity
Jun 5, 2026
Merged

feat: 支持配置渠道被禁用后是否清空渠道粘性#5306
seefs001 merged 2 commits into
QuantumNous:mainfrom
GuangYiDing:fix/stale-channel-affinity

Conversation

@GuangYiDing

@GuangYiDing GuangYiDing commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)
支持配置渠道被禁用后是否清空渠道粘性,默认行为为 渠道被禁用后清空

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Adds ClearCurrentChannelAffinityCache and a setting KeepOnChannelDisabled; distributor now only uses affinity when the preferred channel is enabled and clears affinity otherwise. Frontend and system settings are updated with the new option and i18n entries; unit test validates cache deletion and retry-flag reset.

Changes

Channel Affinity Cache Clearing

Layer / File(s) Summary
Affinity service helper & test
service/channel_affinity.go, service/channel_affinity_template_test.go
Adds ClearCurrentChannelAffinityCache and ShouldKeepChannelAffinityOnChannelDisabled; test TestClearCurrentChannelAffinityCache verifies cache deletion and resets the skip-retry flag.
Distributor integration
middleware/distributor.go
Distributor preferred-channel logic now only uses affinity when the preferred channel is enabled; otherwise marks affinity unusable and clears the current channel-affinity cache instead of returning 403.
Backend setting additions
setting/operation_setting/channel_affinity_setting.go
Adds KeepOnChannelDisabled boolean to ChannelAffinitySetting with default false.
Classic UI: settings + i18n
web/classic/src/pages/Setting/Operation/SettingsChannelAffinity.jsx, web/classic/src/i18n/locales/*
Expose channel_affinity_setting.keep_on_channel_disabled in classic settings UI, hydrate options, render new switch and help text; add translation entries for multiple locales.
Default web app settings & system-settings
web/default/src/features/..., web/default/src/i18n/locales/*
Add default model setting key, extend system-settings component/state/types to include keep_on_channel_disabled, persist changes on save, and add translations across locales.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • seefs001

Poem

🐰 I hopped through cache and setting tree,
Cleared an affinity so services roam free,
A switch in the UI, locales sing along,
Cache wiped, retries reset — the flow moves on.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title accurately summarizes the main change: adding configuration to control whether channel affinity is cleared when a channel becomes disabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@service/channel_affinity.go`:
- Around line 654-659: The early return after cache.DeleteMany leaves
ginKeyChannelAffinitySkipRetry set and prevents retries; ensure
c.Set(ginKeyChannelAffinitySkipRetry, false) always runs even if
cache.DeleteMany returns an error by moving the reset before the error check or,
better, use a defer right after obtaining the context (so the flag is reset
unconditionally). Update the block around cache.DeleteMany (referencing
DeleteMany, ginKeyChannelAffinitySkipRetry, c.Set and shouldRetry) to guarantee
the flag is cleared on both success and error paths.
🪄 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: 2325113e-48aa-4dd5-8e14-c11089287470

📥 Commits

Reviewing files that changed from the base of the PR and between 00d23ab and 090694e.

📒 Files selected for processing (3)
  • middleware/distributor.go
  • service/channel_affinity.go
  • service/channel_affinity_template_test.go

Comment on lines +654 to +659
deleted, err := cache.DeleteMany([]string{cacheKey})
if err != nil {
common.SysError(fmt.Sprintf("channel affinity cache delete current failed: err=%v", err))
return false
}
c.Set(ginKeyChannelAffinitySkipRetry, false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reset retry-skip state even when cache deletion errors.

On Line 655, the early return on DeleteMany error skips resetting ginKeyChannelAffinitySkipRetry. That can keep retries disabled for this request (shouldRetry exits early when the skip flag is true), which weakens fallback resilience on transient cache failures.

💡 Suggested fix
 func ClearCurrentChannelAffinityCache(c *gin.Context) bool {
 	if c == nil {
 		return false
 	}
 	cacheKey, _, ok := getChannelAffinityContext(c)
 	if !ok || cacheKey == "" {
 		return false
 	}
 
+	// Always clear request-level skip-retry state for this request path.
+	c.Set(ginKeyChannelAffinitySkipRetry, false)
+
 	cache := getChannelAffinityCache()
 	deleted, err := cache.DeleteMany([]string{cacheKey})
 	if err != nil {
 		common.SysError(fmt.Sprintf("channel affinity cache delete current failed: err=%v", err))
 		return false
 	}
-	c.Set(ginKeyChannelAffinitySkipRetry, false)
 	for _, ok := range deleted {
 		if ok {
 			return true
 		}
 	}
 	return false
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@service/channel_affinity.go` around lines 654 - 659, The early return after
cache.DeleteMany leaves ginKeyChannelAffinitySkipRetry set and prevents retries;
ensure c.Set(ginKeyChannelAffinitySkipRetry, false) always runs even if
cache.DeleteMany returns an error by moving the reset before the error check or,
better, use a defer right after obtaining the context (so the flag is reset
unconditionally). Update the block around cache.DeleteMany (referencing
DeleteMany, ginKeyChannelAffinitySkipRetry, c.Set and shouldRetry) to guarantee
the flag is cleared on both success and error paths.

@seefs001 seefs001 closed this Jun 4, 2026
@seefs001 seefs001 reopened this Jun 4, 2026
@seefs001

seefs001 commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

我需要改一下,这个需要加入配置。
另外下次提交PR请遵守PR模版来。

@seefs001 seefs001 changed the title fix: 清理失效的 channel affinity 缓存 feat: 支持配置渠道被禁用后是否清空渠道粘性 Jun 4, 2026
@seefs001
seefs001 merged commit 4a188de into QuantumNous:main Jun 5, 2026
1 check passed
Soein added a commit to Soein/new-api that referenced this pull request Jun 6, 2026
… id 等)

主要变更(QuantumNous/new-api → adc390c):
- feat: 渠道被禁用后可配置是否清空渠道粘性 (QuantumNous#5306)
- feat(web): profile 页显示 user id (QuantumNous#5317)
- fix: 复用 channel handler 的 stream scanner buffer (QuantumNous#5225)
- fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
- fix(relay): GLM Anthropic 兼容避免 chunked encoding (QuantumNous#5307)
- fix: 新增 relay idle 连接超时配置 (QuantumNous#5309)
- fix: 限制匿名请求体大小 (QuantumNous#5244)
- fix(distributor): 修复 video generations task_id 模型解析 (QuantumNous#5133)
- fix(dify): 远程图片字段赋值前初始化 file pointer (QuantumNous#5134)
- fix(i18n): 优化 thinking adapter 文案 (QuantumNous#5242)

去合规一致性:上游未触及任何合规文件,合并完整保留本地去合规状态
(payment_setting.go / payment-settings-section.tsx / recharge-form-card.tsx /
risk-acknowledgement-dialog.tsx 均未被改动)。

i18n:web/default 6 语言(en/zh/fr/ja/ru/vi)key 并集三路合并 + i18n:sync
规范化,4584 keys/语言,missing/extras/untranslated 全为 0。

验证:go build ./... ✅ + bun run typecheck ✅
Ember-Moth pushed a commit to Ember-Moth/new-api that referenced this pull request Jun 7, 2026
* fix: evict stale channel affinity

* feat: configure disabled channel affinity retention

---------

Co-authored-by: Seefs <i@seefs.me>
52assert added a commit to 52assert/new-api that referenced this pull request Jun 10, 2026
…codes

* origin/main: (45 commits)
  fix(openai): support streaming image relay and image edit for images API  (QuantumNous#4608)
  perf(web): improve dialog sizing and footer layout
  feat(web): add shared dialog wrapper
  perf(web): simplify public page hero copy
  perf(model-pricing): move pricing tabs into page title
  feat(json-editor): add reusable JSON code editor
  perf(model-pricing): improve JSON pricing editor layout
  perf(model-pricing): reduce duplicate model name display
  fix: support six-decimal steps in model pricing editor
  fix: respect theme for multiselect combobox popover
  fix: reuse stream scanner buffer in channel handlers (QuantumNous#5225)
  fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
  fix(i18n): clarify thinking adapter copy (QuantumNous#5242)
  fix: limit anonymous request body (QuantumNous#5244)
  fix(relay): fix Anthropic-compatible compatibility for GLM (avoid chunked encoding) (QuantumNous#5307)
  feat: 支持配置渠道被禁用后是否清空渠道粘性 (QuantumNous#5306)
  fix: add relay idle connection timeout config (QuantumNous#5309)
  feat(web): show user id on profile page
  perf(model-pricing): refine visual editor actions
  refactor(model-pricing): split visual pricing editor modules
  ...

# Conflicts:
#	router/api-router.go
#	web/default/src/features/usage-logs/components/usage-logs-mobile-card.tsx
endercat-alu pushed a commit to endercat-alu/new-api that referenced this pull request Jun 10, 2026
* fix: evict stale channel affinity

* feat: configure disabled channel affinity retention

---------

Co-authored-by: Seefs <i@seefs.me>
(cherry picked from commit 4a188de)
OuYang-HX pushed a commit to OuYang-HX/new-api that referenced this pull request Jun 13, 2026
* fix: evict stale channel affinity

* feat: configure disabled channel affinity retention

---------

Co-authored-by: Seefs <i@seefs.me>
YeMao11 pushed a commit to YeMao11/new-api that referenced this pull request Jun 16, 2026
Upstream changes (50+ commits, v1.0.0-rc.11):
- data-table perf: row selection memo, column pinning, badge display
- Fixes: channel test dialog (QuantumNous#5517), CC Switch model selector (QuantumNous#5515),
  API key form options (QuantumNous#5512), cell overflow (QuantumNous#5510), kimi k2.6 temp (QuantumNous#5390),
  Anthropic-compatible GLM chunked encoding (QuantumNous#5307), streaming image relay (QuantumNous#4608)
- Feat: audit auth method tracking (QuantumNous#5462), channel affinity clear toggle (QuantumNous#5306),
  relay idle timeout config (QuantumNous#5309), 6-decimal pricing precision (QuantumNous#5332)
- Classic frontend: Rsbuild support, Semi React 19 adapter
- Shared dialog wrapper, JSON code editor, debounce channel search

Conflict resolved: web/bun.lock (accepted upstream, will regenerate)

Co-Authored-By: Claude <noreply@anthropic.com>
YeMao11 pushed a commit to YeMao11/new-api that referenced this pull request Jun 16, 2026
Merge upstream v1.0.0-rc.11 (50+ commits):
- data-table perf: row selection memo, column pinning, badge display
- Fixes: channel test dialog (QuantumNous#5517), CC Switch (QuantumNous#5515), API key (QuantumNous#5512),
  kimi k2.6 temp (QuantumNous#5390), GLM chunked encoding (QuantumNous#5307), streaming image (QuantumNous#4608)
- Feat: audit auth tracking (QuantumNous#5462), channel affinity toggle (QuantumNous#5306),
  relay idle timeout (QuantumNous#5309), 6-decimal pricing (QuantumNous#5332)
- Shared dialog wrapper, JSON code editor, classic Rsbuild support

SEO optimization:
- robots.txt: 10 AI crawler blocks + 22 path disallows + crawl-delay
- sitemap.xml: 7 public URLs with 6-language hreflang annotations
- index.html: hreflang tags, og:locale:alternate, og:image, canonical,
  5 structured data types (Organization, SoftwareApplication, FAQPage,
  WebSite, SearchAction), expanded keywords (gateway, agent router,
  aggregation, orchestration)
- i18n/config.ts: sync <html lang> with active language for SEO

Co-Authored-By: Claude <noreply@anthropic.com>
ruanhangjian pushed a commit to ruanhangjian/new-api that referenced this pull request Jul 11, 2026
* fix: evict stale channel affinity

* feat: configure disabled channel affinity retention

---------

Co-authored-by: Seefs <i@seefs.me>
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
* fix: evict stale channel affinity

* feat: configure disabled channel affinity retention

---------

Co-authored-by: Seefs <i@seefs.me>
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
* fix: evict stale channel affinity

* feat: configure disabled channel affinity retention

---------

Co-authored-by: Seefs <i@seefs.me>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants