注释搬家到 docs/design/message-failure-handling.md。 删除复述代码的注释、历史缺陷说明与批次编号。保留的类型断言、索引语义、声明顺序等约束已在文档中展开。 重写 dlx.go、topology.go、consumer.go 三个文件,其余文件只删注释。 唯一非注释改动是 topology.go 里两处 ExchangeDeclare 由多行压成单行,语义不变。 验证:go test -count=1 ./... 全绿。
351 lines
9.8 KiB
Go
351 lines
9.8 KiB
Go
package rabbitmq
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"log"
|
||
"strings"
|
||
"time"
|
||
|
||
amqp "github.com/rabbitmq/amqp091-go"
|
||
)
|
||
|
||
const (
|
||
// DLXExchange 是停泊专用交换机。
|
||
DLXExchange = "dlx.events"
|
||
// ParkedQueue 是唯一的停泊队列,由 FailedEventWorker 落库到 failed_events。
|
||
ParkedQueue = "failed.events"
|
||
// ParkedKeyPrefix 后接源队列名,构成停泊路由键 parked.<queue>。
|
||
ParkedKeyPrefix = "parked."
|
||
// RetryExchangePrefix 让每个业务队列有独立的重试入口。
|
||
RetryExchangePrefix = "retry.events."
|
||
// RetryQueueSuffix 让每个业务队列有独立的延迟队列。
|
||
RetryQueueSuffix = ".retry"
|
||
|
||
// MaxRetryCount 与既有行为一致:首次投递 + 3 次重试。
|
||
MaxRetryCount = 3
|
||
|
||
// HeaderSourceQueue 记录消息来自哪个队列。
|
||
HeaderSourceQueue = "x-vloop-source-queue"
|
||
// HeaderAttempts 记录停泊时已经用掉的尝试次数。
|
||
HeaderAttempts = "x-vloop-attempts"
|
||
// HeaderLastError 记录最后一次失败原因,截断到 512 字节。
|
||
HeaderLastError = "x-vloop-last-error"
|
||
|
||
// parkTimeout 是一次停泊操作的硬上限。
|
||
parkTimeout = 5 * time.Second
|
||
)
|
||
|
||
// parkRequeueBackoff 是停泊失败后退回 requeue 之前的退避。
|
||
//
|
||
// 变量而非常量:单测把它压到毫秒级,否则"退避确实发生了"这条断言会让每次跑测试多等一秒。
|
||
var parkRequeueBackoff = time.Second
|
||
|
||
// MaxAttempts 是一次投递被允许的最大尝试次数。
|
||
const MaxAttempts = MaxRetryCount + 1
|
||
|
||
// DefaultRetryDelay 是重试队列的队列级 TTL。
|
||
const DefaultRetryDelay = 5 * time.Second
|
||
|
||
// RetryExchange 返回某队列专属的重试交换机名。
|
||
func RetryExchange(queue string) string { return RetryExchangePrefix + queue }
|
||
|
||
// RetryQueueName 返回某队列专属的重试队列名。
|
||
func RetryQueueName(queue string) string { return queue + RetryQueueSuffix }
|
||
|
||
// declareParking 声明停泊链路:DLX 交换机、唯一停泊队列、parked.# 绑定。
|
||
func declareParking(d declarer) error {
|
||
if d == nil {
|
||
return fmt.Errorf("declare park: no declarer")
|
||
}
|
||
if err := d.ExchangeDeclare(DLXExchange, "topic", true, false, false, false, nil); err != nil {
|
||
return fmt.Errorf("declare park exchange %s: %w", DLXExchange, err)
|
||
}
|
||
if _, err := d.QueueDeclare(ParkedQueue, true, false, false, false, nil); err != nil {
|
||
return fmt.Errorf("declare park queue %s: %w", ParkedQueue, err)
|
||
}
|
||
if err := d.QueueBind(ParkedQueue, ParkedKeyPrefix+"#", DLXExchange, false, nil); err != nil {
|
||
return fmt.Errorf("bind park queue %s: %w", ParkedQueue, err)
|
||
}
|
||
log.Printf("DLX ready: exchange=%s queue=%s", DLXExchange, ParkedQueue)
|
||
return nil
|
||
}
|
||
|
||
// RetryArgs 装配业务队列,只把 DLX 指向本队列专属的重试交换机。
|
||
func RetryArgs(queue string) amqp.Table {
|
||
return amqp.Table{"x-dead-letter-exchange": RetryExchange(queue)}
|
||
}
|
||
|
||
// RetryQueueArgs 装配重试队列:队列级 TTL,到期经默认交换机精确回源。
|
||
func RetryQueueArgs(queue string, delay time.Duration) amqp.Table {
|
||
if delay <= 0 {
|
||
delay = DefaultRetryDelay
|
||
}
|
||
return amqp.Table{
|
||
"x-message-ttl": int64(delay / time.Millisecond),
|
||
"x-dead-letter-exchange": "",
|
||
"x-dead-letter-routing-key": queue,
|
||
}
|
||
}
|
||
|
||
// GetRetryCount 返回这条消息被拒绝过的次数,只统计 reason == "rejected"。
|
||
func GetRetryCount(d amqp.Delivery) int {
|
||
deaths, ok := d.Headers["x-death"].([]interface{})
|
||
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,lib 在不同路径上给出不同宽度。
|
||
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
|
||
}
|
||
}
|
||
|
||
// ParkedInfo 是一条停泊消息的自描述信息。
|
||
type ParkedInfo struct {
|
||
SourceQueue string
|
||
Attempts int
|
||
LastError string
|
||
EventID string
|
||
}
|
||
|
||
// ParseParkedInfo 从停泊消息上还原来源与失败原因,header 缺失时从路由键反推。
|
||
func ParseParkedInfo(d amqp.Delivery) ParkedInfo {
|
||
info := ParkedInfo{EventID: EventIDOf(d.Body), Attempts: 1}
|
||
if d.Headers != nil {
|
||
info.SourceQueue = stringField(d.Headers[HeaderSourceQueue])
|
||
if n := intField(d.Headers[HeaderAttempts]); n > 0 {
|
||
info.Attempts = n
|
||
}
|
||
info.LastError = stringField(d.Headers[HeaderLastError])
|
||
}
|
||
if info.SourceQueue == "" {
|
||
info.SourceQueue = sourceQueueFromParkedKey(d.RoutingKey)
|
||
}
|
||
return info
|
||
}
|
||
|
||
// EventIDOf 只解析 event_id 一个字段,解析失败返回空串。
|
||
func EventIDOf(body []byte) string {
|
||
var probe struct {
|
||
EventID string `json:"event_id"`
|
||
}
|
||
if err := json.Unmarshal(body, &probe); err != nil {
|
||
return ""
|
||
}
|
||
return probe.EventID
|
||
}
|
||
|
||
func stringField(v any) string {
|
||
if s, ok := v.(string); ok {
|
||
return s
|
||
}
|
||
return ""
|
||
}
|
||
|
||
func sourceQueueFromParkedKey(key string) string {
|
||
return strings.TrimPrefix(key, ParkedKeyPrefix)
|
||
}
|
||
|
||
// PermanentError 标记"重试也不会成功"的失败。
|
||
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 标记过。
|
||
func IsPermanent(err error) bool {
|
||
var p *PermanentError
|
||
return errors.As(err, &p)
|
||
}
|
||
|
||
// Disposition 是一条消息处理完之后该做什么。
|
||
type Disposition int
|
||
|
||
const (
|
||
// DispositionAck 表示处理成功。
|
||
DispositionAck Disposition = iota
|
||
// DispositionRetry 表示可重试失败,交给重试队列。
|
||
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 报告这条消息的尝试次数是否已经用完。
|
||
func Exhausted(d amqp.Delivery, maxAttempts int) bool {
|
||
if maxAttempts <= 0 {
|
||
maxAttempts = MaxAttempts
|
||
}
|
||
return GetRetryCount(d)+1 >= maxAttempts
|
||
}
|
||
|
||
// Decide 是重试策略的唯一定义点:输入一次处理结果,输出该做什么。
|
||
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 处置。
|
||
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 失败只记日志。
|
||
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 才会进重试队列吃 TTL;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。
|
||
func parkOrRequeue(ctx context.Context, parker Parker, queue string, d amqp.Delivery, attempts int, cause error) {
|
||
if parker == nil {
|
||
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)
|
||
}
|
||
}
|