Skip to content

Commit

Permalink
feat: Update to use go-mod-messaging updated Msgenvelope functions
Browse files Browse the repository at this point in the history
relate to: edgexfoundry/go-mod-messaging#381

Signed-off-by: Ginny Guan <[email protected]>
  • Loading branch information
jinlinGuan committed Feb 3, 2025
1 parent 36ed06c commit 689d11e
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 23 deletions.
17 changes: 5 additions & 12 deletions bootstrap/metrics/reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package metrics

import (
"encoding/json"
"context"
"errors"
"fmt"

Expand Down Expand Up @@ -171,17 +171,10 @@ func (r *messageBusReporter) Report(registry gometrics.Registry, metricTags map[
return
}

payload, err := json.Marshal(nextMetric)
if err != nil {
errs = multierror.Append(errs, fmt.Errorf("failed to marshal metric '%s' to JSON: %s", nextMetric.Name, err.Error()))
return
}

message := types.MessageEnvelope{
CorrelationID: uuid.NewString(),
Payload: payload,
ContentType: common.ContentTypeJSON,
}
ctx := context.Background()
ctx = context.WithValue(ctx, common.CorrelationHeader, uuid.NewString()) //nolint: staticcheck
ctx = context.WithValue(ctx, common.ContentType, common.ContentTypeJSON) //nolint: staticcheck
message := types.NewMessageEnvelope(nextMetric, ctx)

topic := common.BuildTopic(r.baseMetricsTopic, name)
if err := r.messageClient.Publish(message, topic); err != nil {
Expand Down
169 changes: 164 additions & 5 deletions bootstrap/metrics/reporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
package metrics

import (
"encoding/json"
"os"
"testing"

"github.com/edgexfoundry/go-mod-core-contracts/v4/common"
Expand Down Expand Up @@ -97,6 +97,168 @@ func TestMessageBusReporter_Report(t *testing.T) {
Tags: nil,
}

expectedTags := []dtos.MetricTag{
{
Name: serviceNameTagKey,
Value: expectedServiceName,
},
}
intValue := int64(50)
expectedCounterMetric, err := dtos.NewMetric(expectedMetricName,
[]dtos.MetricField{
{
Name: counterCountName,
Value: intValue,
}},
expectedTags)
require.NoError(t, err)

reg := gometrics.NewRegistry()

counter := gometrics.NewCounter()
counter.Inc(intValue)

disabledCounter := gometrics.NewCounter()
disabledCounter.Inc(intValue)
err = reg.Register(unexpectedMetricName, disabledCounter)
require.NoError(t, err)

gauge := gometrics.NewGauge()
gauge.Update(intValue)
expectedGaugeMetric := expectedCounterMetric
expectedGaugeMetric.Fields = []dtos.MetricField{
{
Name: gaugeValueName,
Value: intValue,
}}

floatValue := 50.55
expectedGaugeFloat64Metric := expectedCounterMetric
expectedGaugeFloat64Metric.Fields = []dtos.MetricField{
{
Name: gaugeFloat64ValueName,
Value: floatValue,
}}
gaugeFloat64 := gometrics.NewGaugeFloat64()
gaugeFloat64.Update(floatValue)

expectedTimerMetric := expectedCounterMetric
copy(expectedTimerMetric.Fields, expectedCounterMetric.Fields)
expectedTimerMetric.Fields = []dtos.MetricField{
{
Name: timerCountName,
Value: int64(0),
}}
expectedTimerMetric.Fields = append(expectedTimerMetric.Fields,
[]dtos.MetricField{
{Name: timerMinName, Value: int64(0)},
{Name: timerMaxName, Value: int64(0)},
{Name: timerMeanName, Value: float64(0)},
{Name: timerStddevName, Value: float64(0)},
{Name: timerVarianceName, Value: float64(0)},
}...)
timer := gometrics.NewTimer()

expectedHistogramMetric := expectedCounterMetric
copy(expectedHistogramMetric.Fields, expectedCounterMetric.Fields)
expectedHistogramMetric.Fields = []dtos.MetricField{
{
Name: histogramCountName,
Value: int64(0),
}}
expectedHistogramMetric.Fields = append(expectedHistogramMetric.Fields,
[]dtos.MetricField{
{Name: histogramMinName, Value: int64(0)},
{Name: histogramMaxName, Value: int64(0)},
{Name: histogramMeanName, Value: float64(0)},
{Name: histogramStddevName, Value: float64(0)},
{Name: histogramVarianceName, Value: float64(0)},
}...)
histogram := gometrics.NewHistogram(gometrics.NewUniformSample(1028))

tests := []struct {
Name string
Metric interface{}
ExpectedMetric *dtos.Metric
ExpectError bool
}{
{"Happy path - Counter", counter, &expectedCounterMetric, false},
{"Happy path - Gauge", gauge, &expectedGaugeMetric, false},
{"Happy path - GaugeFloat64", gaugeFloat64, &expectedGaugeFloat64Metric, false},
{"Happy path - Timer", timer, &expectedTimerMetric, false},
{"Happy path - Histogram", histogram, &expectedHistogramMetric, false},
{"No Metrics", nil, nil, false},
{"Unsupported Metric", gometrics.NewMeter(), nil, true},
}

for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
mockClient := &mocks.MessageClient{}
mockClient.On("Publish", mock.Anything, mock.Anything).Return(nil).Run(func(args mock.Arguments) {
metricArg := args.Get(0)
require.NotNil(t, metricArg)
message, ok := metricArg.(types.MessageEnvelope)
require.True(t, ok)
//actual := dtos.Metric{}
actual, err := types.GetMsgPayload[dtos.Metric](message)
require.NoError(t, err)
assert.Equal(t, expectedMetricName, actual.Name)
actual.Timestamp = test.ExpectedMetric.Timestamp
assert.Equal(t, *test.ExpectedMetric, actual)
topicArg := args.Get(1)
require.NotNil(t, topicArg)
assert.Equal(t, expectedTopic, topicArg)
})

dic := di.NewContainer(di.ServiceConstructorMap{
container.MessagingClientName: func(get di.Get) interface{} {
return mockClient
},
})

target := NewMessageBusReporter(logger.NewMockClient(), common.DefaultBaseTopic, expectedServiceName, dic, expectedTelemetryConfig)

if test.Metric != nil {
err = reg.Register(expectedMetricName, test.Metric)
require.NoError(t, err)
defer reg.Unregister(expectedMetricName)
}

err := target.Report(reg, nil)

if test.ExpectError {
require.Error(t, err)
mockClient.AssertNotCalled(t, "Publish")
return
}

require.NoError(t, err)

if test.ExpectedMetric == nil {
mockClient.AssertNotCalled(t, "Publish")
}
})
}
}

