This repository has been archived by the owner on Dec 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
profilesyncd.go
75 lines (66 loc) · 1.66 KB
/
profilesyncd.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
package profilesyncd
import (
"crypto/rand"
"encoding/binary"
"github.com/andres-erbsen/dename/client"
dename "github.com/andres-erbsen/dename/protocol"
"io"
mathrand "math/rand"
"sync"
"time"
)
type ProfileSyncd struct {
stop, force, forceDone chan struct{}
wg sync.WaitGroup
name string
client *client.Client
meanRate time.Duration
onUpdate func(*dename.Profile, *dename.ClientReply, error)
rand io.Reader
}
func New(client *client.Client, meanRate time.Duration, name string, onUpdate func(*dename.Profile, *dename.ClientReply, error), rnd io.Reader) (*ProfileSyncd, error) {
if rnd == nil {
rnd = rand.Reader
}
return &ProfileSyncd{name: name, client: client, meanRate: meanRate, onUpdate: onUpdate, rand: rnd}, nil
}
func (d *ProfileSyncd) Start() {
d.stop = make(chan struct{})
d.force = make(chan struct{})
d.forceDone = make(chan struct{})
d.wg.Add(1)
go func() {
defer d.wg.Done()
d.Run()
}()
}
func (d *ProfileSyncd) Stop() {
close(d.stop)
d.wg.Wait()
}
func (d *ProfileSyncd) Force() {
d.force <- struct{}{}
<-d.forceDone
}
func (d *ProfileSyncd) Run() {
delay := time.After(d.pickDelay())
for {
select {
case <-d.stop:
return
case <-delay:
delay = time.After(d.pickDelay())
d.onUpdate(d.client.LookupReply(d.name))
case <-d.force:
delay = time.After(d.pickDelay())
d.onUpdate(d.client.LookupReply(d.name))
d.forceDone <- struct{}{}
}
}
}
func (d *ProfileSyncd) pickDelay() time.Duration {
var s [8]byte
io.ReadFull(d.rand, s[:])
seed := int64(binary.LittleEndian.Uint64(s[:]))
return time.Duration(mathrand.New(mathrand.NewSource(seed)).ExpFloat64() * float64(d.meanRate))
}