pubsub.go 12.9 KB
Newer Older
vyzo's avatar
vyzo committed
1 2 3
package namesys

import (
4
	"bytes"
vyzo's avatar
vyzo committed
5
	"context"
6
	"encoding/base64"
7
	"errors"
8
	"fmt"
Adin Schmahmann's avatar
Adin Schmahmann committed
9 10
	"sync"
	"time"
11

tavit ohanian's avatar
tavit ohanian committed
12 13 14
	"gitlab.dms3.io/p2p/go-p2p-core/host"
	"gitlab.dms3.io/p2p/go-p2p-core/peer"
	"gitlab.dms3.io/p2p/go-p2p-core/routing"
15

tavit ohanian's avatar
tavit ohanian committed
16 17
	pubsub "gitlab.dms3.io/p2p/go-p2p-pubsub"
	record "gitlab.dms3.io/p2p/go-p2p-record"
18

19 20 21 22
	ds "gitlab.dms3.io/dms3/go-datastore"
	dssync "gitlab.dms3.io/dms3/go-datastore/sync"
	dshelp "gitlab.dms3.io/dms3/go-dms3-ds-help"
	logging "gitlab.dms3.io/dms3/go-log/v2"
vyzo's avatar
vyzo committed
23 24
)

25
var log = logging.Logger("pubsub-valuestore")
vyzo's avatar
vyzo committed
26

27 28 29 30
// 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 {
Steven Allen's avatar
Steven Allen committed
31
	RegisterTopicValidator(topic string, validator interface{}, opts ...pubsub.ValidatorOpt) error
Alex Trottier's avatar
Alex Trottier committed
32 33 34
	Join(topic string, opts ...pubsub.TopicOpt) (*pubsub.Topic, error)
}

Łukasz Magiera's avatar
Łukasz Magiera committed
35
type watchGroup struct {
36
	// Note: this chan must be buffered, see notifyWatchers
37
	listeners map[chan []byte]struct{}
Łukasz Magiera's avatar
Łukasz Magiera committed
38 39
}

40
type PubsubValueStore struct {
41 42
	ctx context.Context
	ds  ds.Datastore
43
	ps  Pubsub
vyzo's avatar
vyzo committed
44

45 46
	host  host.Host
	fetch *fetchProtocol
47 48 49 50

	rebroadcastInitialDelay time.Duration
	rebroadcastInterval     time.Duration

51 52 53
	// Map of keys to topics
	mx     sync.Mutex
	topics map[string]*topicInfo
54

55
	watchLk  sync.Mutex
Łukasz Magiera's avatar
Łukasz Magiera committed
56 57
	watching map[string]*watchGroup

58
	Validator record.Validator
vyzo's avatar
vyzo committed
59 60
}

61 62 63 64 65 66 67 68 69 70 71
type topicInfo struct {
	topic *pubsub.Topic
	evts  *pubsub.TopicEventHandler
	sub   *pubsub.Subscription

	cancel   context.CancelFunc
	finished chan struct{}

	dbWriteMx sync.Mutex
}

72 73 74 75 76 77 78
// 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))
}

79 80 81 82
// 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.
83
func NewPubsubValueStore(ctx context.Context, host host.Host, ps Pubsub, validator record.Validator, opts ...Option) (*PubsubValueStore, error) {
84
	psValueStore := &PubsubValueStore{
Łukasz Magiera's avatar
Łukasz Magiera committed
85 86
		ctx: ctx,

87 88 89 90
		ds:                      dssync.MutexWrap(ds.NewMapDatastore()),
		ps:                      ps,
		host:                    host,
		rebroadcastInitialDelay: 100 * time.Millisecond,
91
		rebroadcastInterval:     time.Minute * 10,
Łukasz Magiera's avatar
Łukasz Magiera committed
92

93
		topics:   make(map[string]*topicInfo),
Łukasz Magiera's avatar
Łukasz Magiera committed
94 95
		watching: make(map[string]*watchGroup),

96
		Validator: validator,
vyzo's avatar
vyzo committed
97
	}
98

99 100 101 102 103 104 105
	for _, opt := range opts {
		err := opt(psValueStore)
		if err != nil {
			return nil, err
		}
	}

106
	psValueStore.fetch = newFetchProtocol(ctx, host, psValueStore.getLocal)
107

108
	go psValueStore.rebroadcast(ctx)
109

110
	return psValueStore, nil
vyzo's avatar
vyzo committed
111 112
}

