feat(mq): 统一消费循环的重试与停泊判断

五个消费者原本各有一份 handleDelivery 副本。副本在重试耗尽后调用 Ack。
因此失败消息会被静默丢弃。本提交先把判断收成一个纯函数。

Decide 只有三个出口。成功返回 Ack。可重试失败返回 Retry。
预算用尽或错误被 Permanent 标记时返回 Park。

ConsumeLoop 不再 time.Sleep。重试延迟由 retry 队列的 TTL 决定。
因此一条坏消息不再阻塞整条队列。重试计数来自 x-death,进程不存状态。

停泊先确认成功、再 Ack 原消息。Park 失败时先退避,再 requeue。
因此停泊链路故障不会变成热循环。

验证:go test -count=1 ./internal/middleware/rabbitmq/ 全绿。
This commit is contained in:
2026-10-30 15:16:17 +08:00
parent e9f2e84b30
commit 03d4301020
2 changed files with 501 additions and 6 deletions

View File

@@ -1,7 +1,9 @@
package rabbitmq
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
@@ -39,14 +41,18 @@ const (
// parkTimeout 是"停泊一条消息"的硬上限:停泊是失败路径,
// 它不能因为连接半死而把消费者的处理协程无限期占住。
parkTimeout = 5 * time.Second
// parkRequeueBackoff 是"停泊失败后退回 requeue"之前的退避。
// 没有它,当 failed.events 缺失(或 dlx.events 被误删)时 Park 会快速失败:
// mandatory 的 basic.return 立刻返回,Nack(requeue=true) 立刻重投,
// 形成每秒上万次的热循环 + 日志洪泛。
parkRequeueBackoff = time.Second
)
// parkRequeueBackoff 是"停泊失败后退回 requeue"之前的退避。
//
// 没有它,当 failed.events 缺失(或 dlx.events 被误删)时 Park 会快速失败:
// mandatory 的 basic.return 立刻返回,Nack(requeue=true) 立刻重投,
// 形成每秒上万次的热循环 + 日志洪泛。
//
// 是变量而不是常量:测试把它压到毫秒级,否则"退避确实发生了"这条断言
// 会让每次跑测试都多等一秒。
var parkRequeueBackoff = time.Second
// MaxAttempts 是一次投递被允许的最大尝试次数(首次 + 重试)。
const MaxAttempts = MaxRetryCount + 1
@@ -245,3 +251,205 @@ func stringField(v any) string {
func sourceQueueFromParkedKey(key string) string {
return strings.TrimPrefix(key, ParkedKeyPrefix)
}
// —— 重试/停泊策略 ——
// PermanentError 标记"重试也不会成功"的失败。
//
// 典型来源:消息体不是合法 JSON、字段非法、未知的 action。
// 这类消息每重投一次就必然再失败一次,重试只是把毒消息在队列里多放 15 秒。
type PermanentError struct {
Err error
}
func (e *PermanentError) Error() string { return e.Err.Error() }
func (e *PermanentError) Unwrap() error { return e.Err }
// Permanent 把错误标记为不可重试。nil 原样返回,已标记的不重复包装。
func Permanent(err error) error {
if err == nil {
return nil
}
if IsPermanent(err) {
return err
}
return &PermanentError{Err: err}
}
// IsPermanent 判断错误是否被 Permanent 标记过(支持 errors.Is/As 链)。
func IsPermanent(err error) bool {
var p *PermanentError
return errors.As(err, &p)
}
// Disposition 是一条消息处理完之后该做什么。
type Disposition int
const (
// DispositionAck 表示处理成功:Ack,消息结束。
DispositionAck Disposition = iota
// DispositionRetry 表示可重试失败:Nack(requeue=false),交给重试队列。
DispositionRetry
// DispositionPark 表示重试预算已用尽或不可重试:落到停泊队列。
DispositionPark
)
func (d Disposition) String() string {
switch d {
case DispositionAck:
return "ack"
case DispositionRetry:
return "retry"
case DispositionPark:
return "park"
default:
return "unknown"
}
}
// Exhausted 报告这条消息的尝试次数是否已经用完。
//
// 单独抽出来是为了留一道安全网:一条被 requeue 回来的消息可能已经超过预算
// (例如上一轮停泊失败),此时无论下一个错误是什么都不该再重试。
func Exhausted(d amqp.Delivery, maxAttempts int) bool {
if maxAttempts <= 0 {
maxAttempts = MaxAttempts
}
return GetRetryCount(d)+1 >= maxAttempts
}
// Decide 是重试策略的唯一定义点:输入一次处理结果,输出该做什么。
//
// 它是纯函数,因此"第几次失败会停泊"这类问题可以完全用表驱动测试锁住,
// 而不需要连 broker。五个消费者共用这一个判断,不会再出现"五份拷贝里
// 有一份永远走不到"的情况。
func Decide(d amqp.Delivery, maxAttempts int, err error) Disposition {
if err == nil {
return DispositionAck
}
if IsPermanent(err) || Exhausted(d, maxAttempts) {
return DispositionPark
}
return DispositionRetry
}
// ConsumeLoop 是全项目唯一的消费循环。
//
// 它只做三件事:取消息、调用 process、按 Decide 的结果处置。策略(重试几次、
// 什么时候停泊)在 Decide 里,业务在 process 里,两者都不在这里。
//
// 与改造前的区别,逐条对应 P0-3 的根因:
// - 重试不再 time.Sleep:Nack 之后由重试队列的 TTL 决定延迟,
// 消费协程立刻处理下一条,队列不会被一条坏消息堵住(D3)。
// - 重试计数来自 broker 的 x-death,进程不存任何状态,重启不丢计数(D2)。
// - 预算是用尽后 Nack 到停泊队列,而不是 Ack 丢弃(D1)。
func ConsumeLoop(
ctx context.Context,
ch *amqp.Channel,
parker Parker,
queue string,
maxAttempts int,
process func(context.Context, amqp.Delivery) error,
) error {
if ch == nil {
return errors.New("consume: channel is nil")
}
if queue == "" {
return errors.New("consume: queue is empty")
}
if process == nil {
return errors.New("consume: process is nil")
}
if maxAttempts <= 0 {
maxAttempts = MaxAttempts
}
deliveries, err := ch.Consume(queue, "", false, false, false, false, nil)
if err != nil {
return fmt.Errorf("consume %s: %w", queue, err)
}
for {
select {
case <-ctx.Done():
return nil
case d, ok := <-deliveries:
if !ok {
// channel 被关闭(连接换代或队列被删):交给 RunConsumer 重建。
return nil
}
handleOne(ctx, parker, queue, maxAttempts, d, process)
}
}
}
// handleOne 处置一条消息。Ack/Nack 失败只记日志:消息要么已经离开队列,
// 要么会被 broker 重投,两种情况下再冒泡一个错误都没有额外价值。
func handleOne(
ctx context.Context,
parker Parker,
queue string,
maxAttempts int,
d amqp.Delivery,
process func(context.Context, amqp.Delivery) error,
) {
err := process(ctx, d)
attempts := GetRetryCount(d) + 1
switch Decide(d, maxAttempts, err) {
case DispositionAck:
if ackErr := d.Ack(false); ackErr != nil {
log.Printf("consume: ack 失败 queue=%s err=%v", queue, ackErr)
}
case DispositionRetry:
log.Printf("consume: 处理失败将重试 queue=%s attempts=%d/%d err=%v", queue, attempts, maxAttempts, err)
// requeue=false:让 broker 把消息交给本队列的重试交换机,
// 由重试队列的 TTL 决定延迟。requeue=true 会立刻重投,等于没有退避。
if nackErr := d.Nack(false, false); nackErr != nil {
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
}
case DispositionPark:
parkOrRequeue(ctx, parker, queue, d, attempts, err)
}
}
// parkOrRequeue 停泊一条消息,并在停泊失败时退回 requeue。
//
// 顺序不可换:先确认停泊成功,再 Ack 原消息(G6)。反过来的话,
// 停泊失败就等于"原消息被删、停泊消息没进队列",正是要修的那种静默丢失。
func parkOrRequeue(ctx context.Context, parker Parker, queue string, d amqp.Delivery, attempts int, cause error) {
if parker == nil {
// 没有 parker 的进程(未接线或测试)宁可把消息留在队列里反复重投,
// 也不能 Ack——Ack 就是丢弃。
log.Printf("consume: 无 parker,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, cause)
if !sleepCtx(ctx, parkRequeueBackoff) {
return
}
if nackErr := d.Nack(false, true); nackErr != nil {
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
}
return
}
parkCtx, cancel := context.WithTimeout(ctx, parkTimeout)
defer cancel()
if err := parker.Park(parkCtx, queue, d, attempts, cause); err != nil {
log.Printf("consume: 停泊失败,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, err)
// 退避后再重投:停泊链路的故障通常是"队列/交换机不存在",Park 会立刻
// 失败,不退避就是一个每秒上万次的热循环。
if !sleepCtx(ctx, parkRequeueBackoff) {
return
}
if nackErr := d.Nack(false, true); nackErr != nil {
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
}
return
}
log.Printf("consume: 已停泊 queue=%s attempts=%d last_error=%v", queue, attempts, cause)
if ackErr := d.Ack(false); ackErr != nil {
log.Printf("consume: ack 失败 queue=%s err=%v", queue, ackErr)
}
}