Skip to content

Commit

Permalink
WIP22: Improved helper func and testing
Browse files Browse the repository at this point in the history
  • Loading branch information
skoeva committed Jul 18, 2023
1 parent 2437195 commit 1668268
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
35 changes: 26 additions & 9 deletions backend/pkg/api/instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"fmt"
"strconv"
"strings"
"time"

"github.com/doug-martin/goqu/v9"
Expand Down Expand Up @@ -48,6 +49,7 @@ const (

const (
validityInterval postgresDuration = "1 days"
defaultInterval time.Duration = 2 * time.Hour
)

// Instance represents an instance running one or more applications for which
Expand Down Expand Up @@ -649,23 +651,38 @@ func (api *API) instanceStatsQuery(t *time.Time, duration *time.Duration) *goqu.
}

if duration == nil {
d := 2 * time.Hour
d := defaultInterval
duration = &d
}

// Helper function to convert duration to PostgreSQL interval string
durationToInterval := func(d time.Duration) string {
str := fmt.Sprintf("%d microseconds", d.Microseconds())
if d.Microseconds() > 999999 {
str = fmt.Sprintf("%d seconds", int(d.Seconds()))
parts := []string{}

hours := int(d.Hours())
if hours != 0 {
parts = append(parts, fmt.Sprintf("%d hours", hours))
}

remainder := d - time.Duration(hours)*time.Hour
minutes := int(remainder.Minutes())
if minutes != 0 {
parts = append(parts, fmt.Sprintf("%d minutes", minutes))
}
if d.Seconds() > 99 {
str = fmt.Sprintf("%d minutes", int(d.Minutes()))

remainder -= time.Duration(minutes) * time.Minute
seconds := int(remainder.Seconds())
if seconds != 0 {
parts = append(parts, fmt.Sprintf("%d seconds", seconds))
}
if d.Minutes() > 99 {
str = fmt.Sprintf("%d hours", int(d.Hours()))

remainder -= time.Duration(seconds) * time.Second
microseconds := remainder.Microseconds()
if microseconds != 0 {
parts = append(parts, fmt.Sprintf("%d microseconds", microseconds))
}
return str

return strings.Join(parts, " ")
}

interval := durationToInterval(*duration)
Expand Down
2 changes: 2 additions & 0 deletions backend/pkg/api/instances_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,8 @@ func TestUpdateInstanceStats(t *testing.T) {
assert.Equal(t, 2, len(instanceStats))
assert.Equal(t, "1.0.0", instanceStats[0].Version)
assert.Equal(t, 1, instanceStats[0].Instances)
assert.Equal(t, "1.0.1", instanceStats[1].Version)
assert.Equal(t, 2, instanceStats[1].Instances)

// Next test case: Switch tInstance1 and tInstance2 versions to workaround the 5-minutes-rate-limiting of the check-in time and add new instance
ts2 := time.Now().UTC()
Expand Down

0 comments on commit 1668268

Please sign in to comment.