113
// PutValue publishes a record through pubsub
114
func (p *PubsubValueStore) PutValue(ctx context.Context, key string, value []byte, opts ...routing.Option) error {
115 116 117 118
	if err := p.Subscribe(key); err != nil {
		return err
	}

119
	log.Debugf("PubsubPublish: publish value for key", key)
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	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(ti, key, value)
	if err != nil {
		return err
	}
	if recCmp < 0 {
		return nil
	}

138
	select {
139
	case err := <-p.psPublishChannel(ctx, ti.topic, value):
140 141 142 143
		return err
	case <-ctx.Done():
		return ctx.Err()
	}
vyzo's avatar
vyzo committed
144 145
}

146
// compare compares the input value with the current value.
Steven Allen's avatar
Steven Allen committed
147 148 149 150
// 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(key string, val []byte) (int, bool) {
151
	if p.Validator.Validate(key, val) != nil {
Steven Allen's avatar
Steven Allen committed
152
		return -1, false
vyzo's avatar
vyzo committed
153 154
	}

155
	old, err := p.getLocal(key)
Adin Schmahmann's avatar
Adin Schmahmann committed
156 157
	if err != nil {
		// If the old one is invalid, the new one is *always* better.
Steven Allen's avatar
Steven Allen committed
158
		return 1, true
Adin Schmahmann's avatar
Adin Schmahmann committed
159
	}
160 161 162

	// Same record is not better
	if old != nil && bytes.Equal(old, val) {
Steven Allen's avatar
Steven Allen committed
163
		return 0, true
vyzo's avatar
vyzo committed
164 165
	}

166
	i, err := p.Validator.Select(key, [][]byte{val, old})
167
	if err == nil && i == 0 {
Steven Allen's avatar
Steven Allen committed
168
		return 1, true
169
	}
Steven Allen's avatar
Steven Allen committed
170
	return -1, true
vyzo's avatar
vyzo committed
171 172
}

173 174
func (p *PubsubValueStore) Subscribe(key string) error {
	p.mx.Lock()
175
	defer p.mx.Unlock()
176

177 178 179
	// see if we already have a pubsub subscription; if not, subscribe
	ti, ok := p.topics[key]
	if ok {
180
		return nil
vyzo's avatar
vyzo committed
181 182
	}

183 184
	topic := KeyToTopic(key)

185 186 187 188
	// 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.
189
	myID := p.host.ID()
Steven Allen's avatar
Steven Allen committed
190 191 192 193 194 195 196 197 198
	_ = p.ps.RegisterTopicValidator(topic, func(
		ctx context.Context,
		src peer.ID,
		msg *pubsub.Message,
	) pubsub.ValidationResult {
		cmp, valid := p.compare(key, msg.GetData())
		if !valid {
			return pubsub.ValidationReject
		}
199

Steven Allen's avatar
Steven Allen committed
200 201 202 203
		if cmp > 0 || cmp == 0 && src == myID {
			return pubsub.ValidationAccept
		}
		return pubsub.ValidationIgnore
204 205
	})

206
	ti, err := p.createTopicHandler(topic)
vyzo's avatar
vyzo committed
207 208 209 210
	if err != nil {
		return err
	}

211
	p.topics[key] = ti
212
	ctx, cancel := context.WithCancel(p.ctx)
213
	ti.cancel = cancel
214

215
	go p.handleSubscription(ctx, ti, key)
vyzo's avatar
vyzo committed
216

217
	log.Debugf("PubsubResolve: subscribed to %s", key)
vyzo's avatar
vyzo committed
218

219 220 221 222 223 224 225 226
	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
227 228
	}

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
	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
249
}
vyzo's avatar
vyzo committed
250

251
func (p *PubsubValueStore) rebroadcast(ctx context.Context) {
252 253 254 255 256
	select {
	case <-time.After(p.rebroadcastInitialDelay):
	case <-ctx.Done():
		return
	}
257 258 259 260 261 262 263

	ticker := time.NewTicker(p.rebroadcastInterval)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
264
			p.mx.Lock()
265 266 267 268 269
			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)
270
			}
271
			p.mx.Unlock()
272 273
			if len(topics) > 0 {
				for i, k := range keys {
274 275
					val, err := p.getLocal(k)
					if err == nil {
276
						topic := topics[i].topic
277
						select {
278
						case <-p.psPublishChannel(ctx, topic, val):
279 280 281 282 283 284 285
						case <-ctx.Done():
							return
						}
					}
				}
			}
		case <-ctx.Done():
