-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
338 lines (284 loc) · 7.25 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package tt
import (
"context"
"fmt"
"io/ioutil"
"log"
"net"
"net/url"
"sync"
"time"
"github.com/gregoryv/mq"
"github.com/gregoryv/tt/event"
)
func NewClient() *Client {
return &Client{
log: log.New(ioutil.Discard, "", log.Flags()),
server: "tcp://127.0.0.1:1883",
app: make(chan interface{}, 1),
}
}
// Client implements a mqtt-v5 client.
type Client struct {
// Server to connect to, defaults to tcp://localhost:1883
server string
// Set to true to include more log output
debug bool
// optional logger, leave empty for no logging
log *log.Logger
// Outgoing packets use ids from 1..MaxPacketID, this limits the
// number of packets in flight.
maxPacketID uint16
// set by Run and used in Send
transmit func(ctx context.Context, p mq.Packet) error
app chan interface{}
// synchronize Send
m sync.Mutex
}
func (c *Client) SetServer(v string) { c.server = v }
func (c *Client) SetDebug(v bool) { c.debug = v }
func (c *Client) SetMaxPacketID(v uint16) { c.maxPacketID = v }
func (c *Client) SetLogger(v *log.Logger) { c.log = v }
func (c *Client) Run(ctx context.Context) error {
err := c.run(ctx)
c.app <- event.ClientStop{err}
close(c.app)
return err
}
// Events returns a channel used by client to inform application layer
// of packets and events. E.g. [event.ClientUp]
func (c *Client) Events() <-chan interface{} {
return c.app
}
// run prepares and initiates transmit and receive logic of packets.
func (c *Client) run(ctx context.Context) error {
s, err := url.Parse(c.server)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(ctx)
maxIDLen := uint(11)
// dial server
c.log.Print("dial ", s.String())
conn, err := net.Dial(s.Scheme, s.Host)
if err != nil {
return err
}
// pool of packet ids for reuse
pool := newIDPool(c.maxPacketID)
ping := newKeepAlive()
// define transmit func first, as it's used when receiving packets
// to e.g. transmit acks.
transmit := func(ctx context.Context, p mq.Packet) error {
// set packet id if needed, blocks if pool is exhausted
if err := pool.SetPacketID(ctx, p); err != nil {
cancel()
return err
}
// use client id
switch p := p.(type) {
case *mq.Connect:
c.log.SetPrefix(trimID(p.ClientID(), maxIDLen) + " ")
if v := p.KeepAlive(); v > 0 {
ping.SetInterval(v)
}
}
// log just before sending
c.log.Printf("out %s%s", p, dump(c.debug, p))
// write packet on the wire
if _, err := p.WriteTo(conn); err != nil {
return err
}
// packet just sent, no need for a ping
ping.delay()
return nil
}
// set for use by method Client.Send
c.transmit = transmit
handle := func(ctx context.Context, p mq.Packet) {
// set log prefix if client was assigned an id
if p, ok := p.(*mq.ConnAck); ok {
if v := p.AssignedClientID(); v != "" {
c.log.SetPrefix(trimID(v, maxIDLen))
}
}
// log incoming packet
c.log.Printf("in %s%s", p, dump(c.debug, p))
// check if malformed
if p, ok := p.(interface{ WellFormed() *mq.Malformed }); ok {
if err := p.WellFormed(); err != nil {
d := mq.NewDisconnect()
d.SetReasonCode(mq.MalformedPacket)
_ = transmit(ctx, d)
}
}
// reuse packet id
if p, ok := p.(mq.HasPacketID); ok {
_ = pool.reuse(p.PacketID())
}
switch p := p.(type) {
case *mq.ConnAck:
code := p.ReasonCode()
switch {
case code == mq.Success:
c.app <- event.ClientConnect(0)
// keep alive as the server instructs
if v := p.ServerKeepAlive(); v > 0 {
ping.SetInterval(v)
}
// client is connected start the ping routine
go ping.run(ctx, transmit)
case code >= 0x80:
c.app <- event.ClientConnectFail(code.String())
}
case *mq.Publish:
switch p.QoS() {
case 0: // no ack is needed
case 1:
ack := mq.NewPubAck()
ack.SetPacketID(p.PacketID())
_ = transmit(ctx, ack)
case 2: // ack is done in PubRec
}
case *mq.PubRec:
// todo what if the application layer doesn't want to
// release a packet based on the PubRec reason
rel := mq.NewPubRel()
rel.SetPacketID(p.PacketID())
_ = transmit(ctx, rel)
}
// finally let the application have the packet
c.app <- p
}
recv := newReceiver(handle, conn)
c.app <- event.ClientUp(0)
return recv.Run(ctx)
}
// Send returns when the packet was successfully encoded on the wire.
// Returns ErrClientStopped if not running. Send is safe to call
// concurrently.
func (c *Client) Send(ctx context.Context, p mq.Packet) error {
if c.transmit == nil {
return ErrClientStopped
}
// sync each outgoing packet
c.m.Lock()
defer c.m.Unlock()
return c.transmit(ctx, p)
}
var ErrClientStopped = fmt.Errorf("Client stopped")
// newIDPool returns a iDPool of reusable id's from 1..max, 0 is not used
func newIDPool(max uint16) *iDPool {
o := iDPool{
nextTimeout: 3 * time.Second,
timer: time.NewTimer(3 * time.Second),
max: max,
used: make([]time.Time, max+1),
values: make(chan uint16, max),
}
for i := uint16(1); i <= max; i++ {
o.values <- i
}
return &o
}
type iDPool struct {
nextTimeout time.Duration
timer *time.Timer
max uint16
used []time.Time // flags id that has been used in Out handler
values chan uint16
}
// reuse returns the given value to the pool, returns the reused value
// or 0 if ignored
func (o *iDPool) reuse(v uint16) uint16 {
if v == 0 || v > o.max {
return 0
}
if o.used[v].IsZero() {
return 0
}
o.values <- v
o.used[v] = zero
return v
}
var zero = time.Time{}
func (o *iDPool) SetPacketID(ctx context.Context, p mq.Packet) error {
if p, ok := p.(mq.HasPacketID); ok {
switch p := p.(type) {
case *mq.Publish:
if p.QoS() > 0 && p.PacketID() == 0 {
id, err := o.next(ctx)
if err != nil {
return err
}
p.SetPacketID(id)
}
case *mq.Subscribe:
id, err := o.next(ctx)
if err != nil {
return err
}
p.SetPacketID(id)
case *mq.Unsubscribe:
id, err := o.next(ctx)
if err != nil {
return err
}
p.SetPacketID(id)
}
}
return nil
}
// next returns the next available ID, blocks until one is available
// or context is canceled. next is safe for concurrent use by multiple
// goroutines.
func (o *iDPool) next(ctx context.Context) (uint16, error) {
o.timer.Reset(o.nextTimeout)
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-o.timer.C:
return 0, ErrIDPoolEmpty
case v := <-o.values:
o.used[v] = time.Now()
return v, nil
}
}
var ErrIDPoolEmpty = fmt.Errorf("no available packet ids")
// sending pings within the given interval. The interval is rounded to
// seconds.
func newKeepAlive() *keepAlive {
return &keepAlive{
packetSent: make(chan struct{}, 1),
}
}
// keepAlive implements client logic for keeping Connection alive.
//
// See 3.1.2.10 Keep Alive
type keepAlive struct {
interval time.Duration
packetSent chan struct{}
}
func (k *keepAlive) SetInterval(v uint16) {
k.interval = time.Duration(v) * time.Second
}
func (k *keepAlive) delay() {
k.packetSent <- struct{}{}
}
func (k *keepAlive) run(ctx context.Context, transmit errHandler) {
last := time.Now()
tick := time.NewTicker(time.Second)
for {
select {
case <-ctx.Done():
tick.Stop()
return
case <-k.packetSent:
last = time.Now()
case <-tick.C:
if k.interval != 0 && time.Since(last) > k.interval {
transmit(ctx, mq.NewPingReq())
}
}
}
}