diff --git a/backend/internal/middleware/rabbitmq/consume_test.go b/backend/internal/middleware/rabbitmq/consume_test.go new file mode 100644 index 0000000..7b078b7 --- /dev/null +++ b/backend/internal/middleware/rabbitmq/consume_test.go @@ -0,0 +1,287 @@ +package rabbitmq + +import ( + "context" + "errors" + "testing" + "time" + + amqp "github.com/rabbitmq/amqp091-go" +) + +// ackAction 记录一次 Ack/Nack/Reject,用于断言"消息到底被怎么处置了"。 +type ackAction struct { + nack bool + requeue bool +} + +type fakeAcknowledger struct { + acks int + action []ackAction +} + +func (a *fakeAcknowledger) Ack(uint64, bool) error { + a.acks++ + return nil +} + +func (a *fakeAcknowledger) Nack(_ uint64, _, requeue bool) error { + a.action = append(a.action, ackAction{nack: true, requeue: requeue}) + return nil +} + +func (a *fakeAcknowledger) Reject(_ uint64, requeue bool) error { + a.action = append(a.action, ackAction{nack: true, requeue: requeue}) + return nil +} + +// deliveryWith 构造一条被拒绝过 retryCount 次的投递:x-death 里只有一条 +// rejected 记录,足够驱动 GetRetryCount。 +func deliveryWith(acks *fakeAcknowledger, retryCount int) amqp.Delivery { + d := amqp.Delivery{Acknowledger: acks, DeliveryTag: 1, RoutingKey: "like.like"} + if retryCount > 0 { + d.Headers = amqp.Table{ + "x-death": []interface{}{ + amqp.Table{"reason": "rejected", "count": int64(retryCount)}, + }, + } + } + return d +} + +type fakeParker struct { + calls int + queue string + attempt int + cause error + err error +} + +func (p *fakeParker) Park(_ context.Context, sourceQueue string, _ amqp.Delivery, attempts int, cause error) error { + p.calls++ + p.queue = sourceQueue + p.attempt = attempts + p.cause = cause + return p.err +} + +func withShortParkBackoff(t *testing.T) { + t.Helper() + old := parkRequeueBackoff + parkRequeueBackoff = 10 * time.Millisecond + t.Cleanup(func() { parkRequeueBackoff = old }) +} + +func TestDecide_Table(t *testing.T) { + acks := &fakeAcknowledger{} + boom := errors.New("db down") + cases := []struct { + name string + err error + retryCount int + maxAttempts int + want Disposition + }{ + {name: "成功即 Ack", err: nil, retryCount: 3, maxAttempts: 4, want: DispositionAck}, + {name: "首次失败且可重试", err: boom, retryCount: 0, maxAttempts: 4, want: DispositionRetry}, + {name: "第二次失败仍可重试", err: boom, retryCount: 1, maxAttempts: 4, want: DispositionRetry}, + {name: "第三次失败仍可重试", err: boom, retryCount: 2, maxAttempts: 4, want: DispositionRetry}, + // 首次 + 3 次重试 = 4 次尝试,与改造前的 for i := 0; i <= 3 等价。 + {name: "第四次失败耗尽预算", err: boom, retryCount: 3, maxAttempts: 4, want: DispositionPark}, + {name: "永久错误立即停泊", err: Permanent(boom), retryCount: 0, maxAttempts: 4, want: DispositionPark}, + {name: "永久错误即使已重试也停泊", err: Permanent(boom), retryCount: 2, maxAttempts: 4, want: DispositionPark}, + {name: "零预算时首次失败即停泊", err: boom, retryCount: 0, maxAttempts: 1, want: DispositionPark}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d := deliveryWith(acks, tc.retryCount) + if got := Decide(d, tc.maxAttempts, tc.err); got != tc.want { + t.Fatalf("Decide() = %v, want %v", got, tc.want) + } + }) + } +} + +// 安全网:一条被 requeue 回来的消息可能已经超过预算(上一轮停泊失败), +// 此时无论下一个错误是什么都不该再重试。 +func TestExhausted_SafetyNet(t *testing.T) { + acks := &fakeAcknowledger{} + if Exhausted(deliveryWith(acks, 2), 4) { + t.Fatal("3 次尝试(retry=2)不应判定为耗尽") + } + if !Exhausted(deliveryWith(acks, 3), 4) { + t.Fatal("4 次尝试(retry=3)应判定为耗尽") + } + if !Exhausted(deliveryWith(acks, 99), 4) { + t.Fatal("超过预算的消息必须判定为耗尽") + } + if Exhausted(deliveryWith(acks, 0), 0) { + t.Fatal("maxAttempts<=0 时应回退到 MaxAttempts,首次失败必须仍可重试") + } +} + +func TestPermanent_MarksAndDetects(t *testing.T) { + boom := errors.New("bad body") + if IsPermanent(boom) { + t.Fatal("普通错误不应被判为永久错误") + } + marked := Permanent(boom) + if !IsPermanent(marked) { + t.Fatal("Permanent 标记后应被识别") + } + if !errors.Is(marked, boom) { + t.Fatal("标记后必须仍能用 errors.Is 找到原始错误") + } + if Permanent(nil) != nil { + t.Fatal("Permanent(nil) 必须是 nil,否则成功路径会被误判为失败") + } + if twice := Permanent(marked); twice != marked { + t.Fatal("重复标记不应再包一层") + } +} + +func TestHandleOne_AcksOnSuccess(t *testing.T) { + acks := &fakeAcknowledger{} + parker := &fakeParker{} + handleOne(context.Background(), parker, "like.events", 4, deliveryWith(acks, 0), + func(context.Context, amqp.Delivery) error { return nil }) + + if acks.acks != 1 || len(acks.action) != 0 || parker.calls != 0 { + t.Fatalf("成功应只 Ack:acks=%d actions=%v park=%d", acks.acks, acks.action, parker.calls) + } +} + +// 可重试失败必须 Nack(requeue=false):requeue=true 会立刻重投,等于没有退避, +// 而 requeue=false 才会让消息进入重试队列并吃 TTL。 +func TestHandleOne_RetryNacksWithoutRequeue(t *testing.T) { + acks := &fakeAcknowledger{} + parker := &fakeParker{} + boom := errors.New("db down") + handleOne(context.Background(), parker, "like.events", 4, deliveryWith(acks, 0), + func(context.Context, amqp.Delivery) error { return boom }) + + if acks.acks != 0 { + t.Fatal("可重试失败不能 Ack(Ack 就是丢弃)") + } + if len(acks.action) != 1 || acks.action[0].requeue { + t.Fatalf("应 Nack(requeue=false),实际 %v", acks.action) + } + if parker.calls != 0 { + t.Fatal("预算未用尽时不应停泊") + } +} + +func TestHandleOne_ParksWhenBudgetUsed(t *testing.T) { + withShortParkBackoff(t) + acks := &fakeAcknowledger{} + parker := &fakeParker{} + boom := errors.New("db down") + handleOne(context.Background(), parker, "like.events", 4, deliveryWith(acks, 3), + func(context.Context, amqp.Delivery) error { return boom }) + + if parker.calls != 1 { + t.Fatalf("预算用尽应停泊一次,实际 %d", parker.calls) + } + if parker.queue != "like.events" || parker.attempt != 4 { + t.Fatalf("停泊信息错误:queue=%q attempts=%d", parker.queue, parker.attempt) + } + if acks.acks != 1 || len(acks.action) != 0 { + t.Fatalf("停泊成功后应 Ack 原消息:acks=%d actions=%v", acks.acks, acks.action) + } +} + +// 不可重试的消息第一次失败就停泊,attempts 必须是 1(它没有浪费重试预算)。 +func TestHandleOne_PermanentParksImmediately(t *testing.T) { + withShortParkBackoff(t) + acks := &fakeAcknowledger{} + parker := &fakeParker{} + handleOne(context.Background(), parker, "comment.events", 4, deliveryWith(acks, 0), + func(context.Context, amqp.Delivery) error { return Permanent(errors.New("bad json")) }) + + if parker.calls != 1 || parker.attempt != 1 { + t.Fatalf("永久错误应立即停泊且 attempts=1,实际 calls=%d attempts=%d", parker.calls, parker.attempt) + } + if acks.acks != 1 { + t.Fatal("停泊成功后必须 Ack") + } +} + +// 停泊失败必须 requeue,且先退避:停泊链路的故障会让 Park 快速失败, +// 不退避就是一个热循环。 +func TestParkOrRequeue_ParkFailureRequeues(t *testing.T) { + withShortParkBackoff(t) + acks := &fakeAcknowledger{} + parker := &fakeParker{err: errors.New("queue not found")} + + start := time.Now() + parkOrRequeue(context.Background(), parker, "like.events", deliveryWith(acks, 3), 4, errors.New("db down")) + elapsed := time.Since(start) + + if acks.acks != 0 { + t.Fatal("停泊失败时绝不能 Ack(那等于丢弃)") + } + if len(acks.action) != 1 || !acks.action[0].requeue { + t.Fatalf("停泊失败应 Nack(requeue=true),实际 %v", acks.action) + } + if elapsed < parkRequeueBackoff { + t.Fatalf("requeue 之前必须退避:elapsed=%v backoff=%v", elapsed, parkRequeueBackoff) + } +} + +func TestParkOrRequeue_NoParkerRequeues(t *testing.T) { + withShortParkBackoff(t) + acks := &fakeAcknowledger{} + parkOrRequeue(context.Background(), nil, "like.events", deliveryWith(acks, 3), 4, errors.New("db down")) + + if acks.acks != 0 { + t.Fatal("没有 parker 时也不能 Ack") + } + if len(acks.action) != 1 || !acks.action[0].requeue { + t.Fatalf("没有 parker 应 Nack(requeue=true),实际 %v", acks.action) + } +} + +// 停泊成功必须先确认、后 Ack:这个顺序是"不丢消息"的全部保证。 +func TestParkOrRequeue_SuccessAcks(t *testing.T) { + acks := &fakeAcknowledger{} + parker := &fakeParker{} + cause := errors.New("db down") + parkOrRequeue(context.Background(), parker, "like.events", deliveryWith(acks, 3), 4, cause) + + if parker.calls != 1 { + t.Fatalf("应停泊一次,实际 %d", parker.calls) + } + if parker.cause != cause { + t.Fatal("停泊必须带上原始失败原因") + } + if acks.acks != 1 || len(acks.action) != 0 { + t.Fatalf("停泊成功后应 Ack:acks=%d actions=%v", acks.acks, acks.action) + } +} + +func TestConsumeLoop_RejectsInvalidArguments(t *testing.T) { + process := func(context.Context, amqp.Delivery) error { return nil } + if err := ConsumeLoop(context.Background(), nil, nil, "q", 4, process); err == nil { + t.Fatal("nil channel 必须报错(否则会静默不消费)") + } + if err := ConsumeLoop(context.Background(), &amqp.Channel{}, nil, "", 4, process); err == nil { + t.Fatal("空队列名必须报错") + } + if err := ConsumeLoop(context.Background(), &amqp.Channel{}, nil, "q", 4, nil); err == nil { + t.Fatal("nil process 必须报错") + } +} + +func TestDisposition_String(t *testing.T) { + cases := map[Disposition]string{ + DispositionAck: "ack", + DispositionRetry: "retry", + DispositionPark: "park", + Disposition(99): "unknown", + } + for d, want := range cases { + if got := d.String(); got != want { + t.Fatalf("Disposition(%d).String() = %q, want %q", int(d), got, want) + } + } +} diff --git a/backend/internal/middleware/rabbitmq/dlx.go b/backend/internal/middleware/rabbitmq/dlx.go index a642dba..a25d0cd 100644 --- a/backend/internal/middleware/rabbitmq/dlx.go +++ b/backend/internal/middleware/rabbitmq/dlx.go @@ -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) + } +}