package jobs import ( "pool-stats/constants" "pool-stats/database" "pool-stats/models" "pool-stats/notlinq" "sort" "time" "github.com/ostafen/clover/v2" ) type RecalculateTimeWindowHighSharesJob struct { DB *clover.DB } func NewRecalculateTimeWindowHighSharesJob(db *clover.DB) *RecalculateTimeWindowHighSharesJob { return &RecalculateTimeWindowHighSharesJob{DB: db} } func (job *RecalculateTimeWindowHighSharesJob) Run() error { ticker := time.NewTicker(constants.RecalculateTimeWindowHighSharesJobInterval) defer ticker.Stop() for { select { case <-ticker.C: job.recalculateTimeWindowHighShares() } } } func (job *RecalculateTimeWindowHighSharesJob) recalculateTimeWindowHighShares() { topShares := database.ListTopShares(job.DB) sort.Slice(topShares, func(i, j int) bool { return topShares[i].SDiff > topShares[j].SDiff }) // All time high share if len(topShares) > 0 { allTimeHighShare := topShares[0] allTimeHighShareStat := &models.TimeWindowHighShare{ TimeWindowID: "0-all-time", TimeWindowName: "All Time", SDiff: allTimeHighShare.SDiff, Time: allTimeHighShare.CreateDate, } database.SetTimeWindowHighShare(job.DB, *allTimeHighShareStat) } // Other ranges timeWindows := []struct { ID string Name string Since time.Time }{ {"1-hour", "Past Hour", time.Now().Add(-1 * time.Hour)}, {"2-day", "Past 24h", time.Now().Add(-24 * time.Hour)}, {"3-week", "Past 7d", time.Now().Add(-7 * 24 * time.Hour)}, } for _, tw := range timeWindows { // Can use one of top shares if in range, // otherwise get highest share in range var highestShare models.ShareLog topSharesInRange := notlinq. Where(topShares, func(s models.ShareLog) bool { shareTime, err := s.ParseCreateDate() if err != nil { return false } return shareTime.After(tw.Since) }) sort.Slice(topSharesInRange, func(i, j int) bool { return topSharesInRange[i].SDiff > topSharesInRange[j].SDiff }) if len(topSharesInRange) > 0 { highestShare = topSharesInRange[0] } else { highestShareDocs, _ := database.GetHighestSharesInRange( job.DB, database.CollectionName, tw.Since, 1) if len(highestShareDocs) > 0 { highestShare = highestShareDocs[0] } } var timeWindowStat models.TimeWindowHighShare if highestShare.SDiff > 0 { timeWindowStat = models.TimeWindowHighShare{ TimeWindowID: tw.ID, TimeWindowName: tw.Name, SDiff: highestShare.SDiff, Time: highestShare.CreateDate, } } else { timeWindowStat = models.TimeWindowHighShare{ TimeWindowID: tw.ID, TimeWindowName: tw.Name, SDiff: 0, Time: "-", } } database.SetTimeWindowHighShare(job.DB, timeWindowStat) } }