Files
VLoop/backend/internal/middleware/rabbitmq/retrycount_test.go
huanghaosheng 5f250fa7cd fix(mq): GetRetryCount 只统计 rejected,并兼容非 int64 计数
原实现取 deaths[0] 并把 count 断言成 int64,在真实链路上两条都会让结果恒为 0:

- deaths[0] 常常是重试队列的 "expired" 条目(TTL 到期),它表示"延迟结束",
  不是"处理失败";把它算进来也会让计数含义失真。
- amqp091-go 在不同路径上给出的 count 宽度不同(int32/int64/float64),
  断言 int64 失败就静默返回 0。

计数恒为 0 的后果不是"少重试几次",而是"重试永远不耗尽"——任何依赖它的
重试上限判定都会失效。改为遍历所有 x-death 条目、只累加 reason=="rejected",
并用 intField 统一宽度。

守护测试 TestGetRetryCount_CountsOnlyRejected 覆盖 7 种 x-death 形状,
含"rejected 与 expired 混合时只累加 rejected"与"多条 rejected 累加"。
2026-10-30 13:12:05 +08:00

65 lines
1.8 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 (
"testing"
amqp "github.com/rabbitmq/amqp091-go"
)
// TestGetRetryCount_CountsOnlyRejected 守护两个曾经让计数恒为 0 的坑:
// 读 deaths[0](真实链路里常常是重试队列的 expired),以及把 count 断言成 int64。
func TestGetRetryCount_CountsOnlyRejected(t *testing.T) {
cases := []struct {
name string
headers amqp.Table
want int
}{
{"无 x-death", amqp.Table{}, 0},
{"x-death 类型不对", amqp.Table{"x-death": "nope"}, 0},
{
name: "只有 expired 不算重试",
headers: amqp.Table{"x-death": []interface{}{
amqp.Table{"queue": "like.events.retry", "reason": "expired", "count": int64(1)},
}},
want: 0,
},
{
name: "int64 计数的 rejected",
headers: amqp.Table{"x-death": []interface{}{
amqp.Table{"queue": "like.events", "reason": "rejected", "count": int64(2)},
}},
want: 2,
},
{
name: "int32 计数的 rejected",
headers: amqp.Table{"x-death": []interface{}{
amqp.Table{"queue": "like.events", "reason": "rejected", "count": int32(1)},
}},
want: 1,
},
{
name: "rejected 与 expired 混合时只累加 rejected",
headers: amqp.Table{"x-death": []interface{}{
amqp.Table{"queue": "like.events.retry", "reason": "expired", "count": int64(3)},
amqp.Table{"queue": "like.events", "reason": "rejected", "count": int64(3)},
}},
want: 3,
},
{
name: "多条 rejected 累加",
headers: amqp.Table{"x-death": []interface{}{
amqp.Table{"queue": "a", "reason": "rejected", "count": int64(1)},
amqp.Table{"queue": "b", "reason": "rejected", "count": int64(2)},
}},
want: 3,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := GetRetryCount(amqp.Delivery{Headers: c.headers}); got != c.want {
t.Fatalf("GetRetryCount = %d, want %d", got, c.want)
}
})
}
}