github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/stats/state.go (about)

     1  package stats
     2  
     3  import (
     4  	"github.com/v2pro/plz/countlog/spi"
     5  	"time"
     6  )
     7  
     8  
     9  type Point struct {
    10  	Event     string
    11  	Timestamp time.Time
    12  	Dimension []string
    13  	Value     float64
    14  }
    15  
    16  type Collector interface {
    17  	Collect(point *Point)
    18  }
    19  
    20  type Monoid interface {
    21  	Add(that Monoid)
    22  	Export() float64
    23  }
    24  
    25  type State interface {
    26  	spi.EventHandler
    27  	GetWindow() *Window
    28  }
    29  
    30  type CounterMonoid uint64
    31  
    32  func NewCounterMonoid() Monoid {
    33  	var c CounterMonoid
    34  	return &c
    35  }
    36  
    37  func (monoid *CounterMonoid) Add(that Monoid) {
    38  	*monoid += *that.(*CounterMonoid)
    39  }
    40  
    41  func (monoid *CounterMonoid) Export() float64 {
    42  	value := float64(*monoid)
    43  	*monoid = 0
    44  	return value
    45  }
    46  
    47  type MapMonoid map[interface{}]Monoid
    48  
    49  func (monoid MapMonoid) Add(that MapMonoid) {
    50  	for k, v := range that {
    51  		existingV := monoid[k]
    52  		if existingV == nil {
    53  			monoid[k] = v
    54  		} else {
    55  			existingV.Add(v)
    56  		}
    57  	}
    58  }