github.com/anycable/anycable-go@v1.5.1/metrics/counter.go (about)

     1  package metrics
     2  
     3  import "sync/atomic"
     4  
     5  // Counter stores information about something "countable".
     6  // Store
     7  type Counter struct {
     8  	name              string
     9  	desc              string
    10  	value             uint64
    11  	lastIntervalValue uint64
    12  	lastIntervalDelta uint64
    13  }
    14  
    15  // NewCounter creates new Counter.
    16  func NewCounter(name string, desc string) *Counter {
    17  	return &Counter{name: name, desc: desc, value: 0}
    18  }
    19  
    20  // Name returns counter name
    21  func (c *Counter) Name() string {
    22  	return c.name
    23  }
    24  
    25  // Desc returns counter description
    26  func (c *Counter) Desc() string {
    27  	return c.desc
    28  }
    29  
    30  // Value allows to get raw counter value.
    31  func (c *Counter) Value() uint64 {
    32  	return atomic.LoadUint64(&c.value)
    33  }
    34  
    35  // IntervalValue allows to get last interval value for counter.
    36  func (c *Counter) IntervalValue() uint64 {
    37  	if c.lastIntervalValue == 0 {
    38  		return c.Value()
    39  	}
    40  	return atomic.LoadUint64(&c.lastIntervalDelta)
    41  }
    42  
    43  // Inc is equivalent to Add(name, 1)
    44  func (c *Counter) Inc() uint64 {
    45  	return c.Add(1)
    46  }
    47  
    48  // Add adds the given number to the counter and returns the new value.
    49  func (c *Counter) Add(n uint64) uint64 {
    50  	return atomic.AddUint64(&c.value, n)
    51  }
    52  
    53  // UpdateDelta updates the delta value for last interval based on current value and previous value.
    54  func (c *Counter) UpdateDelta() {
    55  	now := atomic.LoadUint64(&c.value)
    56  	atomic.StoreUint64(&c.lastIntervalDelta, now-atomic.LoadUint64(&c.lastIntervalValue))
    57  	atomic.StoreUint64(&c.lastIntervalValue, now)
    58  }