-
Notifications
You must be signed in to change notification settings - Fork 12
/
pubsub.go
599 lines (502 loc) · 13 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package namesys
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"sync"
"time"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/routing"
pubsub "github.com/libp2p/go-libp2p-pubsub"
record "github.com/libp2p/go-libp2p-record"
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
dshelp "github.com/ipfs/go-ipfs-ds-help"
logging "github.com/ipfs/go-log/v2"
)
var log = logging.Logger("pubsub-valuestore")
// Pubsub is the minimal subset of the pubsub interface required by the pubsub
// value store. This way, users can wrap the underlying pubsub implementation
// without re-exporting/implementing the entire interface.
type Pubsub interface {
RegisterTopicValidator(topic string, validator interface{}, opts ...pubsub.ValidatorOpt) error
Join(topic string, opts ...pubsub.TopicOpt) (*pubsub.Topic, error)
}
type watchGroup struct {
// Note: this chan must be buffered, see notifyWatchers
listeners map[chan []byte]struct{}
}
type PubsubValueStore struct {
ctx context.Context
ds ds.Datastore
ps Pubsub
host host.Host
fetch *fetchProtocol
rebroadcastInitialDelay time.Duration
rebroadcastInterval time.Duration
// Map of keys to topics
mx sync.Mutex
topics map[string]*topicInfo
watchLk sync.Mutex
watching map[string]*watchGroup
Validator record.Validator
}
type topicInfo struct {
topic *pubsub.Topic
evts *pubsub.TopicEventHandler
sub *pubsub.Subscription
cancel context.CancelFunc
finished chan struct{}
dbWriteMx sync.Mutex
}
// KeyToTopic converts a binary record key to a pubsub topic key.
func KeyToTopic(key string) string {
// Record-store keys are arbitrary binary. However, pubsub requires UTF-8 string topic IDs.
// Encodes to "/record/base64url(key)"
return "/record/" + base64.RawURLEncoding.EncodeToString([]byte(key))
}
// Option is a function that configures a PubsubValueStore during initialization
type Option func(*PubsubValueStore) error
// NewPubsubValueStore constructs a new ValueStore that gets and receives records through pubsub.
func NewPubsubValueStore(ctx context.Context, host host.Host, ps Pubsub, validator record.Validator, opts ...Option) (*PubsubValueStore, error) {
psValueStore := &PubsubValueStore{
ctx: ctx,
ds: dssync.MutexWrap(ds.NewMapDatastore()),
ps: ps,
host: host,
rebroadcastInitialDelay: 100 * time.Millisecond,
rebroadcastInterval: time.Minute * 10,
topics: make(map[string]*topicInfo),
watching: make(map[string]*watchGroup),
Validator: validator,
}
for _, opt := range opts {
err := opt(psValueStore)
if err != nil {
return nil, err
}
}
psValueStore.fetch = newFetchProtocol(ctx, host, psValueStore.getLocal)
go psValueStore.rebroadcast(ctx)
return psValueStore, nil
}
// PutValue publishes a record through pubsub
func (p *PubsubValueStore) PutValue(ctx context.Context, key string, value []byte, opts ...routing.Option) error {
if err := p.Subscribe(key); err != nil {
return err
}
log.Debugf("PubsubPublish: publish value for key", key)
p.mx.Lock()
ti, ok := p.topics[key]
p.mx.Unlock()
if !ok {
return errors.New("could not find topic handle")
}
ti.dbWriteMx.Lock()
defer ti.dbWriteMx.Unlock()
recCmp, err := p.putLocal(ctx, ti, key, value)
if err != nil {
return err
}
if recCmp < 0 {
return nil
}
select {
case err := <-p.psPublishChannel(ctx, ti.topic, value):
return err
case <-ctx.Done():
return ctx.Err()
}
}
// compare compares the input value with the current value.
// First return value is 0 if equal, greater than 0 if better, less than 0 if worse.
// Second return value is true if valid.
//
func (p *PubsubValueStore) compare(ctx context.Context, key string, val []byte) (int, bool) {
if p.Validator.Validate(key, val) != nil {
return -1, false
}
old, err := p.getLocal(ctx, key)
if err != nil {
// If the old one is invalid, the new one is *always* better.
return 1, true
}
// Same record is not better
if old != nil && bytes.Equal(old, val) {
return 0, true
}
i, err := p.Validator.Select(key, [][]byte{val, old})
if err == nil && i == 0 {
return 1, true
}
return -1, true
}
func (p *PubsubValueStore) Subscribe(key string) error {
p.mx.Lock()
defer p.mx.Unlock()
// see if we already have a pubsub subscription; if not, subscribe
_, ok := p.topics[key]
if ok {
return nil
}
topic := KeyToTopic(key)
// Ignore the error. We have to check again anyways to make sure the
// record hasn't expired.
//
// Also, make sure to do this *before* subscribing.
myID := p.host.ID()
_ = p.ps.RegisterTopicValidator(topic, func(
ctx context.Context,
src peer.ID,
msg *pubsub.Message,
) pubsub.ValidationResult {
cmp, valid := p.compare(ctx, key, msg.GetData())
if !valid {
return pubsub.ValidationReject
}
if cmp > 0 || cmp == 0 && src == myID {
return pubsub.ValidationAccept
}
return pubsub.ValidationIgnore
})
ti, err := p.createTopicHandler(topic)
if err != nil {
return err
}
p.topics[key] = ti
ctx, cancel := context.WithCancel(p.ctx)
ti.cancel = cancel
go p.handleSubscription(ctx, ti, key)
log.Debugf("PubsubResolve: subscribed to %s", key)
return nil
}
// createTopicHandler creates an internal topic object. Must be called with p.mx held
func (p *PubsubValueStore) createTopicHandler(topic string) (*topicInfo, error) {
t, err := p.ps.Join(topic)
if err != nil {
return nil, err
}
sub, err := t.Subscribe()
if err != nil {
_ = t.Close()
return nil, err
}
evts, err := t.EventHandler()
if err != nil {
sub.Cancel()
_ = t.Close()
}
ti := &topicInfo{
topic: t,
evts: evts,
sub: sub,
finished: make(chan struct{}, 1),
}
return ti, nil
}
func (p *PubsubValueStore) rebroadcast(ctx context.Context) {
select {
case <-time.After(p.rebroadcastInitialDelay):
case <-ctx.Done():
return
}
ticker := time.NewTicker(p.rebroadcastInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
p.mx.Lock()
keys := make([]string, 0, len(p.topics))
topics := make([]*topicInfo, 0, len(p.topics))
for k, ti := range p.topics {
keys = append(keys, k)
topics = append(topics, ti)
}
p.mx.Unlock()
if len(topics) > 0 {
for i, k := range keys {
val, err := p.getLocal(ctx, k)
if err == nil {
topic := topics[i].topic
select {
case <-p.psPublishChannel(ctx, topic, val):
case <-ctx.Done():
return
}
}
}
}
case <-ctx.Done():
return
}
}
}
func (p *PubsubValueStore) psPublishChannel(ctx context.Context, topic *pubsub.Topic, value []byte) chan error {
done := make(chan error, 1)
go func() {
done <- topic.Publish(ctx, value)
}()
return done
}
// putLocal tries to put the key-value pair into the local datastore
// Requires that the ti.dbWriteMx is held when called
// Returns true if the value is better then what is currently in the datastore
// Returns any errors from putting the data in the datastore
func (p *PubsubValueStore) putLocal(ctx context.Context, ti *topicInfo, key string, value []byte) (int, error) {
cmp, valid := p.compare(ctx, key, value)
if valid && cmp > 0 {
return cmp, p.ds.Put(ctx, dshelp.NewKeyFromBinary([]byte(key)), value)
}
return cmp, nil
}
func (p *PubsubValueStore) getLocal(ctx context.Context, key string) ([]byte, error) {
val, err := p.ds.Get(ctx, dshelp.NewKeyFromBinary([]byte(key)))
if err != nil {
// Don't invalidate due to ds errors.
if err == ds.ErrNotFound {
err = routing.ErrNotFound
}
return nil, err
}
// If the old one is invalid, the new one is *always* better.
if err := p.Validator.Validate(key, val); err != nil {
return nil, err
}
return val, nil
}
func (p *PubsubValueStore) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
if err := p.Subscribe(key); err != nil {
return nil, err
}
return p.getLocal(ctx, key)
}
func (p *PubsubValueStore) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
if err := p.Subscribe(key); err != nil {
return nil, err
}
p.watchLk.Lock()
defer p.watchLk.Unlock()
out := make(chan []byte, 1)
lv, err := p.getLocal(ctx, key)
if err == nil {
out <- lv
close(out)
return out, nil
}
wg, ok := p.watching[key]
if !ok {
wg = &watchGroup{
listeners: map[chan []byte]struct{}{},
}
p.watching[key] = wg
}
proxy := make(chan []byte, 1)
ctx, cancel := context.WithCancel(ctx)
wg.listeners[proxy] = struct{}{}
go func() {
defer func() {
cancel()
p.watchLk.Lock()
delete(wg.listeners, proxy)
if _, ok := p.watching[key]; len(wg.listeners) == 0 && ok {
delete(p.watching, key)
}
p.watchLk.Unlock()
close(out)
}()
for {
select {
case val, ok := <-proxy:
if !ok {
return
}
// outCh is buffered, so we just put the value or swap it for the newer one
select {
case out <- val:
case <-out:
out <- val
}
// 1 is good enough
return
case <-ctx.Done():
return
}
}
}()
return out, nil
}
// GetSubscriptions retrieves a list of active topic subscriptions
func (p *PubsubValueStore) GetSubscriptions() []string {
p.mx.Lock()
defer p.mx.Unlock()
var res []string
for sub := range p.topics {
res = append(res, sub)
}
return res
}
// Cancel cancels a topic subscription; returns true if an active
// subscription was canceled
func (p *PubsubValueStore) Cancel(name string) (bool, error) {
p.mx.Lock()
defer p.mx.Unlock()
p.watchLk.Lock()
if _, wok := p.watching[name]; wok {
p.watchLk.Unlock()
return false, fmt.Errorf("key has active subscriptions")
}
p.watchLk.Unlock()
ti, ok := p.topics[name]
if ok {
p.closeTopic(name, ti)
<-ti.finished
}
return ok, nil
}
// closeTopic must be called under the PubSubValueStore's mutex
func (p *PubsubValueStore) closeTopic(key string, ti *topicInfo) {
ti.cancel()
ti.sub.Cancel()
ti.evts.Cancel()
_ = ti.topic.Close()
delete(p.topics, key)
}
func (p *PubsubValueStore) handleSubscription(ctx context.Context, ti *topicInfo, key string) {
defer func() {
close(ti.finished)
p.mx.Lock()
defer p.mx.Unlock()
p.closeTopic(key, ti)
}()
newMsg := make(chan []byte)
go func() {
defer close(newMsg)
for {
data, err := p.handleNewMsgs(ctx, ti.sub, key)
if err != nil {
return
}
select {
case newMsg <- data:
case <-ctx.Done():
return
}
}
}()
newPeerData := make(chan []byte)
go func() {
defer close(newPeerData)
for {
data, err := p.handleNewPeer(ctx, ti.evts, key)
if err == nil {
if data != nil {
select {
case newPeerData <- data:
case <-ctx.Done():
return
}
}
} else {
select {
case <-ctx.Done():
return
default:
log.Errorf("PubsubPeerJoin: error interacting with new peer: %s", err)
}
}
}
}()
for {
var data []byte
var ok bool
select {
case data, ok = <-newMsg:
if !ok {
return
}
case data, ok = <-newPeerData:
if !ok {
return
}
case <-ctx.Done():
return
}
ti.dbWriteMx.Lock()
recCmp, err := p.putLocal(ctx, ti, key, data)
ti.dbWriteMx.Unlock()
if recCmp > 0 {
if err != nil {
log.Warnf("PubsubResolve: error writing update for %s: %s", key, err)
}
p.notifyWatchers(key, data)
}
}
}
func (p *PubsubValueStore) handleNewMsgs(ctx context.Context, sub *pubsub.Subscription, key string) ([]byte, error) {
msg, err := sub.Next(ctx)
if err != nil {
if err != context.Canceled {
log.Warnf("PubsubResolve: subscription error in %s: %s", key, err.Error())
}
return nil, err
}
return msg.GetData(), nil
}
func (p *PubsubValueStore) handleNewPeer(ctx context.Context, peerEvtHandler *pubsub.TopicEventHandler, key string) ([]byte, error) {
for ctx.Err() == nil {
peerEvt, err := peerEvtHandler.NextPeerEvent(ctx)
if err != nil {
if err != context.Canceled {
log.Warnf("PubsubNewPeer: subscription error in %s: %s", key, err.Error())
}
return nil, err
}
if peerEvt.Type != pubsub.PeerJoin {
continue
}
pid := peerEvt.Peer
value, err := p.fetch.Fetch(ctx, pid, key)
if err == nil {
return value, nil
}
log.Debugf("failed to fetch latest pubsub value for key '%s' from peer '%s': %s", key, pid, err)
}
return nil, ctx.Err()
}
func (p *PubsubValueStore) notifyWatchers(key string, data []byte) {
p.watchLk.Lock()
defer p.watchLk.Unlock()
sg, ok := p.watching[key]
if !ok {
return
}
for watcher := range sg.listeners {
select {
case <-watcher:
watcher <- data
case watcher <- data:
}
}
}
func WithRebroadcastInterval(duration time.Duration) Option {
return func(store *PubsubValueStore) error {
store.rebroadcastInterval = duration
return nil
}
}
func WithRebroadcastInitialDelay(duration time.Duration) Option {
return func(store *PubsubValueStore) error {
store.rebroadcastInitialDelay = duration
return nil
}
}
// WithDatastore returns an option that overrides the default datastore.
func WithDatastore(datastore ds.Datastore) Option {
return func(store *PubsubValueStore) error {
store.ds = datastore
return nil
}
}