Files
VLoop/backend/internal/failedevent/repo.go
huanghaosheng 7fc3436892 feat(failedevent): 新增 failed_events 表与落库仓储
停泊消息需要一个"查得到"的落地形态。此前死信链路只有声明没有消费者,
被拒绝的消息一旦 Ack 就再也无法举证。

表设计的两个要点:

- 复合唯一键 (source_queue, event_id) 而不是只钉 event_id。同一个意图可以
  出现在多个队列里(比如 like.events 与 notification.like 由同一次点赞产生),
  只按 event_id 去重会把第二个队列的失败记录误当成重复丢掉。
- event_id 必须可空(*string):解析不出意图键的坏消息没有 id,NULL 允许
  多行共存,空字符串则会互相撞键。

落库是"只增不改"的:Save 在 event_id 非空时用 OnConflict{DoNothing},
并以 RowsAffected 判断是否真的插入,重复投递因此是幂等的。

包独立成 internal/failedevent 而不是放进 internal/worker:
db.go 已经 import worker(AutoMigrate 需要 Notification),若表定义也放
worker,worker → failedevent → worker 就成环。

db.go 的 AutoMigrate 追加该表,建表入口仍然只有 API 进程这一个。
2026-10-30 13:13:29 +08:00

43 lines
1.2 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 failedevent
import (
"context"
"errors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Repository 是 failed_events 的存储层。
type Repository struct {
db *gorm.DB
}
// NewRepository 构造仓储。
func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}
// Save 写入一条停泊记录,返回它是否是本次新插入的。
//
// 去重键是 (source_queue, event_id):重复投递同一条停泊消息(停泊成功但 Ack 前崩溃、
// 或运维重放)只会留下一条记录。EventID 为 NULL 的消息不参与复合唯一键
// ——MySQL 唯一索引里 NULL 不参与比较,多个 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")
}
if e == nil {
return false, errors.New("failedevent: entity is nil")
}
if e.EventID == nil {
return true, r.db.WithContext(ctx).Create(e).Error
}
res := r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(e)
if res.Error != nil {
return false, res.Error
}
return res.RowsAffected > 0, nil
}