Recalculate yesterday's and today's stats

This commit is contained in:
Pijus Kamandulis 2025-06-24 09:41:24 +03:00
parent b89a1a2a7e
commit 844f7fa08b
4 changed files with 57 additions and 0 deletions

View File

@ -10,6 +10,8 @@ const (
RecalculateTopSharesJobInterval = 30 * time.Second RecalculateTopSharesJobInterval = 30 * time.Second
// IngestSharesJob interval // IngestSharesJob interval
IngestSharesJobInterval = 30 * time.Second IngestSharesJobInterval = 30 * time.Second
// RecalculateCurrentDayStatsJob interval
RecalculateCurrentDayStatsJobInterval = 30 * time.Minute
) )
// counts and stuff // counts and stuff

View File

@ -322,3 +322,15 @@ func ClearDailyStats(db *clover.DB) error {
} }
return nil return nil
} }
func DeleteDailyStatsForDay(db *clover.DB, date time.Time) error {
dateStr := date.Format(time.DateOnly)
// Delete the document for the specific date
if err := db.Delete(c.NewQuery(DailyStatsCollectionName).
Where(c.Field("Date").Eq(dateStr))); err != nil {
return fmt.Errorf("failed to delete daily stats for %s: %v", dateStr, err)
}
return nil
}

View File

@ -0,0 +1,40 @@
package jobs
import (
"pool-stats/constants"
"pool-stats/database"
"time"
"github.com/ostafen/clover/v2"
)
type RecalculateCurrentDayStatsJob struct {
DB *clover.DB
}
func NewRecalculateCurrentDayStatsJob(db *clover.DB) *RecalculateCurrentDayStatsJob {
return &RecalculateCurrentDayStatsJob{DB: db}
}
func (job *RecalculateCurrentDayStatsJob) Run() error {
ticker := time.NewTicker(constants.RecalculateCurrentDayStatsJobInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
job.recalculateCurrentDayStats()
}
}
}
func (job *RecalculateCurrentDayStatsJob) recalculateCurrentDayStats() {
today := time.Now().Truncate(24 * time.Hour)
yesterday := today.Add(-24 * time.Hour)
database.GetDailyStats(job.DB, today)
// Need to keep yesterday's stats cache updated
database.DeleteDailyStatsForDay(job.DB, yesterday)
database.GetDailyStats(job.DB, yesterday)
}

View File

@ -31,6 +31,9 @@ func main() {
timeWindowHighSharesRecalcJob := jobs.NewRecalculateTimeWindowHighSharesJob(db) timeWindowHighSharesRecalcJob := jobs.NewRecalculateTimeWindowHighSharesJob(db)
go timeWindowHighSharesRecalcJob.Run() go timeWindowHighSharesRecalcJob.Run()
currentDayStatsRecalcJob := jobs.NewRecalculateCurrentDayStatsJob(db)
go currentDayStatsRecalcJob.Run()
webServer := web.NewWebServer(db, config.Port) webServer := web.NewWebServer(db, config.Port)
if err := webServer.Start(); err != nil { if err := webServer.Start(); err != nil {
log.Fatalf("Failed to start web server: %v", err) log.Fatalf("Failed to start web server: %v", err)