completedlisteners.go 1.46 KB
Newer Older
1 2 3
package hooks

import (
4
	"github.com/hannahhoward/go-pubsub"
5 6 7 8 9 10
	"github.com/ipfs/go-graphsync"
	peer "github.com/libp2p/go-libp2p-core/peer"
)

// CompletedResponseListeners is a set of listeners for completed responses
type CompletedResponseListeners struct {
11 12 13 14 15 16 17 18 19 20 21 22 23 24
	pubSub *pubsub.PubSub
}

type internalCompletedResponseEvent struct {
	p       peer.ID
	request graphsync.RequestData
	status  graphsync.ResponseStatusCode
}

func completedResponseDispatcher(event pubsub.Event, subscriberFn pubsub.SubscriberFn) error {
	ie := event.(internalCompletedResponseEvent)
	listener := subscriberFn.(graphsync.OnResponseCompletedListener)
	listener(ie.p, ie.request, ie.status)
	return nil
25 26 27 28
}

// NewCompletedResponseListeners returns a new list of completed response listeners
func NewCompletedResponseListeners() *CompletedResponseListeners {
29
	return &CompletedResponseListeners{pubSub: pubsub.New(completedResponseDispatcher)}
30 31 32 33
}

// Register registers an listener for completed responses
func (crl *CompletedResponseListeners) Register(listener graphsync.OnResponseCompletedListener) graphsync.UnregisterHookFunc {
34
	return graphsync.UnregisterHookFunc(crl.pubSub.Subscribe(listener))
35 36 37 38
}

// NotifyCompletedListeners runs notifies all completed listeners that a response has completed
func (crl *CompletedResponseListeners) NotifyCompletedListeners(p peer.ID, request graphsync.RequestData, status graphsync.ResponseStatusCode) {
39
	_ = crl.pubSub.Publish(internalCompletedResponseEvent{p, request, status})
40
}