pool-stats/jobs/recalculateTopShares.go
Pijus Kamandulis 4ddd9abd2e Restructure
2025-06-23 19:38:02 +03:00

61 lines
1.7 KiB
Go

package jobs
import (
"pool-stats/constants"
"pool-stats/database"
"pool-stats/helpers"
"pool-stats/models"
"pool-stats/notlinq"
"sort"
"time"
"github.com/ostafen/clover/v2"
)
type RecalculateTopSharesJob struct {
DB *clover.DB
}
func NewRecalculateTopSharesJob(db *clover.DB) *RecalculateTopSharesJob {
return &RecalculateTopSharesJob{DB: db}
}
func (job *RecalculateTopSharesJob) Run() error {
ticker := time.NewTicker(constants.RecalculateTopSharesJobInterval)
defer ticker.Stop()
for {
<-ticker.C
job.recalculateTopShares()
}
}
func (job *RecalculateTopSharesJob) recalculateTopShares() {
currentTopShares := database.ListTopShares(job.DB)
var newTopShares []models.ShareLog
if currentTopShares == nil || len(currentTopShares) < constants.TopSharesAmount {
newTopShares, _ = database.GetHighestSharesInRange(job.DB, database.CollectionName, time.Unix(0, 0), constants.TopSharesAmount)
} else {
sort.Slice(currentTopShares, func(i, j int) bool {
return currentTopShares[i].CreateDate > currentTopShares[j].CreateDate
})
lastTopShareDate := currentTopShares[0].CreateDate
lastTopShareDateTime := helpers.ParseCreateDate(lastTopShareDate)
newTopShares, _ = database.GetHighestSharesInRange(job.DB, database.CollectionName, lastTopShareDateTime, constants.TopSharesAmount)
}
newTopShares = append(newTopShares, currentTopShares...)
sort.Slice(newTopShares, func(i, j int) bool {
return newTopShares[i].SDiff > newTopShares[j].SDiff
})
newTopShares = notlinq.UniqueBy(newTopShares, func(s models.ShareLog) string {
return s.Hash
})
if len(newTopShares) > constants.TopSharesAmount {
newTopShares = newTopShares[:constants.TopSharesAmount]
}
database.ReplaceTopShares(job.DB, newTopShares)
}