Skip to content

Commit

Permalink
backend: Calculate UpdateInstanceStats interval using latest entry ti…
Browse files Browse the repository at this point in the history
…mestamp
  • Loading branch information
skoeva committed Aug 7, 2023
1 parent 3eddf31 commit c52304c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
16 changes: 16 additions & 0 deletions backend/pkg/api/instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,22 @@ func (api *API) GetInstanceStats() ([]InstanceStats, error) {
return instances, nil
}

// GetLatestInstanceStatsTimestamp returns the latest timestamp value in the
// instance stats table.
func (api *API) GetLatestInstanceStatsTimestamp() (time.Time, error) {
// return latest timestamp
query, _, err := goqu.From("instance_stats").
Select(goqu.MAX("timestamp")).ToSQL()
if err != nil {
return time.Time{}, err
}

var timestamp time.Time
_ = api.db.Get(&timestamp, query)

return timestamp, nil
}

// GetInstanceStatsByTimestamp returns an InstanceStats array of instances matching a
// given timestamp value, ordered by version.
func (api *API) GetInstanceStatsByTimestamp(t time.Time) ([]InstanceStats, error) {
Expand Down
12 changes: 11 additions & 1 deletion backend/pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,17 @@ func New(conf *config.Config, db *db.API) (*echo.Echo, error) {

// setup background job for updating instance stats
go func() {
err := db.UpdateInstanceStats(nil, nil)
// update once at startup based on last run
var interval *time.Duration
lastRun, err := db.GetLatestInstanceStatsTimestamp()
if err != nil {
interval = nil
} else {
t := time.Now().UTC().Sub(lastRun)
interval = &t
}

err = db.UpdateInstanceStats(nil, interval)
if err != nil {
logger.Err(err).Msg("Error updating instance stats")
}
Expand Down

0 comments on commit c52304c

Please sign in to comment.