session_test.go 13.3 KB
Newer Older
hannahhoward's avatar
hannahhoward committed
1 2 3 4 5 6 7 8
package session

import (
	"context"
	"sync"
	"testing"
	"time"

9
	notifications "github.com/ipfs/go-bitswap/notifications"
10
	bssd "github.com/ipfs/go-bitswap/sessiondata"
hannahhoward's avatar
hannahhoward committed
11
	"github.com/ipfs/go-bitswap/testutil"
12
	blocks "github.com/ipfs/go-block-format"
hannahhoward's avatar
hannahhoward committed
13 14
	cid "github.com/ipfs/go-cid"
	blocksutil "github.com/ipfs/go-ipfs-blocksutil"
15
	delay "github.com/ipfs/go-ipfs-delay"
Raúl Kripalani's avatar
Raúl Kripalani committed
16
	peer "github.com/libp2p/go-libp2p-core/peer"
hannahhoward's avatar
hannahhoward committed
17 18 19
)

type wantReq struct {
20 21
	cids  []cid.Cid
	peers []peer.ID
hannahhoward's avatar
hannahhoward committed
22 23 24
}

type fakeWantManager struct {
25 26
	wantReqs   chan wantReq
	cancelReqs chan wantReq
hannahhoward's avatar
hannahhoward committed
27 28 29
}

func (fwm *fakeWantManager) WantBlocks(ctx context.Context, cids []cid.Cid, peers []peer.ID, ses uint64) {
30 31 32 33
	select {
	case fwm.wantReqs <- wantReq{cids, peers}:
	case <-ctx.Done():
	}
hannahhoward's avatar
hannahhoward committed
34 35 36
}

func (fwm *fakeWantManager) CancelWants(ctx context.Context, cids []cid.Cid, peers []peer.ID, ses uint64) {
37 38 39 40
	select {
	case fwm.cancelReqs <- wantReq{cids, peers}:
	case <-ctx.Done():
	}
hannahhoward's avatar
hannahhoward committed
41 42 43
}

type fakePeerManager struct {
44
	lk                     sync.RWMutex
hannahhoward's avatar
hannahhoward committed
45
	peers                  []peer.ID
46
	findMorePeersRequested chan cid.Cid
hannahhoward's avatar
hannahhoward committed
47 48
}

49 50
func (fpm *fakePeerManager) FindMorePeers(ctx context.Context, k cid.Cid) {
	select {
51
	case fpm.findMorePeersRequested <- k:
52 53
	case <-ctx.Done():
	}
hannahhoward's avatar
hannahhoward committed
54 55
}

56
func (fpm *fakePeerManager) GetOptimizedPeers() []bssd.OptimizedPeer {
57 58
	fpm.lk.Lock()
	defer fpm.lk.Unlock()
59 60 61 62 63
	optimizedPeers := make([]bssd.OptimizedPeer, 0, len(fpm.peers))
	for _, peer := range fpm.peers {
		optimizedPeers = append(optimizedPeers, bssd.OptimizedPeer{Peer: peer, OptimizationRating: 1.0})
	}
	return optimizedPeers
hannahhoward's avatar
hannahhoward committed
64 65 66
}

func (fpm *fakePeerManager) RecordPeerRequests([]peer.ID, []cid.Cid) {}
67
func (fpm *fakePeerManager) RecordPeerResponse(p peer.ID, c []cid.Cid) {
68
	fpm.lk.Lock()
hannahhoward's avatar
hannahhoward committed
69
	fpm.peers = append(fpm.peers, p)
70
	fpm.lk.Unlock()
hannahhoward's avatar
hannahhoward committed
71
}
72
func (fpm *fakePeerManager) RecordCancels(c []cid.Cid) {}
hannahhoward's avatar
hannahhoward committed
73

74 75 76
type fakeRequestSplitter struct {
}

