-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
121 lines (94 loc) · 1.97 KB
/
store.go
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package tasks
import (
"bytes"
"encoding/json"
"io"
"sort"
"sync"
"github.com/f1shl3gs/gossiping/tasks/targetpb"
"github.com/matttproud/golang_protobuf_extensions/pbutil"
)
type Store struct {
mtx sync.RWMutex
entries map[string]*targetpb.MeshEntry
callbacks map[string]func(me *targetpb.MeshEntry)
}
func NewStore() *Store {
return &Store{
entries: make(map[string]*targetpb.MeshEntry),
callbacks: make(map[string]func(me *targetpb.MeshEntry)),
}
}
func (s *Store) Snapshot(w io.Writer) error {
s.mtx.RLock()
defer s.mtx.RUnlock()
mes := make([]*targetpb.MeshEntry, 0, len(s.entries))
for _, ent := range s.entries {
mes = append(mes, ent)
}
return json.NewEncoder(w).Encode(&mes)
}
// todo: may the enable compress for the state
func (s *Store) MarshalBinary() ([]byte, error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
buf := bytes.NewBuffer(nil)
for _, entry := range s.entries {
_, err := pbutil.WriteDelimited(buf, entry)
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}
func (s *Store) Merge(b []byte) error {
var buf = bytes.NewBuffer(b)
s.mtx.Lock()
defer s.mtx.Unlock()
for {
var ent targetpb.MeshEntry
_, err := pbutil.ReadDelimited(buf, &ent)
if err == io.EOF {
return nil
}
if err != nil {
return err
}
if !s.merge(&ent) {
continue
}
for _, cb := range s.callbacks {
if cb == nil {
continue
}
cb(&ent)
}
}
}
func (s *Store) Jobs() []string {
s.mtx.RLock()
defer s.mtx.RUnlock()
var names []string
for name := range s.entries {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (s *Store) merge(me *targetpb.MeshEntry) bool {
prev := s.entries[me.Name]
if prev == nil {
s.entries[me.Name] = me
return true
}
if prev.Updated.After(me.Updated) {
return false
}
s.entries[me.Name] = me
return true
}
func (s *Store) AddCallback(name string, fn func(me *targetpb.MeshEntry)) {
s.mtx.Lock()
defer s.mtx.Unlock()
s.callbacks[name] = fn
}