style(backend): 清理消息失败处理路径的注释
注释搬家到 docs/design/message-failure-handling.md。 删除复述代码的注释、历史缺陷说明与批次编号。保留的类型断言、索引语义、声明顺序等约束已在文档中展开。 重写 dlx.go、topology.go、consumer.go 三个文件,其余文件只删注释。 唯一非注释改动是 topology.go 里两处 ExchangeDeclare 由多行压成单行,语义不变。 验证:go test -count=1 ./... 全绿。
This commit is contained in:
@@ -16,14 +16,8 @@ import (
|
||||
|
||||
// BuildDSN 组装 MySQL DSN。
|
||||
//
|
||||
// 抽成函数只是为了让"DSN 里有哪些参数"可被单测钉住——它看起来是纯配置,
|
||||
// 实际上承载着一个正确性前提:**不得开启 clientFoundRows**。
|
||||
//
|
||||
// clientFoundRows 会让 MySQL 在 UPDATE 未改动任何行时也报告 1 行受影响,
|
||||
// 而 P0-4 的判重依赖 RowsAffected==0 来识别"这条意图已经落过库"
|
||||
// (见 video.CommentRepository.CreateIdempotentWithPopularity)。一旦打开,
|
||||
// 重复写入会被当成首次写入,评论去重与热度门控同时静默失效——它不会报错,
|
||||
// 只会悄悄多出一行评论和一份热度。
|
||||
// 不得开启 clientFoundRows:它会让 UPDATE 未改动行时也报告 1 行受影响,
|
||||
// 而判重依赖 RowsAffected==0。
|
||||
func BuildDSN(dbcfg config.DatabaseConfig) string {
|
||||
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
dbcfg.User, dbcfg.Password, dbcfg.Host, dbcfg.Port, dbcfg.DBName)
|
||||
@@ -43,8 +37,7 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&account.Account{}, &video.Video{}, &video.Like{}, &video.Comment{},
|
||||
&social.Social{}, &video.OutboxMsg{}, &video.Tag{}, &video.VideoTag{},
|
||||
&message.Message{}, ¬ification.Notification{},
|
||||
// 停泊消息的落库表(P0-3)。它的写入方是 Worker 的 FailedEventWorker,
|
||||
// 但建表仍由 API 进程的 AutoMigrate 统一负责——建表入口只有一个。
|
||||
// 停泊消息的落库表;建表入口只有这一个。
|
||||
&failedevent.FailedEvent{},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
// Package failedevent 存放"处理不了的消息"的持久化记录。
|
||||
//
|
||||
// 独立成包而不是放进 worker:db.go 已经 import worker(为了 Notification),
|
||||
// 而 worker 又要 import failedevent(为了写库)。放进 worker 会形成
|
||||
// worker → failedevent → worker 的循环;独立包让依赖方向恒为 worker → failedevent。
|
||||
package failedevent
|
||||
|
||||
import "time"
|
||||
|
||||
// 停泊记录的处置状态。
|
||||
const (
|
||||
// StatusPending 表示这条失败事件还没有被人工/工具处理。
|
||||
// StatusPending 表示这条失败事件还没有被处理。
|
||||
StatusPending = "pending"
|
||||
// StatusReplayed 表示已经重放过。
|
||||
StatusReplayed = "replayed"
|
||||
@@ -20,8 +16,7 @@ const (
|
||||
// FailedEvent 是一条停泊消息的落库记录。
|
||||
type FailedEvent struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
// SourceQueue + EventID 构成复合唯一键:同一意图键的评论事件与热度事件
|
||||
// 来自两个不同的源队列,只用 event_id 去重会把它们误判成同一条。
|
||||
// SourceQueue + EventID 是复合唯一键:同一意图键的评论事件与热度事件来自不同源队列。
|
||||
SourceQueue string `gorm:"column:source_queue;type:varchar(100);not null;uniqueIndex:uk_failed_source_event,priority:1" json:"source_queue"`
|
||||
EventID *string `gorm:"column:event_id;type:varchar(64);uniqueIndex:uk_failed_source_event,priority:2" json:"event_id"`
|
||||
RoutingKey string `gorm:"column:routing_key;type:varchar(200)" json:"routing_key"`
|
||||
@@ -29,7 +24,7 @@ type FailedEvent struct {
|
||||
Body []byte `gorm:"column:body;type:mediumblob" json:"-"`
|
||||
Headers string `gorm:"column:headers;type:json" json:"-"`
|
||||
LastError string `gorm:"column:last_error;type:varchar(512)" json:"last_error"`
|
||||
// Status 取值见本包的 StatusPending / StatusReplayed / StatusDiscarded。
|
||||
|
||||
Status string `gorm:"column:status;type:varchar(20);default:'pending';index" json:"status"`
|
||||
ReplayCount int `gorm:"column:replay_count;default:0" json:"replay_count"`
|
||||
FirstFailedAt time.Time `gorm:"column:first_failed_at" json:"first_failed_at"`
|
||||
@@ -37,6 +32,5 @@ type FailedEvent struct {
|
||||
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName 固定表名:默认命名是 failed_events,但显式写出来可以避免
|
||||
// 有人把类型改名之后表名跟着漂移。
|
||||
// TableName 固定表名,避免类型改名后表名跟着漂移。
|
||||
func (FailedEvent) TableName() string { return "failed_events" }
|
||||
|
||||
@@ -18,12 +18,9 @@ func NewRepository(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
// Save 写入一条停泊记录,返回它是否是本次新插入的。
|
||||
// Save 写入一条停泊记录,返回是否是本次新插入的。
|
||||
//
|
||||
// 去重键是 (source_queue, event_id):重复投递同一条停泊消息(停泊成功但 Ack 前崩溃、
|
||||
// 或运维重放)只会留下一条记录。EventID 为 NULL 的消息不参与复合唯一键
|
||||
// ——MySQL 唯一索引里 NULL 不参与比较,多个 NULL 可以共存,这是有意的:
|
||||
// 没有意图键的坏消息本来就没有身份,去重无从谈起。
|
||||
// 去重键是 (source_queue, event_id);EventID 为 NULL 时不参与唯一索引,可多条共存。
|
||||
func (r *Repository) Save(ctx context.Context, e *FailedEvent) (bool, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return false, errors.New("failedevent: repository is not initialized")
|
||||
|
||||
@@ -9,15 +9,9 @@ import (
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// RunConsumer 在连接管理器上运行一个消费循环——全项目唯一的消费循环实现。
|
||||
//
|
||||
// 行为:
|
||||
// - 连接断开的整个期间,它阻塞在 mgr.WaitReady 上:不轮询、不打日志,
|
||||
// 从而不会被"每 5 秒一行"的噪声掩盖真正的错误;
|
||||
// - 连接恢复后,自动重建 channel、重新设置 QoS、重新执行 fn(即重新 Consume);
|
||||
// - 若 channel 因"连接仍健康"的原因失效(队列被删、声明参数冲突等),
|
||||
// 先重放一次拓扑再退避重试,覆盖 P0-2 之外的第二种永久卡死模式。
|
||||
// RunConsumer 在连接管理器上运行一个消费循环。
|
||||
//
|
||||
// 连接断开期间阻塞在 WaitReady;恢复后重建 channel、重设 QoS、重新 Consume。
|
||||
// fn 应在 deliveries channel 关闭或 ctx 取消时返回。
|
||||
func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int, fn func(*amqp.Channel) error) {
|
||||
if mgr == nil {
|
||||
@@ -32,9 +26,7 @@ func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int,
|
||||
opts := mgr.opts
|
||||
backoff := opts.MinBackoff
|
||||
|
||||
// 消费前先确保拓扑存在。这覆盖了"连接建立早于拓扑登记"的启动顺序:
|
||||
// 例如 API 进程先建立连接,再构造各 publisher/consumer 并登记拓扑,
|
||||
// 此时当前连接上还没有声明过任何队列。重连路径由 supervise 的 declareAll 覆盖。
|
||||
// 消费前先确保拓扑存在,覆盖"连接建立早于拓扑登记"的启动顺序。
|
||||
if err := mgr.EnsureTopology(ctx); err != nil && ctx.Err() == nil {
|
||||
log.Printf("%s: 初始拓扑声明失败: %v", name, err)
|
||||
}
|
||||
@@ -53,8 +45,7 @@ func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int,
|
||||
continue
|
||||
}
|
||||
|
||||
// QoS 是 channel 级状态,必须在【每次】重建 channel 后重新设置。
|
||||
// 切勿把它提到循环外——那样重连后会静默失去 prefetch 限制。
|
||||
// QoS 是 channel 级状态,每次重建 channel 后都必须重设。
|
||||
if prefetch > 0 {
|
||||
if err := sess.Ch.Qos(prefetch, 0, false); err != nil {
|
||||
log.Printf("%s: QoS 设置失败: %v", name, err)
|
||||
@@ -69,15 +60,8 @@ func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int,
|
||||
return
|
||||
}
|
||||
|
||||
// 把"channel 失效"分成两类:连接级失效 vs channel 级异常。
|
||||
//
|
||||
// 不能只用 sess.Done 判断:库在 shutdown 中是【先】派发 NotifyClose、
|
||||
// 【后】关闭所有 channel 的 deliveries(connection.go:600-641),而
|
||||
// supervise 处理 NotifyClose 还需要一次 goroutine 调度。因此 deliveries
|
||||
// 关闭的瞬间,sess.Done 往往【还没有】关闭——此时若按"连接仍健康"处理,
|
||||
// 就会打出一条误导日志("连接仍健康"其实连接刚死)并白白重放一次拓扑。
|
||||
// 直接复查连接状态既准确、又不依赖调度时序(shutdown 一开始就置位了
|
||||
// closed 标志,所以此刻 conn.IsClosed() 必为 true)。
|
||||
// 不能只看 sess.Done:库先派发 NotifyClose、后关闭 deliveries,
|
||||
// 那一瞬 sess.Done 往往还没关闭。直接复查连接状态更准确。
|
||||
connLost := false
|
||||
select {
|
||||
case <-sess.Done:
|
||||
@@ -87,8 +71,6 @@ func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int,
|
||||
}
|
||||
|
||||
if connLost {
|
||||
// 连接级失效:等新一代连接。断连/恢复已由 supervise 记录,
|
||||
// 这里刻意不打日志——8 个消费者各刷一行才是真正的噪声源。
|
||||
if err := mgr.WaitReady(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -96,7 +78,7 @@ func RunConsumer(ctx context.Context, mgr *RabbitMQ, name string, prefetch int,
|
||||
continue
|
||||
}
|
||||
|
||||
// 连接确实仍然健康 → channel 级异常(队列或绑定丢失、声明冲突等)
|
||||
// 连接仍健康 → channel 级异常(队列或绑定丢失、声明冲突等)
|
||||
if runErr != nil {
|
||||
log.Printf("%s: %v;连接仍健康,重放拓扑后重试", name, runErr)
|
||||
}
|
||||
|
||||
@@ -13,54 +13,40 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// DLXExchange 是停泊专用交换机(复用改造前就存在的那个名字)。
|
||||
// DLXExchange 是停泊专用交换机。
|
||||
DLXExchange = "dlx.events"
|
||||
// ParkedQueue 是唯一的停泊队列:项目里所有"处理不了"的消息最终都落到这里,
|
||||
// 由 FailedEventWorker 落库到 failed_events。
|
||||
// ParkedQueue 是唯一的停泊队列,由 FailedEventWorker 落库到 failed_events。
|
||||
ParkedQueue = "failed.events"
|
||||
// ParkedKeyPrefix 后接源队列名,构成停泊路由键 parked.<queue>。
|
||||
// 源队列由路由键带回,因此一条停泊消息能自证"我从哪来"。
|
||||
ParkedKeyPrefix = "parked."
|
||||
// RetryExchangePrefix 让每个业务队列有独立的重试入口。
|
||||
// 不能共用:like.events 与 notification.like 共享同一个业务交换机且路由键重叠,
|
||||
// 共用重试exchange 无法区分来源,会把消息重投到错误的队列。
|
||||
RetryExchangePrefix = "retry.events."
|
||||
// RetryQueueSuffix 让每个业务队列有独立的重试队列(TTL 到期后精确回源)。
|
||||
// RetryQueueSuffix 让每个业务队列有独立的延迟队列。
|
||||
RetryQueueSuffix = ".retry"
|
||||
|
||||
// MaxRetryCount 与既有行为保持一致:首次投递 + 3 次重试 = 4 次尝试。
|
||||
// MaxRetryCount 与既有行为一致:首次投递 + 3 次重试。
|
||||
MaxRetryCount = 3
|
||||
|
||||
// HeaderSourceQueue 记录消息来自哪个队列。
|
||||
HeaderSourceQueue = "x-vloop-source-queue"
|
||||
// HeaderAttempts 记录停泊时已经用掉的尝试次数。
|
||||
HeaderAttempts = "x-vloop-attempts"
|
||||
// HeaderLastError 记录最后一次处理失败的原因(截断到 512 字节)。
|
||||
// HeaderLastError 记录最后一次失败原因,截断到 512 字节。
|
||||
HeaderLastError = "x-vloop-last-error"
|
||||
|
||||
// parkTimeout 是"停泊一条消息"的硬上限:停泊是失败路径,
|
||||
// 它不能因为连接半死而把消费者的处理协程无限期占住。
|
||||
// parkTimeout 是一次停泊操作的硬上限。
|
||||
parkTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// parkRequeueBackoff 是"停泊失败后退回 requeue"之前的退避。
|
||||
// parkRequeueBackoff 是停泊失败后退回 requeue 之前的退避。
|
||||
//
|
||||
// 没有它,当 failed.events 缺失(或 dlx.events 被误删)时 Park 会快速失败:
|
||||
// mandatory 的 basic.return 立刻返回,Nack(requeue=true) 立刻重投,
|
||||
// 形成每秒上万次的热循环 + 日志洪泛。
|
||||
//
|
||||
// 是变量而不是常量:测试把它压到毫秒级,否则"退避确实发生了"这条断言
|
||||
// 会让每次跑测试都多等一秒。
|
||||
// 变量而非常量:单测把它压到毫秒级,否则"退避确实发生了"这条断言会让每次跑测试多等一秒。
|
||||
var parkRequeueBackoff = time.Second
|
||||
|
||||
// MaxAttempts 是一次投递被允许的最大尝试次数(首次 + 重试)。
|
||||
// MaxAttempts 是一次投递被允许的最大尝试次数。
|
||||
const MaxAttempts = MaxRetryCount + 1
|
||||
|
||||
// DefaultRetryDelay 是队列级 TTL。
|
||||
//
|
||||
// 用常量延迟而不是指数退避:指数退避需要客户端在每次拒绝时改写 x-message-ttl
|
||||
// (= 重发消息 = 又一个重复窗口),而队列级 TTL 让"重试"完全由 broker 完成,
|
||||
// 进程崩溃也不丢计数。
|
||||
// DefaultRetryDelay 是重试队列的队列级 TTL。
|
||||
const DefaultRetryDelay = 5 * time.Second
|
||||
|
||||
// RetryExchange 返回某队列专属的重试交换机名。
|
||||
@@ -69,14 +55,7 @@ func RetryExchange(queue string) string { return RetryExchangePrefix + queue }
|
||||
// RetryQueueName 返回某队列专属的重试队列名。
|
||||
func RetryQueueName(queue string) string { return queue + RetryQueueSuffix }
|
||||
|
||||
// declareParking 声明停泊链路:DLX 交换机 + 唯一停泊队列 + parked.# 绑定。
|
||||
//
|
||||
// 幂等,每代连接都会重放(P0-2 不变式)。停泊链路只有一个队列、一次绑定,
|
||||
// 因此一条死信只会产生【一份】记录。
|
||||
//
|
||||
// 历史:改造前每个业务队列都声明一个 <queue>.dlx,并且都以 "#" 绑定同一个
|
||||
// 交换机——topic 会把同一条死信扇出成 N 份。那条链路从未被触发过,
|
||||
// 因此缺陷一直没暴露。它已随重试链路一起被删除。
|
||||
// declareParking 声明停泊链路:DLX 交换机、唯一停泊队列、parked.# 绑定。
|
||||
func declareParking(d declarer) error {
|
||||
if d == nil {
|
||||
return fmt.Errorf("declare park: no declarer")
|
||||
@@ -90,31 +69,16 @@ func declareParking(d declarer) error {
|
||||
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 指向,不设 x-dead-letter-routing-key。
|
||||
//
|
||||
// 不设 routing key 的效果是"第 1 次被拒绝时保留原路由键"(like.like 仍是 like.like)。
|
||||
// 注意它只对第一次成立:回源那一步由 RetryQueueArgs 显式把路由键写成队列名,
|
||||
// 所以从第 2 次投递起 routingKey == 队列名。任何按 routingKey 分派的消费者
|
||||
// 都会因此失效——通知 worker 因此改为按队列 + body action 分派。
|
||||
// RetryArgs 装配业务队列,只把 DLX 指向本队列专属的重试交换机。
|
||||
func RetryArgs(queue string) amqp.Table {
|
||||
return amqp.Table{"x-dead-letter-exchange": RetryExchange(queue)}
|
||||
}
|
||||
|
||||
// RetryQueueArgs 装配重试队列:队列级 TTL + 回源到默认交换机。
|
||||
//
|
||||
// 队列级(而不是消息级)TTL 的理由:classic queue 只在【队首】检查过期,
|
||||
// 队列级 TTL 保证队首一定是最早入队的,因此不会出现"队首还没过期、
|
||||
// 后面的消息已经过期"的队头阻塞。代价是延迟是个常量。
|
||||
//
|
||||
// x-dead-letter-exchange 显式写 "":空串就是默认交换机。
|
||||
// x-dead-letter-routing-key 写队列名:默认交换机按队列名精确投递,
|
||||
// 这就是"不经过业务交换机、不可能扇出"的实现。
|
||||
// RetryQueueArgs 装配重试队列:队列级 TTL,到期经默认交换机精确回源。
|
||||
func RetryQueueArgs(queue string, delay time.Duration) amqp.Table {
|
||||
if delay <= 0 {
|
||||
delay = DefaultRetryDelay
|
||||
@@ -126,12 +90,7 @@ func RetryQueueArgs(queue string, delay time.Duration) amqp.Table {
|
||||
}
|
||||
}
|
||||
|
||||
// GetRetryCount 返回这条消息被【拒绝过】的次数。
|
||||
//
|
||||
// 两个坑:
|
||||
// 1. 不读 deaths[0]。真实链路里最新一条往往是重试队列的 "expired"(TTL 到期),
|
||||
// 那是"延迟结束",不是"处理失败"。只数 reason == "rejected"。
|
||||
// 2. 不假定 count 是 int64。amqp091-go 在不同路径上会给出 int32/int64/float64。
|
||||
// GetRetryCount 返回这条消息被拒绝过的次数,只统计 reason == "rejected"。
|
||||
func GetRetryCount(d amqp.Delivery) int {
|
||||
deaths, ok := d.Headers["x-death"].([]interface{})
|
||||
if !ok {
|
||||
@@ -151,7 +110,7 @@ func GetRetryCount(d amqp.Delivery) int {
|
||||
return total
|
||||
}
|
||||
|
||||
// intField 把 AMQP table 里的整数值统一成 int(库在不同路径上给出不同宽度)。
|
||||
// intField 把 AMQP table 里的整数值统一成 int,lib 在不同路径上给出不同宽度。
|
||||
func intField(v any) int {
|
||||
switch n := v.(type) {
|
||||
case int:
|
||||
@@ -179,7 +138,7 @@ type ParkedInfo struct {
|
||||
EventID string
|
||||
}
|
||||
|
||||
// ParseParkedInfo 从停泊消息上还原来源与失败原因。
|
||||
// ParseParkedInfo 从停泊消息上还原来源与失败原因,header 缺失时从路由键反推。
|
||||
func ParseParkedInfo(d amqp.Delivery) ParkedInfo {
|
||||
info := ParkedInfo{EventID: EventIDOf(d.Body), Attempts: 1}
|
||||
if d.Headers != nil {
|
||||
@@ -190,14 +149,12 @@ func ParseParkedInfo(d amqp.Delivery) ParkedInfo {
|
||||
info.LastError = stringField(d.Headers[HeaderLastError])
|
||||
}
|
||||
if info.SourceQueue == "" {
|
||||
// 兜底:从 parked.<queue> 反推。两条来源互为校验。
|
||||
info.SourceQueue = sourceQueueFromParkedKey(d.RoutingKey)
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// EventIDOf 只解析 event_id 一个字段,避免为取一个键而反序列化整条消息。
|
||||
// 解析失败返回 ""(坏消息没有意图键,落库时写 NULL)。
|
||||
// EventIDOf 只解析 event_id 一个字段,解析失败返回空串。
|
||||
func EventIDOf(body []byte) string {
|
||||
var probe struct {
|
||||
EventID string `json:"event_id"`
|
||||
@@ -219,12 +176,7 @@ func sourceQueueFromParkedKey(key string) string {
|
||||
return strings.TrimPrefix(key, ParkedKeyPrefix)
|
||||
}
|
||||
|
||||
// —— 重试/停泊策略 ——
|
||||
|
||||
// PermanentError 标记"重试也不会成功"的失败。
|
||||
//
|
||||
// 典型来源:消息体不是合法 JSON、字段非法、未知的 action。
|
||||
// 这类消息每重投一次就必然再失败一次,重试只是把毒消息在队列里多放 15 秒。
|
||||
type PermanentError struct {
|
||||
Err error
|
||||
}
|
||||
@@ -233,7 +185,7 @@ func (e *PermanentError) Error() string { return e.Err.Error() }
|
||||
|
||||
func (e *PermanentError) Unwrap() error { return e.Err }
|
||||
|
||||
// Permanent 把错误标记为不可重试。nil 原样返回,已标记的不重复包装。
|
||||
// Permanent 把错误标记为不可重试,nil 原样返回,已标记的不重复包装。
|
||||
func Permanent(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
@@ -244,7 +196,7 @@ func Permanent(err error) error {
|
||||
return &PermanentError{Err: err}
|
||||
}
|
||||
|
||||
// IsPermanent 判断错误是否被 Permanent 标记过(支持 errors.Is/As 链)。
|
||||
// IsPermanent 判断错误是否被 Permanent 标记过。
|
||||
func IsPermanent(err error) bool {
|
||||
var p *PermanentError
|
||||
return errors.As(err, &p)
|
||||
@@ -254,11 +206,11 @@ func IsPermanent(err error) bool {
|
||||
type Disposition int
|
||||
|
||||
const (
|
||||
// DispositionAck 表示处理成功:Ack,消息结束。
|
||||
// DispositionAck 表示处理成功。
|
||||
DispositionAck Disposition = iota
|
||||
// DispositionRetry 表示可重试失败:Nack(requeue=false),交给重试队列。
|
||||
// DispositionRetry 表示可重试失败,交给重试队列。
|
||||
DispositionRetry
|
||||
// DispositionPark 表示重试预算已用尽或不可重试:落到停泊队列。
|
||||
// DispositionPark 表示预算耗尽或不可重试,落到停泊队列。
|
||||
DispositionPark
|
||||
)
|
||||
|
||||
@@ -276,9 +228,6 @@ func (d Disposition) String() string {
|
||||
}
|
||||
|
||||
// Exhausted 报告这条消息的尝试次数是否已经用完。
|
||||
//
|
||||
// 单独抽出来是为了留一道安全网:一条被 requeue 回来的消息可能已经超过预算
|
||||
// (例如上一轮停泊失败),此时无论下一个错误是什么都不该再重试。
|
||||
func Exhausted(d amqp.Delivery, maxAttempts int) bool {
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = MaxAttempts
|
||||
@@ -287,10 +236,6 @@ func Exhausted(d amqp.Delivery, maxAttempts int) bool {
|
||||
}
|
||||
|
||||
// Decide 是重试策略的唯一定义点:输入一次处理结果,输出该做什么。
|
||||
//
|
||||
// 它是纯函数,因此"第几次失败会停泊"这类问题可以完全用表驱动测试锁住,
|
||||
// 而不需要连 broker。五个消费者共用这一个判断,不会再出现"五份拷贝里
|
||||
// 有一份永远走不到"的情况。
|
||||
func Decide(d amqp.Delivery, maxAttempts int, err error) Disposition {
|
||||
if err == nil {
|
||||
return DispositionAck
|
||||
@@ -301,16 +246,7 @@ func Decide(d amqp.Delivery, maxAttempts int, err error) Disposition {
|
||||
return DispositionRetry
|
||||
}
|
||||
|
||||
// ConsumeLoop 是全项目唯一的消费循环。
|
||||
//
|
||||
// 它只做三件事:取消息、调用 process、按 Decide 的结果处置。策略(重试几次、
|
||||
// 什么时候停泊)在 Decide 里,业务在 process 里,两者都不在这里。
|
||||
//
|
||||
// 与改造前的区别,逐条对应 P0-3 的根因:
|
||||
// - 重试不再 time.Sleep:Nack 之后由重试队列的 TTL 决定延迟,
|
||||
// 消费协程立刻处理下一条,队列不会被一条坏消息堵住(D3)。
|
||||
// - 重试计数来自 broker 的 x-death,进程不存任何状态,重启不丢计数(D2)。
|
||||
// - 预算是用尽后 Nack 到停泊队列,而不是 Ack 丢弃(D1)。
|
||||
// ConsumeLoop 是全项目唯一的消费循环:取消息、调用 process、按 Decide 处置。
|
||||
func ConsumeLoop(
|
||||
ctx context.Context,
|
||||
ch *amqp.Channel,
|
||||
@@ -343,7 +279,7 @@ func ConsumeLoop(
|
||||
return nil
|
||||
case d, ok := <-deliveries:
|
||||
if !ok {
|
||||
// channel 被关闭(连接换代或队列被删):交给 RunConsumer 重建。
|
||||
// channel 被关闭:交给 RunConsumer 重建。
|
||||
return nil
|
||||
}
|
||||
handleOne(ctx, parker, queue, maxAttempts, d, process)
|
||||
@@ -351,8 +287,7 @@ func ConsumeLoop(
|
||||
}
|
||||
}
|
||||
|
||||
// handleOne 处置一条消息。Ack/Nack 失败只记日志:消息要么已经离开队列,
|
||||
// 要么会被 broker 重投,两种情况下再冒泡一个错误都没有额外价值。
|
||||
// handleOne 处置一条消息,Ack/Nack 失败只记日志。
|
||||
func handleOne(
|
||||
ctx context.Context,
|
||||
parker Parker,
|
||||
@@ -371,8 +306,7 @@ func handleOne(
|
||||
}
|
||||
case DispositionRetry:
|
||||
log.Printf("consume: 处理失败将重试 queue=%s attempts=%d/%d err=%v", queue, attempts, maxAttempts, err)
|
||||
// requeue=false:让 broker 把消息交给本队列的重试交换机,
|
||||
// 由重试队列的 TTL 决定延迟。requeue=true 会立刻重投,等于没有退避。
|
||||
// requeue=false 才会进重试队列吃 TTL;true 会立刻重投,等于没有退避。
|
||||
if nackErr := d.Nack(false, false); nackErr != nil {
|
||||
log.Printf("consume: nack 失败 queue=%s err=%v", queue, nackErr)
|
||||
}
|
||||
@@ -381,14 +315,9 @@ func handleOne(
|
||||
}
|
||||
}
|
||||
|
||||
// parkOrRequeue 停泊一条消息,并在停泊失败时退回 requeue。
|
||||
//
|
||||
// 顺序不可换:先确认停泊成功,再 Ack 原消息(G6)。反过来的话,
|
||||
// 停泊失败就等于"原消息被删、停泊消息没进队列",正是要修的那种静默丢失。
|
||||
// parkOrRequeue 停泊一条消息,停泊失败时退避后 requeue。
|
||||
func parkOrRequeue(ctx context.Context, parker Parker, queue string, d amqp.Delivery, attempts int, cause error) {
|
||||
if parker == nil {
|
||||
// 没有 parker 的进程(未接线或测试)宁可把消息留在队列里反复重投,
|
||||
// 也不能 Ack——Ack 就是丢弃。
|
||||
log.Printf("consume: 无 parker,退回 requeue queue=%s attempts=%d err=%v", queue, attempts, cause)
|
||||
if !sleepCtx(ctx, parkRequeueBackoff) {
|
||||
return
|
||||
@@ -404,8 +333,7 @@ func parkOrRequeue(ctx context.Context, parker Parker, queue string, d amqp.Deli
|
||||
|
||||
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 会立刻
|
||||
// 失败,不退避就是一个每秒上万次的热循环。
|
||||
// 退避后再重投:停泊链路故障时 Park 会立刻失败,不退避就是热循环。
|
||||
if !sleepCtx(ctx, parkRequeueBackoff) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -401,9 +401,7 @@ func (r *RabbitMQ) RegisterTopology(topo ...Topology) {
|
||||
continue
|
||||
}
|
||||
if existing, ok := findTopology(r.topology, t); ok {
|
||||
// 去重键是 (Exchange, Queue, BindingKey):同一条线缆契约只声明一次。
|
||||
// RetryDelay 刻意不参与——同一队列登记两种延迟会产生两次不等价的
|
||||
// queue declare,broker 回 406,而重放失败会让这一代连接不 install。
|
||||
// RetryDelay 不参与去重:同一队列两种延迟会产生两次不等价声明(406)。
|
||||
if existing.RetryDelay != t.RetryDelay {
|
||||
log.Printf("rabbitmq: 拓扑 %s/%s 已登记,忽略重复登记的 RetryDelay=%v(保留 %v)",
|
||||
t.Exchange, t.Queue, t.RetryDelay, existing.RetryDelay)
|
||||
@@ -552,19 +550,12 @@ func (r *RabbitMQ) PublishJSON(ctx context.Context, exchange string, routingKey
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parker 由连接管理器实现。抽成接口是为了让消费循环可以在没有 broker 的
|
||||
// 单测里被验证:停泊失败必须 requeue,而不是 Ack 掉。
|
||||
// Parker 由连接管理器实现,抽成接口是为了在没有 broker 的单测里验证停泊失败必须 requeue。
|
||||
type Parker interface {
|
||||
Park(ctx context.Context, sourceQueue string, d amqp.Delivery, attempts int, cause error) error
|
||||
}
|
||||
|
||||
// Park 把一条无法处理的消息停泊到 failed.events。
|
||||
//
|
||||
// 必须「先确认、后 Ack」:
|
||||
// - Confirm(false) + NotifyPublish:等到 broker 确认收到;
|
||||
// - Mandatory=true + NotifyReturn:消息路由不到队列时立刻报错,而不是静默丢弃;
|
||||
// - 逐字段构造 Publishing:不复用 d.Publishing,避免把 per-message Expiration
|
||||
// 带过去让停泊消息自己过期(那会让 failed.events 变成"又一个会消失的地方")。
|
||||
// Park 把一条无法处理的消息停泊到 failed.events,调用方须在返回 nil 后才 Ack 原消息。
|
||||
func (r *RabbitMQ) Park(ctx context.Context, sourceQueue string, d amqp.Delivery, attempts int, cause error) error {
|
||||
if r == nil {
|
||||
return errors.New("rabbitmq manager is nil")
|
||||
@@ -615,8 +606,7 @@ func (r *RabbitMQ) Park(ctx context.Context, sourceQueue string, d amqp.Delivery
|
||||
if !ok || !c.Ack {
|
||||
return errors.New("park: broker rejected the message (nack)")
|
||||
}
|
||||
// broker 的顺序是 basic.return 先于 basic.ack。所以确认之后要
|
||||
// 非阻塞地复查一次 return:有 return 说明这条消息根本没路由到队列。
|
||||
// broker 先发 basic.return 再发 basic.ack,确认后需非阻塞复查一次。
|
||||
select {
|
||||
case ret := <-returns:
|
||||
return fmt.Errorf("park: unroutable code=%d text=%q", ret.ReplyCode, ret.ReplyText)
|
||||
@@ -672,10 +662,7 @@ func closeIfOpen(ch chan struct{}) {
|
||||
}
|
||||
}
|
||||
|
||||
// findTopology 按 (Exchange, Queue, BindingKey) 三元组查找已登记的拓扑。
|
||||
//
|
||||
// 刻意不用结构体全等:那样 RetryDelay 会参与比较,同一队列的两种延迟
|
||||
// 就会被当成两条不同拓扑登记,随后产生两次不等价声明。
|
||||
// findTopology 按 (Exchange, Queue, BindingKey) 三元组查找已登记的拓扑,RetryDelay 不参与比较。
|
||||
func findTopology(list []Topology, t Topology) (Topology, bool) {
|
||||
for _, x := range list {
|
||||
if x.Exchange == t.Exchange && x.Queue == t.Queue && x.BindingKey == t.BindingKey {
|
||||
|
||||
@@ -9,47 +9,24 @@ import (
|
||||
)
|
||||
|
||||
// Topology 描述一组"交换机 + 队列 + 绑定键",是可重复声明的幂等单元。
|
||||
//
|
||||
// 连接管理器会在每一代连接上重放已登记的拓扑,因此 broker 侧拓扑丢失
|
||||
// (数据卷重建、队列被手工删除、集群节点替换)之后也能自动恢复——
|
||||
// 这一条与"连接重连"同等重要:只重连不重放拓扑,
|
||||
// 会退化为"连接健康但队列不存在"的 404 死循环。
|
||||
type Topology struct {
|
||||
Exchange string
|
||||
Queue string
|
||||
BindingKey string
|
||||
// RetryDelay 是本队列专属重试队列的 TTL,零值取 DefaultRetryDelay。
|
||||
//
|
||||
// 它【不参与】拓扑去重:同一队列登记两种延迟会产生两次不等价的
|
||||
// queue declare,broker 回 406,而重放失败意味着这一代连接不 install。
|
||||
// RetryDelay 是本队列重试队列的 TTL,零值取 DefaultRetryDelay;不参与去重。
|
||||
RetryDelay time.Duration
|
||||
}
|
||||
|
||||
// declarer 是 *amqp.Channel 上拓扑声明所需方法的最小集合。
|
||||
//
|
||||
// 抽出接口的唯一目的是可测性:声明顺序与 DLX 参数是"重构时最容易静默丢失"
|
||||
// 的两件事,有了它就能在没有 broker 的情况下断言它们。
|
||||
// declarer 是拓扑声明所需方法的最小集合,抽出接口只为可测性。
|
||||
type declarer interface {
|
||||
ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error
|
||||
QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error)
|
||||
QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error
|
||||
}
|
||||
|
||||
// DeclareTopology 声明一组拓扑:交换机 → 重试交换机 → 业务队列 → 绑定 →
|
||||
// 重试队列 → 重试绑定。
|
||||
// DeclareTopology 按固定顺序声明一组拓扑。
|
||||
//
|
||||
// 顺序不可换:业务队列被拒绝的那一刻必须能找到一个已存在的 DLX,
|
||||
// 否则 broker 直接丢弃消息,只在日志里留一行 warning。因此重试交换机
|
||||
// 声明在业务队列之前。
|
||||
//
|
||||
// 每个队列有独立的重试交换机(retry.events.<Q>)与重试队列(<Q>.retry)。
|
||||
// 共享一个重试入口是不行的:like.events 与 notification.like 共享业务
|
||||
// 交换机且路由键重叠,从共享入口回来无法区分来源。评论侧更糟——
|
||||
// notification.comment 的重试落回 comment.events 会再插一条评论。
|
||||
//
|
||||
// 注意:d 为 nil 的判断只能拦住"nil 接口"。若调用方传入类型化的 nil
|
||||
// (如 var ch *amqp.Channel = nil),此处无法识别——因此 *amqp.Channel
|
||||
// 的入口(DeclareTopic)保留了自己的 nil 检查。
|
||||
// 顺序不可换:业务队列被拒绝时必须能找到一个已存在的 DLX,否则 broker 直接丢弃消息。
|
||||
func DeclareTopology(d declarer, t Topology) error {
|
||||
if d == nil {
|
||||
return errors.New("channel is not initialized")
|
||||
@@ -59,86 +36,42 @@ func DeclareTopology(d declarer, t Topology) error {
|
||||
}
|
||||
|
||||
// 1. 业务交换机
|
||||
if err := d.ExchangeDeclare(
|
||||
t.Exchange,
|
||||
"topic",
|
||||
true, // durable
|
||||
false, // autoDelete
|
||||
false, // internal
|
||||
false, // noWait
|
||||
nil,
|
||||
); err != nil {
|
||||
if err := d.ExchangeDeclare(t.Exchange, "topic", true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. 本队列专属的重试交换机,必须先于业务队列
|
||||
retryExchange := RetryExchange(t.Queue)
|
||||
if err := d.ExchangeDeclare(
|
||||
retryExchange,
|
||||
"topic",
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
); err != nil {
|
||||
if err := d.ExchangeDeclare(retryExchange, "topic", true, false, false, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. 业务队列:DLX 指向重试交换机,不设 routing-key
|
||||
q, err := d.QueueDeclare(
|
||||
t.Queue,
|
||||
true, // durable
|
||||
false, // autoDelete
|
||||
false, // exclusive
|
||||
false, // noWait
|
||||
RetryArgs(t.Queue),
|
||||
)
|
||||
// 3. 业务队列:DLX 指向重试交换机
|
||||
q, err := d.QueueDeclare(t.Queue, true, false, false, false, RetryArgs(t.Queue))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. 业务绑定
|
||||
if err := d.QueueBind(
|
||||
q.Name,
|
||||
t.BindingKey,
|
||||
t.Exchange,
|
||||
false, // noWait
|
||||
nil,
|
||||
); err != nil {
|
||||
if err := d.QueueBind(q.Name, t.BindingKey, t.Exchange, false, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 5. 重试队列:没有消费者,消息靠 TTL 到期经默认交换机精确回源
|
||||
// 5. 重试队列:没有消费者,靠 TTL 到期经默认交换机回源
|
||||
delay := t.RetryDelay
|
||||
if delay <= 0 {
|
||||
delay = DefaultRetryDelay
|
||||
}
|
||||
rq, err := d.QueueDeclare(
|
||||
RetryQueueName(t.Queue),
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
RetryQueueArgs(t.Queue, delay),
|
||||
)
|
||||
rq, err := d.QueueDeclare(RetryQueueName(t.Queue), true, false, false, false, RetryQueueArgs(t.Queue, delay))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 6. 重试队列绑定到重试交换机。路由键用通配:第 1 次被拒时保留的
|
||||
// 是原路由键(like.like、like.unlike 都可能),一条 # 绑定覆盖全部。
|
||||
// 6. 重试绑定:第 1 次被拒时保留的是原路由键,一条 # 绑定覆盖全部
|
||||
return d.QueueBind(rq.Name, "#", retryExchange, false, nil)
|
||||
}
|
||||
|
||||
// DeclareTopologies 先声明停泊链路,再逐个声明业务拓扑。
|
||||
//
|
||||
// 顺序理由:业务队列被拒绝时,消息要立刻有地方可去——停泊链路晚一步,
|
||||
// 那段时间里 broker 会直接丢弃,而 worker 以为自己已经处理完了。
|
||||
//
|
||||
// 前提:调用方至少登记了一条业务拓扑(两个二进制都登记 ≥3 条)。
|
||||
// rabbitMQ.go 的 declareAll 在 len(topo)==0 时会提前返回,
|
||||
// 那种情况下这里的 declareParking 不会被执行。
|
||||
func DeclareTopologies(d declarer, topo []Topology) error {
|
||||
if err := declareParking(d); err != nil {
|
||||
return fmt.Errorf("declare parking: %w", err)
|
||||
@@ -151,7 +84,7 @@ func DeclareTopologies(d declarer, topo []Topology) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeclareTopic 保留原有签名,既有调用点无需改动。
|
||||
// DeclareTopic 保留原有签名。
|
||||
func DeclareTopic(ch *amqp.Channel, exchange string, queue string, bindingKey string) error {
|
||||
if ch == nil {
|
||||
return errors.New("channel is not initialized")
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
)
|
||||
|
||||
// failedEventSaver 是这个 worker 对存储的唯一依赖。
|
||||
// 抽成接口是为了用假实现验证"落库失败必须 requeue"这条契约(无需 MySQL)。
|
||||
type failedEventSaver interface {
|
||||
Save(ctx context.Context, e *failedevent.FailedEvent) (bool, error)
|
||||
}
|
||||
@@ -26,8 +25,7 @@ type FailedEventWorker struct {
|
||||
queue string
|
||||
}
|
||||
|
||||
// failedEventRetryBackoff 是"落库失败后重投"之前的退避。
|
||||
// 变量而非常量:单测要把它调到 0 以免为了等 2 秒而拖慢整个套件。
|
||||
// failedEventRetryBackoff 是落库失败后重投之前的退避,变量以便单测调小。
|
||||
var failedEventRetryBackoff = 2 * time.Second
|
||||
|
||||
// NewFailedEventWorker 构造停泊消费者。
|
||||
@@ -35,11 +33,7 @@ func NewFailedEventWorker(ch *amqp.Channel, repo failedEventSaver, queue string)
|
||||
return &FailedEventWorker{ch: ch, repo: repo, queue: queue}
|
||||
}
|
||||
|
||||
// Run 消费停泊队列直到 ctx 取消。
|
||||
//
|
||||
// 它自己【不】走 rabbitmq.ConsumeLoop:ConsumeLoop 的失败动作是"停泊",
|
||||
// 而这个 worker 的职责就是停泊落库——让它停泊自己会形成递归
|
||||
// (停泊队列消费失败 → 停泊 → 停泊队列 → …)。见方案 §6.9.3。
|
||||
// Run 消费停泊队列直到 ctx 取消;刻意不走 ConsumeLoop,否则停泊失败会递归停泊自己。
|
||||
func (w *FailedEventWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil {
|
||||
return fmt.Errorf("failedevent worker: channel is not initialized")
|
||||
@@ -61,13 +55,11 @@ func (w *FailedEventWorker) Run(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
// persist 是这个 worker 的"最后一道防线":它自己不再停泊。
|
||||
// 落库失败 → requeue + 退避,不 Ack、不停泊(把消息停泊到一个不存在的消费者没有意义)。
|
||||
// persist 把停泊消息落库:失败则退避后 requeue,不 Ack、也不停泊自己。
|
||||
func (w *FailedEventWorker) persist(ctx context.Context, d amqp.Delivery) {
|
||||
info := rabbitmq.ParseParkedInfo(d)
|
||||
headers, err := json.Marshal(d.Headers)
|
||||
if err != nil {
|
||||
// 序列化失败不该阻止落库:Body 才是重放所需的主体,headers 只是附注。
|
||||
headers = []byte("{}")
|
||||
}
|
||||
record := &failedevent.FailedEvent{
|
||||
@@ -104,8 +96,7 @@ func nilIfEmpty(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
// sleepCtx 是 worker 包自己的实现:rabbitmq.sleepCtx 未导出,不能跨包复用。
|
||||
// 返回 false 表示 ctx 已取消(调用方应尽快退出,不要再处理下一条消息)。
|
||||
// sleepCtx 返回 false 表示 ctx 已取消。
|
||||
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
|
||||
@@ -42,8 +42,6 @@ func (w *PopularityWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
if evt.VideoID == 0 || evt.Change == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("popularity worker: invalid event video_id=%d change=%d", evt.VideoID, evt.Change))
|
||||
}
|
||||
// 关键:这里必须把错误上抛(P0-3 的 N2)。原来三条路径全返回 nil,
|
||||
// 于是重试分支全是死代码——Redis 短暂不可用就等于热度凭空丢失,
|
||||
// 且没有任何日志能证明发生过。
|
||||
// 必须把错误上抛,否则重试分支是死代码。
|
||||
return video.UpdatePopularityCache(ctx, w.cache, evt.VideoID, evt.Change, evt.EventID)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user