group_leave.go 2.35 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
package event_m

import (
	"gorm.io/gorm"
	"hilo-user/domain"
	"hilo-user/resource/mysql"
	"time"
)

// 离房事件消息
type EventGroupLeave struct {
	mysql.Entity
	*domain.Model `gorm:"-"`
	Proto         mysql.Type
	Payload       []byte
	Mark          mysql.YesNo
}

// 偏移值
type EventGroupLeaveOffset struct {
	mysql.Entity
	*domain.Model `gorm:"-"`
	MarkOffset    mysql.ID
}

// 获取当前偏移值
func GroupLeaveOffset(model *domain.Model) (*EventGroupLeaveOffset, error) {
	offset := new(EventGroupLeaveOffset)
	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 FetchEventGroupLeave(model *domain.Model, limit int) ([]*EventGroupLeave, *EventGroupLeaveOffset, error) {
	offset, err := GroupLeaveOffset(model)
	if err != nil {
		return nil, nil, err
	}
	var events []*EventGroupLeave
	if err := model.Db.WithContext(model).Model(EventGroupLeave{}).
		Where("id > ?", offset.MarkOffset).
		Order("id asc").Limit(limit).Find(&events).Error; err != nil {
		model.Log.Errorf("FetchEventGroupLeave fail:%v", err)
		return nil, nil, err
	}
	return events, offset, nil
}

// 标记已完成
func (p *EventGroupLeave) MarkDone() error {
	p.Mark = mysql.YES
	return p.Db.WithContext(p.Model).Model(EventGroupLeave{}).Where("id = ?", p.ID).Update("mark", p.Mark).Limit(1).Error
}

// 查询过去1小时-5分钟前未mark的事件
// 用来补偿
// 记得加limit
func FetchGroupLeaveUnMarkEvents(model *domain.Model, limit int) ([]*EventGroupLeave, error) {
	offset, err := GroupLeaveOffset(model)
	if err != nil {
		return nil, err
	}
	t := time.Now().Add(-time.Minute * 5)
	lt := t.Add(-time.Hour)
	var events []*EventGroupLeave
	if err := model.Db.WithContext(model).Model(EventGroupLeave{}).
		Where("mark = ?", 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 AddGroupLeaveUnMarkEvent(model *domain.Model, event *EventGroupLeave) error {
	return model.Db.WithContext(model).Create(event).Error
}