feat(ops): 优雅停机 drain —— 三 Go 服务 SIGTERM 后排空在途,不硬切
滚动更新/重启时旧的"信号到→进程退"会硬切在途工作:dispatcher 在途任务被掐断、 mcp-go 在途工具调用让 dispatcher 干等超时、gateway 在途 HTTP 请求被截断。 共享 bus 加在途追踪 + drain: - ConsumeTasks/ServeTool 各加 sync.WaitGroup 跟踪在途 goroutine,返回 drain(ctx): 先停止接新活(cc.Stop / Unsubscribe),再等在途跑完至 drain 超时。 - 关键修复:任务 handler 的 ctx 改为派生自 context.Background()(而非信号 ctx), 否则 SIGTERM 会立即取消在途任务的 ctx,drain 形同虚设。超时未跑完才由 JetStream AckWait 重投兜底(不丢任务)。 - DrainTimeout():SHUTDOWN_DRAIN_TIMEOUT 秒,默认 30s。 各服务收尾: - gateway:r.Run → http.Server + signal.NotifyContext + srv.Shutdown(drain 在途请求), 随后 defer 关 db/redis/bus(HTTP 排空后才断后端连接)。 - dispatcher:收到信号 → drain 在途任务跑完再退。 - mcp-go:收到信号 → drain 在途工具调用回完再退(dispatcher 拿到结果而非超时)。 bus 加 TestGracefulDrain(drain 等满在途任务 + 验证在途 ctx 不被取消),e2e 测试适配 新签名,四模块全绿。live:在途任务执行中 kill -TERM dispatcher → 日志「drain 在途任务」 → 11s 后 task done(511字完整生成) → 「drain 完成,退出」,任务终态 done 非 failed; gateway/mcp-go 同样优雅退出。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -33,15 +33,21 @@ func MustConnect(url string) *Subscriber {
|
||||
|
||||
// ConsumeTasks 从 sundynix.tasks.* 持续消费任务(队列组负载均衡),阻塞至 ctx 取消。
|
||||
func (s *Subscriber) ConsumeTasks(ctx context.Context, h TaskHandler) error {
|
||||
stop, err := s.inner.ConsumeTasks(ctx, func(c context.Context, t *contract.Task) error {
|
||||
drain, err := s.inner.ConsumeTasks(ctx, func(c context.Context, t *contract.Task) error {
|
||||
return h(c, t)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stop()
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
<-ctx.Done() // 收到停机信号
|
||||
// 优雅停机:停止消费新任务 + 等在途任务跑完(至多 DrainTimeout),再退出。
|
||||
to := sharedbus.DrainTimeout()
|
||||
log.Printf("[dispatcher] 收到停机信号,drain 在途任务(≤%s)…", to)
|
||||
dctx, cancel := context.WithTimeout(context.Background(), to)
|
||||
defer cancel()
|
||||
drain(dctx)
|
||||
log.Printf("[dispatcher] drain 完成,退出")
|
||||
return nil
|
||||
}
|
||||
|
||||
// PublishToken / CompleteStream 让 Subscriber 满足 eino.TokenSink,
|
||||
|
||||
Reference in New Issue
Block a user