-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
390 lines (331 loc) · 8.7 KB
/
client.go
File metadata and controls
390 lines (331 loc) · 8.7 KB
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
package stomp
import (
"context"
"fmt"
"log/slog"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
)
// Client represents a STOMP client connection
type Client struct {
conn *websocket.Conn
url string
version string
sessionID string
connected bool
mutex sync.RWMutex
messageChan chan *Frame
errorChan chan error
closeChan chan struct{}
subscriptions map[string]chan *Frame
subMutex sync.RWMutex
}
// ClientConfig holds configuration for STOMP client
type ClientConfig struct {
URL string
Login string
Passcode string
Version string // "1.0", "1.1", "1.2" or "1.0,1.1,1.2"
Heartbeat string // "cx,cy" format
ConnectTimeout time.Duration
MessageTimeout time.Duration
}
// DefaultClientConfig returns a default client configuration
func DefaultClientConfig() *ClientConfig {
return &ClientConfig{
Version: "1.0,1.1,1.2",
Heartbeat: "10000,10000",
ConnectTimeout: 30 * time.Second,
MessageTimeout: 30 * time.Second,
}
}
// NewClient creates a new STOMP client
func NewClient(config *ClientConfig) *Client {
if config == nil {
config = DefaultClientConfig()
}
return &Client{
url: config.URL,
version: config.Version,
messageChan: make(chan *Frame, 100),
errorChan: make(chan error, 10),
closeChan: make(chan struct{}),
subscriptions: make(map[string]chan *Frame),
}
}
// Connect establishes a connection to the STOMP server
func (c *Client) Connect(ctx context.Context, config *ClientConfig) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.connected {
return fmt.Errorf("client is already connected")
}
// Parse URL
u, err := url.Parse(config.URL)
if err != nil {
return fmt.Errorf("invalid URL: %v", err)
}
// Create WebSocket connection
dialer := websocket.Dialer{
HandshakeTimeout: config.ConnectTimeout,
}
conn, _, err := dialer.Dial(u.String(), nil)
if err != nil {
return fmt.Errorf("failed to connect: %v", err)
}
c.conn = conn
// Start message reader
go c.readMessages(ctx)
// Send CONNECT frame
connectFrame := NewFrame("CONNECT")
if config.Login != "" {
connectFrame.SetHeader("login", config.Login)
}
if config.Passcode != "" {
connectFrame.SetHeader("passcode", config.Passcode)
}
if config.Version != "" {
connectFrame.SetHeader("accept-version", config.Version)
}
if config.Heartbeat != "" {
connectFrame.SetHeader("heart-beat", config.Heartbeat)
}
err = c.sendFrame(connectFrame)
if err != nil {
c.conn.Close()
return fmt.Errorf("failed to send CONNECT frame: %v", err)
}
// Wait for CONNECTED frame
select {
case frame := <-c.messageChan:
if frame.Command == "CONNECTED" {
c.connected = true
c.version = frame.Headers["version"]
c.sessionID = frame.Headers["session"]
return nil
} else if frame.Command == "ERROR" {
c.conn.Close()
return fmt.Errorf("connection error: %s", string(frame.Body))
}
case err := <-c.errorChan:
c.conn.Close()
return fmt.Errorf("connection error: %v", err)
case <-time.After(config.ConnectTimeout):
c.conn.Close()
return fmt.Errorf("connection timeout")
}
return fmt.Errorf("unexpected response")
}
// Disconnect closes the connection to the STOMP server
func (c *Client) Disconnect(ctx context.Context) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if !c.connected {
return fmt.Errorf("client is not connected")
}
// Send DISCONNECT frame
disconnectFrame := NewFrame("DISCONNECT")
err := c.sendFrame(disconnectFrame)
if err != nil {
return fmt.Errorf("failed to send DISCONNECT frame: %v", err)
}
// Close connection
c.connected = false
close(c.closeChan)
c.conn.Close()
return nil
}
// Send sends a message to the specified destination
func (c *Client) Send(destination string, body []byte, headers map[string]string) error {
c.mutex.RLock()
connected := c.connected
c.mutex.RUnlock()
if !connected {
return fmt.Errorf("client is not connected")
}
sendFrame := NewFrame("SEND")
sendFrame.SetHeader("destination", destination)
sendFrame.SetBody(body)
// Add custom headers
for key, value := range headers {
sendFrame.SetHeader(key, value)
}
return c.sendFrame(sendFrame)
}
// Subscribe subscribes to a destination and returns a channel for receiving messages
func (c *Client) Subscribe(destination, ack string) (<-chan *Frame, error) {
c.mutex.RLock()
connected := c.connected
c.mutex.RUnlock()
if !connected {
return nil, fmt.Errorf("client is not connected")
}
// Generate subscription ID
subID := fmt.Sprintf("sub-%d", time.Now().UnixNano())
// Create subscription channel
subChan := make(chan *Frame, 100)
c.subMutex.Lock()
c.subscriptions[subID] = subChan
c.subMutex.Unlock()
// Send SUBSCRIBE frame
subscribeFrame := NewFrame("SUBSCRIBE")
subscribeFrame.SetHeader("destination", destination)
subscribeFrame.SetHeader("id", subID)
if ack != "" {
subscribeFrame.SetHeader("ack", ack)
}
err := c.sendFrame(subscribeFrame)
if err != nil {
c.subMutex.Lock()
delete(c.subscriptions, subID)
c.subMutex.Unlock()
close(subChan)
return nil, err
}
return subChan, nil
}
// Unsubscribe unsubscribes from a destination
func (c *Client) Unsubscribe(destination string) error {
c.mutex.RLock()
connected := c.connected
c.mutex.RUnlock()
if !connected {
return fmt.Errorf("client is not connected")
}
// Find subscription ID for destination
c.subMutex.Lock()
var subID string
for id := range c.subscriptions {
// In a real implementation, you'd track destination per subscription
// For simplicity, we'll use the destination as a hint
subID = id
break
}
if subID != "" {
delete(c.subscriptions, subID)
}
c.subMutex.Unlock()
if subID == "" {
return fmt.Errorf("no subscription found for destination: %s", destination)
}
// Send UNSUBSCRIBE frame
unsubscribeFrame := NewFrame("UNSUBSCRIBE")
unsubscribeFrame.SetHeader("id", subID)
return c.sendFrame(unsubscribeFrame)
}
// Ack acknowledges a message
func (c *Client) Ack(messageID string) error {
c.mutex.RLock()
connected := c.connected
version := c.version
c.mutex.RUnlock()
if !connected {
return fmt.Errorf("client is not connected")
}
ackFrame := NewFrame("ACK")
if version == "1.2" {
ackFrame.SetHeader("id", messageID)
} else {
ackFrame.SetHeader("message-id", messageID)
}
return c.sendFrame(ackFrame)
}
// Nack negatively acknowledges a message (STOMP 1.1+)
func (c *Client) Nack(messageID string) error {
c.mutex.RLock()
connected := c.connected
version := c.version
c.mutex.RUnlock()
if !connected {
return fmt.Errorf("client is not connected")
}
if version == "1.0" {
return fmt.Errorf("NACK not supported in STOMP 1.0")
}
nackFrame := NewFrame("NACK")
if version == "1.2" {
nackFrame.SetHeader("id", messageID)
} else {
nackFrame.SetHeader("message-id", messageID)
}
return c.sendFrame(nackFrame)
}
// sendFrame sends a frame to the server
func (c *Client) sendFrame(frame *Frame) error {
data := frame.Marshal()
return c.conn.WriteMessage(websocket.TextMessage, data)
}
// readMessages reads messages from the WebSocket connection
func (c *Client) readMessages(ctx context.Context) {
for {
select {
case <-c.closeChan:
return
default:
_, message, err := c.conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) {
c.errorChan <- err
}
return
}
frame, err := ParseFrame(message)
if err != nil {
c.errorChan <- err
continue
}
c.handleFrame(ctx, frame)
}
}
}
// handleFrame handles incoming frames
func (c *Client) handleFrame(ctx context.Context, frame *Frame) {
switch frame.Command {
case "MESSAGE":
// Route to appropriate subscription
subID := frame.Headers["subscription"]
if subID != "" {
c.subMutex.RLock()
subChan, exists := c.subscriptions[subID]
c.subMutex.RUnlock()
if exists {
select {
case subChan <- frame:
default:
// Channel is full, drop message
slog.Warn("Subscription channel full, Dropped message")
}
}
}
case "ERROR":
c.errorChan <- fmt.Errorf("server error: %s", string(frame.Body))
default:
// Route to main message channel
select {
case c.messageChan <- frame:
default:
// Channel is full, drop message
slog.Warn("Message channel full, dropping frame")
}
}
}
// IsConnected returns whether the client is connected
func (c *Client) IsConnected() bool {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.connected
}
// GetVersion returns the negotiated STOMP version
func (c *Client) GetVersion() string {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.version
}
// GetSessionID returns the session ID
func (c *Client) GetSessionID() string {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.sessionID
}