-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
184 lines (157 loc) · 3.74 KB
/
client.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package connqc
import (
"context"
"fmt"
"net"
"time"
"github.com/hamba/logger/v2"
lctx "github.com/hamba/logger/v2/ctx"
"github.com/nitrado/connqc/tcp"
"github.com/nitrado/connqc/udp"
)
// Client attempts to hold a connection with a server, sending probe messages at a configured interval.
type Client struct {
backoff time.Duration
sendInterval time.Duration
readTimeout time.Duration
writeTimeout time.Duration
log *logger.Logger
}
// NewClient returns a client.
func NewClient(backoff, sendInterval, readTimeout, writeTimeout time.Duration, log *logger.Logger) *Client {
return &Client{
backoff: backoff,
sendInterval: sendInterval,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
log: log,
}
}
// Run sends probe messages to the server continuously.
// If the connection fails, it retries at the configured backoff interval.
func (c *Client) Run(ctx context.Context, protocol, addr string) {
var (
conn net.Conn
err error
idx int
)
for {
log := c.log.With(lctx.Str("protocol", protocol), lctx.Str("addr", addr), lctx.Int("reconnect", idx))
idx++
switch protocol {
case "tcp":
conn, err = tcp.Connect(addr)
case "udp":
conn, err = udp.Connect(addr)
default:
log.Error("Unexpected protocol")
return
}
if err != nil {
log.Error("Could not connect to server", lctx.Err(err))
select {
case <-ctx.Done():
return
case <-time.After(c.backoff):
continue
}
}
if err = c.handleConn(ctx, conn); err != nil {
log.Error("Connection error", lctx.Err(err))
}
select {
case <-ctx.Done():
return
default:
}
}
}
type expectation struct {
timestamp time.Time
probe Probe
}
func (c *Client) handleConn(ctx context.Context, conn net.Conn) error { //nolint:funlen // Simplify readability.
defer func() { _ = conn.Close() }()
readCh := make(chan readResponse)
go c.readLoop(conn, readCh)
enc := NewEncoder(conn)
id := uint64(1)
var expect []expectation
for {
select {
case <-ctx.Done():
return nil
case <-time.After(c.sendInterval):
_ = conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
p := Probe{
ID: id,
Data: fmt.Sprintf("Hello %d", id),
}
if err := enc.Encode(p); err != nil {
return fmt.Errorf("writing message: %w", err)
}
c.log.Info("Message sent", lctx.Interface("probe", p))
id++
expect = append(expect, expectation{timestamp: time.Now(), probe: p})
case resp, ok := <-readCh:
if !ok {
return nil
}
if resp.err != nil {
return fmt.Errorf("reading response: %w", resp.err)
}
var (
exp expectation
found bool
)
for {
if len(expect) == 0 {
break
}
exp, expect = expect[0], expect[1:]
if exp.probe.ID == resp.probe.ID {
found = true
break
}
c.log.Warn("Message dropped",
lctx.Str("error", "unexpected ID"),
lctx.Uint64("expected_id", resp.probe.ID),
lctx.Uint64("id", exp.probe.ID),
lctx.Str("data", exp.probe.Data),
)
}
if !found {
c.log.Error("No expectation found")
continue
}
c.log.Info("Message received",
lctx.Uint64("id", exp.probe.ID),
lctx.Str("data", exp.probe.Data),
lctx.Duration("took", resp.timestamp.Sub(exp.timestamp)),
)
}
}
}
type readResponse struct {
timestamp time.Time
probe Probe
err error
}
func (c *Client) readLoop(conn net.Conn, ch chan readResponse) {
defer close(ch)
dec := NewDecoder(conn)
for {
_ = conn.SetReadDeadline(time.Now().Add(c.readTimeout))
msg, err := dec.Decode()
if err != nil {
ch <- readResponse{err: err}
return
}
p, ok := msg.(Probe)
if !ok {
ch <- readResponse{err: fmt.Errorf("message not a probe: %T", msg)}
continue
}
ch <- readResponse{timestamp: time.Now(), probe: p}
}
}