fix(并发): 修复 wrapReleaseOnDone goroutine 泄露问题

问题描述:
- wrapReleaseOnDone 函数创建的 goroutine 会持续等待 ctx.Done()
- 即使 release() 已被调用,goroutine 仍不会退出
- 高并发场景下(1000 req/s)会产生 3000+ 个泄露 goroutine

修复方案:
- 添加 quit channel 作为退出信号
- 正常释放时 close(quit) 通知 goroutine 立即退出
- 使用 select 监听 ctx.Done() 和 quit 两个信号
- 确保 goroutine 在正常流程中及时退出

测试覆盖:
- 新增 5 个单元测试验证修复效果
- 验证 goroutine 不泄露
- 验证并发安全性和多次调用保护
- 性能影响:471.9 ns/op, 208 B/op

影响范围:
- gateway_handler.go: 每请求调用 2-4 次
- openai_gateway_handler.go: 每请求调用 2-3 次
- 修复后 goroutine 泄露数量从 3/req 降至 0

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
yangjianbo
2026-01-06 20:31:40 +08:00
parent 66fe484f0d
commit 823497a2af
2 changed files with 160 additions and 5 deletions

View File

@@ -83,19 +83,33 @@ func NewConcurrencyHelper(concurrencyService *service.ConcurrencyService, pingFo
// wrapReleaseOnDone ensures release runs at most once and still triggers on context cancellation.
// 用于避免客户端断开或上游超时导致的并发槽位泄漏。
// 修复:添加 quit channel 确保 goroutine 及时退出,避免泄露
func wrapReleaseOnDone(ctx context.Context, releaseFunc func()) func() {
if releaseFunc == nil {
return nil
}
var once sync.Once
wrapped := func() {
once.Do(releaseFunc)
quit := make(chan struct{})
release := func() {
once.Do(func() {
releaseFunc()
close(quit) // 通知监听 goroutine 退出
})
}
go func() {
<-ctx.Done()
wrapped()
select {
case <-ctx.Done():
// Context 取消时释放资源
release()
case <-quit:
// 正常释放已完成goroutine 退出
return
}
}()
return wrapped
return release
}
// IncrementWaitCount increments the wait count for a user