fix(metrics): add doc comments, fix labels mutation and nil returns, add idempotent Close, add nil guards, add tests

- Fix promMetrics.Gauge/Counter/Observer mutating caller's labels map by
  using maps.Copy instead of direct assignment
- Fix Gauge/Counter/Observer returning nil for unknown metric names
  (now return noop implementations)
- Fix metricService.Close() race with sync.Once for safe concurrent calls
- Fix SetDSCP returning nil instead of errUnsupport on unsupported ops
- Add nil guards to WrapConn, WrapPacketConn, WrapUDPConn, WrapListener
- Add doc comments to all exported symbols
- Add 45 unit tests (metrics, noop, prom, service, wrapper)
This commit is contained in:
ginuerzh
2026-05-24 22:50:41 +08:00
parent 64f9a048f8
commit bc3d12ec2c
12 changed files with 950 additions and 23 deletions
+9
View File
@@ -34,14 +34,19 @@ var (
enabled atomic.Bool
)
// Enable enables or disables metrics collection globally. When disabled, all
// GetCounter, GetGauge, and GetObserver calls return noop implementations.
func Enable(b bool) {
enabled.Store(b)
}
// IsEnabled reports whether metrics collection is enabled.
func IsEnabled() bool {
return enabled.Load()
}
// GetCounter returns a Counter for the given name and labels. When metrics are
// disabled, a noop implementation is returned.
func GetCounter(name metrics.MetricName, labels metrics.Labels) metrics.Counter {
if IsEnabled() {
return defaultMetrics.Counter(name, labels)
@@ -49,6 +54,8 @@ func GetCounter(name metrics.MetricName, labels metrics.Labels) metrics.Counter
return noop.Counter(name, labels)
}
// GetGauge returns a Gauge for the given name and labels. When metrics are
// disabled, a noop implementation is returned.
func GetGauge(name metrics.MetricName, labels metrics.Labels) metrics.Gauge {
if IsEnabled() {
return defaultMetrics.Gauge(name, labels)
@@ -56,6 +63,8 @@ func GetGauge(name metrics.MetricName, labels metrics.Labels) metrics.Gauge {
return noop.Gauge(name, labels)
}
// GetObserver returns an Observer for the given name and labels. When metrics are
// disabled, a noop implementation is returned.
func GetObserver(name metrics.MetricName, labels metrics.Labels) metrics.Observer {
if IsEnabled() {
return defaultMetrics.Observer(name, labels)