77 78 79 80 81 82
func (frs *fakeRequestSplitter) SplitRequest(optimizedPeers []bssd.OptimizedPeer, keys []cid.Cid) []bssd.PartialRequest {
	peers := make([]peer.ID, len(optimizedPeers))
	for i, optimizedPeer := range optimizedPeers {
		peers[i] = optimizedPeer.Peer
	}
	return []bssd.PartialRequest{bssd.PartialRequest{Peers: peers, Keys: keys}}
83 84 85 86 87
}

func (frs *fakeRequestSplitter) RecordDuplicateBlock() {}
func (frs *fakeRequestSplitter) RecordUniqueBlock()    {}

hannahhoward's avatar
hannahhoward committed
88 89 90
func TestSessionGetBlocks(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
	defer cancel()
91 92 93
	wantReqs := make(chan wantReq, 1)
	cancelReqs := make(chan wantReq, 1)
	fwm := &fakeWantManager{wantReqs, cancelReqs}
hannahhoward's avatar
hannahhoward committed
94
	fpm := &fakePeerManager{}
95
	frs := &fakeRequestSplitter{}
96 97
	notif := notifications.New()
	defer notif.Shutdown()
hannahhoward's avatar
hannahhoward committed
98
	id := testutil.GenerateSessionID()
99
	session := New(ctx, id, fwm, fpm, frs, notif, time.Second, delay.Fixed(time.Minute))
hannahhoward's avatar
hannahhoward committed
100
	blockGenerator := blocksutil.NewBlockGenerator()
101
	blks := blockGenerator.Blocks(broadcastLiveWantsLimit * 2)
hannahhoward's avatar
hannahhoward committed
102 103 104 105 106
	var cids []cid.Cid
	for _, block := range blks {
		cids = append(cids, block.Cid())
	}
	getBlocksCh, err := session.GetBlocks(ctx, cids)
107

hannahhoward's avatar
hannahhoward committed
108 109 110 111 112
	if err != nil {
		t.Fatal("error getting blocks")
	}

	// check initial want request
113 114
	receivedWantReq := <-fwm.wantReqs

115
	if len(receivedWantReq.cids) != broadcastLiveWantsLimit {
hannahhoward's avatar
hannahhoward committed
116 117 118 119 120
		t.Fatal("did not enqueue correct initial number of wants")
	}
	if receivedWantReq.peers != nil {
		t.Fatal("first want request should be a broadcast")
	}
121 122 123 124 125 126 127 128
	for _, c := range cids {
		if !session.IsWanted(c) {
			t.Fatal("expected session to want cids")
		}
		if !session.InterestedIn(c) {
			t.Fatal("expected session to be interested in cids")
		}
	}
hannahhoward's avatar
hannahhoward committed
129 130

	// now receive the first set of blocks
131
	peers := testutil.GeneratePeers(broadcastLiveWantsLimit)
132 133 134
	var newCancelReqs []wantReq
	var newBlockReqs []wantReq
	var receivedBlocks []blocks.Block
hannahhoward's avatar
hannahhoward committed
135
	for i, p := range peers {
136
		// simulate what bitswap does on receiving a message:
137
		// - calls ReceiveFrom() on session
138 139
		// - publishes block to pubsub channel
		blk := blks[testutil.IndexOf(blks, receivedWantReq.cids[i])]
140
		session.ReceiveFrom(p, []cid.Cid{blk.Cid()})
141 142
		notif.Publish(blk)

143 144 145 146 147 148 149 150 151 152 153 154 155 156
		select {
		case cancelBlock := <-cancelReqs:
			newCancelReqs = append(newCancelReqs, cancelBlock)
		case <-ctx.Done():
			t.Fatal("did not cancel block want")
		}

		select {
		case receivedBlock := <-getBlocksCh:
			receivedBlocks = append(receivedBlocks, receivedBlock)
		case <-ctx.Done():
			t.Fatal("Did not receive block!")
		}

157 158 159 160 161
		select {
		case wantBlock := <-wantReqs:
			newBlockReqs = append(newBlockReqs, wantBlock)
		default:
		}
hannahhoward's avatar
hannahhoward committed
162 163 164
	}

	// verify new peers were recorded
165
	fpm.lk.Lock()
166
	if len(fpm.peers) != broadcastLiveWantsLimit {
hannahhoward's avatar
hannahhoward committed
167 168 169 170 171 172 173
		t.Fatal("received blocks not recorded by the peer manager")
	}
	for _, p := range fpm.peers {
		if !testutil.ContainsPeer(peers, p) {
			t.Fatal("incorrect peer recorded to peer manager")
		}
	}
174
	fpm.lk.Unlock()
hannahhoward's avatar
hannahhoward committed
175 176 177 178

	// look at new interactions with want manager

	// should have cancelled each received block
179
	if len(newCancelReqs) != broadcastLiveWantsLimit {
hannahhoward's avatar
hannahhoward committed
180 181 182
		t.Fatal("did not cancel each block once it was received")
	}
	// new session reqs should be targeted
183
	var newCidsRequested []cid.Cid
hannahhoward's avatar
hannahhoward committed
184 185 186 187
	for _, w := range newBlockReqs {
		if len(w.peers) == 0 {
			t.Fatal("should not have broadcast again after initial broadcast")
		}
188
		newCidsRequested = append(newCidsRequested, w.cids...)
hannahhoward's avatar
hannahhoward committed
189 190 191
	}

	// full new round of cids should be requested
192
	if len(newCidsRequested) != broadcastLiveWantsLimit {
hannahhoward's avatar
hannahhoward committed
193 194 195 196 197
		t.Fatal("new blocks were not requested")
	}

	// receive remaining blocks
	for i, p := range peers {
198
		// simulate what bitswap does on receiving a message:
199
		// - calls ReceiveFrom() on session
200 201
		// - publishes block to pubsub channel
		blk := blks[testutil.IndexOf(blks, newCidsRequested[i])]
202
		session.ReceiveFrom(p, []cid.Cid{blk.Cid()})
203 204
		notif.Publish(blk)

205 206 207 208
		receivedBlock := <-getBlocksCh
		receivedBlocks = append(receivedBlocks, receivedBlock)
		cancelBlock := <-cancelReqs
		newCancelReqs = append(newCancelReqs, cancelBlock)
hannahhoward's avatar
hannahhoward committed
209 210 211 212 213
	}

	if len(receivedBlocks) != len(blks) {
		t.Fatal("did not receive enough blocks")
	}
Steven Allen's avatar
Steven Allen committed
214 215 216
	if len(newCancelReqs) != len(receivedBlocks) {
		t.Fatal("expected an equal number of received blocks and cancels")
	}
hannahhoward's avatar
hannahhoward committed
217 218 219 220 221
	for _, block := range receivedBlocks {
		if !testutil.ContainsBlock(blks, block) {
			t.Fatal("received incorrect block")
		}
	}
222 223 224 225 226 227 228 229
	for _, c := range cids {
		if session.IsWanted(c) {
			t.Fatal("expected session NOT to want cids")
		}
		if !session.InterestedIn(c) {
			t.Fatal("expected session to still be interested in cids")
		}
	}
hannahhoward's avatar
hannahhoward committed
230 231 232 233
}

