forked from alexcesaro/statsd
-
Notifications
You must be signed in to change notification settings - Fork 4
/
safeconn.go
69 lines (57 loc) · 1.66 KB
/
safeconn.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
package statsd
import (
"fmt"
"io"
"net"
"time"
)
const (
defaultReadTimeout = 10 * time.Millisecond
defaultConnTimeout = 5 * time.Second
)
// SafeConn is an implementation of the io.WriteCloser that wraps a net.Conn type
// its purpose is to perform a guard as a part of each Write call to first check if
// the connection is still up by performing a small read. The use case of this is to
// protect against the case where a TCP connection comes disconnected and the Write
// continues to retry for up to 15 minutes before determining that the connection has
// been broken off.
// See also the WriteCloser option.
type SafeConn struct {
netConn net.Conn
connTimeout time.Duration
readTimeout time.Duration
}
func NewSafeConn(network, address string, connTimeout, readTimeout time.Duration) (*SafeConn, error) {
newConn, err := dialTimeout(network, address, connTimeout)
if err != nil {
return nil, err
}
c := &SafeConn{
netConn: newConn,
connTimeout: connTimeout,
readTimeout: readTimeout,
}
return c, nil
}
func NewSafeConnWithDefaultTimeouts(network string, address string) (*SafeConn, error) {
return NewSafeConn(network, address, defaultConnTimeout, defaultReadTimeout)
}
func (s *SafeConn) Write(p []byte) (n int, err error) {
// check if connection is closed
if s.connIsClosed() {
return 0, fmt.Errorf("connection is closed")
}
return s.netConn.Write(p)
}
func (s *SafeConn) Close() error {
return s.netConn.Close()
}
func (s *SafeConn) connIsClosed() bool {
err := s.netConn.SetReadDeadline(time.Now().Add(s.readTimeout))
if err != nil {
return true
}
one := make([]byte, 1)
_, err = s.netConn.Read(one)
return err == io.EOF
}