linstrom/storage/inboundJobs.go

68 lines
2 KiB
Go
Raw Permalink Normal View History

package storage
import (
"github.com/rs/zerolog/log"
2024-12-18 14:24:56 +00:00
"git.mstar.dev/mstar/linstrom/util"
2024-09-16 15:42:16 +00:00
"gorm.io/gorm"
)
// Auto-generate string names for the various constants
//go:generate stringer -type InboundJobSource
type InboundJobSource int
// TODO: Adjust and expand these constants later, depending on sources
const (
InJobSourceAccInbox InboundJobSource = iota
InJobSourceServerInbox
InJobSourceApiMasto
InJobSourceApiLinstrom
)
// Store inbound jobs from api and ap in the db until they finished processing
// Ensures data consistency in case the server is forced to restart unexpectedly
2024-09-18 11:49:10 +00:00
// Inbound jobs must allways be processed in order from oldest to newest to ensure consistency
type InboundJob struct {
gorm.Model
// Raw data, could be json or gob data, check source for how to interpret
2024-09-16 13:49:03 +00:00
RawData []byte `gorm:"->;<-create"`
// Where this job is coming from. Important for figuring out how to decode the raw data and what to do with it
2024-09-16 13:49:03 +00:00
Source InboundJobSource `gorm:"->;<-create"`
// Section: Various data
// TODO: Expand based on needs
// If from an inbox, include the owner id here
2024-09-16 13:49:03 +00:00
InboxOwner *string `gorm:"->;<-create"`
}
2024-09-16 15:42:16 +00:00
func (s *Storage) AddNewInboundJob(data []byte, source InboundJobSource, inboxOwner *string) {
defer util.Untrace(util.Trace(&log.Logger))
2024-09-16 15:42:16 +00:00
newJob := InboundJob{
RawData: data,
Source: source,
InboxOwner: inboxOwner,
}
s.db.Create(&newJob)
}
// Get the specified amount of jobs, sorted by age (oldest first)
func (s *Storage) GetOldestInboundJobs(amount uint) ([]InboundJob, error) {
defer util.Untrace(util.Trace(&log.Logger))
2024-09-16 15:42:16 +00:00
jobs := []InboundJob{}
switch err := s.db.Order("id asc, created_at asc").Limit(int(amount)).Find(jobs).Error; err {
2024-09-16 15:42:16 +00:00
case gorm.ErrRecordNotFound:
return nil, ErrEntryNotFound
case nil:
return jobs, nil
default:
return nil, err
}
}
func (s *Storage) CompleteInboundJob(id uint) error {
defer util.Untrace(util.Trace(&log.Logger))
s.db.Delete(InboundJob{Model: gorm.Model{ID: id}})
return nil
}