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
+11 -1
View File
@@ -26,6 +26,8 @@ type serverConn struct {
clientIP string
}
// WrapConn wraps a net.Conn with metrics tracking. Bytes read/written are
// counted as service transfer input/output. If c is nil, nil is returned.
func WrapConn(service string, c net.Conn) net.Conn {
if c == nil {
return c
@@ -101,6 +103,8 @@ type packetConn struct {
service string
}
// WrapPacketConn wraps a net.PacketConn with metrics tracking. Bytes read/written
// are counted as service transfer input/output. If pc is nil, nil is returned.
func WrapPacketConn(service string, pc net.PacketConn) net.PacketConn {
if pc == nil {
return pc
@@ -161,7 +165,13 @@ type udpConn struct {
service string
}
// WrapUDPConn wraps a net.PacketConn as a udp.Conn with metrics tracking. Bytes
// read/written are counted as service transfer input/output. If pc is nil, nil
// is returned.
func WrapUDPConn(service string, pc net.PacketConn) udp.Conn {
if pc == nil {
return nil
}
return &udpConn{
PacketConn: pc,
service: service,
@@ -377,7 +387,7 @@ func (c *udpConn) SetDSCP(n int) error {
if nc, ok := c.PacketConn.(xnet.SetDSCP); ok {
return nc.SetDSCP(n)
}
return nil
return errUnsupport
}
func (c *udpConn) Context() context.Context {