func TestSessionFindMorePeers(t *testing.T) {

234
	ctx, cancel := context.WithTimeout(context.Background(), 900*time.Millisecond)
hannahhoward's avatar
hannahhoward committed
235
	defer cancel()
236 237 238
	wantReqs := make(chan wantReq, 1)
	cancelReqs := make(chan wantReq, 1)
	fwm := &fakeWantManager{wantReqs, cancelReqs}
239
	fpm := &fakePeerManager{findMorePeersRequested: make(chan cid.Cid, 1)}
240
	frs := &fakeRequestSplitter{}
241 242
	notif := notifications.New()
	defer notif.Shutdown()
hannahhoward's avatar
hannahhoward committed
243
	id := testutil.GenerateSessionID()
244
	session := New(ctx, id, fwm, fpm, frs, notif, time.Second, delay.Fixed(time.Minute))
245
	session.SetBaseTickDelay(200 * time.Microsecond)
hannahhoward's avatar
hannahhoward committed
246
	blockGenerator := blocksutil.NewBlockGenerator()
247
	blks := blockGenerator.Blocks(broadcastLiveWantsLimit * 2)
hannahhoward's avatar
hannahhoward committed
248 249 250 251 252 253 254 255 256
	var cids []cid.Cid
	for _, block := range blks {
		cids = append(cids, block.Cid())
	}
	getBlocksCh, err := session.GetBlocks(ctx, cids)
	if err != nil {
		t.Fatal("error getting blocks")
	}

257
	// clear the initial block of wants
258 259 260 261 262
	select {
	case <-wantReqs:
	case <-ctx.Done():
		t.Fatal("Did not make first want request ")
	}
263

hannahhoward's avatar
hannahhoward committed
264
	// receive a block to trigger a tick reset
265 266 267
	time.Sleep(20 * time.Millisecond) // need to make sure some latency registers
	// or there will be no tick set -- time precision on Windows in go is in the
	// millisecond range
hannahhoward's avatar
hannahhoward committed
268
	p := testutil.GeneratePeers(1)[0]
269 270

	// simulate what bitswap does on receiving a message:
271
	// - calls ReceiveFrom() on session
272 273
	// - publishes block to pubsub channel
	blk := blks[0]
274
	session.ReceiveFrom(p, []cid.Cid{blk.Cid()})
275
	notif.Publish(blk)
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
	select {
	case <-cancelReqs:
	case <-ctx.Done():
		t.Fatal("Did not cancel block")
	}
	select {
	case <-getBlocksCh:
	case <-ctx.Done():
		t.Fatal("Did not get block")
	}
	select {
	case <-wantReqs:
	case <-ctx.Done():
		t.Fatal("Did not make second want request ")
	}
hannahhoward's avatar
hannahhoward committed
291 292

	// verify a broadcast was made
293 294 295 296 297 298 299 300 301 302
	select {
	case receivedWantReq := <-wantReqs:
		if len(receivedWantReq.cids) < broadcastLiveWantsLimit {
			t.Fatal("did not rebroadcast whole live list")
		}
		if receivedWantReq.peers != nil {
			t.Fatal("did not make a broadcast")
		}
	case <-ctx.Done():
		t.Fatal("Never rebroadcast want list")
hannahhoward's avatar
hannahhoward committed
303
	}
304 305 306 307 308 309

	// wait for a request to get more peers to occur
	select {
	case <-fpm.findMorePeersRequested:
	case <-ctx.Done():
		t.Fatal("Did not find more peers")
hannahhoward's avatar
hannahhoward committed
310 311
	}
}
312 313

