package db_updater import ( "github.com/robfig/cron/v3" "github.com/rs/zerolog/log" "sync/atomic" "thuanle.me/ip-info/configs" "thuanle.me/ip-info/internal/data" "time" ) // DbUpdatedAt stores the DB last-updated time as unix milliseconds. // Accessed concurrently by the cron goroutine (writer) and the /metrics // handler (reader), so it must be synchronized — hence atomic.Int64. var DbUpdatedAt atomic.Int64 // DbUpdatedAtMillis returns the last DB update time in unix milliseconds, // or 0 if the DB has never been updated. func DbUpdatedAtMillis() int64 { return DbUpdatedAt.Load() } func StartUpdateDbService() { c := cron.New() _, _ = c.AddFunc("@daily", fetchDbs) c.Start() fetchDbs() } func fetchDbs() { newFlag := false for _, url := range configs.GeoDbSourcePaths { newFlag = download(url) || newFlag } if newFlag { log.Info().Msg("New DB downloaded. Recreating mmdb") if err := mergeMmdb(); err != nil { // Keep the current (previous) DB rather than reloading a // potentially empty/corrupt merge output. log.Err(err).Msg("Failed to merge mmdb, keeping current DB") return } err := data.Ins().Reload() if err != nil { log.Err(err).Msg("Failed to reload mmdb") return } DbUpdatedAt.Store(time.Now().UnixMilli()) } }