-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
67 lines (59 loc) · 1.25 KB
/
node.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
package deks
import (
"context"
"log"
"time"
"github.com/simia-tech/errx"
)
// Node defines the node.
type Node struct {
Store *Store
server *Server
cancel context.CancelFunc
}
// NewNode returns a new node.
func NewNode(o Options, m Metric) (*Node, error) {
store := NewStore(m)
server, err := NewServer(store, o.ListenURL, m)
if err != nil {
return nil, errx.Annotatef(err, "new server")
}
for _, peerURL := range o.PeerURLs {
_, err := server.Reconcilate(peerURL)
if err != nil {
log.Printf("reconsilate: %v", err)
}
if err := server.AddPeer(peerURL, o.PeerPingInterval, o.PeerReconnectInterval); err != nil {
return nil, errx.Annotatef(err, "peer add")
}
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
ticker := time.NewTicker(o.TidyInterval)
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-ticker.C:
if err := store.Tidy(); err != nil {
log.Printf("tidy: %v", err)
}
}
}
}()
return &Node{
Store: store,
server: server,
cancel: cancel,
}, nil
}
// ListenURL returns the listen url.
func (n *Node) ListenURL() string {
return n.server.ListenURL()
}
// Close tears down the node.
func (n *Node) Close() error {
n.cancel()
return n.server.Close()
}