diff --git a/constants/constants.go b/constants/constants.go index e389176..e767b50 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -10,6 +10,8 @@ const ( RecalculateTopSharesJobInterval = 30 * time.Second // IngestSharesJob interval IngestSharesJobInterval = 30 * time.Second + // RecalculateCurrentDayStatsJob interval + RecalculateCurrentDayStatsJobInterval = 30 * time.Minute ) // counts and stuff diff --git a/database/db.go b/database/db.go index 0e5a960..87d2c88 100644 --- a/database/db.go +++ b/database/db.go @@ -322,3 +322,15 @@ func ClearDailyStats(db *clover.DB) error { } 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 +} diff --git a/jobs/recalculateCurrentDayStatsJob.go b/jobs/recalculateCurrentDayStatsJob.go new file mode 100644 index 0000000..f523390 --- /dev/null +++ b/jobs/recalculateCurrentDayStatsJob.go @@ -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) +} diff --git a/main.go b/main.go index 99dcbae..2fa0102 100644 --- a/main.go +++ b/main.go @@ -31,6 +31,9 @@ func main() { timeWindowHighSharesRecalcJob := jobs.NewRecalculateTimeWindowHighSharesJob(db) go timeWindowHighSharesRecalcJob.Run() + currentDayStatsRecalcJob := jobs.NewRecalculateCurrentDayStatsJob(db) + go currentDayStatsRecalcJob.Run() + webServer := web.NewWebServer(db, config.Port) if err := webServer.Start(); err != nil { log.Fatalf("Failed to start web server: %v", err)