Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

metrics: Sink contructor from metric type #3068

Merged
merged 1 commit into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 1 addition & 14 deletions metrics/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,7 @@ func (r *Registry) newMetric(name string, mt MetricType, vt ...ValueType) *Metri
valueType = vt[0]
}

var sink Sink
switch mt {
case Counter:
sink = &CounterSink{}
case Gauge:
sink = &GaugeSink{}
case Trend:
sink = &TrendSink{}
case Rate:
sink = &RateSink{}
default:
return nil
}

sink := NewSink(mt)
return &Metric{
registry: r,
Name: name,
Expand Down
23 changes: 23 additions & 0 deletions metrics/sink.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package metrics

import (
"errors"
"fmt"
"math"
"sort"
"time"
Expand All @@ -21,6 +22,28 @@ type Sink interface {
IsEmpty() bool // Check if the Sink is empty.
}

// NewSink creates the related Sink for
// the provided MetricType.
func NewSink(mt MetricType) Sink {
var sink Sink
switch mt {
case Counter:
sink = &CounterSink{}
case Gauge:
sink = &GaugeSink{}
case Trend:
sink = &TrendSink{}
case Rate:
sink = &RateSink{}
default:
// Should not be possible to create
// an invalid metric type except for specific
// and controlled tests
panic(fmt.Sprintf("MetricType %q is not supported", mt))
}
return sink
}

type CounterSink struct {
Value float64
First time.Time
Expand Down
22 changes: 22 additions & 0 deletions metrics/sink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@ import (
"github.com/stretchr/testify/require"
)

func TestNewSink(t *testing.T) {
t.Parallel()

tests := []struct {
sink interface{}
mt MetricType
}{
{mt: Counter, sink: &CounterSink{}},
{mt: Gauge, sink: &GaugeSink{}},
{mt: Rate, sink: &RateSink{}},
{mt: Trend, sink: &TrendSink{}},
}
for _, tc := range tests {
assert.Equal(t, tc.sink, NewSink(tc.mt))
}
}

func TestNewSinkInvalidMetricType(t *testing.T) {
t.Parallel()
assert.Panics(t, func() { NewSink(MetricType(6)) })
}

func TestCounterSink(t *testing.T) {
samples10 := []float64{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 100.0}
now := time.Now()
Expand Down