listener.go 1.17 KB
Newer Older
1 2
package p2p

3
import (
Łukasz Magiera's avatar
Łukasz Magiera committed
4
	"errors"
5 6 7
	"sync"
)

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

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

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

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

29 30 31 32 33 34 35 36 37 38 39 40 41 42
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()
}

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

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

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

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

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