Skip to content

Commit

Permalink
Merge pull request #1114 from circleci/dm/timestamp-httpmetrics
Browse files Browse the repository at this point in the history
Add timestamp to httpmetric
  • Loading branch information
danmux authored Feb 24, 2025
2 parents 6cbe68c + ad19cfc commit f74e0e6
Showing 2 changed files with 46 additions and 10 deletions.
18 changes: 10 additions & 8 deletions o11y/httpmetrics/provider.go
Original file line number Diff line number Diff line change
@@ -39,10 +39,11 @@ type Provider struct {
}

type metricData struct {
Type string `json:"type"`
Name string `json:"name"`
Value float64 `json:"value"`
Tags []string `json:"tags"`
Type string `json:"type"`
Name string `json:"name"`
Timestamp int64 `json:"timestamp"`
Value float64 `json:"value"`
Tags []string `json:"tags"`
}

type Tags map[string]string
@@ -124,10 +125,11 @@ func (m *Provider) record(metricType, metricName string, metricValue float64, me
name = fmt.Sprintf("%s.%s", m.namespace, name)
}
m.data = append(m.data, metricData{
Type: metricType,
Name: name,
Value: metricValue,
Tags: metricTags,
Type: metricType,
Name: name,
Timestamp: time.Now().Unix(),
Value: metricValue,
Tags: metricTags,
})
}

38 changes: 36 additions & 2 deletions o11y/httpmetrics/provider_test.go
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import (
"testing"
"time"

gcmp "github.com/google/go-cmp/cmp"
"golang.org/x/sync/errgroup"
"gotest.tools/v3/assert"
"gotest.tools/v3/assert/cmp"
@@ -132,7 +133,11 @@ func TestProvider_Record(t *testing.T) {
m.record(aMet.Type, aMet.Name, aMet.Value, aMet.Tags)
}

assert.Check(t, cmp.DeepEqual(m.data, tt.expectedMetricsData))
for i := range tt.expectedMetricsData {
tt.expectedMetricsData[i].Timestamp = time.Now().Unix()
}

assert.Check(t, cmp.DeepEqual(m.data, tt.expectedMetricsData, equateApproxUnixTime(1)))
})
}
}
@@ -255,7 +260,11 @@ func TestProvider_Publish(t *testing.T) {
err := eg.Wait()
assert.NilError(t, err)

assert.Check(t, cmp.DeepEqual(m.data, tt.expectedMetricsData))
for i := range tt.expectedMetricsData {
tt.expectedMetricsData[i].Timestamp = time.Now().Unix()
}

assert.Check(t, cmp.DeepEqual(m.data, tt.expectedMetricsData, equateApproxUnixTime(1)))
})
}
}
@@ -353,3 +362,28 @@ func TestProvider_New(t *testing.T) {
})
}
}

func equateApproxUnixTime(marginSec int64) gcmp.Option {
if marginSec < 0 {
panic("margin must be a non-negative number")
}
a := timeApproximator{marginSec}
return gcmp.FilterValues(areNonZeroTimes, gcmp.Comparer(a.compare))
}

func areNonZeroTimes(x, y int64) bool {
return x > 0 && y > 0
}

type timeApproximator struct {
marginSec int64
}

func (a timeApproximator) compare(x, y int64) bool {
if x > y {
// Ensure x is always before y
x, y = y, x
}
// We're within the margin if x+margin >= y.
return x+a.marginSec >= y
}

0 comments on commit f74e0e6

Please sign in to comment.