aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/yandex/unistat/number.go
blob: c9b26ef073d39ec0f76241816bee27eecb230a42 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package unistat

import (
	"math"
	"sync"

	"github.com/goccy/go-json"
)

// Numeric implements Metric interface.
type Numeric struct {
	mu        sync.RWMutex
	name      string
	tags      []Tag
	priority  Priority
	aggr      Aggregation
	localAggr AggregationRule

	value float64
}

// NewNumeric allocates Numeric value metric.
func NewNumeric(name string, priority Priority, aggr Aggregation, localAggr AggregationRule, tags ...Tag) *Numeric {
	return &Numeric{
		name:      formatTags(tags) + name,
		priority:  priority,
		aggr:      aggr,
		localAggr: localAggr,
	}
}

// Name from Metric interface.
func (n *Numeric) Name() string {
	return n.name
}

// Aggregation from Metric interface.
func (n *Numeric) Aggregation() Aggregation {
	return n.aggr
}

// Priority from Metric interface.
func (n *Numeric) Priority() Priority {
	return n.priority
}

// Update from Metric interface.
func (n *Numeric) Update(value float64) {
	n.mu.Lock()
	defer n.mu.Unlock()

	switch n.localAggr {
	case Max:
		n.value = math.Max(n.value, value)
	case Min:
		n.value = math.Min(n.value, value)
	case Sum:
		n.value += value
	case Last:
		n.value = value
	default:
		n.value = -1
	}
}

// MarshalJSON from Metric interface.
func (n *Numeric) MarshalJSON() ([]byte, error) {
	jsonName := n.name + "_" + n.aggr.Suffix()
	return json.Marshal([]interface{}{jsonName, n.GetValue()})
}

// GetValue returns current metric value.
func (n *Numeric) GetValue() float64 {
	n.mu.RLock()
	defer n.mu.RUnlock()

	return n.value
}

// SetValue sets current metric value.
func (n *Numeric) SetValue(value float64) {
	n.mu.Lock()
	defer n.mu.Unlock()

	n.value = value
}