-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathconn.go
610 lines (526 loc) · 15.3 KB
/
conn.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package stomp
import (
"errors"
"io"
"log"
"net"
"strconv"
"sync"
"time"
"github.com/go-stomp/stomp/frame"
)
// Default time span to add to read/write heart-beat timeouts
// to avoid premature disconnections due to network latency.
const DefaultHeartBeatError = 5 * time.Second
// A Conn is a connection to a STOMP server. Create a Conn using either
// the Dial or Connect function.
type Conn struct {
conn io.ReadWriteCloser
readCh chan *frame.Frame
writeCh chan writeRequest
version Version
session string
server string
readTimeout time.Duration
writeTimeout time.Duration
closed bool
options *connOptions
}
type writeRequest struct {
Frame *frame.Frame // frame to send
C chan *frame.Frame // response channel
}
// Dial creates a network connection to a STOMP server and performs
// the STOMP connect protocol sequence. The network endpoint of the
// STOMP server is specified by network and addr. STOMP protocol
// options can be specified in opts.
func Dial(network, addr string, opts ...func(*Conn) error) (*Conn, error) {
c, err := net.Dial(network, addr)
if err != nil {
return nil, err
}
host, _, err := net.SplitHostPort(c.RemoteAddr().String())
if err != nil {
c.Close()
return nil, err
}
// Add option to set host and make it the first option in list,
// so that if host has been explicitly specified it will override.
opts = append([](func(*Conn) error){ConnOpt.Host(host)}, opts...)
return Connect(c, opts...)
}
// Connect creates a STOMP connection and performs the STOMP connect
// protocol sequence. The connection to the STOMP server has already
// been created by the program. The opts parameter provides the
// opportunity to specify STOMP protocol options.
func Connect(conn io.ReadWriteCloser, opts ...func(*Conn) error) (*Conn, error) {
reader := frame.NewReader(conn)
writer := frame.NewWriter(conn)
c := &Conn{
conn: conn,
readCh: make(chan *frame.Frame, 8),
writeCh: make(chan writeRequest, 8),
}
options, err := newConnOptions(c, opts)
if err != nil {
return nil, err
}
if options.Host == "" {
// host not specified yet, attempt to get from net.Conn if possible
if connection, ok := conn.(net.Conn); ok {
host, _, err := net.SplitHostPort(connection.RemoteAddr().String())
if err == nil {
options.Host = host
}
}
// if host is still blank, use default
if options.Host == "" {
options.Host = "default"
}
}
connectFrame, err := options.NewFrame()
if err != nil {
return nil, err
}
err = writer.Write(connectFrame)
if err != nil {
return nil, err
}
response, err := reader.Read()
if err != nil {
return nil, err
}
if response.Command != frame.CONNECTED {
return nil, newError(response)
}
c.server = response.Header.Get(frame.Server)
c.session = response.Header.Get(frame.Session)
if versionString := response.Header.Get(frame.Version); versionString != "" {
version := Version(versionString)
if err = version.CheckSupported(); err != nil {
return nil, Error{
Message: err.Error(),
Frame: response,
}
}
c.version = version
} else {
// no version in the response, so assume version 1.0
c.version = V10
}
if heartBeat, ok := response.Header.Contains(frame.HeartBeat); ok {
readTimeout, writeTimeout, err := frame.ParseHeartBeat(heartBeat)
if err != nil {
return nil, Error{
Message: err.Error(),
Frame: response,
}
}
c.readTimeout = readTimeout
c.writeTimeout = writeTimeout
if c.readTimeout > 0 {
// Add time to the read timeout to account for time
// delay in other station transmitting timeout
c.readTimeout += options.HeartBeatError
}
if c.writeTimeout > options.HeartBeatError {
// Reduce time from the write timeout to account
// for time delay in transmitting to the other station
c.writeTimeout -= options.HeartBeatError
}
}
// TODO(jpj): make any non-standard headers in the CONNECTED
// frame available. This could be implemented as:
// (a) a callback function supplied as an option; or
// (b) a property of the Conn structure (eg CustomHeaders)
// Neither options are particularly elegant, so wait until
// there is a real need for this.
go readLoop(c, reader)
go processLoop(c, writer)
return c, nil
}
// Version returns the version of the STOMP protocol that
// is being used to communicate with the STOMP server. This
// version is negotiated with the server during the connect sequence.
func (c *Conn) Version() Version {
return c.version
}
// Session returns the session identifier, which can be
// returned by the STOMP server during the connect sequence.
// If the STOMP server does not return a session header entry,
// this value will be a blank string.
func (c *Conn) Session() string {
return c.session
}
// Server returns the STOMP server identification, which can
// be returned by the STOMP server during the connect sequence.
// If the STOMP server does not return a server header entry,
// this value will be a blank string.
func (c *Conn) Server() string {
return c.server
}
// readLoop is a goroutine that reads frames from the
// reader and places them onto a channel for processing
// by the processLoop goroutine
func readLoop(c *Conn, reader *frame.Reader) {
for {
f, err := reader.Read()
if err != nil {
close(c.readCh)
return
}
c.readCh <- f
}
}
// processLoop is a goroutine that handles io with
// the server.
func processLoop(c *Conn, writer *frame.Writer) {
channels := make(map[string]chan *frame.Frame)
var readTimeoutChannel <-chan time.Time
var readTimer *time.Timer
var writeTimeoutChannel <-chan time.Time
var writeTimer *time.Timer
for {
if c.readTimeout > 0 && readTimer == nil {
readTimer := time.NewTimer(c.readTimeout)
readTimeoutChannel = readTimer.C
}
if c.writeTimeout > 0 && writeTimer == nil {
writeTimer := time.NewTimer(c.writeTimeout)
writeTimeoutChannel = writeTimer.C
}
select {
case <-readTimeoutChannel:
// read timeout, close the connection
err := newErrorMessage("read timeout")
sendError(channels, err)
return
case <-writeTimeoutChannel:
// write timeout, send a heart-beat frame
err := writer.Write(nil)
if err != nil {
sendError(channels, err)
return
}
writeTimer = nil
writeTimeoutChannel = nil
case f, ok := <-c.readCh:
// stop the read timer
if readTimer != nil {
readTimer.Stop()
readTimer = nil
readTimeoutChannel = nil
}
if !ok {
err := newErrorMessage("connection closed")
sendError(channels, err)
return
}
if f == nil {
// heart-beat received
continue
}
switch f.Command {
case frame.RECEIPT:
if id, ok := f.Header.Contains(frame.ReceiptId); ok {
if ch, ok := channels[id]; ok {
ch <- f
delete(channels, id)
close(ch)
}
} else {
err := &Error{Message: "missing receipt-id", Frame: f}
sendError(channels, err)
return
}
case frame.ERROR:
log.Println("received ERROR; Closing underlying connection")
for _, ch := range channels {
ch <- f
close(ch)
}
c.closed = true
c.conn.Close()
return
case frame.MESSAGE:
if id, ok := f.Header.Contains(frame.Subscription); ok {
if ch, ok := channels[id]; ok {
ch <- f
} else {
log.Println("ignored MESSAGE for subscription", id)
}
}
}
case req, ok := <-c.writeCh:
// stop the write timeout
if writeTimer != nil {
writeTimer.Stop()
writeTimer = nil
writeTimeoutChannel = nil
}
if !ok {
sendError(channels, errors.New("write channel closed"))
return
}
if req.C != nil {
if receipt, ok := req.Frame.Header.Contains(frame.Receipt); ok {
// remember the channel for this receipt
channels[receipt] = req.C
}
}
switch req.Frame.Command {
case frame.SUBSCRIBE:
id, _ := req.Frame.Header.Contains(frame.Id)
channels[id] = req.C
case frame.UNSUBSCRIBE:
id, _ := req.Frame.Header.Contains(frame.Id)
// is this trying to be too clever -- add a receipt
// header so that when the server responds with a
// RECEIPT frame, the corresponding channel will be closed
req.Frame.Header.Set(frame.Receipt, id)
}
// frame to send
err := writer.Write(req.Frame)
if err != nil {
sendError(channels, err)
return
}
}
}
}
// Send an error to all receipt channels.
func sendError(m map[string]chan *frame.Frame, err error) {
frame := frame.New(frame.ERROR, frame.Message, err.Error())
for _, ch := range m {
ch <- frame
}
}
// Disconnect will disconnect from the STOMP server. This function
// follows the STOMP standard's recommended protocol for graceful
// disconnection: it sends a DISCONNECT frame with a receipt header
// element. Once the RECEIPT frame has been received, the connection
// with the STOMP server is closed and any further attempt to write
// to the server will fail.
func (c *Conn) Disconnect() error {
if c.closed {
return nil
}
ch := make(chan *frame.Frame)
c.writeCh <- writeRequest{
Frame: frame.New(frame.DISCONNECT, frame.Receipt, allocateId()),
C: ch,
}
response := <-ch
if response.Command != frame.RECEIPT {
return newError(response)
}
c.closed = true
return c.conn.Close()
}
// MustDisconnect will disconnect 'ungracefully' from the STOMP server.
// This method should be used only as last resort when there are fatal
// network errors that prevent to do a proper disconnect from the server.
func (c *Conn) MustDisconnect() error {
if c.closed {
return nil
}
// just close readCh and writeCh
// close(c.readCh)
close(c.writeCh)
c.closed = true
return c.conn.Close()
}
// Send sends a message to the STOMP server, which in turn sends the message to the specified destination.
// If the STOMP server fails to receive the message for any reason, the connection will close.
//
// The content type should be specified, according to the STOMP specification, but if contentType is an empty
// string, the message will be delivered without a content-type header entry. The body array contains the
// message body, and its content should be consistent with the specified content type.
//
// Any number of options can be specified in opts. See the examples for usage. Options include whether
// to receive a RECEIPT, should the content-length be suppressed, and sending custom header entries.
func (c *Conn) Send(destination, contentType string, body []byte, opts ...func(*frame.Frame) error) error {
if c.closed {
return ErrAlreadyClosed
}
f, err := createSendFrame(destination, contentType, body, opts)
if err != nil {
return err
}
if _, ok := f.Header.Contains(frame.Receipt); ok {
// receipt required
request := writeRequest{
Frame: f,
C: make(chan *frame.Frame),
}
c.writeCh <- request
response := <-request.C
if response.Command != frame.RECEIPT {
return newError(response)
}
} else {
// no receipt required
request := writeRequest{Frame: f}
c.writeCh <- request
}
return nil
}
func createSendFrame(destination, contentType string, body []byte, opts []func(*frame.Frame) error) (*frame.Frame, error) {
// Set the content-length before the options, because this provides
// an opportunity to remove content-length.
f := frame.New(frame.SEND, frame.ContentLength, strconv.Itoa(len(body)))
f.Body = body
for _, opt := range opts {
if opt == nil {
return nil, ErrNilOption
}
if err := opt(f); err != nil {
return nil, err
}
}
f.Header.Set(frame.Destination, destination)
if contentType != "" {
f.Header.Set(frame.ContentType, contentType)
}
return f, nil
}
func (c *Conn) sendFrame(f *frame.Frame) error {
if _, ok := f.Header.Contains(frame.Receipt); ok {
// receipt required
request := writeRequest{
Frame: f,
C: make(chan *frame.Frame),
}
c.writeCh <- request
response, ok := <-request.C
if ok {
if response.Command != frame.RECEIPT {
return newError(response)
}
} else {
return ErrClosedUnexpectedly
}
} else {
// no receipt required
request := writeRequest{Frame: f}
c.writeCh <- request
}
return nil
}
// Subscribe creates a subscription on the STOMP server.
// The subscription has a destination, and messages sent to that destination
// will be received by this subscription. A subscription has a channel
// on which the calling program can receive messages.
func (c *Conn) Subscribe(destination string, ack AckMode, opts ...func(*frame.Frame) error) (*Subscription, error) {
ch := make(chan *frame.Frame)
subscribeFrame := frame.New(frame.SUBSCRIBE,
frame.Destination, destination,
frame.Ack, ack.String())
for _, opt := range opts {
if opt == nil {
return nil, ErrNilOption
}
err := opt(subscribeFrame)
if err != nil {
return nil, err
}
}
// If the option functions have not specified the "id" header entry,
// create one.
id, ok := subscribeFrame.Header.Contains(frame.Id)
if !ok {
id = allocateId()
subscribeFrame.Header.Add(frame.Id, id)
}
request := writeRequest{
Frame: subscribeFrame,
C: ch,
}
sub := &Subscription{
id: id,
destination: destination,
conn: c,
ackMode: ack,
C: make(chan *Message, 16),
completedMutex: &sync.Mutex{},
}
go sub.readLoop(ch)
c.writeCh <- request
return sub, nil
}
// Ack acknowledges a message received from the STOMP server.
// If the message was received on a subscription with AckMode == AckAuto,
// then no operation is performed.
func (c *Conn) Ack(m *Message) error {
f, err := c.createAckNackFrame(m, true)
if err != nil {
return err
}
if f != nil {
c.sendFrame(f)
}
return nil
}
// Nack indicates to the server that a message was not received
// by the client. Returns an error if the STOMP version does not
// support the NACK message.
func (c *Conn) Nack(m *Message) error {
f, err := c.createAckNackFrame(m, false)
if err != nil {
return err
}
if f != nil {
c.sendFrame(f)
}
return nil
}
// Begin is used to start a transaction. Transactions apply to sending
// and acknowledging. Any messages sent or acknowledged during a transaction
// will be processed atomically by the STOMP server based on the transaction.
func (c *Conn) Begin() *Transaction {
id := allocateId()
f := frame.New(frame.BEGIN, frame.Transaction, id)
c.sendFrame(f)
return &Transaction{id: id, conn: c}
}
// Create an ACK or NACK frame. Complicated by version incompatibilities.
func (c *Conn) createAckNackFrame(msg *Message, ack bool) (*frame.Frame, error) {
if !ack && !c.version.SupportsNack() {
return nil, ErrNackNotSupported
}
if msg.Header == nil || msg.Subscription == nil || msg.Conn == nil {
return nil, ErrNotReceivedMessage
}
if msg.Subscription.AckMode() == AckAuto {
if ack {
// not much point sending an ACK to an auto subscription
return nil, nil
} else {
// sending a NACK for an ack:auto subscription makes no
// sense
return nil, ErrCannotNackAutoSub
}
}
var f *frame.Frame
if ack {
f = frame.New(frame.ACK)
} else {
f = frame.New(frame.NACK)
}
switch c.version {
case V10, V11:
f.Header.Add(frame.Subscription, msg.Subscription.Id())
if messageId, ok := msg.Header.Contains(frame.MessageId); ok {
f.Header.Add(frame.MessageId, messageId)
} else {
return nil, missingHeader(frame.MessageId)
}
case V12:
if ack, ok := msg.Header.Contains(frame.Ack); ok {
f.Header.Add(frame.Id, ack)
} else {
return nil, missingHeader(frame.Ack)
}
}
return f, nil
}