func TestSessionFailingToGetFirstBlock(t *testing.T) {
314
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
315 316 317 318 319 320
	defer cancel()
	wantReqs := make(chan wantReq, 1)
	cancelReqs := make(chan wantReq, 1)
	fwm := &fakeWantManager{wantReqs, cancelReqs}
	fpm := &fakePeerManager{findMorePeersRequested: make(chan cid.Cid, 1)}
	frs := &fakeRequestSplitter{}
321 322
	notif := notifications.New()
	defer notif.Shutdown()
323
	id := testutil.GenerateSessionID()
324

325
	session := New(ctx, id, fwm, fpm, frs, notif, 10*time.Millisecond, delay.Fixed(100*time.Millisecond))
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	blockGenerator := blocksutil.NewBlockGenerator()
	blks := blockGenerator.Blocks(4)
	var cids []cid.Cid
	for _, block := range blks {
		cids = append(cids, block.Cid())
	}
	startTick := time.Now()
	_, err := session.GetBlocks(ctx, cids)
	if err != nil {
		t.Fatal("error getting blocks")
	}

	// clear the initial block of wants
	select {
	case <-wantReqs:
	case <-ctx.Done():
		t.Fatal("Did not make first want request ")
	}

	// verify a broadcast is made
	select {
	case receivedWantReq := <-wantReqs:
		if len(receivedWantReq.cids) < len(cids) {
			t.Fatal("did not rebroadcast whole live list")
		}
		if receivedWantReq.peers != nil {
			t.Fatal("did not make a broadcast")
		}
	case <-ctx.Done():
		t.Fatal("Never rebroadcast want list")
	}

	// wait for a request to get more peers to occur
	select {
	case k := <-fpm.findMorePeersRequested:
		if testutil.IndexOf(blks, k) == -1 {
			t.Fatal("did not rebroadcast an active want")
		}
	case <-ctx.Done():
		t.Fatal("Did not find more peers")
	}
	firstTickLength := time.Since(startTick)

	// wait for another broadcast to occur
	select {
	case receivedWantReq := <-wantReqs:
		if len(receivedWantReq.cids) < len(cids) {
			t.Fatal("did not rebroadcast whole live list")
		}
		if receivedWantReq.peers != nil {
			t.Fatal("did not make a broadcast")
		}
	case <-ctx.Done():
		t.Fatal("Never rebroadcast want list")
	}
	startTick = time.Now()
	// wait for another broadcast to occur
	select {
	case receivedWantReq := <-wantReqs:
		if len(receivedWantReq.cids) < len(cids) {
			t.Fatal("did not rebroadcast whole live list")
		}
		if receivedWantReq.peers != nil {
			t.Fatal("did not make a broadcast")
		}
	case <-ctx.Done():
		t.Fatal("Never rebroadcast want list")
	}
	consecutiveTickLength := time.Since(startTick)
	// tick should take longer
	if firstTickLength > consecutiveTickLength {
		t.Fatal("Should have increased tick length after first consecutive tick")
	}
	startTick = time.Now()
	// wait for another broadcast to occur
	select {
	case receivedWantReq := <-wantReqs:
		if len(receivedWantReq.cids) < len(cids) {
			t.Fatal("did not rebroadcast whole live list")
		}
		if receivedWantReq.peers != nil {
			t.Fatal("did not make a broadcast")
		}
	case <-ctx.Done():
		t.Fatal("Never rebroadcast want list")
	}
	secondConsecutiveTickLength := time.Since(startTick)
	// tick should take longer
	if consecutiveTickLength > secondConsecutiveTickLength {
		t.Fatal("Should have increased tick length after first consecutive tick")
	}

	// should not have looked for peers on consecutive ticks
	select {
	case <-fpm.findMorePeersRequested:
		t.Fatal("Should not have looked for peers on consecutive tick")
	default:
	}

	// wait for rebroadcast to occur
	select {
	case k := <-fpm.findMorePeersRequested:
		if testutil.IndexOf(blks, k) == -1 {
			t.Fatal("did not rebroadcast an active want")
		}
	case <-ctx.Done():
		t.Fatal("Did not rebroadcast to find more peers")
	}
}
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

