Files
VLoop/backend/internal/middleware/rabbitmq/consume_test.go
huanghaosheng 03d4301020 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/ 全绿。
2026-10-30 15:16:17 +08:00

288 lines
9.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}
}
}