github.com/neatlab/neatio@v1.7.3-0.20220425043230-d903e92fcc75/utilities/metrics/gauge.go (about)

     1  package metrics
     2  
     3  import "sync/atomic"
     4  
     5  type Gauge interface {
     6  	Snapshot() Gauge
     7  	Update(int64)
     8  	Value() int64
     9  }
    10  
    11  func GetOrRegisterGauge(name string, r Registry) Gauge {
    12  	if nil == r {
    13  		r = DefaultRegistry
    14  	}
    15  	return r.GetOrRegister(name, NewGauge).(Gauge)
    16  }
    17  
    18  func NewGauge() Gauge {
    19  	if !Enabled {
    20  		return NilGauge{}
    21  	}
    22  	return &StandardGauge{0}
    23  }
    24  
    25  func NewRegisteredGauge(name string, r Registry) Gauge {
    26  	c := NewGauge()
    27  	if nil == r {
    28  		r = DefaultRegistry
    29  	}
    30  	r.Register(name, c)
    31  	return c
    32  }
    33  
    34  func NewFunctionalGauge(f func() int64) Gauge {
    35  	if !Enabled {
    36  		return NilGauge{}
    37  	}
    38  	return &FunctionalGauge{value: f}
    39  }
    40  
    41  func NewRegisteredFunctionalGauge(name string, r Registry, f func() int64) Gauge {
    42  	c := NewFunctionalGauge(f)
    43  	if nil == r {
    44  		r = DefaultRegistry
    45  	}
    46  	r.Register(name, c)
    47  	return c
    48  }
    49  
    50  type GaugeSnapshot int64
    51  
    52  func (g GaugeSnapshot) Snapshot() Gauge { return g }
    53  
    54  func (GaugeSnapshot) Update(int64) {
    55  	panic("Update called on a GaugeSnapshot")
    56  }
    57  
    58  func (g GaugeSnapshot) Value() int64 { return int64(g) }
    59  
    60  type NilGauge struct{}
    61  
    62  func (NilGauge) Snapshot() Gauge { return NilGauge{} }
    63  
    64  func (NilGauge) Update(v int64) {}
    65  
    66  func (NilGauge) Value() int64 { return 0 }
    67  
    68  type StandardGauge struct {
    69  	value int64
    70  }
    71  
    72  func (g *StandardGauge) Snapshot() Gauge {
    73  	return GaugeSnapshot(g.Value())
    74  }
    75  
    76  func (g *StandardGauge) Update(v int64) {
    77  	atomic.StoreInt64(&g.value, v)
    78  }
    79  
    80  func (g *StandardGauge) Value() int64 {
    81  	return atomic.LoadInt64(&g.value)
    82  }
    83  
    84  type FunctionalGauge struct {
    85  	value func() int64
    86  }
    87  
    88  func (g FunctionalGauge) Value() int64 {
    89  	return g.value()
    90  }
    91  
    92  func (g FunctionalGauge) Snapshot() Gauge { return GaugeSnapshot(g.Value()) }
    93  
    94  func (FunctionalGauge) Update(int64) {
    95  	panic("Update called on a FunctionalGauge")
    96  }