-
Notifications
You must be signed in to change notification settings - Fork 0
/
bayeux.go
363 lines (297 loc) · 9.17 KB
/
bayeux.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package client
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"golang.org/x/net/publicsuffix"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/utils/clock"
)
const (
connectChannel = "/meta/connect"
subscribeChannel = "/meta/subscribe"
handshakeChannel = "/meta/handshake"
)
// ConnectResponseCallback is the signature for callback functions
// that handle connect responses that contain data.
type ConnectResponseCallback func(msg *ConnectResponse)
// Bayeux client runner
type Bayeux interface {
Start(ctx context.Context) error
}
// bayeux client according to CometD 3.1.14
// and the subset needed for Salesforce Streaming API.
// See: https://docs.cometd.org/current3/reference/
type bayeux struct {
needsHandshake bool
client *http.Client
clientID string
apiVersion string
url string
errCh chan error
msgCh chan *ConnectResponse
stopCh chan struct{}
// store replayID per subscription
subsReplays map[string]*int64
dispatcher EventDispatcher
logger *zap.SugaredLogger
ctx context.Context
mutex sync.RWMutex
}
// NewBayeux creates a Bayeux client for Salesforce Streaming API consumption.
func NewBayeux(apiVersion string, url string, subscriptions []Subscription, dispatcher EventDispatcher, client *http.Client, logger *zap.SugaredLogger) Bayeux {
// replayID is stored in a map and will keep track of the latest event received,
// we copy the configured value for initialization.
sr := make(map[string]*int64, len(subscriptions))
for _, s := range subscriptions {
r := int64(s.ReplayID)
sr[s.Channel] = &r
}
url = strings.TrimRight(url, "/")
url = fmt.Sprintf("%s/cometd/%s", url, apiVersion)
return &bayeux{
needsHandshake: true,
client: client,
apiVersion: apiVersion,
url: url,
msgCh: make(chan *ConnectResponse),
errCh: make(chan error),
stopCh: make(chan struct{}),
dispatcher: dispatcher,
subsReplays: sr,
logger: logger,
}
}
// init does handshake and subscriptions.
func (b *bayeux) init() error {
if err := b.handshake(); err != nil {
return err
}
for k, v := range b.subsReplays {
replayID := atomic.LoadInt64(v)
sbs, err := b.subscribe(k, int(replayID))
if err != nil {
return err
}
for _, sb := range sbs {
if !sb.Successful {
return fmt.Errorf("could not subscribe to %s: %s", sb.Subscription, sb.Error)
}
}
}
return nil
}
// Start is a blocking function that will loop according to Bayeux,
// autheticating, handshaking, subscripting, and then connecting and
// sending data to the dispatcher until the connection is no longer valid.
// The process is stopped by cancelling the passed context.
func (b *bayeux) Start(ctx context.Context) error {
// Received context is used for all HTTP calls and
// at the connect loop to cancel processing.
b.mutex.Lock()
b.ctx = ctx
b.mutex.Unlock()
bom := wait.NewExponentialBackoffManager(time.Second, time.Second*60, time.Second*100, 2, 0, &clock.RealClock{})
// Connect loop will run until context is done
go func() {
// helper variable for signaling channels
empty := struct{}{}
// poll channel receives a signal when it is ok to
// receive data from Salesforce. We won't send signals
// to this channel when an error occurs at connection and
// we need to temporarily retry using backoffs, or when
// the context is done.
// All other cases at the processing loop MUST put the signal
// in the poll channel.
poll := make(chan struct{}, 1)
// errc channel receives a signal when a connection error occurs.
errc := make(chan struct{}, 1)
// we signal the poll channel at the beginning to start the processing.
poll <- empty
for {
select {
case <-b.ctx.Done():
close(b.stopCh)
return
case <-errc:
// return control to the loop to make sure we exit when the
// context is done. The go routine will send a signal to
// the poll channel when the backoff timer has ended.
go func() {
<-bom.Backoff().C()
poll <- empty
}()
case <-poll:
// default:
if b.needsHandshake {
if err := b.init(); err != nil {
b.errCh <- err
// init was not successful, either the handshake or the subscription
// failed, we need to continue with the next loop iteration which will
// retry the operation.
// backing off to avoid locking the Salesforce account.
errc <- empty
continue
}
// we are good to receive from channels, remove handshake flag
b.mutex.Lock()
b.needsHandshake = false
b.mutex.Unlock()
}
crs, err := b.Connect()
if err != nil {
b.errCh <- err
// backing off to avoid locking the Salesforce account.
errc <- empty
continue
}
for i := range crs {
// if the message comes from meta channel it is processed immediately and
// not sent to a processing channel. That way we avoid launching new connects
// when some action (handshake) needs to be taken.
if strings.HasPrefix(crs[i].Channel, "/meta") {
b.manageMeta(&crs[i])
continue
}
b.msgCh <- &crs[i]
}
// process next item.
poll <- empty
}
}
}()
// Worker loop will run until the connect loop is stopped.
for {
select {
case msg := <-b.msgCh:
b.dispatcher.DispatchEvent(b.ctx, msg)
r, ok := b.subsReplays[msg.Channel]
if ok {
atomic.StoreInt64(r, msg.Data.Event.ReplayID)
}
case err := <-b.errCh:
b.dispatcher.DispatchError(err)
case <-b.stopCh:
return nil
}
}
}
func (b *bayeux) manageMeta(cr *ConnectResponse) {
if cr.Successful {
b.logger.Debugf("Meta channel (channel: %s client: %s) ok", cr.Channel, cr.ClientID)
return
}
b.logger.Warnf("meta channel (channel: %s client: %s) was not successful: %+v", cr.Channel, cr.ClientID, *cr)
if cr.Advice.Reconnect == "handshake" {
b.logger.Debug("Marking handshake needed as advised by channel response")
b.mutex.Lock()
defer b.mutex.Unlock()
b.needsHandshake = true
}
}
// handshake should only be called when a new session is needed, which
// will be when starting the stream process and when auth errors are
// received from any call.
func (b *bayeux) handshake() error {
payload := `{"channel": "` + handshakeChannel + `", "supportedConnectionTypes": ["long-polling"], "version": "1.0"}`
// lock to write CookieJar and ClientID
b.mutex.Lock()
defer b.mutex.Unlock()
jOpts := cookiejar.Options{PublicSuffixList: publicsuffix.List}
jar, err := cookiejar.New(&jOpts)
if err != nil {
return fmt.Errorf("could not setup cookiejar: %+w", err)
}
b.client.Jar = jar
res, err := b.doPost(payload)
if err != nil {
return err
}
defer res.Body.Close()
h := []HandshakeResponse{}
err = json.NewDecoder(res.Body).Decode(&h)
if err != nil {
return fmt.Errorf("could not decode handshake response: %+w", err)
}
if len(h) == 0 {
return errors.New("empty handshake response")
}
if !h[0].Successful {
return fmt.Errorf("handshake failed: %s", h[0].Error)
}
// store client ID for further connect calls
b.clientID = h[0].ClientID
return nil
}
// Connect will start to receive events.
// This is a blocking function
func (b *bayeux) Connect() ([]ConnectResponse, error) {
payload := `{"channel": "` + connectChannel + `", "connectionType": "long-polling", "clientId": "` + b.clientID + `"}`
res, err := b.doPost(payload)
if err != nil {
return nil, fmt.Errorf("error sending connect request: %+w", err)
}
defer res.Body.Close()
c := []ConnectResponse{}
err = json.NewDecoder(res.Body).Decode(&c)
if err != nil {
return nil, fmt.Errorf("could not decode connect response: %+w", err)
}
if len(c) == 0 {
return nil, errors.New("empty connect response")
}
return c, nil
}
func (b *bayeux) subscribe(topic string, replayID int) ([]SubscriptionResponse, error) {
payload := `{"channel": "` + subscribeChannel + `", "subscription": "` + topic + `", "clientId": "` + b.clientID + `","ext":{"replay": {"` + topic + `": ` + strconv.Itoa(replayID) + `}}}`
res, err := b.doPost(payload)
if err != nil {
return nil, fmt.Errorf("error sending subscription request: %+w", err)
}
defer res.Body.Close()
s := []SubscriptionResponse{}
err = json.NewDecoder(res.Body).Decode(&s)
if err != nil {
return nil, fmt.Errorf("could not decode subscription response: %+w", err)
}
if len(s) == 0 {
return nil, errors.New("empty subscription response")
}
return s, nil
}
func (b *bayeux) doPost(payload string) (*http.Response, error) {
req, err := http.NewRequest("POST", b.url, bytes.NewBuffer([]byte(payload)))
if err != nil {
return nil, fmt.Errorf("could not build request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
req = req.WithContext(b.ctx)
res, err := b.client.Do(req)
if err != nil {
return nil, fmt.Errorf("could not execute request: %w", err)
}
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
b.mutex.Lock()
b.needsHandshake = true
b.mutex.Unlock()
}
if res.StatusCode >= 300 {
msg := fmt.Sprintf("received unexpected status code %d", res.StatusCode)
if resb, err := io.ReadAll(res.Body); err == nil {
msg += ": " + string(resb)
}
return nil, errors.New(msg)
}
return res, nil
}