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 累加"。
This commit is contained in:
2026-10-30 13:12:05 +08:00
parent a224651e4c
commit 5f250fa7cd
2 changed files with 102 additions and 9 deletions

View File

@@ -43,19 +43,48 @@ func declareDLX(d declarer, queueName string) error {
return nil
}
// GetRetryCount 从 AMQP x-death header 中提取当前消息已被重试的次数
// GetRetryCount 返回这条消息被【拒绝过】的次数。
//
// 两个坑:
// 1. 不读 deaths[0]。真实链路里最新一条往往是重试队列的 "expired"(TTL 到期),
// 那是"延迟结束",不是"处理失败"。只数 reason == "rejected"。
// 2. 不假定 count 是 int64。amqp091-go 在不同路径上会给出 int32/int64/float64,
// 断言成 int64 会在真实消息上静默返回 0——计数恒为 0 就意味着"永远不重试耗尽"。
func GetRetryCount(d amqp.Delivery) int {
deaths, ok := d.Headers["x-death"].([]interface{})
if !ok || len(deaths) == 0 {
return 0
}
death, ok := deaths[0].(amqp.Table)
if !ok {
return 0
}
count, ok := death["count"].(int64)
if !ok {
return 0
total := 0
for _, raw := range deaths {
entry, ok := raw.(amqp.Table)
if !ok {
continue
}
if reason, _ := entry["reason"].(string); reason != "rejected" {
continue
}
total += intField(entry["count"])
}
return total
}
// intField 把 AMQP table 里的整数值统一成 int(库在不同路径上给出不同宽度)。
func intField(v any) int {
switch n := v.(type) {
case int:
return n
case int32:
return int(n)
case int64:
return int(n)
case uint32:
return int(n)
case uint64:
return int(n)
case float64:
return int(n)
default:
return 0
}
return int(count)
}