forked from walterwanderley/xk6-stomp
/
stomp.go
executable file
·348 lines (308 loc) · 8.25 KB
/
stomp.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
package stomp
import (
"context"
"crypto/tls"
"fmt"
"io"
"net"
"time"
"github.com/go-stomp/stomp/v3"
"github.com/go-stomp/stomp/v3/frame"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules"
"go.k6.io/k6/metrics"
)
// Register the extension on module initialization, available to
// import from JS as "k6/x/stomp".
func init() {
modules.Register("k6/x/stomp", New())
}
const (
defaultProtocol = "tcp"
defaultTimeout = "10s"
)
type (
RootModule struct{}
// Stomp is the k6 extension for a Stomp client.
Stomp struct {
vu modules.VU
*Client
}
)
type Options struct {
Addr string
Protocol string
Path string
Query string
Timeout string
TLS bool
Headers map[string]string
Host string
User string
Pass string
MessageSendTimeout string
ReceiptTimeout string
Heartbeat struct {
Incoming string
Outgoing string
}
ReadBufferSize int
ReadChannelCapacity int
WriteBufferSize int
WriteChannelCapacity int
Verbose bool
}
// Client is the Stomp conn wrapper.
type Client struct {
conn *stomp.Conn
vu modules.VU
metrics stompMetrics
}
type SendOptions struct {
Headers map[string]string
Receipt bool
}
// Listener is a callback function to execute when the subscription reads a message
type Listener func(*Message)
type SubscribeOptions struct {
Ack string
Headers map[string]string
Id string
Listener Listener
}
func New() *RootModule {
return &RootModule{}
}
func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
m, err := registerMetrics(vu)
if err != nil {
common.Throw(vu.Runtime(), err)
}
return &Stomp{vu: vu, Client: &Client{vu: vu, metrics: m}}
}
func (s *Stomp) Exports() modules.Exports {
return modules.Exports{Default: s.Client}
}
// Connect to a stomp server
func (c *Client) Connect(opts *Options) *Client {
if c.conn != nil {
return c
}
rt := c.vu.Runtime()
if opts.Protocol == "" {
opts.Protocol = defaultProtocol
}
if opts.Timeout == "" {
opts.Timeout = defaultTimeout
}
netConn, err := openNetConn(opts, c)
if err != nil {
common.Throw(rt, err)
return nil
}
connOpts := make([]func(*stomp.Conn) error, 0)
if opts.User != "" || opts.Pass != "" {
connOpts = append(connOpts, stomp.ConnOpt.Login(opts.User, opts.Pass))
}
for k, v := range opts.Headers {
connOpts = append(connOpts, stomp.ConnOpt.Header(k, v))
}
if opts.Host != "" {
connOpts = append(connOpts, stomp.ConnOpt.Host(opts.Host))
}
if opts.MessageSendTimeout != "" {
timeout, err := time.ParseDuration(opts.MessageSendTimeout)
if err != nil {
common.Throw(rt, err)
return nil
}
connOpts = append(connOpts, stomp.ConnOpt.MsgSendTimeout(timeout))
}
if opts.ReceiptTimeout != "" {
timeout, err := time.ParseDuration(opts.ReceiptTimeout)
if err != nil {
common.Throw(rt, err)
return nil
}
connOpts = append(connOpts, stomp.ConnOpt.RcvReceiptTimeout(timeout))
}
if opts.ReadBufferSize > 0 {
connOpts = append(connOpts, stomp.ConnOpt.ReadBufferSize(opts.ReadBufferSize))
}
if opts.ReadChannelCapacity > 0 {
connOpts = append(connOpts, stomp.ConnOpt.ReadChannelCapacity(opts.ReadChannelCapacity))
}
if opts.WriteBufferSize > 0 {
connOpts = append(connOpts, stomp.ConnOpt.WriteBufferSize(opts.WriteBufferSize))
}
if opts.WriteChannelCapacity > 0 {
connOpts = append(connOpts, stomp.ConnOpt.WriteChannelCapacity(opts.WriteChannelCapacity))
}
if opts.Heartbeat.Incoming != "" || opts.Heartbeat.Outgoing != "" {
sendTimeout, receiveTimeout := time.Minute, time.Minute
if opts.Heartbeat.Outgoing != "" {
sendTimeout, err = time.ParseDuration(opts.Heartbeat.Outgoing)
if err != nil {
common.Throw(rt, err)
return nil
}
}
if opts.Heartbeat.Incoming != "" {
receiveTimeout, err = time.ParseDuration(opts.Heartbeat.Incoming)
if err != nil {
common.Throw(rt, err)
return nil
}
}
connOpts = append(connOpts, stomp.ConnOpt.HeartBeat(sendTimeout, receiveTimeout))
}
c.conn, err = stomp.Connect(netConn, connOpts...)
if err != nil {
common.Throw(rt, err)
return nil
}
return c
}
func openNetConn(opts *Options, c *Client) (io.ReadWriteCloser, error) {
timeout, err := time.ParseDuration(opts.Timeout)
if err != nil {
return nil, err
}
var rwc io.ReadWriteCloser
switch {
case opts.Protocol == "ws" || opts.Protocol == "wss":
rwc, err = openWSConn(opts, timeout)
case opts.TLS:
rwc, err = tls.DialWithDialer(&net.Dialer{Timeout: timeout},
opts.Protocol, opts.Addr, nil)
default:
rwc, err = net.DialTimeout(opts.Protocol, opts.Addr, timeout)
}
rwc = &StatsReadWriteClose{rwc, c}
if opts.Verbose {
return &VerboseReadWriteClose{rwc}, err
}
return rwc, err
}
// Disconnect will disconnect from the STOMP server.
func (c *Client) Disconnect() error {
return c.conn.Disconnect()
}
// Send sends a message to the STOMP server.
func (c *Client) Send(destination, contentType string, body []byte, opts *SendOptions) (err error) {
startedAt := time.Now()
defer func() {
now := time.Now()
c.reportStats(c.metrics.sendMessageTiming, nil, now, metrics.D(now.Sub(startedAt)))
if err != nil {
c.reportStats(c.metrics.sendMessageErrors, nil, now, 1)
} else {
c.reportStats(c.metrics.sendMessage, nil, now, 1)
}
}()
if opts == nil {
opts = new(SendOptions)
}
var sendOpts []func(*frame.Frame) error
if opts.Receipt {
sendOpts = append(sendOpts, stomp.SendOpt.Receipt)
}
for k, v := range opts.Headers {
sendOpts = append(sendOpts, stomp.SendOpt.Header(k, v))
}
err = c.conn.Send(destination, contentType, body, sendOpts...)
return
}
// Subscribe creates a subscription on the STOMP server.
func (c *Client) Subscribe(destination string, opts *SubscribeOptions) (*Subscription, error) {
if opts == nil {
opts = new(SubscribeOptions)
}
var mode stomp.AckMode
switch opts.Ack {
case "client":
mode = stomp.AckClient
case "client-individual":
mode = stomp.AckClientIndividual
case "", "auto":
mode = stomp.AckAuto
default:
return nil, fmt.Errorf("ackMode should be 'auto', 'client' or 'client-individual'")
}
var subOpts []func(*frame.Frame) error
for k, v := range opts.Headers {
subOpts = append(subOpts, stomp.SubscribeOpt.Header(k, v))
}
if opts.Id != "" {
subOpts = append(subOpts, stomp.SubscribeOpt.Id(opts.Id))
}
sub, err := c.conn.Subscribe(destination, mode, subOpts...)
if err != nil {
return nil, err
}
return NewSubscription(c, sub, opts.Listener), nil
}
// Ack acknowledges a message received from the STOMP server.
func (c *Client) Ack(m *Message) error {
now := time.Now()
if m.Header.Get(frame.Id) == "" {
m.Header.Set(frame.Id, m.Header.Get(frame.Ack))
}
if m.Header.Get(frame.MessageId) == "" {
m.Header.Set(frame.MessageId, m.Header.Get(frame.Ack))
}
err := c.conn.Ack(m.Message)
if err != nil {
c.reportStats(c.metrics.ackMessageErrors, nil, now, 1)
} else {
c.reportStats(c.metrics.ackMessage, nil, now, 1)
}
return err
}
// Nack indicates to the server that a message was not received
// by the client.
func (c *Client) Nack(m *Message) error {
now := time.Now()
if m.Header.Get(frame.Id) == "" {
m.Header.Set(frame.Id, m.Header.Get(frame.Ack))
}
if m.Header.Get(frame.MessageId) == "" {
m.Header.Set(frame.MessageId, m.Header.Get(frame.Ack))
}
err := c.conn.Nack(m.Message)
if err != nil {
c.reportStats(c.metrics.nackMessageErrors, nil, now, 1)
} else {
c.reportStats(c.metrics.nackMessage, nil, now, 1)
}
return err
}
// Server returns the STOMP server identification.
func (c *Client) Server() string {
return c.conn.Server()
}
// Session returns the session identifier.
func (c *Client) Session() string {
return c.conn.Session()
}
// Begin is used to start a transaction.
func (c *Client) Begin() *Transaction {
return &Transaction{Transaction: c.conn.Begin(), client: c}
}
// BeginWithError is used to start a transaction, but also returns the error.
func (c *Client) BeginWithError(ctx context.Context) (*Transaction, error) {
tx, err := c.conn.BeginWithError()
return &Transaction{Transaction: tx, client: c}, err
}
func (c *Client) reportStats(metric *metrics.Metric, tags map[string]string, now time.Time, value float64) {
state := c.vu.State()
if state == nil {
return
}
metrics.PushIfNotDone(c.vu.Context(), state.Samples, metrics.Sample{
Time: now,
Metric: metric,
Tags: metrics.IntoSampleTags(&tags),
Value: value,
})
}