/
polling.go
76 lines (66 loc) · 1.74 KB
/
polling.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
package discovery
import (
"context"
"time"
"github.com/brendoncarroll/stdctx/logctx"
"golang.org/x/sync/errgroup"
"github.com/inet256/inet256/pkg/inet256"
"github.com/inet256/inet256/pkg/serde"
)
type FindFunc = func(ctx context.Context, x inet256.Addr) ([]string, error)
type AnnounceFunc = func(ctx context.Context, privateKey inet256.PrivateKey, addrs []string, ttl time.Duration) error
type PollingDiscovery struct {
Period time.Duration
Announce AnnounceFunc
Find FindFunc
}
func (s *PollingDiscovery) Run(ctx context.Context, params Params) error {
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
return s.findLoop(ctx, params)
})
eg.Go(func() error {
return s.announceLoop(ctx, params)
})
return eg.Wait()
}
func (s *PollingDiscovery) findLoop(ctx context.Context, params Params) error {
return s.poll(ctx, func() error {
for _, target := range params.AddressBook.ListPeers() {
addrStrs, err := s.Find(ctx, target)
if err != nil {
return err
}
addrs, err := serde.ParseAddrs(params.AddrParser, addrStrs)
if err != nil {
return err
}
params.AddressBook.SetAddrs(target, addrs)
}
return nil
})
}
func (s *PollingDiscovery) announceLoop(ctx context.Context, params Params) error {
return s.poll(ctx, func() error {
return s.Announce(ctx, params.PrivateKey, serde.MarshalAddrs(params.GetLocalAddrs()), s.Period*3/2)
})
}
func (s *PollingDiscovery) poll(ctx context.Context, fn func() error) error {
ticker := time.NewTicker(s.Period)
defer ticker.Stop()
for {
if err := fn(); err != nil {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
logctx.Errorln(ctx, "while polling", err)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}