snapshot of https://github.com/mattermost/mattermost.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Server CI / Postgres (shard 0) (push) Has been skipped
Server CI / Postgres (shard 3) (push) Has been skipped
BuildEnv Docker Image / build-image (push) Failing after 4s
BuildEnv Docker Image / build-image-fips (push) Failing after 4s
Migration Review & Release Notes / Generate migration review & release notes (push) Failing after 3s
Server CI / Build Environment (push) Failing after 3s
Server CI / Postgres (shard 1) (push) Has been skipped
Tools CI / check-style (mattermost-govet) (push) Failing after 4s
Server CI / Postgres (shard 2) (push) Has been skipped
Tools CI / check-style (mmgotool) (push) Failing after 3s
Server CI / Elasticsearch v8 Compatibility (push) Has been skipped
Server CI / OpenSearch v2 Compatibility (push) Has been skipped
Server CI / Postgres FIPS (shard 0) (push) Has been skipped
Tools CI / Test (mattermost-govet) (push) Failing after 3s
Server CI / Postgres FIPS (shard 1) (push) Has been skipped
Server CI / Postgres FIPS (shard 2) (push) Has been skipped
Tools CI / Test (mmgotool) (push) Failing after 3s
Server CI / Postgres FIPS (shard 3) (push) Has been skipped
Server CI / Run mmctl tests (push) Has been skipped
Server CI / Run mmctl tests (FIPS) (push) Has been skipped
Server CI / Merge Postgres Test Results (push) Has been skipped
Server CI / Merge Postgres FIPS Test Results (push) Has been skipped
Server CI / Check backport migrations (push) Has been skipped
Server CI / Check generated files (push) Has been skipped
Server CI / check-style (push) Has been skipped
Server CI / Vet API (push) Has been skipped
Server CI / Build mattermost server app (push) Has been skipped
Server CI / Server CI Complete (push) Failing after 2s
Server CI / Server CI Artifacts (push) Has been skipped
Server CI / Sentry Upload (push) Has been skipped
Server CI / Server CI Report (push) Failing after 5m1s
Server CI Nightly Race / Race Detector (push) Has been skipped
CodeQL / Analyze (go) (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
Webapp CI Cache Warm / Warm Webapp node_modules Cache (push) Has been cancelled
E2E CI Cache Warm / Warm E2E npm Registry Cache (push) Has been cancelled
API / build (push) Has been cancelled
Web App CI / check-types (push) Has been cancelled
Web App CI / check-lint (push) Has been cancelled
Web App CI / check-i18n (push) Has been cancelled
Web App CI / check-external-links (push) Has been cancelled
Web App CI / test (platform) (push) Has been cancelled
Web App CI / test (mattermost-redux) (push) Has been cancelled
Web App CI / test (channels shard 1/4) (push) Has been cancelled
Web App CI / test (channels shard 2/4) (push) Has been cancelled
Web App CI / test (channels shard 3/4) (push) Has been cancelled
Web App CI / test (channels shard 4/4) (push) Has been cancelled
Web App CI / upload-coverage (push) Has been cancelled
Web App CI / build (push) Has been cancelled
YAML Lint / yamllint (push) Has been cancelled
Push mirrored docker images / cd/Push mirrored docker images (push) Has been cancelled
docs-cd / Build and deploy docs (push) Has been cancelled
Docs CI / build (push) Has been cancelled
E2E Cache Warm: Cypress deps / Warm Cypress deps cache (push) Has been cancelled
Scorecards supply-chain security / Scorecard analysis (push) Has been cancelled
Server CI Weekly / Postgres FIPS (push) Has been skipped
Server CI Weekly / Run mmctl tests (FIPS) (push) Has been skipped
Server CI Weekly / Postgres with binary parameters (push) Has been skipped
Server CI Weekly / Build Environment (push) Failing after 1s
Server CI Cache Warm / Warm Go Module and Build Cache (push) Failing after 2s
Server CI Nightly Race / Build Environment (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 00:29:55 +05:00
commit 240db4e2a7
15309 changed files with 2173406 additions and 0 deletions

View File

@@ -0,0 +1,81 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.enterprise for license information.
package metrics
import (
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/prometheus/client_golang/prometheus"
)
// DynamicCounter provides a CounterVec that can create new counters via label values at runtime.
// This allows applications to create counters at runtime without locking into Prometheus as the
// metrics manager.
type DynamicCounter struct {
counter *prometheus.CounterVec
}
// NewDynamicCounter creates a new dynamic counter with corresponding labels.
func NewDynamicCounter(opts prometheus.CounterOpts, labels ...string) *DynamicCounter {
return &DynamicCounter{
counter: prometheus.NewCounterVec(opts, labels),
}
}
// GetCounter fetches a counter associated with the label values provided. An error is
// returned if the number of values differs from the number of labels provided when
// creating the DynamicCounter
func (dc *DynamicCounter) GetCounter(values ...string) (prometheus.Counter, error) {
return dc.counter.GetMetricWithLabelValues(values...)
}
// DynamicGauge provides a GaugeVec that can create new gauges via label values at runtime.
// This allows applications to create gauges at runtime without locking into Prometheus as the
// metrics manager.
type DynamicGauge struct {
gauge *prometheus.GaugeVec
}
// NewDynamicGauge creates a new dynamic gauge with corresponding labels.
func NewDynamicGauge(opts prometheus.GaugeOpts, labels ...string) *DynamicGauge {
return &DynamicGauge{
gauge: prometheus.NewGaugeVec(opts, labels),
}
}
// GetGauge fetches a gauge associated with the label values provided. An error is
// returned if the number of values differs from the number of labels provided when
// creating the DynamicGauge
func (dg *DynamicGauge) GetGauge(values ...string) (prometheus.Gauge, error) {
return dg.gauge.GetMetricWithLabelValues(values...)
}
// LoggerMetricsCollector provides counters for server logging.
// Implements Logr.MetricsCollector
type LoggerMetricsCollector struct {
queueGauge *DynamicGauge
loggedCounters *DynamicCounter
errorCounters *DynamicCounter
droppedCounters *DynamicCounter
blockedCounters *DynamicCounter
}
func (c *LoggerMetricsCollector) QueueSizeGauge(target string) (mlog.Gauge, error) {
return c.queueGauge.GetGauge(target)
}
func (c *LoggerMetricsCollector) LoggedCounter(target string) (mlog.Counter, error) {
return c.loggedCounters.GetCounter(target)
}
func (c *LoggerMetricsCollector) ErrorCounter(target string) (mlog.Counter, error) {
return c.errorCounters.GetCounter(target)
}
func (c *LoggerMetricsCollector) DroppedCounter(target string) (mlog.Counter, error) {
return c.droppedCounters.GetCounter(target)
}
func (c *LoggerMetricsCollector) BlockedCounter(target string) (mlog.Counter, error) {
return c.blockedCounters.GetCounter(target)
}

View File

@@ -0,0 +1,74 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.enterprise for license information.
package metrics
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/mattermost/mattermost/server/public/shared/mlog"
)
// HistogramVec is a wrapper of prometheus.HistogramVec that stores the buckets
// which are later passed down to WrappedObserver.
type HistogramVec struct {
*prometheus.HistogramVec
buckets []float64
fqName string
logger mlog.LoggerIFace
}
// WrappedObserver is a wrapper of prometheus.Observer which addtionally
// logs userIDs when the value exceeds or equals to the one in the highest bucket.
type WrappedObserver struct {
prometheus.Observer
labels prometheus.Labels
buckets []float64
logger mlog.LoggerIFace
metricName string
userID string
}
// NewHistogramVec returns a custom-purpose HistogramVec.
func NewHistogramVec(opts prometheus.HistogramOpts, labelNames []string, logger mlog.LoggerIFace) *HistogramVec {
if len(opts.Buckets) == 0 {
opts.Buckets = prometheus.DefBuckets
}
return &HistogramVec{
HistogramVec: prometheus.NewHistogramVec(opts, labelNames),
buckets: opts.Buckets,
fqName: prometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
logger: logger,
}
}
func (v *HistogramVec) With(labels prometheus.Labels, userID string) prometheus.Observer {
h, err := v.GetMetricWith(labels)
if err != nil {
panic(err)
}
return &WrappedObserver{
Observer: h,
labels: labels,
buckets: v.buckets,
logger: v.logger,
metricName: v.fqName,
userID: userID,
}
}
func (o *WrappedObserver) Observe(v float64) {
if v >= o.buckets[len(o.buckets)-1] {
fields := []mlog.Field{
mlog.String("metric_name", o.metricName),
mlog.String("user_id", o.userID),
mlog.Float("observed_value", v),
mlog.Float("highest_bucket_value", o.buckets[len(o.buckets)-1]),
}
for k, v := range o.labels {
fields = append(fields, mlog.String(k, v))
}
o.logger.Warn("Metric observation exceeded.", fields...)
}
o.Observer.Observe(v)
}

View File

@@ -0,0 +1,34 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.enterprise for license information.
package metrics
import (
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/v8/channels/api4"
"github.com/mattermost/mattermost/server/v8/channels/testlib"
)
func TestWrappedObserver(t *testing.T) {
th := api4.Setup(t)
h := NewHistogramVec(prometheus.HistogramOpts{
Namespace: MetricsNamespace,
Subsystem: MetricsSubsystemClientsWeb,
Name: "test",
Buckets: []float64{0, 5, 10},
}, []string{"l1"}, th.TestLogger)
h.With(prometheus.Labels{"l1": "hello"}, th.BasicUser.Id).Observe(6)
require.NoError(t, th.TestLogger.Flush())
testlib.AssertNoLog(t, th.LogBuffer, mlog.LvlWarn.Name, "Metric observation exceeded.")
h.With(prometheus.Labels{"l1": "hello"}, th.BasicUser.Id).Observe(10)
require.NoError(t, th.TestLogger.Flush())
testlib.AssertLog(t, th.LogBuffer, mlog.LvlWarn.Name, "Metric observation exceeded.")
}

View File

@@ -0,0 +1,21 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.enterprise for license information.
package metrics
import (
"testing"
"github.com/mattermost/mattermost/server/v8/channels/api4"
"github.com/mattermost/mattermost/server/v8/channels/testlib"
)
var mainHelper *testlib.MainHelper
func TestMain(m *testing.M) {
mainHelper = testlib.NewMainHelper()
defer mainHelper.Close()
api4.SetMainHelper(mainHelper)
mainHelper.Main(m)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,401 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.enterprise for license information.
package metrics
import (
"fmt"
"strconv"
"testing"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/v8/channels/api4"
"github.com/mattermost/mattermost/server/v8/channels/app"
seMocks "github.com/mattermost/mattermost/server/v8/platform/services/searchengine/mocks"
"github.com/mattermost/mattermost/server/public/plugin/plugintest/mock"
"github.com/mattermost/mattermost/server/v8/channels/store/storetest/mocks"
"github.com/prometheus/client_golang/prometheus"
prometheusModels "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/require"
)
func configureMetrics(th *api4.TestHelper) {
th.App.Srv().SetLicense(nil) // clear license
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.MetricsSettings.Enable = true
*cfg.MetricsSettings.ListenAddress = ":0"
})
th.App.Srv().SetLicense(model.NewTestLicense("metrics"))
}
func TestMetrics(t *testing.T) {
th := api4.SetupEnterpriseWithStoreMock(t, app.StartMetrics)
mockStore := th.App.Srv().Platform().Store.(*mocks.Store)
mockUserStore := mocks.UserStore{}
mockUserStore.On("Count", mock.Anything).Return(int64(10), nil)
mockPostStore := mocks.PostStore{}
mockPostStore.On("GetMaxPostSize").Return(model.PostMessageMaxBytesV2, nil)
mockSystemStore := mocks.SystemStore{}
mockSystemStore.On("GetByName", "UpgradedFromTE").Return(&model.System{Name: "UpgradedFromTE", Value: "false"}, nil)
mockSystemStore.On("GetByName", "InstallationDate").Return(&model.System{Name: "InstallationDate", Value: "10"}, nil)
mockStore.On("User").Return(&mockUserStore)
mockStore.On("Post").Return(&mockPostStore)
mockStore.On("System").Return(&mockSystemStore)
mockStore.On("GetDBSchemaVersion").Return(1, nil)
configureMetrics(th)
mi := th.App.Metrics()
_, ok := mi.(*MetricsInterfaceImpl)
require.True(t, ok, fmt.Sprintf("App.Metrics is not *MetricsInterfaceImpl, but %T", mi))
mi.IncrementHTTPRequest()
mi.IncrementHTTPError()
mi.IncrementPostFileAttachment(5)
mi.IncrementPostCreate()
mi.IncrementPostSentEmail()
mi.IncrementPostSentPush()
mi.IncrementPostBroadcast()
mi.IncrementLogin()
mi.IncrementLoginFail()
mi.IncrementClusterRequest()
mi.ObserveClusterRequestDuration(2.0)
mi.IncrementClusterEventType(model.ClusterEventPublish)
loggerCollector := mi.GetLoggerMetricsCollector()
g, err := loggerCollector.QueueSizeGauge("_logr")
require.NoError(t, err)
g.Set(59)
c, err := loggerCollector.LoggedCounter("_logr")
require.NoError(t, err)
c.Inc()
c, err = loggerCollector.ErrorCounter("_logr")
require.NoError(t, err)
c.Inc()
c, err = loggerCollector.DroppedCounter("_logr")
require.NoError(t, err)
c.Inc()
c, err = loggerCollector.BlockedCounter("_logr")
require.NoError(t, err)
c.Inc()
}
func TestPluginMetrics(t *testing.T) {
th := api4.SetupEnterprise(t, app.StartMetrics)
configureMetrics(th)
mi := th.App.Metrics()
miImpl, ok := mi.(*MetricsInterfaceImpl)
require.True(t, ok, fmt.Sprintf("App.Metrics is not *MetricsInterfaceImpl, but %T", mi))
t.Run("test ObservePluginHookDuration", func(t *testing.T) {
pluginID := "id_"
hookName := "hook_"
elapsed := 999.1
m := &prometheusModels.Metric{}
for _, success := range []bool{true, false} {
actualMetric, err := miImpl.PluginHookTimeHistogram.GetMetricWith(prometheus.Labels{"plugin_id": pluginID, "hook_name": hookName, "success": strconv.FormatBool(success)})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(0), m.Histogram.GetSampleCount())
require.Equal(t, 0.0, m.Histogram.GetSampleSum())
mi.ObservePluginHookDuration(pluginID, hookName, success, elapsed)
actualMetric, err = miImpl.PluginHookTimeHistogram.GetMetricWith(prometheus.Labels{"plugin_id": pluginID, "hook_name": hookName, "success": strconv.FormatBool(success)})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(1), m.Histogram.GetSampleCount())
require.InDelta(t, elapsed, m.Histogram.GetSampleSum(), 0.001)
}
})
t.Run("test ObservePluginAPIDuration", func(t *testing.T) {
pluginID := "id_"
apiName := "api_"
elapsed := 999.1
m := &prometheusModels.Metric{}
for _, success := range []bool{true, false} {
actualMetric, err := miImpl.PluginAPITimeHistogram.GetMetricWith(prometheus.Labels{"plugin_id": pluginID, "api_name": apiName, "success": strconv.FormatBool(success)})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(0), m.Histogram.GetSampleCount())
require.Equal(t, 0.0, m.Histogram.GetSampleSum())
mi.ObservePluginAPIDuration(pluginID, apiName, success, elapsed)
actualMetric, err = miImpl.PluginAPITimeHistogram.GetMetricWith(prometheus.Labels{"plugin_id": pluginID, "api_name": apiName, "success": strconv.FormatBool(success)})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(1), m.Histogram.GetSampleCount())
require.InDelta(t, elapsed, m.Histogram.GetSampleSum(), 0.001)
}
})
t.Run("test ObservePluginMultiHookIterationDuration", func(t *testing.T) {
pluginID := "id_"
elapsed := 999.1
m := &prometheusModels.Metric{}
actualMetric, err := miImpl.PluginMultiHookTimeHistogram.GetMetricWith(prometheus.Labels{"plugin_id": pluginID})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(0), m.Histogram.GetSampleCount())
require.Equal(t, 0.0, m.Histogram.GetSampleSum())
mi.ObservePluginMultiHookIterationDuration(pluginID, elapsed)
actualMetric, err = miImpl.PluginMultiHookTimeHistogram.GetMetricWith(prometheus.Labels{"plugin_id": pluginID})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(1), m.Histogram.GetSampleCount())
require.InDelta(t, elapsed, m.Histogram.GetSampleSum(), 0.001)
})
t.Run("test ObservePluginMultiHookDuration", func(t *testing.T) {
elapsed := 50.0
m := &prometheusModels.Metric{}
require.NoError(t, miImpl.PluginMultiHookServerTimeHistogram.Write(m))
require.InDelta(t, 0.0, m.Histogram.GetSampleSum(), 0.001)
mi.ObservePluginMultiHookDuration(elapsed)
require.NoError(t, miImpl.PluginMultiHookServerTimeHistogram.Write(m))
require.InDelta(t, elapsed, m.Histogram.GetSampleSum(), 0.001)
})
}
func TestMobileMetrics(t *testing.T) {
th := api4.SetupEnterprise(t, app.StartMetrics)
configureMetrics(th)
mi := th.App.Metrics()
miImpl, ok := mi.(*MetricsInterfaceImpl)
require.True(t, ok, fmt.Sprintf("App.Metrics is not *MetricsInterfaceImpl, but %T", mi))
ttcc := []struct {
name string
histogramVec *prometheus.HistogramVec
observeFunc func(string, float64)
}{
{
name: "load duration",
histogramVec: miImpl.MobileClientLoadDuration,
observeFunc: mi.ObserveMobileClientLoadDuration,
},
{
name: "channel switch duration",
histogramVec: miImpl.MobileClientChannelSwitchDuration,
observeFunc: mi.ObserveMobileClientChannelSwitchDuration,
},
{
name: "team switch duration",
histogramVec: miImpl.MobileClientTeamSwitchDuration,
observeFunc: mi.ObserveMobileClientTeamSwitchDuration,
},
}
for _, tc := range ttcc {
t.Run(tc.name, func(t *testing.T) {
m := &prometheusModels.Metric{}
elapsed := 999.1
for _, platform := range []string{"ios", "android"} {
actualMetric, err := tc.histogramVec.GetMetricWith(prometheus.Labels{"platform": platform})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(0), m.Histogram.GetSampleCount())
require.Equal(t, 0.0, m.Histogram.GetSampleSum())
tc.observeFunc(platform, elapsed)
actualMetric, err = tc.histogramVec.GetMetricWith(prometheus.Labels{"platform": platform})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(1), m.Histogram.GetSampleCount())
require.InDelta(t, elapsed, m.Histogram.GetSampleSum(), 0.001)
}
})
}
}
func TestExtractDBCluster(t *testing.T) {
testCases := []struct {
description string
driver string
connectionStr string
expectedClusterName string
}{
{
description: "postgres full",
driver: "postgres",
connectionStr: "postgres://user1234:password1234@rds-cluster-multitenant-1234-postgres.cluster-abcd.us-east-1.rds.amazonaws.com:5432/cloud?connect_timeout=10",
expectedClusterName: "rds-cluster-multitenant-1234-postgres",
},
{
description: "postgres no credentials",
driver: "postgres",
connectionStr: "postgres://rds-cluster-multitenant-1234-postgres.cluster-abcd.us-east-1.rds.amazonaws.com:5432/cloud?connect_timeout=10",
expectedClusterName: "rds-cluster-multitenant-1234-postgres",
},
}
for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
host, err := extractDBCluster(tc.driver, tc.connectionStr)
require.NoError(t, err)
require.Equal(t, tc.expectedClusterName, host)
})
}
}
func TestSearchEngineStatusGauge(t *testing.T) {
th := api4.SetupEnterprise(t, app.StartMetrics)
configureMetrics(th)
mi := th.App.Metrics()
miImpl, ok := mi.(*MetricsInterfaceImpl)
require.True(t, ok, fmt.Sprintf("App.Metrics is not *MetricsInterfaceImpl, but %T", mi))
readGauge := func() float64 {
m := &prometheusModels.Metric{}
require.NoError(t, miImpl.SearchEngineStatusGauge.Write(m))
return m.Gauge.GetValue()
}
setEngine := func(t *testing.T, engine *seMocks.SearchEngineInterface) {
t.Helper()
miImpl.Platform.SearchEngine.ElasticsearchEngine = engine
t.Cleanup(func() {
miImpl.Platform.SearchEngine.ElasticsearchEngine = nil
})
}
t.Run("nil engine returns 1", func(t *testing.T) {
miImpl.Platform.SearchEngine.ElasticsearchEngine = nil
require.Equal(t, 1.0, readGauge())
})
t.Run("disabled engine returns 1", func(t *testing.T) {
esMock := &seMocks.SearchEngineInterface{}
esMock.On("IsEnabled").Return(false)
setEngine(t, esMock)
require.Equal(t, 1.0, readGauge())
})
t.Run("enabled healthy engine returns 1", func(t *testing.T) {
esMock := &seMocks.SearchEngineInterface{}
esMock.On("IsEnabled").Return(true)
esMock.On("IsHealthy").Return(true)
setEngine(t, esMock)
require.Equal(t, 1.0, readGauge())
})
t.Run("enabled unhealthy engine returns 0", func(t *testing.T) {
esMock := &seMocks.SearchEngineInterface{}
esMock.On("IsEnabled").Return(true)
esMock.On("IsHealthy").Return(false)
setEngine(t, esMock)
require.Equal(t, 0.0, readGauge())
})
}
func TestObserveClusterReliableFallbackLength(t *testing.T) {
th := api4.SetupEnterprise(t, app.StartMetrics)
configureMetrics(th)
mi := th.App.Metrics()
miImpl, ok := mi.(*MetricsInterfaceImpl)
require.True(t, ok, fmt.Sprintf("App.Metrics is not *MetricsInterfaceImpl, but %T", mi))
event := model.ClusterEvent("ws_event")
length := 42
m := &prometheusModels.Metric{}
t.Run("labels are correct", func(t *testing.T) {
_, err := miImpl.ClusterReliableFallbackLength.GetMetricWith(prometheus.Labels{"event": "x"})
require.NoError(t, err, "expected 'event' to be a registered label")
_, err = miImpl.ClusterReliableFallbackLength.GetMetricWith(prometheus.Labels{"wrong_label": "x"})
require.Error(t, err, "expected no label other than 'event' to be registered")
})
t.Run("metric is registered and initialized at 0", func(t *testing.T) {
actualMetric, err := miImpl.ClusterReliableFallbackLength.GetMetricWith(prometheus.Labels{"event": string(event)})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(0), m.Histogram.GetSampleCount())
require.Equal(t, 0.0, m.Histogram.GetSampleSum())
})
t.Run("metric can be observed and the registered value is correct", func(t *testing.T) {
mi.ObserveClusterReliableFallbackLength(event, length)
actualMetric, err := miImpl.ClusterReliableFallbackLength.GetMetricWith(prometheus.Labels{"event": string(event)})
require.NoError(t, err)
require.NoError(t, actualMetric.(prometheus.Histogram).Write(m))
require.Equal(t, uint64(1), m.Histogram.GetSampleCount())
require.InDelta(t, float64(length), m.Histogram.GetSampleSum(), 0.001)
})
}
func TestMergeLabels(t *testing.T) {
t.Run("combines both maps", func(t *testing.T) {
got := mergeLabels(map[string]string{"a": "1"}, map[string]string{"b": "2"})
require.Equal(t, prometheus.Labels{"a": "1", "b": "2"}, got)
})
t.Run("extra takes precedence over base", func(t *testing.T) {
got := mergeLabels(map[string]string{"a": "1"}, map[string]string{"a": "2"})
require.Equal(t, prometheus.Labels{"a": "2"}, got)
})
t.Run("handles nil maps", func(t *testing.T) {
require.Equal(t, prometheus.Labels{}, mergeLabels(nil, nil))
})
}
func TestServerInfo(t *testing.T) {
th := api4.SetupEnterprise(t, app.StartMetrics)
configureMetrics(th)
mi := th.App.Metrics()
miImpl, ok := mi.(*MetricsInterfaceImpl)
require.True(t, ok, fmt.Sprintf("App.Metrics is not *MetricsInterfaceImpl, but %T", mi))
m := &prometheusModels.Metric{}
require.NoError(t, miImpl.ServerInfo.Write(m))
t.Run("gauge value is always 1", func(t *testing.T) {
require.Equal(t, 1.0, m.Gauge.GetValue())
})
t.Run("carries the build information as labels", func(t *testing.T) {
labels := map[string]string{}
for _, pair := range m.GetLabel() {
labels[pair.GetName()] = pair.GetValue()
}
for key, want := range map[string]string{
"version": model.CurrentVersion,
"build_number": model.BuildNumber,
"build_hash": model.BuildHash,
"build_hash_enterprise": model.BuildHashEnterprise,
} {
require.Contains(t, labels, key)
require.Equal(t, want, labels[key])
}
})
}