github.com/theQRL/go-zond@v0.1.1/metrics/gauge_info.go (about)

     1  package metrics
     2  
     3  import (
     4  	"encoding/json"
     5  	"sync"
     6  )
     7  
     8  type GaugeInfoSnapshot interface {
     9  	Value() GaugeInfoValue
    10  }
    11  
    12  // GaugeInfos hold a GaugeInfoValue value that can be set arbitrarily.
    13  type GaugeInfo interface {
    14  	Update(GaugeInfoValue)
    15  	Snapshot() GaugeInfoSnapshot
    16  }
    17  
    18  // GaugeInfoValue is a mapping of keys to values
    19  type GaugeInfoValue map[string]string
    20  
    21  func (val GaugeInfoValue) String() string {
    22  	data, _ := json.Marshal(val)
    23  	return string(data)
    24  }
    25  
    26  // GetOrRegisterGaugeInfo returns an existing GaugeInfo or constructs and registers a
    27  // new StandardGaugeInfo.
    28  func GetOrRegisterGaugeInfo(name string, r Registry) GaugeInfo {
    29  	if nil == r {
    30  		r = DefaultRegistry
    31  	}
    32  	return r.GetOrRegister(name, NewGaugeInfo()).(GaugeInfo)
    33  }
    34  
    35  // NewGaugeInfo constructs a new StandardGaugeInfo.
    36  func NewGaugeInfo() GaugeInfo {
    37  	if !Enabled {
    38  		return NilGaugeInfo{}
    39  	}
    40  	return &StandardGaugeInfo{
    41  		value: GaugeInfoValue{},
    42  	}
    43  }
    44  
    45  // NewRegisteredGaugeInfo constructs and registers a new StandardGaugeInfo.
    46  func NewRegisteredGaugeInfo(name string, r Registry) GaugeInfo {
    47  	c := NewGaugeInfo()
    48  	if nil == r {
    49  		r = DefaultRegistry
    50  	}
    51  	r.Register(name, c)
    52  	return c
    53  }
    54  
    55  // gaugeInfoSnapshot is a read-only copy of another GaugeInfo.
    56  type gaugeInfoSnapshot GaugeInfoValue
    57  
    58  // Value returns the value at the time the snapshot was taken.
    59  func (g gaugeInfoSnapshot) Value() GaugeInfoValue { return GaugeInfoValue(g) }
    60  
    61  type NilGaugeInfo struct{}
    62  
    63  func (NilGaugeInfo) Snapshot() GaugeInfoSnapshot { return NilGaugeInfo{} }
    64  func (NilGaugeInfo) Update(v GaugeInfoValue)     {}
    65  func (NilGaugeInfo) Value() GaugeInfoValue       { return GaugeInfoValue{} }
    66  
    67  // StandardGaugeInfo is the standard implementation of a GaugeInfo and uses
    68  // sync.Mutex to manage a single string value.
    69  type StandardGaugeInfo struct {
    70  	mutex sync.Mutex
    71  	value GaugeInfoValue
    72  }
    73  
    74  // Snapshot returns a read-only copy of the gauge.
    75  func (g *StandardGaugeInfo) Snapshot() GaugeInfoSnapshot {
    76  	return gaugeInfoSnapshot(g.value)
    77  }
    78  
    79  // Update updates the gauge's value.
    80  func (g *StandardGaugeInfo) Update(v GaugeInfoValue) {
    81  	g.mutex.Lock()
    82  	defer g.mutex.Unlock()
    83  	g.value = v
    84  }