package event_m import ( "git.hilo.cn/hilo-common/domain" "git.hilo.cn/hilo-common/resource/mysql" "github.com/pkg/errors" "gorm.io/gorm" "time" ) // 送礼事件消息 type EventGiftSend struct { mysql.Entity *domain.Model `gorm:"-"` Proto mysql.Type Payload []byte Mark mysql.YesNo MarkHiloGroup mysql.YesNo MarkHiloUser mysql.YesNo } func (EventGiftSend) TableName() string { return "event_gift_send" } // 偏移值 type EventGiftSendOffsetHiloGroup struct { mysql.Entity *domain.Model `gorm:"-"` MarkOffset mysql.ID } // 获取当前偏移值 func Offset(model *domain.Model) (*EventGiftSendOffsetHiloGroup, error) { offset := new(EventGiftSendOffsetHiloGroup) if err := model.Db.WithContext(model).First(offset).Error; err != nil { if err != gorm.ErrRecordNotFound { model.Log.Errorf("Offset fail:%v", err) return nil, err } // gorm.ErrRecordNotFound } offset.Model = model return offset, nil } // 批量获取送礼 func FetchEventGiftSend(model *domain.Model, limit int) ([]*EventGiftSend, *EventGiftSendOffsetHiloGroup, error) { offset, err := Offset(model) if err != nil { return nil, nil, err } var events []*EventGiftSend if err := model.Db.WithContext(model).Model(EventGiftSend{}). Where("id > ?", offset.MarkOffset). Order("id asc").Limit(limit).Find(&events).Error; err != nil { model.Log.Errorf("FetchEventGiftSend fail:%v", err) return nil, nil, err } return events, offset, nil } // 标记已完成 func (p *EventGiftSend) MarkDone() error { p.MarkHiloGroup = mysql.YES result := p.Db.WithContext(p.Model).Model(EventGiftSend{}).Where("id = ?", p.ID).Update("mark_hilo_group", p.MarkHiloGroup).Limit(1) if result.Error != nil { return result.Error } if result.RowsAffected <= 0 { p.Model.Log.Errorf("MarkDone row affeced 0") return errors.New("row affect 0") } return nil } // 查询过去1小时-5分钟前未mark的事件 // 用来补偿 // 记得加limit func FetchUnMarkEvents(model *domain.Model, limit int) ([]*EventGiftSend, error) { offset, err := Offset(model) if err != nil { return nil, err } t := time.Now().Add(-time.Minute * 5) lt := t.Add(-time.Hour) var events []*EventGiftSend if err := model.Db.WithContext(model).Model(EventGiftSend{}). Where("mark_hilo_group = ?", mysql.NO). Where("id <= ?", offset.MarkOffset). Where("created_time < ?", t). Where("created_time > ?", lt). Order("id asc").Limit(limit).Find(&events).Error; err != nil { model.Log.Errorf("FetchUnMarkEvents fail:%v", err) return nil, err } return events, nil } // 补偿加上unmark的event func AddUnMarkEvent(model *domain.Model, event *EventGiftSend) error { return model.Db.WithContext(model).Create(event).Error }