43 lines
1.2 KiB
Go
43 lines
1.2 KiB
Go
|
|
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
|
|||
|
|
}
|