2026-04-25 15:54:55 +08:00
|
|
|
|
package rabbitmq
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2026-10-30 15:16:17 +08:00
|
|
|
|
"context"
|
2026-10-30 13:12:38 +08:00
|
|
|
|
"encoding/json"
|
2026-10-30 15:16:17 +08:00
|
|
|
|
"errors"
|
2026-10-30 13:12:38 +08:00
|
|
|
|
"fmt"
|
2026-04-25 15:54:55 +08:00
|
|
|
|
"log"
|
2026-10-30 13:12:38 +08:00
|
|
|
|
"strings"
|
|
|
|
|
|
"time"
|
2026-04-25 15:54:55 +08:00
|
|
|
|
|
|
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
const (
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// DLXExchange 是停泊专用交换机。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
DLXExchange = "dlx.events"
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// ParkedQueue 是唯一的停泊队列,由 FailedEventWorker 落库到 failed_events。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
ParkedQueue = "failed.events"
|
|
|
|
|
|
// ParkedKeyPrefix 后接源队列名,构成停泊路由键 parked.<queue>。
|
|
|
|
|
|
ParkedKeyPrefix = "parked."
|
|
|
|
|
|
// RetryExchangePrefix 让每个业务队列有独立的重试入口。
|
|
|
|
|
|
RetryExchangePrefix = "retry.events."
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// RetryQueueSuffix 让每个业务队列有独立的延迟队列。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
RetryQueueSuffix = ".retry"
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// MaxRetryCount 与既有行为一致:首次投递 + 3 次重试。
|
2026-04-25 15:54:55 +08:00
|
|
|
|
MaxRetryCount = 3
|
2026-10-30 13:12:38 +08:00
|
|
|
|
|
|
|
|
|
|
// HeaderSourceQueue 记录消息来自哪个队列。
|
|
|
|
|
|
HeaderSourceQueue = "x-vloop-source-queue"
|
|
|
|
|
|
// HeaderAttempts 记录停泊时已经用掉的尝试次数。
|
|
|
|
|
|
HeaderAttempts = "x-vloop-attempts"
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// HeaderLastError 记录最后一次失败原因,截断到 512 字节。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
HeaderLastError = "x-vloop-last-error"
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// parkTimeout 是一次停泊操作的硬上限。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
parkTimeout = 5 * time.Second
|
2026-04-25 15:54:55 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// parkRequeueBackoff 是停泊失败后退回 requeue 之前的退避。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
//
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// 变量而非常量:单测把它压到毫秒级,否则"退避确实发生了"这条断言会让每次跑测试多等一秒。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
var parkRequeueBackoff = time.Second
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// MaxAttempts 是一次投递被允许的最大尝试次数。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
const MaxAttempts = MaxRetryCount + 1
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// DefaultRetryDelay 是重试队列的队列级 TTL。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
const DefaultRetryDelay = 5 * time.Second
|
|
|
|
|
|
|
|
|
|
|
|
// RetryExchange 返回某队列专属的重试交换机名。
|
|
|
|
|
|
func RetryExchange(queue string) string { return RetryExchangePrefix + queue }
|
|
|
|
|
|
|
|
|
|
|
|
// RetryQueueName 返回某队列专属的重试队列名。
|
|
|
|
|
|
func RetryQueueName(queue string) string { return queue + RetryQueueSuffix }
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// declareParking 声明停泊链路:DLX 交换机、唯一停泊队列、parked.# 绑定。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// RetryArgs 装配业务队列,只把 DLX 指向本队列专属的重试交换机。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
func RetryArgs(queue string) amqp.Table {
|
|
|
|
|
|
return amqp.Table{"x-dead-letter-exchange": RetryExchange(queue)}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// RetryQueueArgs 装配重试队列:队列级 TTL,到期经默认交换机精确回源。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
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,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// GetRetryCount 返回这条消息被拒绝过的次数,只统计 reason == "rejected"。
|
2026-04-25 15:54:55 +08:00
|
|
|
|
func GetRetryCount(d amqp.Delivery) int {
|
|
|
|
|
|
deaths, ok := d.Headers["x-death"].([]interface{})
|
|
|
|
|
|
if !ok {
|
|
|
|
|
|
return 0
|
|
|
|
|
|
}
|
2026-10-30 13:12:05 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// intField 把 AMQP table 里的整数值统一成 int,lib 在不同路径上给出不同宽度。
|
2026-10-30 13:12:05 +08:00
|
|
|
|
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:
|
2026-04-25 15:54:55 +08:00
|
|
|
|
return 0
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-10-30 13:12:38 +08:00
|
|
|
|
|
|
|
|
|
|
// ParkedInfo 是一条停泊消息的自描述信息。
|
|
|
|
|
|
type ParkedInfo struct {
|
|
|
|
|
|
SourceQueue string
|
|
|
|
|
|
Attempts int
|
|
|
|
|
|
LastError string
|
|
|
|
|
|
EventID string
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// ParseParkedInfo 从停泊消息上还原来源与失败原因,header 缺失时从路由键反推。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// EventIDOf 只解析 event_id 一个字段,解析失败返回空串。
|
2026-10-30 13:12:38 +08:00
|
|
|
|
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)
|
|
|
|
|
|
}
|
2026-10-30 15:16:17 +08:00
|
|
|
|
|
|
|
|
|
|
// PermanentError 标记"重试也不会成功"的失败。
|
|
|
|
|
|
type PermanentError struct {
|
|
|
|
|
|
Err error
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (e *PermanentError) Error() string { return e.Err.Error() }
|
|
|
|
|
|
|
|
|
|
|
|
func (e *PermanentError) Unwrap() error { return e.Err }
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// Permanent 把错误标记为不可重试,nil 原样返回,已标记的不重复包装。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
func Permanent(err error) error {
|
|
|
|
|
|
if err == nil {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
if IsPermanent(err) {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
return &PermanentError{Err: err}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// IsPermanent 判断错误是否被 Permanent 标记过。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
func IsPermanent(err error) bool {
|
|
|
|
|
|
var p *PermanentError
|
|
|
|
|
|
return errors.As(err, &p)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Disposition 是一条消息处理完之后该做什么。
|
|
|
|
|
|
type Disposition int
|
|
|
|
|
|
|
|
|
|
|
|
const (
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// DispositionAck 表示处理成功。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
DispositionAck Disposition = iota
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// DispositionRetry 表示可重试失败,交给重试队列。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
DispositionRetry
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// DispositionPark 表示预算耗尽或不可重试,落到停泊队列。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// ConsumeLoop 是全项目唯一的消费循环:取消息、调用 process、按 Decide 处置。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
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 {
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// channel 被关闭:交给 RunConsumer 重建。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
handleOne(ctx, parker, queue, maxAttempts, d, process)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// handleOne 处置一条消息,Ack/Nack 失败只记日志。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
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)
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// requeue=false 才会进重试队列吃 TTL;true 会立刻重投,等于没有退避。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
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)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// parkOrRequeue 停泊一条消息,停泊失败时退避后 requeue。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
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)
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// 退避后再重投:停泊链路故障时 Park 会立刻失败,不退避就是热循环。
|
2026-10-30 15:16:17 +08:00
|
|
|
|
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)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|