func TestMessageBusReporter_ReportWithEnv(t *testing.T) {
_ = os.Setenv("EDGEX_MSG_BASE64_PAYLOAD", common.ValueTrue)
defer os.Setenv("EDGEX_MSG_BASE64_PAYLOAD", common.ValueFalse)

expectedServiceName := "test-service"
expectedMetricName := "test-metric"
unexpectedMetricName := "disabled-metric"
expectedTopic := common.BuildTopic(common.DefaultBaseTopic, common.MetricsPublishTopic, expectedServiceName, expectedMetricName)

expectedTelemetryConfig := &config.TelemetryInfo{
Interval: "30s",
Metrics: map[string]bool{
expectedMetricName: true,
unexpectedMetricName: false,
},
Tags: nil,
}

expectedTags := []dtos.MetricTag{
{
Name: serviceNameTagKey,
Expand Down Expand Up @@ -149,7 +311,6 @@ func TestMessageBusReporter_Report(t *testing.T) {
Name: timerCountName,
Value: float64(0),
}}
expectedTimerMetric.Fields[0].Value = float64(0)
expectedTimerMetric.Fields = append(expectedTimerMetric.Fields,
[]dtos.MetricField{
{Name: timerMinName, Value: float64(0)},
Expand All @@ -167,7 +328,6 @@ func TestMessageBusReporter_Report(t *testing.T) {
Name: histogramCountName,
Value: float64(0),
}}
expectedHistogramMetric.Fields[0].Value = float64(0)
expectedHistogramMetric.Fields = append(expectedHistogramMetric.Fields,
[]dtos.MetricField{
{Name: histogramMinName, Value: float64(0)},
Expand Down Expand Up @@ -201,8 +361,7 @@ func TestMessageBusReporter_Report(t *testing.T) {
require.NotNil(t, metricArg)
message, ok := metricArg.(types.MessageEnvelope)
require.True(t, ok)
actual := dtos.Metric{}
err := json.Unmarshal(message.Payload, &actual)
actual, err := types.GetMsgPayload[dtos.Metric](message)
require.NoError(t, err)
assert.Equal(t, expectedMetricName, actual.Name)
actual.Timestamp = test.ExpectedMetric.Timestamp
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ go 1.23

require (
github.com/eclipse/paho.mqtt.golang v1.5.0
github.com/edgexfoundry/go-mod-configuration/v4 v4.0.0-dev.11
github.com/edgexfoundry/go-mod-configuration/v4 v4.0.0-dev.12
github.com/edgexfoundry/go-mod-core-contracts/v4 v4.0.0-dev.22
github.com/edgexfoundry/go-mod-messaging/v4 v4.0.0-dev.10
github.com/edgexfoundry/go-mod-messaging/v4 v4.0.0-dev.11
github.com/edgexfoundry/go-mod-registry/v4 v4.0.0-dev.3
github.com/edgexfoundry/go-mod-secrets/v4 v4.0.0-dev.5
github.com/golang-jwt/jwt/v5 v5.2.1
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/eclipse/paho.mqtt.golang v1.5.0 h1:EH+bUVJNgttidWFkLLVKaQPGmkTUfQQqjOsyvMGvD6o=
github.com/eclipse/paho.mqtt.golang v1.5.0/go.mod h1:du/2qNQVqJf/Sqs4MEL77kR8QTqANF7XU7Fk0aOTAgk=
github.com/edgexfoundry/go-mod-configuration/v4 v4.0.0-dev.11 h1:VCDeyEwhSb01dhJ3Rw0DbtV8pc18TILAoUGSFn7NR64=
github.com/edgexfoundry/go-mod-configuration/v4 v4.0.0-dev.11/go.mod h1:ltUpMcOpJSzmabBtZox5qg1AK2wEikvZJyIBXtJ7mUQ=
github.com/edgexfoundry/go-mod-configuration/v4 v4.0.0-dev.12 h1:2P7kCcGMd5BX9NFubHxfZ+Q19Q0ctMwh11rgSyPT5uc=
github.com/edgexfoundry/go-mod-configuration/v4 v4.0.0-dev.12/go.mod h1:sx5Zx+zAhmlFRNK2EblvOnCuUc099F2mHLWtZGfoWB8=
github.com/edgexfoundry/go-mod-core-contracts/v4 v4.0.0-dev.22 h1:XzDtbAmvp/v+DZlFoSgttnUQsIXGhlf+H8xgGxBClUA=
github.com/edgexfoundry/go-mod-core-contracts/v4 v4.0.0-dev.22/go.mod h1:D35HIMZkFFy82shKtPYaEL3Nn+ZNEjUjZI1RLn1j23E=
github.com/edgexfoundry/go-mod-messaging/v4 v4.0.0-dev.10 h1:xvDQDIJtmj/ZCmKzbAzg3h1F2ZdWz1MPoJSNfYZANGc=
github.com/edgexfoundry/go-mod-messaging/v4 v4.0.0-dev.10/go.mod h1:ibaiw7r3RgLYDuuFfWT1kh//bjP+onDOOQsnSsdD4E8=
github.com/edgexfoundry/go-mod-messaging/v4 v4.0.0-dev.11 h1:JNhS2eIPNJI5Ie043pvxGlP+4SLXglGw+dHAqCguC48=
github.com/edgexfoundry/go-mod-messaging/v4 v4.0.0-dev.11/go.mod h1:BfIFNR+dinBvg3s2bHoIuRwpw5KwCbMtjtIu5T/0WwM=
github.com/edgexfoundry/go-mod-registry/v4 v4.0.0-dev.3 h1:6tw6JqEJDOqo2lEgxjZ+scvsub5R20WGpInCuoxS6zE=
github.com/edgexfoundry/go-mod-registry/v4 v4.0.0-dev.3/go.mod h1:QpZW5bWxsk0Leh1nvgojBZrpHA/B6dSw6LgT0zxh9hg=
github.com/edgexfoundry/go-mod-secrets/v4 v4.0.0-dev.5 h1:PnbvMnedIlbqXsnUp2+i18BJ9e6CJ7GzwNA9vjPU3Jk=
Expand Down

0 comments on commit 689d11e

Please sign in to comment.