-
Notifications
You must be signed in to change notification settings - Fork 23
/
pubsub.go
422 lines (343 loc) · 12.1 KB
/
pubsub.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package rpc
import (
"context"
"reflect"
"sync"
"sync/atomic"
"github.com/Conflux-Chain/confura/util"
rpcutil "github.com/Conflux-Chain/confura/util/rpc"
sdk "github.com/Conflux-Chain/go-conflux-sdk"
"github.com/Conflux-Chain/go-conflux-sdk/types"
"github.com/openweb3/go-rpc-provider"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type delegateStatus uint32
const (
// pre-defined delegate status
delegateStatusInit delegateStatus = iota + 1
delegateStatusErr
delegateStatusOK
// default pubsub channel buffer size
pubsubChannelBufferSize = 2000
// pre-defined delegate context name
nhCtxName = "new_heads" // for newHeads subscription
lmEpochCtxName = "latest_mined_epochs" // for latest minted epoch subscription
lsEpochCtxName = "latest_state_epochs" // for latest state epoch subscription
logsCtxName = "logs" // for logs subscription
)
var (
// errSubscriptionProxyError uniform error returned to the end user when pubsub error.
errSubscriptionProxyError = errors.New("subscription proxy error")
// errDelegateNotReady returned when the delegate is not ready for service.
errDelegateNotReady = errors.New("delegate not ready")
// delegateClients cache store delegate clients
delegateClients util.ConcurrentMap // node name => *delegateClient
)
type delegateSubFilter func(item interface{}) bool // result filter for delegate subscription
// delegateSubscription is a subscription established through the delegateClient's `Subscribe` methods.
type delegateSubscription struct {
dCtx *delegateContext
subId rpc.ID // rpc subscription ID
etype reflect.Type // channel type
channel reflect.Value // channel to send result to
quitOnce sync.Once // ensures quit is closed once
quit chan struct{} // quit is closed when the subscription exits
err chan error // channel to send/receive delegate error
filters []delegateSubFilter // blacklist filter chain
}
func newDelegateSubscription(
dCtx *delegateContext, subId rpc.ID, channel interface{}, filters ...delegateSubFilter) *delegateSubscription {
// check type of channel first
chanVal := reflect.ValueOf(channel)
if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 || chanVal.IsNil() {
panic("Delegate subscription channel must be a writable channel and not be nil")
}
return &delegateSubscription{
dCtx: dCtx,
subId: subId,
etype: chanVal.Type().Elem(),
channel: chanVal,
quit: make(chan struct{}),
err: make(chan error, 1),
filters: filters,
}
}
func (sub *delegateSubscription) deliver(result interface{}) bool {
// filter result before deliver
for _, blacklist := range sub.filters {
if blacklist(result) {
logrus.WithField("result", result).
Debug("Blacklisted to deliver from delegate subscription")
return false
}
}
cases := []reflect.SelectCase{
{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(sub.quit)},
{Dir: reflect.SelectSend, Chan: sub.channel, Send: reflect.ValueOf(result)},
{Dir: reflect.SelectDefault},
}
switch index, _, _ := reflect.Select(cases); index {
case 0: // <-sub.quit:
return false
case 1: // sub.channel<-
return true
case 2: // never blocking for subscription queue overflow
sub.err <- rpc.ErrSubscriptionQueueOverflow
return false
}
return false
}
// unsubscribe the notification and closes the error channel.
// It can safely be called more than once.
func (sub *delegateSubscription) unsubscribe() {
sub.quitOnce.Do(func() {
// deregister delegate subscriptions
sub.dCtx.deregisterDelegateSub(sub.subId)
close(sub.quit)
close(sub.err)
})
}
// delegateContext delegate context used for each delegation type
type delegateContext struct {
oncer sync.Once
lock sync.RWMutex
status delegateStatus
delegateSubs util.ConcurrentMap // client subscription ID => *delegateSubscription
epoch *types.Epoch // epochs subscription type
}
// functional options to set delegateContext
type delegateCtxOption func(ctx *delegateContext)
func newDelegateContext(options ...delegateCtxOption) *delegateContext {
ctx := &delegateContext{status: delegateStatusInit}
for i := 0; i < len(options); i++ {
options[i](ctx)
}
return ctx
}
func withEpoch(epoch *types.Epoch) delegateCtxOption {
return func(ctx *delegateContext) {
ctx.epoch = epoch
}
}
func (dctx *delegateContext) getStatus() delegateStatus {
return delegateStatus(atomic.LoadUint32((*uint32)(&dctx.status)))
}
func (dctx *delegateContext) setStatus(status delegateStatus) {
atomic.StoreUint32((*uint32)(&dctx.status), uint32(status))
}
func (dctx *delegateContext) registerDelegateSub(
pubsubRunLoop func(dctx *delegateContext) error,
subId rpc.ID, channel interface{}, filters ...delegateSubFilter,
) (*delegateSubscription, error) {
dctx.lock.Lock()
defer dctx.lock.Unlock()
var err error
if pubsubRunLoop != nil { // start delegate pubsub run loop once
dctx.oncer.Do(func() {
err = pubsubRunLoop(dctx)
})
}
if err != nil {
dctx.oncer = sync.Once{}
return nil, err
}
delegateSub := newDelegateSubscription(dctx, subId, channel, filters...)
dctx.delegateSubs.Store(subId, delegateSub)
return delegateSub, nil
}
func (dctx *delegateContext) deregisterDelegateSub(subId rpc.ID) *delegateSubscription {
dctx.lock.Lock()
defer dctx.lock.Unlock()
if dsub, loaded := dctx.delegateSubs.LoadAndDelete(subId); loaded {
return dsub.(*delegateSubscription)
}
return nil
}
// cancel all delegated subscriptions
func (dctx *delegateContext) cancel(err error) {
dctx.lock.Lock()
defer dctx.lock.Unlock()
if err == nil {
err = rpc.ErrClientQuit
}
dctx.delegateSubs.Range(func(key, value interface{}) bool {
dsub := value.(*delegateSubscription)
dsub.err <- err
dctx.delegateSubs.Delete(key)
return true
})
dctx.oncer = sync.Once{}
}
// notify all delegated subscriptions for new result
func (dctx *delegateContext) notify(result interface{}) {
dctx.lock.RLock()
defer dctx.lock.RUnlock()
dctx.delegateSubs.Range(func(key, value interface{}) bool {
dsub := value.(*delegateSubscription)
dsub.deliver(result)
return true
})
}
// delegateClient client delegated for pubsub subscription
type delegateClient struct {
sdk.ClientOperator
delegateContexts util.ConcurrentMap // context name => *delegateContext
}
func getOrNewDelegateClient(cfx sdk.ClientOperator) *delegateClient {
nodeName := rpcutil.Url2NodeName(cfx.GetNodeURL())
client, _ := delegateClients.LoadOrStore(nodeName, &delegateClient{ClientOperator: cfx})
return client.(*delegateClient)
}
func (client *delegateClient) getDelegateCtx(ctxName string) *delegateContext {
dctx, _ := client.delegateContexts.LoadOrStore(ctxName, newDelegateContext())
return dctx.(*delegateContext)
}
func (client *delegateClient) getDelegateCtxWithEpoch(ctxName string, epoch *types.Epoch) *delegateContext {
dctx, _ := client.delegateContexts.LoadOrStore(ctxName, newDelegateContext(withEpoch(epoch)))
return dctx.(*delegateContext)
}
func (client *delegateClient) delegateSubscribeNewHeads(
subId rpc.ID, channel chan *types.BlockHeader) (*delegateSubscription, error) {
dCtx := client.getDelegateCtx(nhCtxName)
if dCtx.getStatus() == delegateStatusErr {
return nil, errDelegateNotReady
}
return dCtx.registerDelegateSub(client.proxySubscribeNewHeads, subId, channel)
}
func (client *delegateClient) proxySubscribeNewHeads(dctx *delegateContext) error {
nhCh := make(chan types.BlockHeader, pubsubChannelBufferSize)
csub, err := client.SubscribeNewHeads(nhCh)
if err != nil {
logrus.WithField("nodeURL", client.GetNodeURL()).
WithError(err).
Info("CFX Pub/Sub NewHead proxy subscription conn error")
return err
}
go func() { // run subscription loop
dctx.setStatus(delegateStatusOK)
defer dctx.setStatus(delegateStatusInit)
for dctx.getStatus() == delegateStatusOK {
select {
case err = <-csub.Err():
logrus.WithField("nodeURL", client.GetNodeURL()).
WithError(err).
Info("CFX Pub/Sub NewHeads subscription delegate error")
dctx.setStatus(delegateStatusErr)
csub.Unsubscribe()
dctx.cancel(err)
case h := <-nhCh: // notify all delegated subscriptions
dctx.notify(&h)
}
}
}()
logrus.WithField("nodeURL", client.GetNodeURL()).
Info("CFX Pub/Sub NewHead proxy subscription run loop started")
return nil
}
func (client *delegateClient) delegateSubscribeEpochs(
subId rpc.ID, channel chan *types.WebsocketEpochResponse, subscriptionEpochType ...types.Epoch,
) (*delegateSubscription, error) {
subEpochType, dctxName := types.EpochLatestMined, lmEpochCtxName
if len(subscriptionEpochType) > 0 && subscriptionEpochType[0].Equals(types.EpochLatestState) {
subEpochType, dctxName = types.EpochLatestState, lsEpochCtxName
}
dCtx := client.getDelegateCtxWithEpoch(dctxName, subEpochType)
if dCtx.getStatus() == delegateStatusErr {
return nil, errDelegateNotReady
}
return dCtx.registerDelegateSub(client.proxySubscribeEpochs, subId, channel)
}
func (client *delegateClient) proxySubscribeEpochs(dctx *delegateContext) error {
logger := logrus.WithFields(logrus.Fields{
"nodeURL": client.GetNodeURL(),
"subEpochType": dctx.epoch,
})
epochCh := make(chan types.WebsocketEpochResponse, pubsubChannelBufferSize)
csub, err := client.SubscribeEpochs(epochCh, *dctx.epoch)
if err != nil {
logger.WithError(err).Info("CFX Pub/Sub Epochs proxy subscription conn error")
return err
}
go func() { // run subscription loop
dctx.setStatus(delegateStatusOK)
defer dctx.setStatus(delegateStatusInit)
for dctx.getStatus() == delegateStatusOK {
select {
case err = <-csub.Err():
logger.WithError(err).Info("CFX Pub/Sub Epochs proxy subscription delegate error")
dctx.setStatus(delegateStatusErr)
csub.Unsubscribe()
dctx.cancel(err)
case e := <-epochCh: // notify all delegated subscriptions
dctx.notify(&e)
}
}
}()
logrus.WithField("nodeURL", client.GetNodeURL()).
Info("CFX Pub/Sub Epochs proxy subscription run loop started")
return nil
}
func (client *delegateClient) delegateSubscribeLogs(
subId rpc.ID, channel chan *types.SubscriptionLog, filter types.LogFilter) (*delegateSubscription, error) {
dCtx := client.getDelegateCtx(logsCtxName)
if dCtx.getStatus() == delegateStatusErr {
return nil, errDelegateNotReady
}
return dCtx.registerDelegateSub(client.proxySubscribeLogs, subId, channel, func(item interface{}) bool {
log, ok := item.(*types.SubscriptionLog)
return !ok || !matchPubSubLogFilter(log, &filter)
})
}
func (client *delegateClient) proxySubscribeLogs(dctx *delegateContext) error {
logsCh := make(chan types.SubscriptionLog, pubsubChannelBufferSize)
csub, err := client.SubscribeLogs(logsCh, types.LogFilter{})
if err != nil {
logrus.WithField("nodeURL", client.GetNodeURL()).
WithError(err).
Info("CFX Pub/Sub Logs subscription conn error")
return err
}
go func() { // run subscription loop
dctx.setStatus(delegateStatusOK)
defer dctx.setStatus(delegateStatusInit)
for dctx.getStatus() == delegateStatusOK {
select {
case err = <-csub.Err():
logrus.WithField("nodeURL", client.GetNodeURL()).
WithError(err).
Info("CFX Pub/Sub Logs proxy subscription delegate error")
dctx.setStatus(delegateStatusErr)
csub.Unsubscribe()
dctx.cancel(err)
case l := <-logsCh: // notify all delegated subscriptions
dctx.notify(&l)
}
}
}()
logrus.WithField("nodeURL", client.GetNodeURL()).
Info("CFX Pub/Sub Logs proxy subscription run loop started")
return nil
}
func matchPubSubLogFilter(log *types.SubscriptionLog, filter *types.LogFilter) bool {
if (len(filter.Address) == 0 && len(filter.Topics) == 0) || log.IsRevertLog() {
return true
}
return util.IncludeCfxLogAddrs(log.Log, filter.Address) && util.MatchCfxLogTopics(log.Log, filter.Topics)
}
func isEmptyLogFilter(filter types.LogFilter) bool {
if len(filter.Address) > 0 {
return false
}
for i := range filter.Topics {
if len(filter.Topics[i]) > 0 {
return false
}
}
return true
}
// rpcClientFromContext returns the rpc client value stored in ctx, if any.
func rpcClientFromContext(ctx context.Context) (*rpc.Client, bool) {
client, supported := ctx.Value("client").(*rpc.Client)
return client, supported
}