diff --git a/backend/internal/middleware/rabbitmq/p03_e2e_integration_test.go b/backend/internal/middleware/rabbitmq/p03_e2e_integration_test.go new file mode 100644 index 0000000..c3ee6c3 --- /dev/null +++ b/backend/internal/middleware/rabbitmq/p03_e2e_integration_test.go @@ -0,0 +1,302 @@ +//go:build integration + +package rabbitmq + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + amqp "github.com/rabbitmq/amqp091-go" +) + +// 这三条用例验证 P0-3 的对外承诺,而不是内部函数。 +// +// 单元测试能证明 Decide 返回 "retry",只有真实 broker 能证明消息确实 +// 走过 .retry、按 x-message-ttl 延迟、耗尽后确实停在 failed.events。 +// 因此它们放在 integration 构建标签下: +// +// RABBITMQ_TEST_URL=amqp://admin:123456@127.0.0.1:5672/ \ +// go test -tags integration -count=1 -run TestP0_3 ./internal/middleware/rabbitmq/ + +// p03Declare 建一条唯一命名的测试拓扑,并登记清理。 +// +// 队列名带随机后缀:用例失败时残留对象不会污染下一次运行, +// 也不会影响 failed.events 上其他用例的断言。 +func p03Declare(t *testing.T, mgr *RabbitMQ, delay time.Duration) Topology { + t.Helper() + topo := Topology{ + Exchange: "p0_3.e2e.events." + randSuffix(t), + Queue: "p0_3.e2e.queue." + randSuffix(t), + BindingKey: "#", + RetryDelay: delay, + } + mgr.RegisterTopology(topo) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := mgr.EnsureTopology(ctx); err != nil { + t.Fatalf("EnsureTopology: %v", err) + } + t.Cleanup(func() { p03Cleanup(mgr, topo) }) + return topo +} + +func p03Cleanup(mgr *RabbitMQ, topo Topology) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + sess, err := mgr.Session(ctx) + if err != nil { + return + } + defer sess.Ch.Close() + _, _ = sess.Ch.QueueDelete(topo.Queue, false, false, false) + _, _ = sess.Ch.QueueDelete(RetryQueueName(topo.Queue), false, false, false) + _ = sess.Ch.ExchangeDelete(topo.Exchange, false, false) + _ = sess.Ch.ExchangeDelete(RetryExchange(topo.Queue), false, false) +} + +func p03Publish(t *testing.T, mgr *RabbitMQ, topo Topology, eventID string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := mgr.PublishJSON(ctx, topo.Exchange, "p0_3.e2e", map[string]string{"event_id": eventID}); err != nil { + t.Fatalf("publish: %v", err) + } +} + +// p03WaitParked 在 failed.events 上等待属于 sourceQueue 的停泊消息。 +// +// 两个细节都是被真实 broker 打出来的教训: +// +// 1. 必须在 channel 关闭前确认。关闭后 Ack 返回 ErrClosed,被 `_ =` 吞掉, +// 消息留在队列里——上一版正是这样把"已确认"变成了一句空话。 +// 2. 不属于本用例的消息要确认掉,不能 requeue。停泊队列只有一个,Get 总是 +// 取队头,requeue 会把同一条消息反复放回队头,形成饥饿:后面的消息永远 +// 读不到。用例在同一包里串行执行,没有别的并发生产者,所以确认掉是安全的。 +func p03WaitParked(t *testing.T, mgr *RabbitMQ, sourceQueue string, timeout time.Duration) amqp.Delivery { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + sess, err := mgr.Session(ctx) + if err != nil { + cancel() + time.Sleep(50 * time.Millisecond) + continue + } + msg, ok, getErr := sess.Ch.Get(ParkedQueue, false) + var ackErr error + ours := getErr == nil && ok && p03StringHeader(msg, HeaderSourceQueue) == sourceQueue + if getErr == nil && ok { + // 必须在 channel 仍然打开时确认。关闭后再 Ack 会返回 ErrClosed, + // 被 `_ =` 吞掉,消息留在队列里——上一版正是这样把"已确认"变成空话。 + ackErr = msg.Ack(false) + } + _ = sess.Ch.Close() + cancel() + if ours { + if ackErr != nil { + t.Fatalf("确认停泊消息失败: %v", ackErr) + } + return msg + } + time.Sleep(50 * time.Millisecond) + } + t.Fatalf("等待停泊消息超时(source_queue=%s)", sourceQueue) + return amqp.Delivery{} +} + +func p03StringHeader(d amqp.Delivery, key string) string { + v, ok := d.Headers[key].(string) + if !ok { + return "" + } + return v +} + +func p03IntHeader(d amqp.Delivery, key string) int { + switch v := d.Headers[key].(type) { + case int32: + return int(v) + case int64: + return int(v) + case int: + return v + } + return -1 +} + +func p03QueueLen(t *testing.T, mgr *RabbitMQ, queue string) int { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + sess, err := mgr.Session(ctx) + if err != nil { + t.Fatalf("Session: %v", err) + } + defer sess.Ch.Close() + q, err := sess.Ch.QueueInspect(queue) + if err != nil { + t.Fatalf("QueueInspect(%s): %v", queue, err) + } + return q.Messages +} + +// 瞬时失败一次后必须自愈:消息经 .retry 延迟重投,第二次处理成功。 +// +// 同时钉住"重试计数来自 broker":第二次投递上 GetRetryCount 必须是 1, +// 而不是进程内存里的某个计数器。 +func TestP0_3_TransientFailureRecoversAfterRetryDelay(t *testing.T) { + mgr, _ := integrationTestManager(t) + const delay = 300 * time.Millisecond + topo := p03Declare(t, mgr, delay) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + sess, err := mgr.Session(ctx) + if err != nil { + t.Fatalf("Session: %v", err) + } + defer sess.Ch.Close() + + var mu sync.Mutex + var retryCounts []int + start := time.Now() + var once sync.Once + processed := make(chan time.Duration, 1) + + go func() { + _ = ConsumeLoop(ctx, sess.Ch, mgr, topo.Queue, 4, func(_ context.Context, d amqp.Delivery) error { + mu.Lock() + retryCounts = append(retryCounts, GetRetryCount(d)) + n := len(retryCounts) + mu.Unlock() + if n == 1 { + return errors.New("handler: transient failure") + } + once.Do(func() { processed <- time.Since(start) }) + return nil + }) + }() + + p03Publish(t, mgr, topo, "transient") + + select { + case elapsed := <-processed: + if elapsed < delay { + t.Fatalf("第二次投递只用了 %v,短于 RetryDelay=%v:说明消息没有经过重试队列", elapsed, delay) + } + case <-time.After(30 * time.Second): + t.Fatal("超时:消息没有在重试后恢复处理") + } + + mu.Lock() + got := append([]int(nil), retryCounts...) + mu.Unlock() + if len(got) != 2 { + t.Fatalf("投递次数 = %d (%v), want 2", len(got), got) + } + if got[0] != 0 || got[1] != 1 { + t.Fatalf("GetRetryCount 序列 = %v, want [0 1](第二次必须是 broker 的 x-death 计数)", got) + } + if n := p03QueueLen(t, mgr, topo.Queue); n != 0 { + t.Fatalf("业务队列剩余 %d 条,want 0", n) + } +} + +// 毒消息耗尽预算后必须停泊,而不是被 Ack 丢弃。 +func TestP0_3_PoisonEndsInParkedQueue(t *testing.T) { + mgr, _ := integrationTestManager(t) + const delay = 300 * time.Millisecond + topo := p03Declare(t, mgr, delay) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + sess, err := mgr.Session(ctx) + if err != nil { + t.Fatalf("Session: %v", err) + } + defer sess.Ch.Close() + + var mu sync.Mutex + handlerCalls := 0 + go func() { + _ = ConsumeLoop(ctx, sess.Ch, mgr, topo.Queue, 2, func(_ context.Context, _ amqp.Delivery) error { + mu.Lock() + handlerCalls++ + mu.Unlock() + return errors.New("handler: db down") + }) + }() + + p03Publish(t, mgr, topo, "poison") + + msg := p03WaitParked(t, mgr, topo.Queue, 30*time.Second) + + if got := p03StringHeader(msg, HeaderSourceQueue); got != topo.Queue { + t.Fatalf("source_queue = %q, want %q", got, topo.Queue) + } + if got := p03IntHeader(msg, HeaderAttempts); got != 2 { + t.Fatalf("attempts = %d, want 2(首次 + 1 次重试)", got) + } + if got := p03StringHeader(msg, HeaderLastError); !strings.Contains(got, "db down") { + t.Fatalf("last_error = %q, want 含最后的处理错误", got) + } + if got := GetRetryCount(msg); got < 1 { + t.Fatalf("停泊消息的 rejected 计数 = %d, want ≥1", got) + } + if !strings.Contains(string(msg.Body), "poison") { + t.Fatalf("停泊消息体 = %q, want 保留原始 body", string(msg.Body)) + } + + mu.Lock() + calls := handlerCalls + mu.Unlock() + if calls < 2 { + t.Fatalf("处理次数 = %d, want ≥2(预算用满才停泊)", calls) + } + if n := p03QueueLen(t, mgr, topo.Queue); n != 0 { + t.Fatalf("业务队列剩余 %d 条,want 0", n) + } +} + +// 不可重试的失败必须立即停泊:不进重试队列,attempts 为 1。 +func TestP0_3_PermanentGoesStraightToParked(t *testing.T) { + mgr, _ := integrationTestManager(t) + const delay = 10 * time.Second // 故意设长:一旦进重试队列,本用例会超时失败 + topo := p03Declare(t, mgr, delay) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + sess, err := mgr.Session(ctx) + if err != nil { + t.Fatalf("Session: %v", err) + } + defer sess.Ch.Close() + + start := time.Now() + go func() { + _ = ConsumeLoop(ctx, sess.Ch, mgr, topo.Queue, 4, func(_ context.Context, _ amqp.Delivery) error { + return Permanent(errors.New("handler: malformed event")) + }) + }() + + p03Publish(t, mgr, topo, "permanent") + + msg := p03WaitParked(t, mgr, topo.Queue, 15*time.Second) + if elapsed := time.Since(start); elapsed > delay/2 { + t.Fatalf("停泊耗时 %v:不可重试的错误不应进入 %v 的重试队列", elapsed, delay) + } + if got := p03IntHeader(msg, HeaderAttempts); got != 1 { + t.Fatalf("attempts = %d, want 1", got) + } + if got := p03StringHeader(msg, HeaderLastError); !strings.Contains(got, "malformed") { + t.Fatalf("last_error = %q, want 含原始错误", got) + } +}