forked from tylertreat/bench
/
nats_streaming_requester.go
95 lines (87 loc) · 2.24 KB
/
nats_streaming_requester.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
package requester
import (
"errors"
"fmt"
"math/rand"
"strconv"
"time"
"github.com/nats-io/stan.go"
"github.com/arush15june/bench"
)
// NATSStreamingRequesterFactory implements RequesterFactory by creating a
// Requester which publishes messages to NATS Streaming and waits to receive
// them.
type NATSStreamingRequesterFactory struct {
PayloadSize int
Subject string
ClientID string
ClusterID string
URL string
}
// GetRequester returns a new Requester, called for each Benchmark connection.
func (n *NATSStreamingRequesterFactory) GetRequester(num uint64) bench.Requester {
return &natsStreamingRequester{
url: n.URL,
clientID: n.ClientID,
clusterID: n.ClusterID,
payloadSize: n.PayloadSize,
subject: n.Subject + "-" + strconv.FormatUint(num, 10),
}
}
// natsStreamingRequester implements Requester by publishing a message to NATS
// Streaming and waiting to receive it.
type natsStreamingRequester struct {
url string
clientID string
clusterID string
payloadSize int
subject string
conn stan.Conn
sub stan.Subscription
msg []byte
msgChan chan []byte
}
// Setup prepares the Requester for benchmarking.
func (n *natsStreamingRequester) Setup() error {
conn, err := stan.Connect(n.clusterID, fmt.Sprintf("%s-%d", n.clientID, time.Now().UnixNano()), stan.NatsURL(n.url))
if err != nil {
return err
}
n.msgChan = make(chan []byte)
sub, err := conn.Subscribe(n.subject, func(msg *stan.Msg) {
n.msgChan <- msg.Data
})
if err != nil {
conn.Close()
return err
}
n.conn = conn
n.sub = sub
n.msg = make([]byte, n.payloadSize)
for i := 0; i < n.payloadSize; i++ {
n.msg[i] = 'A' + uint8(rand.Intn(26))
}
return nil
}
// Request performs a synchronous request to the system under test.
func (n *natsStreamingRequester) Request() error {
if _, err := n.conn.PublishAsync(n.subject, n.msg, nil); err != nil {
return err
}
select {
case <-n.msgChan:
return nil
case <-time.After(30 * time.Second):
return errors.New("timeout")
}
}
// Teardown is called upon benchmark completion.
func (n *natsStreamingRequester) Teardown() error {
if err := n.sub.Unsubscribe(); err != nil {
return err
}
n.sub = nil
n.conn.Close()
n.conn = nil
return nil
}