-
Notifications
You must be signed in to change notification settings - Fork 5
/
messageshipper.go
67 lines (57 loc) · 1.84 KB
/
messageshipper.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
package gamq
import (
"github.com/FireEater64/gamq/message"
log "github.com/cihub/seelog"
"time"
)
type messageShipper struct {
messageChannel chan *message.Message
metricsChannel chan<- *Metric
subscriber *Client
ClientName string
CloseChannel chan bool
queueName string
endBytes []byte
}
func newMessageShipper(inputChannel chan *message.Message, subscriber *Client, givenMetricsChannel chan<- *Metric, queueName string) *messageShipper {
shipper := messageShipper{}
shipper.subscriber = subscriber
shipper.messageChannel = inputChannel
shipper.CloseChannel = make(chan bool)
shipper.ClientName = subscriber.Name
shipper.metricsChannel = givenMetricsChannel
shipper.queueName = queueName
shipper.endBytes = []byte{'\r', '\n', '.', '\r', '\n'}
go shipper.forwardMessageToClient()
return &shipper
}
func (shipper *messageShipper) forwardMessageToClient() {
for {
select {
case message, more := <-shipper.messageChannel:
if more {
_, err := shipper.subscriber.Writer.Write(*message.Body)
if err != nil {
log.Errorf("Error whilst sending message to consumer: %s", err)
}
// Write end runes
shipper.subscriber.Writer.Write(shipper.endBytes)
shipper.subscriber.Writer.Flush()
// Bit of a hack - but stops an infinite loop
if shipper.queueName != metricsQueueName {
// Calculate and log the latency for the sent message
shipper.metricsChannel <- NewMetric("latency", "timing", time.Now().Sub(message.ReceivedAt).Nanoseconds()/1000000)
// Log the number of bytes received
shipper.metricsChannel <- NewMetric("bytesout", "counter", int64(len(*message.Body)+len(shipper.endBytes)))
}
} else {
return
}
case closing := <-shipper.CloseChannel:
if closing {
log.Debugf("Message shipper for %s closing down", shipper.ClientName)
return
}
}
}
}