listener.go 1.19 KB
Newer Older
1 2
package p2p

3 4
import (
	"sync"
5 6

	"github.com/pkg/errors"
7 8
)

9 10
type Listener interface {
	Protocol() string
Łukasz Magiera's avatar
Łukasz Magiera committed
11 12
	ListenAddress() string
	TargetAddress() string
13 14 15 16 17

	// Close closes the listener. Does not affect child streams
	Close() error
}

18 19 20 21 22 23
type listenerKey struct {
	proto  string
	listen string
	target string
}

24 25
// ListenerRegistry is a collection of local application proto listeners.
type ListenerRegistry struct {
26
	Listeners map[listenerKey]Listener
27
	lk        *sync.Mutex
28 29
}

30 31 32 33 34 35 36 37 38 39 40 41 42 43
func (r *ListenerRegistry) Lock(l Listener) error {
	r.lk.Lock()

	if _, ok := r.Listeners[getListenerKey(l)]; ok {
		r.lk.Unlock()
		return errors.New("listener already registered")
	}
	return nil
}

func (r *ListenerRegistry) Unlock() {
	r.lk.Unlock()
}

44
// Register registers listenerInfo in this registry
45 46 47 48
func (r *ListenerRegistry) Register(l Listener) {
	defer r.lk.Unlock()

	r.Listeners[getListenerKey(l)] = l
49 50 51
}

// Deregister removes p2p listener from this registry
52 53 54 55 56
func (r *ListenerRegistry) Deregister(k listenerKey) {
	r.lk.Lock()
	defer r.lk.Unlock()

	delete(r.Listeners, k)
57 58 59 60 61 62 63 64
}

func getListenerKey(l Listener) listenerKey {
	return listenerKey{
		proto:  l.Protocol(),
		listen: l.ListenAddress(),
		target: l.TargetAddress(),
	}
65
}