-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
117 lines (104 loc) · 2.27 KB
/
stream.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
package deks
import (
"context"
"log"
"sync"
"time"
"github.com/simia-tech/errx"
)
type stream struct {
ctx context.Context
cancel context.CancelFunc
peerURL string
peerPingInterval time.Duration
peerReconnectInterval time.Duration
updates chan streamUpdate
updatesMutex sync.Mutex
metric Metric
}
type streamUpdate struct {
keyHash keyHash
container *container
}
func newStream(
peerURL string,
peerPingInterval time.Duration,
peerReconnectInterval time.Duration,
m Metric,
) *stream {
ctx, cancel := context.WithCancel(context.Background())
s := &stream{
ctx: ctx,
cancel: cancel,
peerURL: peerURL,
peerPingInterval: peerPingInterval,
peerReconnectInterval: peerReconnectInterval,
metric: m,
}
go s.loop()
return s
}
func (s *stream) loop() {
for {
select {
case <-s.ctx.Done():
return
default:
s.metric.PeerConnected(s.peerURL)
if err := s.connect(); err != nil {
log.Printf("stream [%s]: %v", s.peerURL, err)
}
s.metric.PeerDisconnected(s.peerURL)
time.Sleep(s.peerReconnectInterval)
}
}
}
func (s *stream) connect() error {
conn, err := Dial(s.peerURL)
if err != nil {
return errx.Annotatef(err, "dial")
}
defer conn.Close()
ticker := time.NewTicker(s.peerPingInterval)
updates := make(chan streamUpdate)
defer func() {
s.updatesMutex.Lock()
s.updates = nil
close(updates)
s.updatesMutex.Unlock()
ticker.Stop()
}()
s.updatesMutex.Lock()
s.updates = updates
s.updatesMutex.Unlock()
for {
select {
case <-s.ctx.Done():
return nil
case <-ticker.C:
if err := conn.Ping(); err != nil {
return errx.Annotatef(err, "ping")
}
case u := <-updates:
bytes, err := u.container.MarshalBinary()
if err != nil {
return errx.Annotatef(err, "marshal binary")
}
if err := conn.setContainer(u.keyHash, bytes); err != nil {
return errx.Annotatef(err, "set container")
}
}
}
}
func (s *stream) update(kh keyHash, container *container) {
s.updatesMutex.Lock()
if s.updates == nil {
s.updatesMutex.Unlock()
return
}
s.updates <- streamUpdate{kh, container}
s.updatesMutex.Unlock()
}
func (s *stream) close() {
s.cancel()
}