func TestSessionCtxCancelClosesGetBlocksChannel(t *testing.T) {
	wantReqs := make(chan wantReq, 1)
	cancelReqs := make(chan wantReq, 1)
	fwm := &fakeWantManager{wantReqs, cancelReqs}
	fpm := &fakePeerManager{}
	frs := &fakeRequestSplitter{}
	notif := notifications.New()
	defer notif.Shutdown()
	id := testutil.GenerateSessionID()

	// Create a new session with its own context
	sessctx, sesscancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	session := New(sessctx, id, fwm, fpm, frs, notif, time.Second, delay.Fixed(time.Minute))

	timerCtx, timerCancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
	defer timerCancel()

	// Request a block with a new context
	blockGenerator := blocksutil.NewBlockGenerator()
	blks := blockGenerator.Blocks(1)
	getctx, getcancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer getcancel()

	getBlocksCh, err := session.GetBlocks(getctx, []cid.Cid{blks[0].Cid()})
	if err != nil {
		t.Fatal("error getting blocks")
	}

	// Cancel the session context
	sesscancel()

	// Expect the GetBlocks() channel to be closed
	select {
	case _, ok := <-getBlocksCh:
		if ok {
			t.Fatal("expected channel to be closed but was not closed")
		}
	case <-timerCtx.Done():
		t.Fatal("expected channel to be closed before timeout")
	}
}