virtual.go 5.64 KB
Newer Older
Brian Tiger Chow's avatar
Brian Tiger Chow committed
1 2 3
package bitswap

import (
4
	"context"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
5
	"errors"
Steven Allen's avatar
Steven Allen committed
6
	"sync"
7
	"sync/atomic"
8
	"time"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
9

Jeromy's avatar
Jeromy committed
10 11
	bsmsg "github.com/ipfs/go-bitswap/message"
	bsnet "github.com/ipfs/go-bitswap/network"
12

Jeromy's avatar
Jeromy committed
13 14 15 16 17 18 19 20
	cid "github.com/ipfs/go-cid"
	delay "github.com/ipfs/go-ipfs-delay"
	mockrouting "github.com/ipfs/go-ipfs-routing/mock"
	logging "github.com/ipfs/go-log"
	ifconnmgr "github.com/libp2p/go-libp2p-interface-connmgr"
	peer "github.com/libp2p/go-libp2p-peer"
	routing "github.com/libp2p/go-libp2p-routing"
	testutil "github.com/libp2p/go-testutil"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
21 22
)

23 24
var log = logging.Logger("bstestnet")

25
func VirtualNetwork(rs mockrouting.Server, d delay.D) Network {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
26
	return &network{
27
		clients:       make(map[peer.ID]*receiverQueue),
28
		delay:         d,
29
		routingserver: rs,
30
		conns:         make(map[string]struct{}),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
31 32 33 34
	}
}

type network struct {
Steven Allen's avatar
Steven Allen committed
35
	mu            sync.Mutex
36
	clients       map[peer.ID]*receiverQueue
37 38
	routingserver mockrouting.Server
	delay         delay.D
39
	conns         map[string]struct{}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
40 41
}

42 43 44 45 46 47 48 49 50 51
type message struct {
	from       peer.ID
	msg        bsmsg.BitSwapMessage
	shouldSend time.Time
}

// receiverQueue queues up a set of messages to be sent, and sends them *in
// order* with their delays respected as much as sending them in order allows
// for
type receiverQueue struct {
52
	receiver *networkClient
53 54 55 56 57
	queue    []*message
	active   bool
	lk       sync.Mutex
}

58
func (n *network) Adapter(p testutil.Identity) bsnet.BitSwapNetwork {
Steven Allen's avatar
Steven Allen committed
59 60 61
	n.mu.Lock()
	defer n.mu.Unlock()

Brian Tiger Chow's avatar
Brian Tiger Chow committed
62
	client := &networkClient{
63
		local:   p.ID(),
64
		network: n,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
65
		routing: n.routingserver.Client(p),
Brian Tiger Chow's avatar
Brian Tiger Chow committed
66
	}
67
	n.clients[p.ID()] = &receiverQueue{receiver: client}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
68 69 70
	return client
}

