forked from jjeffery/stomp
-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathsubscription.go
230 lines (209 loc) · 5.79 KB
/
subscription.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
package stomp
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/go-stomp/stomp/v3/frame"
)
const (
subStateActive = 0
subStateClosing = 1
subStateClosed = 2
)
// The Subscription type represents a client subscription to
// a destination. The subscription is created by calling Conn.Subscribe.
//
// Once a client has subscribed, it can receive messages from the C channel.
type Subscription struct {
C chan *Message
id string
replyToSet bool
destination string
conn *Conn
ackMode AckMode
state int32
closeMutex *sync.Mutex
closeCond *sync.Cond
closeOnce sync.Once
unsubscribeReceiptTimeout time.Duration
}
// BUG(jpj): If the client does not read messages from the Subscription.C
// channel quickly enough, the client will stop reading messages from the
// server.
// Identification for this subscription. Unique among
// all subscriptions for the same Client.
func (s *Subscription) Id() string {
return s.id
}
// Destination for which the subscription applies.
func (s *Subscription) Destination() string {
return s.destination
}
// AckMode returns the Acknowledgement mode specified when the
// subscription was created.
func (s *Subscription) AckMode() AckMode {
return s.ackMode
}
// Active returns whether the subscription is still active.
// Returns false if the subscription has been unsubscribed.
func (s *Subscription) Active() bool {
return atomic.LoadInt32(&s.state) == subStateActive
}
// Unsubscribes and closes the channel C.
func (s *Subscription) Unsubscribe(opts ...func(*frame.Frame) error) error {
// transition to the "closing" state
if !atomic.CompareAndSwapInt32(&s.state, subStateActive, subStateClosing) {
return ErrCompletedSubscription
}
f := frame.New(frame.UNSUBSCRIBE, frame.Id, s.id)
for _, opt := range opts {
if opt == nil {
return ErrNilOption
}
err := opt(f)
if err != nil {
return err
}
}
if s.replyToSet {
f.Header.Set(ReplyToHeader, s.id)
}
err := s.conn.sendFrame(f)
if errors.Is(err, ErrClosedUnexpectedly) {
msg := s.subscriptionErrorMessage("connection closed unexpectedly")
s.closeChannel(msg)
return err
}
// UNSUBSCRIBE is a bit weird in that it is tagged with a "receipt" header
// on the I/O goroutine, so the above call to sendFrame() will not wait
// for the resulting RECEIPT.
//
// We don't want to interfere with `s.C` since we might be "stealing"
// MESSAGEs or ERRORs from another goroutine, so use a sync.Cond to
// wait for the terminal state transition instead.
s.closeMutex.Lock()
for atomic.LoadInt32(&s.state) != subStateClosed {
err = waitWithTimeout(s.closeCond, s.unsubscribeReceiptTimeout)
if err != nil && errors.Is(err, &ErrUnsubscribeReceiptTimeout) {
// The [closeCond.Broadcast] can race with the timeout, so make sure
// the channel is still available.
if atomic.LoadInt32(&s.state) != subStateClosed {
msg := s.subscriptionErrorMessage("channel unsubscribe receipt timeout")
s.C <- msg
}
return err
}
}
s.closeMutex.Unlock()
return err
}
func waitWithTimeout(cond *sync.Cond, timeout time.Duration) error {
if timeout == 0 {
cond.Wait()
return nil
}
waitChan := make(chan struct{})
go func() {
cond.Wait()
close(waitChan)
}()
select {
case <-waitChan:
return nil
case <-time.After(timeout):
return &ErrUnsubscribeReceiptTimeout
}
}
// Read a message from the subscription. This is a convenience
// method: many callers will prefer to read from the channel C
// directly.
func (s *Subscription) Read() (*Message, error) {
if !s.Active() {
return nil, ErrCompletedSubscription
}
msg, ok := <-s.C
if !ok {
return nil, ErrCompletedSubscription
}
if msg.Err != nil {
return nil, msg.Err
}
return msg, nil
}
func (s *Subscription) closeChannel(msg *Message) {
s.closeOnce.Do(func() {
if msg != nil {
s.C <- msg
}
atomic.StoreInt32(&s.state, subStateClosed)
close(s.C)
s.closeCond.Broadcast()
})
}
func (s *Subscription) subscriptionErrorMessage(message string) *Message {
return &Message{
Err: &Error{
Message: fmt.Sprintf("Subscription %s: %s: %s", s.id, s.destination, message),
},
}
}
func (s *Subscription) readLoop(ch chan *frame.Frame) {
for {
f, ok := <-ch
if !ok {
state := atomic.LoadInt32(&s.state)
if state == subStateActive || state == subStateClosing {
msg := s.subscriptionErrorMessage("channel read failed")
s.closeChannel(msg)
}
return
}
if f.Command == frame.MESSAGE {
destination := f.Header.Get(frame.Destination)
contentType := f.Header.Get(frame.ContentType)
msg := &Message{
Destination: destination,
ContentType: contentType,
Conn: s.conn,
Subscription: s,
Header: f.Header,
Body: f.Body,
}
s.C <- msg
} else if f.Command == frame.ERROR {
state := atomic.LoadInt32(&s.state)
if state == subStateActive || state == subStateClosing {
message, _ := f.Header.Contains(frame.Message)
text := fmt.Sprintf("Subscription %s: %s: ERROR message:%s",
s.id,
s.destination,
message)
s.conn.log.Info(text)
contentType := f.Header.Get(frame.ContentType)
msg := &Message{
Err: &Error{
Message: f.Header.Get(frame.Message),
Frame: f,
},
ContentType: contentType,
Conn: s.conn,
Subscription: s,
Header: f.Header,
Body: f.Body,
}
s.closeChannel(msg)
}
return
} else if f.Command == frame.RECEIPT {
state := atomic.LoadInt32(&s.state)
if state == subStateActive || state == subStateClosing {
s.closeChannel(nil)
}
return
} else {
s.conn.log.Infof("Subscription %s: %s: unsupported frame type: %+v", s.id, s.destination, f)
}
}
}