-
Notifications
You must be signed in to change notification settings - Fork 1
/
dialer.go
74 lines (64 loc) · 1.63 KB
/
dialer.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
package p2p
import (
"fmt"
"net"
"sync"
"time"
)
// Dialer is a construct to throttle dialing and limit by attempts
type Dialer struct {
dialer net.Dialer
bindTo string
interval time.Duration // Minimum duration enforced between two dial attempts
timeout time.Duration
attempts map[Endpoint]time.Time
attemptsMtx sync.RWMutex
}
// NewDialer creates a new Dialer
func NewDialer(bindTo string, interval, timeout time.Duration) (*Dialer, error) {
d := new(Dialer)
d.interval = interval
d.timeout = timeout
d.attempts = make(map[Endpoint]time.Time)
err := d.Bind(bindTo)
if err != nil {
return nil, err
}
return d, nil
}
func (d *Dialer) Bind(to string) error {
local, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:0", to))
if err != nil {
return err
}
d.bindTo = to
d.dialer = net.Dialer{
LocalAddr: local,
Timeout: d.timeout,
}
return nil
}
// CanDial checks if the given ip can be dialed yet
func (d *Dialer) CanDial(ep Endpoint) bool {
d.attemptsMtx.RLock()
defer d.attemptsMtx.RUnlock()
if a, ok := d.attempts[ep]; !ok || time.Since(a) >= d.interval {
return true
}
return false
}
// Dial an ip. Returns the active TCP connection or error if it failed to connect
func (d *Dialer) Dial(ep Endpoint) (net.Conn, error) {
d.attemptsMtx.Lock() // don't unlock with defer so we can dial concurrently
if t, ok := d.attempts[ep]; ok && time.Since(t) < d.interval {
d.attemptsMtx.Unlock()
return nil, fmt.Errorf("dialing too soon")
}
d.attempts[ep] = time.Now()
d.attemptsMtx.Unlock()
con, err := d.dialer.Dial("tcp", ep.String())
if err != nil {
return nil, err
}
return con, nil
}