286 287 288 289 290
			return
		}
	}
}

291
func (p *PubsubValueStore) psPublishChannel(ctx context.Context, topic *pubsub.Topic, value []byte) chan error {
292 293
	done := make(chan error, 1)
	go func() {
294
		done <- topic.Publish(ctx, value)
295 296 297 298
	}()
	return done
}

299 300 301 302 303
// 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(ti *topicInfo, key string, value []byte) (int, error) {
Steven Allen's avatar
Steven Allen committed
304 305
	cmp, valid := p.compare(key, value)
	if valid && cmp > 0 {
306 307 308 309 310
		return cmp, p.ds.Put(dshelp.NewKeyFromBinary([]byte(key)), value)
	}
	return cmp, nil
}

311
func (p *PubsubValueStore) getLocal(key string) ([]byte, error) {
Steven Allen's avatar
Steven Allen committed
312
	val, err := p.ds.Get(dshelp.NewKeyFromBinary([]byte(key)))
vyzo's avatar
vyzo committed
313
	if err != nil {
314
		// Don't invalidate due to ds errors.
vyzo's avatar
vyzo committed
315
		if err == ds.ErrNotFound {
316
			err = routing.ErrNotFound
vyzo's avatar
vyzo committed
317
		}
318
		return nil, err
vyzo's avatar
vyzo committed
319
	}
320 321

	// If the old one is invalid, the new one is *always* better.
322
	if err := p.Validator.Validate(key, val); err != nil {
Adin Schmahmann's avatar
Adin Schmahmann committed
323
		return nil, err
vyzo's avatar
vyzo committed
324
	}
325 326
	return val, nil
}
vyzo's avatar
vyzo committed
327

328
func (p *PubsubValueStore) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
329 330
	if err := p.Subscribe(key); err != nil {
		return nil, err
vyzo's avatar
vyzo committed
331 332
	}

333
	return p.getLocal(key)
vyzo's avatar
vyzo committed
334 335
}

336
func (p *PubsubValueStore) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
Łukasz Magiera's avatar
Łukasz Magiera committed
337 338 339 340
	if err := p.Subscribe(key); err != nil {
		return nil, err
	}

341 342 343
	p.watchLk.Lock()
	defer p.watchLk.Unlock()

344 345 346 347
	out := make(chan []byte, 1)
	lv, err := p.getLocal(key)
	if err == nil {
		out <- lv
348 349
		close(out)
		return out, nil
350 351
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
352 353 354
	wg, ok := p.watching[key]
	if !ok {
		wg = &watchGroup{
355
			listeners: map[chan []byte]struct{}{},
Łukasz Magiera's avatar
Łukasz Magiera committed
356
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
357
		p.watching[key] = wg
Łukasz Magiera's avatar
Łukasz Magiera committed
358 359
	}

360 361 362
	proxy := make(chan []byte, 1)

	ctx, cancel := context.WithCancel(ctx)
363
	wg.listeners[proxy] = struct{}{}
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

	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
				}
393 394 395

				// 1 is good enough
				return
396 397 398 399 400
			case <-ctx.Done():
				return
			}
		}
	}()
Łukasz Magiera's avatar
Łukasz Magiera committed
401 402 403 404

	return out, nil
}

vyzo's avatar
vyzo committed
405
// GetSubscriptions retrieves a list of active topic subscriptions
406 407 408
func (p *PubsubValueStore) GetSubscriptions() []string {
	p.mx.Lock()
	defer p.mx.Unlock()
vyzo's avatar
vyzo committed
409 410

	var res []string
411
	for sub := range p.topics {
vyzo's avatar
vyzo committed
412 413 414 415 416 417 418 419
		res = append(res, sub)
	}

	return res
}

// Cancel cancels a topic subscription; returns true if an active
// subscription was canceled
420
func (p *PubsubValueStore) Cancel(name string) (bool, error) {
421 422
	p.mx.Lock()
	defer p.mx.Unlock()
vyzo's avatar
vyzo committed
423

424 425 426
	p.watchLk.Lock()
	if _, wok := p.watching[name]; wok {
		p.watchLk.Unlock()
427
		return false, fmt.Errorf("key has active subscriptions")
428 429 430
	}
	p.watchLk.Unlock()

431
	ti, ok := p.topics[name]
vyzo's avatar
vyzo committed
432
	if ok {
433 434
		p.closeTopic(name, ti)
		<-ti.finished
435 436
	}

437
	return ok, nil
vyzo's avatar
vyzo committed
438 439
}

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
// 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)
	}()
