session_test.go 13.1 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
	for _, c := range cids {
		if !session.IsWanted(c) {
			t.Fatal("expected session to want cids")
		}
	}
hannahhoward's avatar
hannahhoward committed
126 127

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

140 141 142 143 144 145 146 147 148 149 150 151 152 153
		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!")
		}

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

	// verify new peers were recorded
162
	fpm.lk.Lock()
163
	if len(fpm.peers) != broadcastLiveWantsLimit {
hannahhoward's avatar
hannahhoward committed
164 165 166 167 168 169 170
		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")
		}
	}
171
	fpm.lk.Unlock()
hannahhoward's avatar
hannahhoward committed
172 173 174 175

	// look at new interactions with want manager

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

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

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

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

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

func TestSessionFindMorePeers(t *testing.T) {

228
	ctx, cancel := context.WithTimeout(context.Background(), 900*time.Millisecond)
hannahhoward's avatar
hannahhoward committed
229
	defer cancel()
230 231 232
	wantReqs := make(chan wantReq, 1)
	cancelReqs := make(chan wantReq, 1)
	fwm := &fakeWantManager{wantReqs, cancelReqs}
233
	fpm := &fakePeerManager{findMorePeersRequested: make(chan cid.Cid, 1)}
234
	frs := &fakeRequestSplitter{}
235 236
	notif := notifications.New()
	defer notif.Shutdown()
hannahhoward's avatar
hannahhoward committed
237
	id := testutil.GenerateSessionID()
238
	session := New(ctx, id, fwm, fpm, frs, notif, time.Second, delay.Fixed(time.Minute))
239
	session.SetBaseTickDelay(200 * time.Microsecond)
hannahhoward's avatar
hannahhoward committed
240
	blockGenerator := blocksutil.NewBlockGenerator()
241
	blks := blockGenerator.Blocks(broadcastLiveWantsLimit * 2)
hannahhoward's avatar
hannahhoward committed
242 243 244 245 246 247 248 249 250
	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")
	}

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

hannahhoward's avatar
hannahhoward committed
258
	// receive a block to trigger a tick reset
259 260 261
	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
262
	p := testutil.GeneratePeers(1)[0]
263 264

	// simulate what bitswap does on receiving a message:
265
	// - calls ReceiveFrom() on session
266 267
	// - publishes block to pubsub channel
	blk := blks[0]
268
	session.ReceiveFrom(p, []cid.Cid{blk.Cid()})
269
	notif.Publish(blk)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
	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
285 286

	// verify a broadcast was made
287 288 289 290 291 292 293 294 295 296
	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
297
	}
298 299 300 301 302 303

	// 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
304 305
	}
}
306 307

func TestSessionFailingToGetFirstBlock(t *testing.T) {
308
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
309 310 311 312 313 314
	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{}
315 316
	notif := notifications.New()
	defer notif.Shutdown()
317
	id := testutil.GenerateSessionID()
318

319
	session := New(ctx, id, fwm, fpm, frs, notif, 10*time.Millisecond, delay.Fixed(100*time.Millisecond))
320 321 322 323 324 325 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
	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")
	}
}
429 430 431 432 433 434 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

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")
	}
}