-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go
327 lines (288 loc) · 8.89 KB
/
client.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
package gobayeux
import (
"context"
"net/http"
"time"
"github.com/sirupsen/logrus"
)
// Client is a high-level abstraction
type Client struct {
client *BayeuxClient
subscriptions *subscriptionsMap
logger logrus.FieldLogger
subscribeRequestChannel chan subscriptionRequest
unsubscribeRequestChannel chan Channel
connectRequestChannel chan struct{}
connectMessageChannel chan []Message
handshakeRequestChannel chan struct{}
shutdown chan struct{}
}
// Options stores the available configuration options for a Client
type Options struct {
Logger logrus.FieldLogger
Client *http.Client
Transport http.RoundTripper
}
// Option defines the type passed into NewClient for configuration
type Option func(*Options)
// WithLogger returns an Option with logger.
func WithLogger(logger logrus.FieldLogger) Option {
return func(options *Options) {
options.Logger = logger
}
}
// WithHTTPClient returns an Option with custom http.Client.
func WithHTTPClient(client *http.Client) Option {
return func(options *Options) {
options.Client = client
}
}
// WithHTTPTransport returns an Option with custom http.RoundTripper.
func WithHTTPTransport(transport http.RoundTripper) Option {
return func(options *Options) {
options.Transport = transport
}
}
// NewClient creates a new high-level client
func NewClient(serverAddress string, opts ...Option) (*Client, error) {
options := &Options{}
// Apply passed opts
for _, opt := range opts {
if opt != nil {
opt(options)
}
}
if options.Logger == nil {
l := logrus.New()
l.SetLevel(logrus.PanicLevel)
options.Logger = l
}
bc, err := NewBayeuxClient(options.Client, options.Transport, serverAddress, options.Logger)
if err != nil {
return nil, err
}
return &Client{
client: bc,
subscriptions: newSubscriptionsMap(),
subscribeRequestChannel: make(chan subscriptionRequest, 10),
unsubscribeRequestChannel: make(chan Channel, 10),
connectRequestChannel: make(chan struct{}, 1),
connectMessageChannel: make(chan []Message, 5),
handshakeRequestChannel: make(chan struct{}),
shutdown: make(chan struct{}),
logger: options.Logger,
}, nil
}
// Subscribe queues a request to subscribe to a new channel from the server
func (c *Client) Subscribe(ch Channel, receiving chan []Message) {
c.subscribeRequestChannel <- subscriptionRequest{ch, receiving}
}
// Start begins the background process that talks to the server
func (c *Client) Start(ctx context.Context) <-chan error {
errors := make(chan error)
go c.start(ctx, errors)
return errors
}
// Disconnect issues a /meta/disconnect request to the Bayeux server and then
// cleans up channels and our timer.
func (c *Client) Disconnect(ctx context.Context) error {
_, err := c.client.Disconnect(ctx)
close(c.subscribeRequestChannel)
close(c.unsubscribeRequestChannel)
close(c.connectRequestChannel)
close(c.connectMessageChannel)
close(c.handshakeRequestChannel)
return err
}
// Publish is not yet implemented. When implemented, it will - in a separate thread
// from the polling task - publish messages to the Bayeux Server.
//
// See also: https://docs.cometd.org/current/reference/#_two_connection_operation
func (c *Client) Publish(ctx context.Context, messages []Message) error {
// TODO:
// * Locking mechanism to ensure only one outstanding Publish request at a
// time
// * Ensure that this separate from Start()/poll()
// * Implement Publish() in *BayeuxClient
panic("Publish() is not yet implemented")
}
// UseExtension adds the provided MessageExtender as an extension for use with
// this Client session.
//
// See also: https://docs.cometd.org/current/reference/#_bayeux_ext
func (c *Client) UseExtension(ext MessageExtender) error {
return c.client.UseExtension(ext)
}
func (c *Client) start(ctx context.Context, errors chan error) {
logger := c.logger.WithField("at", "start")
if _, err := c.client.Handshake(ctx); err != nil {
errors <- err
return
}
_ = c.subscriptions.Add(MetaConnect, c.connectMessageChannel)
/*
subReqs, channels := c.getSubscriptionRequests()
logger.WithField("count", len(channels)).Debug("issuing subscription requests")
if _, err := c.client.Subscribe(ctx, channels); err != nil {
errors <- err
return
}
for _, subReq := range subReqs {
if err := c.subscriptions.Add(subReq.subscription, subReq.msgChan); err != nil {
logger.WithError(err).Debug("unable to add subscription")
errors <- err
return
}
}
c.enqueueConnectRequest()
*/
logger.Debug("starting long-polling loop")
if err := c.poll(ctx); err != nil {
errors <- err
return
}
if _, err := c.client.Disconnect(ctx); err != nil {
errors <- err
return
}
}
func (c *Client) poll(ctx context.Context) error {
logger := c.logger.WithField("at", "poll")
_poll_loop:
for {
logger.Debug("in polling loop")
select {
case <-c.shutdown: // When the user calls the Disconnect() method
logger.Debug("shutting down due to Disconnect()")
break _poll_loop
case <-ctx.Done(): // When the user cancels the Start() context
if err := ctx.Err(); err != nil {
logger.WithError(err).Debug("shutting down due to error")
return err
}
logger.Debug("shutting down due to cancelled context")
break _poll_loop
case subReq := <-c.subscribeRequestChannel:
logger.Debug("got subscription requests")
// Let's attempt to drain the channel before sending a
// /meta/unsubscribe request to more efficiently use HTTP
// requests
subReqs, channels := c.getSubscriptionRequests()
subReqs = append(subReqs, subReq)
channels = append(channels, subReq.subscription)
// TODO: Find a way to consolidate this logic and the logic in
// start()
if _, err := c.client.Subscribe(ctx, channels); err != nil {
return err
}
for _, subReq := range subReqs {
if err := c.subscriptions.Add(subReq.subscription, subReq.msgChan); err != nil {
return err
}
}
c.enqueueConnectRequest()
case unsubReq := <-c.unsubscribeRequestChannel:
logger.Debug("got unsubscribe requests")
channels := c.getUnsubscriptionRequests()
channels = append(channels, unsubReq)
if _, err := c.client.Unsubscribe(ctx, channels); err != nil {
return err
}
for _, channel := range channels {
c.subscriptions.Remove(channel)
}
case <-c.handshakeRequestChannel:
logger.Debug("re-handshaking")
if _, err := c.client.Handshake(ctx); err != nil {
return err
}
c.enqueueConnectRequest()
case ms := <-c.connectMessageChannel:
logger.Debug("handling messages from /meta/connect")
for _, m := range ms {
if m.Advice.ShouldHandshake() {
logger.Debug("queueing new handshake request")
c.handshakeRequestChannel <- struct{}{}
}
interval := m.Advice.IntervalAsDuration()
go func() {
c.logger.WithField("interval", interval).Debug("waiting per advice")
<-time.After(interval)
c.enqueueConnectRequest()
}()
}
case <-c.connectRequestChannel:
logger.Debug("checking for new messages")
ms, err := c.client.Connect(ctx)
if err != nil {
logger.WithError(err).Debug("error in /meta/connect")
return err
}
batch := make([]Message, 0)
lastChannel := emptyChannel
logger.Debug("delivering messages")
for _, m := range ms {
switch lastChannel {
case emptyChannel:
lastChannel = m.Channel
batch = append(batch, m)
case m.Channel:
batch = append(batch, m)
default:
msgChan, err := c.subscriptions.Get(lastChannel)
if err != nil {
return err
}
logger.WithField("channel", lastChannel).Debug("sending batch")
msgChan <- batch
lastChannel = m.Channel
batch = append([]Message(nil), m)
}
}
default:
c.enqueueConnectRequest()
}
}
return nil
}
func (c *Client) getSubscriptionRequests() ([]subscriptionRequest, []Channel) {
subscriptionRequests := make([]subscriptionRequest, 0)
channels := make([]Channel, 0)
_get_subs_for_loop:
for {
select {
case req := <-c.subscribeRequestChannel:
subscriptionRequests = append(subscriptionRequests, req)
channels = append(channels, req.subscription)
default:
break _get_subs_for_loop
}
}
return subscriptionRequests, channels
}
func (c *Client) enqueueConnectRequest() {
logger := c.logger.WithField("at", "enqueueConnectRequest")
select {
case c.connectRequestChannel <- struct{}{}:
logger.Debug("queued next /meta/connect request")
default:
logger.Debug("/meta/connect request queue full")
}
}
func (c *Client) getUnsubscriptionRequests() []Channel {
unsubscriptionRequests := make([]Channel, 0)
_get_unsubs_for_loop:
for {
select {
case req := <-c.unsubscribeRequestChannel:
unsubscriptionRequests = append(unsubscriptionRequests, req)
default:
break _get_unsubs_for_loop
}
}
return unsubscriptionRequests
}
type subscriptionRequest struct {
subscription Channel
msgChan chan []Message
}