vyzo's avatar
vyzo committed
458

459 460
	newMsg := make(chan []byte)
	go func() {
461
		defer close(newMsg)
462
		for {
463
			data, err := p.handleNewMsgs(ctx, ti.sub, key)
464 465
			if err != nil {
				return
vyzo's avatar
vyzo committed
466
			}
467 468 469 470 471
			select {
			case newMsg <- data:
			case <-ctx.Done():
				return
			}
472 473 474 475 476
		}
	}()

	newPeerData := make(chan []byte)
	go func() {
477
		defer close(newPeerData)
478
		for {
479
			data, err := p.handleNewPeer(ctx, ti.evts, key)
480 481 482 483 484 485 486 487 488 489 490 491 492
			if err == nil {
				if data != nil {
					select {
					case newPeerData <- data:
					case <-ctx.Done():
						return
					}
				}
			} else {
				select {
				case <-ctx.Done():
					return
				default:
493
					log.Errorf("PubsubPeerJoin: error interacting with new peer: %s", err)
494
				}
495 496 497 498 499 500
			}
		}
	}()

	for {
		var data []byte
501
		var ok bool
502
		select {
503 504 505 506 507 508 509 510 511 512
		case data, ok = <-newMsg:
			if !ok {
				return
			}
		case data, ok = <-newPeerData:
			if !ok {
				return
			}
		case <-ctx.Done():
			return
vyzo's avatar
vyzo committed
513
		}
514

515 516 517 518
		ti.dbWriteMx.Lock()
		recCmp, err := p.putLocal(ti, key, data)
		ti.dbWriteMx.Unlock()
		if recCmp > 0 {
519
			if err != nil {
Steven Allen's avatar
Steven Allen committed
520
				log.Warnf("PubsubResolve: error writing update for %s: %s", key, err)
521
			}
522 523 524 525 526
			p.notifyWatchers(key, data)
		}
	}
}

527 528
func (p *PubsubValueStore) handleNewMsgs(ctx context.Context, sub *pubsub.Subscription, key string) ([]byte, error) {
	msg, err := sub.Next(ctx)
529 530
	if err != nil {
		if err != context.Canceled {
Steven Allen's avatar
Steven Allen committed
531
			log.Warnf("PubsubResolve: subscription error in %s: %s", key, err.Error())
532 533 534 535 536 537
		}
		return nil, err
	}
	return msg.GetData(), nil
}

538
func (p *PubsubValueStore) handleNewPeer(ctx context.Context, peerEvtHandler *pubsub.TopicEventHandler, key string) ([]byte, error) {
539
	for ctx.Err() == nil {
540
		peerEvt, err := peerEvtHandler.NextPeerEvent(ctx)
541 542
		if err != nil {
			if err != context.Canceled {
Steven Allen's avatar
Steven Allen committed
543
				log.Warnf("PubsubNewPeer: subscription error in %s: %s", key, err.Error())
544 545 546
			}
			return nil, err
		}
547 548 549

		if peerEvt.Type != pubsub.PeerJoin {
			continue
vyzo's avatar
vyzo committed
550
		}
551

552 553 554 555 556 557 558 559
		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()
vyzo's avatar
vyzo committed
560 561
}

Łukasz Magiera's avatar
Łukasz Magiera committed
562
func (p *PubsubValueStore) notifyWatchers(key string, data []byte) {
563 564
	p.watchLk.Lock()
	defer p.watchLk.Unlock()
Łukasz Magiera's avatar
Łukasz Magiera committed
565 566 567 568 569
	sg, ok := p.watching[key]
	if !ok {
		return
	}

570
	for watcher := range sg.listeners {
Łukasz Magiera's avatar
Łukasz Magiera committed
571
		select {
572 573 574
		case <-watcher:
			watcher <- data
		case watcher <- data:
Łukasz Magiera's avatar
Łukasz Magiera committed
575
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
576 577
	}
}
578

579 580 581 582
func WithRebroadcastInterval(duration time.Duration) Option {
	return func(store *PubsubValueStore) error {
		store.rebroadcastInterval = duration
		return nil
583
	}
584
}
585

586 587 588 589 590
func WithRebroadcastInitialDelay(duration time.Duration) Option {
	return func(store *PubsubValueStore) error {
		store.rebroadcastInitialDelay = duration
		return nil
	}
591
}
Keenan Nemetz's avatar
Keenan Nemetz committed
592 593 594 595 596 597 598 599

// 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
	}
}