71
func (n *network) HasPeer(p peer.ID) bool {
Steven Allen's avatar
Steven Allen committed
72 73 74
	n.mu.Lock()
	defer n.mu.Unlock()

75
	_, found := n.clients[p]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76 77 78
	return found
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
79 80 81 82
// TODO should this be completely asynchronous?
// TODO what does the network layer do with errors received from services?
func (n *network) SendMessage(
	ctx context.Context,
83 84
	from peer.ID,
	to peer.ID,
85
	mes bsmsg.BitSwapMessage) error {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
86

Steven Allen's avatar
Steven Allen committed
87 88 89
	n.mu.Lock()
	defer n.mu.Unlock()

90
	receiver, ok := n.clients[to]
Brian Tiger Chow's avatar
Brian Tiger Chow committed
91
	if !ok {
Łukasz Magiera's avatar
Łukasz Magiera committed
92
		return errors.New("cannot locate peer on network")
Brian Tiger Chow's avatar
Brian Tiger Chow committed
93 94 95 96 97
	}

	// nb: terminate the context since the context wouldn't actually be passed
	// over the network in a real scenario

98 99 100 101 102 103
	msg := &message{
		from:       from,
		msg:        mes,
		shouldSend: time.Now().Add(n.delay.Get()),
	}
	receiver.enqueue(msg)
Brian Tiger Chow's avatar
Brian Tiger Chow committed
104 105 106 107 108

	return nil
}

type networkClient struct {
109
	local peer.ID
Brian Tiger Chow's avatar
Brian Tiger Chow committed
110
	bsnet.Receiver
111
	network *network
112
	routing routing.IpfsRouting
113
	stats   bsnet.NetworkStats
Brian Tiger Chow's avatar
Brian Tiger Chow committed
114 115 116 117
}

func (nc *networkClient) SendMessage(
	ctx context.Context,
118
	to peer.ID,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
119
	message bsmsg.BitSwapMessage) error {
120 121 122 123 124 125 126 127 128 129 130 131
	if err := nc.network.SendMessage(ctx, nc.local, to, message); err != nil {
		return err
	}
	atomic.AddUint64(&nc.stats.MessagesSent, 1)
	return nil
}

func (nc *networkClient) Stats() bsnet.NetworkStats {
	return bsnet.NetworkStats{
		MessagesRecvd: atomic.LoadUint64(&nc.stats.MessagesRecvd),
		MessagesSent:  atomic.LoadUint64(&nc.stats.MessagesSent),
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
132 133
}

134
// FindProvidersAsync returns a channel of providers for the given key
135
func (nc *networkClient) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
136 137 138 139 140 141 142 143 144

	// NB: this function duplicates the PeerInfo -> ID transformation in the
	// bitswap network adapter. Not to worry. This network client will be
	// deprecated once the ipfsnet.Mock is added. The code below is only
	// temporary.

	out := make(chan peer.ID)
	go func() {
		defer close(out)
145
		providers := nc.routing.FindProvidersAsync(ctx, k, max)
146 147 148 149 150 151 152 153
		for info := range providers {
			select {
			case <-ctx.Done():
			case out <- info.ID:
			}
		}
	}()
	return out
154 155
}

156 157 158 159
func (nc *networkClient) ConnectionManager() ifconnmgr.ConnManager {
	return &ifconnmgr.NullConnMgr{}
}

Jeromy's avatar
Jeromy committed
160
type messagePasser struct {
161
	net    *networkClient
Jeromy's avatar
Jeromy committed
162 163 164 165 166
	target peer.ID
	local  peer.ID
	ctx    context.Context
}

167
func (mp *messagePasser) SendMsg(ctx context.Context, m bsmsg.BitSwapMessage) error {
168
	return mp.net.SendMessage(ctx, mp.target, m)
Jeromy's avatar
Jeromy committed
169 170 171 172 173 174
}

func (mp *messagePasser) Close() error {
	return nil
}

175 176 177 178
func (mp *messagePasser) Reset() error {
	return nil
}

Jeromy's avatar
Jeromy committed
179 180
func (n *networkClient) NewMessageSender(ctx context.Context, p peer.ID) (bsnet.MessageSender, error) {
	return &messagePasser{
181
		net:    n,
Jeromy's avatar
Jeromy committed
182 183 184 185 186 187
		target: p,
		local:  n.local,
		ctx:    ctx,
	}, nil
}

188
// Provide provides the key to the network
189
func (nc *networkClient) Provide(ctx context.Context, k cid.Cid) error {
190
	return nc.routing.Provide(ctx, k, true)
191 192
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
193 194 195
func (nc *networkClient) SetDelegate(r bsnet.Receiver) {
	nc.Receiver = r
}
196 197

func (nc *networkClient) ConnectTo(_ context.Context, p peer.ID) error {
Steven Allen's avatar
Steven Allen committed
198 199 200 201 202
	nc.network.mu.Lock()

	otherClient, ok := nc.network.clients[p]
	if !ok {
		nc.network.mu.Unlock()
203 204
		return errors.New("no such peer in network")
	}
Steven Allen's avatar
Steven Allen committed
205

206 207
	tag := tagForPeers(nc.local, p)
	if _, ok := nc.network.conns[tag]; ok {
Steven Allen's avatar
Steven Allen committed
208
		nc.network.mu.Unlock()
209 210 211 212
		log.Warning("ALREADY CONNECTED TO PEER (is this a reconnect? test lib needs fixing)")
		return nil
	}
	nc.network.conns[tag] = struct{}{}
Steven Allen's avatar
Steven Allen committed
213 214
	nc.network.mu.Unlock()

215 216
	// TODO: add handling for disconnects

217
	otherClient.receiver.PeerConnected(nc.local)
218 219 220
	nc.Receiver.PeerConnected(p)
	return nil
}
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
func (rq *receiverQueue) enqueue(m *message) {
	rq.lk.Lock()
	defer rq.lk.Unlock()
	rq.queue = append(rq.queue, m)
	if !rq.active {
		rq.active = true
		go rq.process()
	}
}

func (rq *receiverQueue) process() {
	for {
		rq.lk.Lock()
		if len(rq.queue) == 0 {
			rq.active = false
			rq.lk.Unlock()
			return
		}
		m := rq.queue[0]
		rq.queue = rq.queue[1:]
		rq.lk.Unlock()

		time.Sleep(time.Until(m.shouldSend))
245
		atomic.AddUint64(&rq.receiver.stats.MessagesRecvd, 1)
246 247 248 249
		rq.receiver.ReceiveMessage(context.TODO(), m.from, m.msg)
	}
}

250 251 252 253 254 255
func tagForPeers(a, b peer.ID) string {
	if a < b {
		return string(a + b)
	}
	return string(b + a)
}