aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/yandex/unistat/registry.go
blob: 0873ab7c662a623c0c9f55730a0381dea79ac812 (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
package unistat

import (
	"encoding/json"
	"sort"
	"sync"
)

type registry struct {
	mu     sync.Mutex
	byName map[string]Metric

	metrics  []Metric
	unsorted bool
}

// NewRegistry allocate new registry container for unistat metrics.
func NewRegistry() Registry {
	return &registry{
		byName:  map[string]Metric{},
		metrics: []Metric{},
	}
}

func (r *registry) Register(m Metric) {
	r.mu.Lock()
	defer r.mu.Unlock()

	if _, ok := r.byName[m.Name()]; ok {
		panic(ErrDuplicate)
	}

	r.byName[m.Name()] = m
	r.metrics = append(r.metrics, m)
	r.unsorted = true
}

func (r *registry) MarshalJSON() ([]byte, error) {
	r.mu.Lock()
	defer r.mu.Unlock()

	if r.unsorted {
		sort.Sort(byPriority(r.metrics))
		r.unsorted = false
	}
	return json.Marshal(r.metrics)
}

type byPriority []Metric

func (m byPriority) Len() int { return len(m) }
func (m byPriority) Less(i, j int) bool {
	if m[i].Priority() == m[j].Priority() {
		return m[i].Name() < m[j].Name()
	}

	return m[i].Priority() > m[j].Priority()
}
func (m byPriority) Swap(i, j int) { m[i], m[j] = m[j], m[i] }