requestmanager_test.go 27.2 KB
Newer Older
1 2 3 4
package requestmanager

import (
	"context"
5
	"errors"
6 7
	"fmt"
	"sync"
8 9 10
	"testing"
	"time"

11
	"github.com/ipfs/go-graphsync"
Hannah Howard's avatar
Hannah Howard committed
12
	"github.com/ipfs/go-graphsync/requestmanager/hooks"
13
	"github.com/ipfs/go-graphsync/requestmanager/types"
14
	"github.com/libp2p/go-libp2p-core/peer"
Hannah Howard's avatar
Hannah Howard committed
15
	"github.com/stretchr/testify/require"
16 17 18

	"github.com/ipfs/go-graphsync/metadata"

19
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
20 21 22

	"github.com/ipld/go-ipld-prime"

23 24 25 26 27 28
	blocks "github.com/ipfs/go-block-format"
	gsmsg "github.com/ipfs/go-graphsync/message"
	"github.com/ipfs/go-graphsync/testutil"
)

type requestRecord struct {
29 30
	gsr gsmsg.GraphSyncRequest
	p   peer.ID
31
}
32

33 34 35 36
type fakePeerHandler struct {
	requestRecordChan chan requestRecord
}

37 38
func (fph *fakePeerHandler) SendRequest(p peer.ID,
	graphSyncRequest gsmsg.GraphSyncRequest) {
39
	fph.requestRecordChan <- requestRecord{
40 41
		gsr: graphSyncRequest,
		p:   p,
42 43 44
	}
}

45
type requestKey struct {
46
	requestID graphsync.RequestID
47 48 49
	link      ipld.Link
}

50 51 52 53 54
type storeKey struct {
	requestID graphsync.RequestID
	storeName string
}

55 56 57
type fakeAsyncLoader struct {
	responseChannelsLk sync.RWMutex
	responseChannels   map[requestKey]chan types.AsyncLoadResult
58
	responses          chan map[graphsync.RequestID]metadata.Metadata
59
	blks               chan []blocks.Block
60 61
	storesRequestedLk  sync.RWMutex
	storesRequested    map[storeKey]struct{}
62 63 64 65 66
}

func newFakeAsyncLoader() *fakeAsyncLoader {
	return &fakeAsyncLoader{
		responseChannels: make(map[requestKey]chan types.AsyncLoadResult),
67
		responses:        make(chan map[graphsync.RequestID]metadata.Metadata, 1),
68
		blks:             make(chan []blocks.Block, 1),
69
		storesRequested:  make(map[storeKey]struct{}),
70 71
	}
}
72 73 74 75 76 77

func (fal *fakeAsyncLoader) StartRequest(requestID graphsync.RequestID, name string) error {
	fal.storesRequestedLk.Lock()
	fal.storesRequested[storeKey{requestID, name}] = struct{}{}
	fal.storesRequestedLk.Unlock()
	return nil
78
}
79

80
func (fal *fakeAsyncLoader) ProcessResponse(responses map[graphsync.RequestID]metadata.Metadata,
81 82 83 84 85
	blks []blocks.Block) {
	fal.responses <- responses
	fal.blks <- blks
}
func (fal *fakeAsyncLoader) verifyLastProcessedBlocks(ctx context.Context, t *testing.T, expectedBlocks []blocks.Block) {
Hannah Howard's avatar
Hannah Howard committed
86 87 88
	var processedBlocks []blocks.Block
	testutil.AssertReceive(ctx, t, fal.blks, &processedBlocks, "did not process blocks")
	require.Equal(t, expectedBlocks, processedBlocks, "did not process correct blocks")
89
}
Hannah Howard's avatar
Hannah Howard committed
90

91
func (fal *fakeAsyncLoader) verifyLastProcessedResponses(ctx context.Context, t *testing.T,
92
	expectedResponses map[graphsync.RequestID]metadata.Metadata) {
Hannah Howard's avatar
Hannah Howard committed
93 94 95
	var responses map[graphsync.RequestID]metadata.Metadata
	testutil.AssertReceive(ctx, t, fal.responses, &responses, "did not process responses")
	require.Equal(t, expectedResponses, responses, "did not process correct responses")
96 97
}

98
func (fal *fakeAsyncLoader) verifyNoRemainingData(t *testing.T, requestID graphsync.RequestID) {
99 100
	fal.responseChannelsLk.Lock()
	for key := range fal.responseChannels {
Hannah Howard's avatar
Hannah Howard committed
101
		require.NotEqual(t, key.requestID, requestID, "did not clean up request properly")
102 103 104 105
	}
	fal.responseChannelsLk.Unlock()
}

106 107 108 109 110 111 112
func (fal *fakeAsyncLoader) verifyStoreUsed(t *testing.T, requestID graphsync.RequestID, storeName string) {
	fal.storesRequestedLk.RLock()
	_, ok := fal.storesRequested[storeKey{requestID, storeName}]
	require.True(t, ok, "request should load from correct store")
	fal.storesRequestedLk.RUnlock()
}

113
func (fal *fakeAsyncLoader) asyncLoad(requestID graphsync.RequestID, link ipld.Link) chan types.AsyncLoadResult {
114 115 116 117 118 119 120 121 122 123
	fal.responseChannelsLk.Lock()
	responseChannel, ok := fal.responseChannels[requestKey{requestID, link}]
	if !ok {
		responseChannel = make(chan types.AsyncLoadResult, 1)
		fal.responseChannels[requestKey{requestID, link}] = responseChannel
	}
	fal.responseChannelsLk.Unlock()
	return responseChannel
}

124
func (fal *fakeAsyncLoader) AsyncLoad(requestID graphsync.RequestID, link ipld.Link) <-chan types.AsyncLoadResult {
125 126
	return fal.asyncLoad(requestID, link)
}
127 128
func (fal *fakeAsyncLoader) CompleteResponsesFor(requestID graphsync.RequestID) {}
func (fal *fakeAsyncLoader) CleanupRequest(requestID graphsync.RequestID) {
129 130 131 132 133 134 135 136 137
	fal.responseChannelsLk.Lock()
	for key := range fal.responseChannels {
		if key.requestID == requestID {
			delete(fal.responseChannels, key)
		}
	}
	fal.responseChannelsLk.Unlock()
}

138
func (fal *fakeAsyncLoader) responseOn(requestID graphsync.RequestID, link ipld.Link, result types.AsyncLoadResult) {
139 140 141 142 143
	responseChannel := fal.asyncLoad(requestID, link)
	responseChannel <- result
	close(responseChannel)
}

144
func (fal *fakeAsyncLoader) successResponseOn(requestID graphsync.RequestID, blks []blocks.Block) {
145 146 147 148 149
	for _, block := range blks {
		fal.responseOn(requestID, cidlink.Link{Cid: block.Cid()}, types.AsyncLoadResult{Data: block.RawData(), Err: nil})
	}
}

150 151 152 153 154 155
func readNNetworkRequests(ctx context.Context,
	t *testing.T,
	requestRecordChan <-chan requestRecord,
	count int) []requestRecord {
	requestRecords := make([]requestRecord, 0, count)
	for i := 0; i < count; i++ {
Hannah Howard's avatar
Hannah Howard committed
156 157 158
		var rr requestRecord
		testutil.AssertReceive(ctx, t, requestRecordChan, &rr, fmt.Sprintf("did not receive request %d", i))
		requestRecords = append(requestRecords, rr)
159 160 161 162
	}
	return requestRecords
}

163 164 165 166 167 168 169 170 171 172 173
func metadataForBlocks(blks []blocks.Block, present bool) metadata.Metadata {
	md := make(metadata.Metadata, 0, len(blks))
	for _, block := range blks {
		md = append(md, metadata.Item{
			Link:         cidlink.Link{Cid: block.Cid()},
			BlockPresent: present,
		})
	}
	return md
}

174
func encodedMetadataForBlocks(t *testing.T, blks []blocks.Block, present bool) graphsync.ExtensionData {
175
	md := metadataForBlocks(blks, present)
176
	metadataEncoded, err := metadata.EncodeMetadata(md)
Hannah Howard's avatar
Hannah Howard committed
177
	require.NoError(t, err, "did not encode metadata")
178 179
	return graphsync.ExtensionData{
		Name: graphsync.ExtensionMetadata,
180 181
		Data: metadataEncoded,
	}
182 183
}

184 185 186 187
func TestNormalSimultaneousFetch(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
188
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
189 190 191
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
192 193 194 195 196
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
197
	peers := testutil.GeneratePeers(1)
198

199
	blockStore := make(map[ipld.Link][]byte)
200
	loader, storer := testutil.NewTestStore(blockStore)
201 202
	blockChain1 := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
	blockChain2 := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
203

204 205
	returnedResponseChan1, returnedErrorChan1 := requestManager.SendRequest(requestCtx, peers[0], blockChain1.TipLink, blockChain1.Selector())
	returnedResponseChan2, returnedErrorChan2 := requestManager.SendRequest(requestCtx, peers[0], blockChain2.TipLink, blockChain2.Selector())
206

207
	requestRecords := readNNetworkRequests(requestCtx, t, requestRecordChan, 2)
208

Hannah Howard's avatar
Hannah Howard committed
209 210 211 212
	require.Equal(t, peers[0], requestRecords[0].p)
	require.Equal(t, peers[0], requestRecords[1].p)
	require.False(t, requestRecords[0].gsr.IsCancel())
	require.False(t, requestRecords[1].gsr.IsCancel())
213 214
	require.Equal(t, defaultPriority, requestRecords[0].gsr.Priority())
	require.Equal(t, defaultPriority, requestRecords[1].gsr.Priority())
215

Hannah Howard's avatar
Hannah Howard committed
216 217
	require.Equal(t, blockChain1.Selector(), requestRecords[0].gsr.Selector(), "did not encode selector properly")
	require.Equal(t, blockChain2.Selector(), requestRecords[1].gsr.Selector(), "did not encode selector properly")
218

219 220
	firstBlocks := append(blockChain1.AllBlocks(), blockChain2.Blocks(0, 3)...)
	firstMetadata1 := metadataForBlocks(blockChain1.AllBlocks(), true)
221
	firstMetadataEncoded1, err := metadata.EncodeMetadata(firstMetadata1)
Hannah Howard's avatar
Hannah Howard committed
222
	require.NoError(t, err, "did not encode metadata")
223
	firstMetadata2 := metadataForBlocks(blockChain2.Blocks(0, 3), true)
224
	firstMetadataEncoded2, err := metadata.EncodeMetadata(firstMetadata2)
Hannah Howard's avatar
Hannah Howard committed
225
	require.NoError(t, err, "did not encode metadata")
226
	firstResponses := []gsmsg.GraphSyncResponse{
227 228
		gsmsg.NewResponse(requestRecords[0].gsr.ID(), graphsync.RequestCompletedFull, graphsync.ExtensionData{
			Name: graphsync.ExtensionMetadata,
229 230
			Data: firstMetadataEncoded1,
		}),
231 232
		gsmsg.NewResponse(requestRecords[1].gsr.ID(), graphsync.PartialResponse, graphsync.ExtensionData{
			Name: graphsync.ExtensionMetadata,
233 234
			Data: firstMetadataEncoded2,
		}),
235 236
	}

237 238
	requestManager.ProcessResponses(peers[0], firstResponses, firstBlocks)
	fal.verifyLastProcessedBlocks(ctx, t, firstBlocks)
239
	fal.verifyLastProcessedResponses(ctx, t, map[graphsync.RequestID]metadata.Metadata{
240 241 242
		requestRecords[0].gsr.ID(): firstMetadata1,
		requestRecords[1].gsr.ID(): firstMetadata2,
	})
243 244
	fal.successResponseOn(requestRecords[0].gsr.ID(), blockChain1.AllBlocks())
	fal.successResponseOn(requestRecords[1].gsr.ID(), blockChain2.Blocks(0, 3))
245

246 247
	blockChain1.VerifyWholeChain(requestCtx, returnedResponseChan1)
	blockChain2.VerifyResponseRange(requestCtx, returnedResponseChan2, 0, 3)
248

249
	moreBlocks := blockChain2.RemainderBlocks(3)
250
	moreMetadata := metadataForBlocks(moreBlocks, true)
251
	moreMetadataEncoded, err := metadata.EncodeMetadata(moreMetadata)
Hannah Howard's avatar
Hannah Howard committed
252
	require.NoError(t, err, "did not encode metadata")
253
	moreResponses := []gsmsg.GraphSyncResponse{
254 255
		gsmsg.NewResponse(requestRecords[1].gsr.ID(), graphsync.RequestCompletedFull, graphsync.ExtensionData{
			Name: graphsync.ExtensionMetadata,
256 257
			Data: moreMetadataEncoded,
		}),
258 259
	}

260 261
	requestManager.ProcessResponses(peers[0], moreResponses, moreBlocks)
	fal.verifyLastProcessedBlocks(ctx, t, moreBlocks)
262
	fal.verifyLastProcessedResponses(ctx, t, map[graphsync.RequestID]metadata.Metadata{
263 264
		requestRecords[1].gsr.ID(): moreMetadata,
	})
265

266 267
	fal.successResponseOn(requestRecords[1].gsr.ID(), moreBlocks)

268
	blockChain2.VerifyRemainder(requestCtx, returnedResponseChan2, 3)
269 270
	testutil.VerifyEmptyErrors(requestCtx, t, returnedErrorChan1)
	testutil.VerifyEmptyErrors(requestCtx, t, returnedErrorChan2)
271 272 273 274 275 276
}

func TestCancelRequestInProgress(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
277
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
278 279 280
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
281 282 283 284 285 286 287
	requestManager.SetDelegate(fph)
	requestManager.Startup()
	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	requestCtx1, cancel1 := context.WithCancel(requestCtx)
	requestCtx2, cancel2 := context.WithCancel(requestCtx)
	defer cancel2()
288
	peers := testutil.GeneratePeers(1)
289

290
	blockStore := make(map[ipld.Link][]byte)
291
	loader, storer := testutil.NewTestStore(blockStore)
292
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
293

294 295
	returnedResponseChan1, returnedErrorChan1 := requestManager.SendRequest(requestCtx1, peers[0], blockChain.TipLink, blockChain.Selector())
	returnedResponseChan2, returnedErrorChan2 := requestManager.SendRequest(requestCtx2, peers[0], blockChain.TipLink, blockChain.Selector())
296

297
	requestRecords := readNNetworkRequests(requestCtx, t, requestRecordChan, 2)
298

299 300
	firstBlocks := blockChain.Blocks(0, 3)
	firstMetadata := encodedMetadataForBlocks(t, firstBlocks, true)
301
	firstResponses := []gsmsg.GraphSyncResponse{
302 303
		gsmsg.NewResponse(requestRecords[0].gsr.ID(), graphsync.PartialResponse, firstMetadata),
		gsmsg.NewResponse(requestRecords[1].gsr.ID(), graphsync.PartialResponse, firstMetadata),
304 305
	}

306
	requestManager.ProcessResponses(peers[0], firstResponses, firstBlocks)
307

308 309 310
	fal.successResponseOn(requestRecords[0].gsr.ID(), firstBlocks)
	fal.successResponseOn(requestRecords[1].gsr.ID(), firstBlocks)
	blockChain.VerifyResponseRange(requestCtx1, returnedResponseChan1, 0, 3)
311
	cancel1()
312
	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]
Hannah Howard's avatar
Hannah Howard committed
313 314 315

	require.True(t, rr.gsr.IsCancel())
	require.Equal(t, requestRecords[0].gsr.ID(), rr.gsr.ID())
316

317 318
	moreBlocks := blockChain.RemainderBlocks(3)
	moreMetadata := encodedMetadataForBlocks(t, moreBlocks, true)
319
	moreResponses := []gsmsg.GraphSyncResponse{
320 321
		gsmsg.NewResponse(requestRecords[0].gsr.ID(), graphsync.RequestCompletedFull, moreMetadata),
		gsmsg.NewResponse(requestRecords[1].gsr.ID(), graphsync.RequestCompletedFull, moreMetadata),
322
	}
323
	requestManager.ProcessResponses(peers[0], moreResponses, moreBlocks)
324 325
	fal.successResponseOn(requestRecords[0].gsr.ID(), moreBlocks)
	fal.successResponseOn(requestRecords[1].gsr.ID(), moreBlocks)
326

327 328
	testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan1)
	blockChain.VerifyWholeChain(requestCtx, returnedResponseChan2)
329 330
	testutil.VerifyEmptyErrors(requestCtx, t, returnedErrorChan1)
	testutil.VerifyEmptyErrors(requestCtx, t, returnedErrorChan2)
331 332 333 334 335 336 337
}

func TestCancelManagerExitsGracefully(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
	managerCtx, managerCancel := context.WithCancel(ctx)
338
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
339 340 341
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(managerCtx, fal, requestHooks, responseHooks)
342 343 344 345
	requestManager.SetDelegate(fph)
	requestManager.Startup()
	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
346
	peers := testutil.GeneratePeers(1)
347

348
	blockStore := make(map[ipld.Link][]byte)
349
	loader, storer := testutil.NewTestStore(blockStore)
350
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
351

352
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
353

354
	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]
355

356
	firstBlocks := blockChain.Blocks(0, 3)
357
	firstMetadata := encodedMetadataForBlocks(t, firstBlocks, true)
358
	firstResponses := []gsmsg.GraphSyncResponse{
359
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.PartialResponse, firstMetadata),
360
	}
361 362
	requestManager.ProcessResponses(peers[0], firstResponses, firstBlocks)
	fal.successResponseOn(rr.gsr.ID(), firstBlocks)
363
	blockChain.VerifyResponseRange(ctx, returnedResponseChan, 0, 3)
364 365
	managerCancel()

366
	moreBlocks := blockChain.RemainderBlocks(3)
367
	moreMetadata := encodedMetadataForBlocks(t, moreBlocks, true)
368
	moreResponses := []gsmsg.GraphSyncResponse{
369
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestCompletedFull, moreMetadata),
370
	}
371 372
	requestManager.ProcessResponses(peers[0], moreResponses, moreBlocks)
	fal.successResponseOn(rr.gsr.ID(), moreBlocks)
373
	testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan)
374
	testutil.VerifyEmptyErrors(requestCtx, t, returnedErrorChan)
375 376
}

377 378 379 380
func TestFailedRequest(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
381
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
382 383 384
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
385 386 387 388 389
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
390
	peers := testutil.GeneratePeers(1)
391

392
	blockStore := make(map[ipld.Link][]byte)
393
	loader, storer := testutil.NewTestStore(blockStore)
394 395 396
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)

	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
397 398

	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]
399
	failedResponses := []gsmsg.GraphSyncResponse{
400
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestFailedContentNotFound),
401
	}
402
	requestManager.ProcessResponses(peers[0], failedResponses, nil)
403

404 405
	testutil.VerifySingleTerminalError(requestCtx, t, returnedErrorChan)
	testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan)
406 407 408 409 410 411 412
}

func TestLocallyFulfilledFirstRequestFailsLater(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
413 414 415
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
416 417 418 419 420 421 422
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	peers := testutil.GeneratePeers(1)

423
	blockStore := make(map[ipld.Link][]byte)
424
	loader, storer := testutil.NewTestStore(blockStore)
425 426 427
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)

	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
428 429 430 431

	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]

	// async loaded response responds immediately
432
	fal.successResponseOn(rr.gsr.ID(), blockChain.AllBlocks())
433

434
	blockChain.VerifyWholeChain(requestCtx, returnedResponseChan)
435 436 437

	// failure comes in later over network
	failedResponses := []gsmsg.GraphSyncResponse{
438
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestFailedContentNotFound),
439 440 441
	}

	requestManager.ProcessResponses(peers[0], failedResponses, nil)
442
	testutil.VerifyEmptyErrors(ctx, t, returnedErrorChan)
443 444 445 446 447 448 449 450

}

func TestLocallyFulfilledFirstRequestSucceedsLater(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
451 452 453
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
454 455 456 457 458 459 460
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	peers := testutil.GeneratePeers(1)

461
	blockStore := make(map[ipld.Link][]byte)
462
	loader, storer := testutil.NewTestStore(blockStore)
463 464
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
465 466 467 468

	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]

	// async loaded response responds immediately
469
	fal.successResponseOn(rr.gsr.ID(), blockChain.AllBlocks())
470

471
	blockChain.VerifyWholeChain(requestCtx, returnedResponseChan)
472

473
	md := encodedMetadataForBlocks(t, blockChain.AllBlocks(), true)
474
	firstResponses := []gsmsg.GraphSyncResponse{
475
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestCompletedFull, md),
476
	}
477
	requestManager.ProcessResponses(peers[0], firstResponses, blockChain.AllBlocks())
478 479

	fal.verifyNoRemainingData(t, rr.gsr.ID())
480
	testutil.VerifyEmptyErrors(ctx, t, returnedErrorChan)
481 482 483 484 485 486 487
}

func TestRequestReturnsMissingBlocks(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
488 489 490
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
491 492 493 494 495 496 497
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	peers := testutil.GeneratePeers(1)

498
	blockStore := make(map[ipld.Link][]byte)
499
	loader, storer := testutil.NewTestStore(blockStore)
500 501
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
502 503 504

	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]

505
	md := encodedMetadataForBlocks(t, blockChain.AllBlocks(), false)
506
	firstResponses := []gsmsg.GraphSyncResponse{
507
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestCompletedPartial, md),
508 509
	}
	requestManager.ProcessResponses(peers[0], firstResponses, nil)
510
	for _, block := range blockChain.AllBlocks() {
511 512
		fal.responseOn(rr.gsr.ID(), cidlink.Link{Cid: block.Cid()}, types.AsyncLoadResult{Data: nil, Err: fmt.Errorf("Terrible Thing")})
	}
513 514
	testutil.VerifyEmptyResponse(ctx, t, returnedResponseChan)
	errs := testutil.CollectErrors(ctx, t, returnedErrorChan)
Hannah Howard's avatar
Hannah Howard committed
515
	require.NotEqual(t, len(errs), 0, "did not send errors")
516
}
517 518 519 520 521 522

func TestEncodingExtensions(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
523 524 525
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
526 527 528 529 530 531 532
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	peers := testutil.GeneratePeers(1)

533
	blockStore := make(map[ipld.Link][]byte)
534
	loader, storer := testutil.NewTestStore(blockStore)
535
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
536 537 538 539 540 541 542 543 544 545 546 547 548

	extensionData1 := testutil.RandomBytes(100)
	extensionName1 := graphsync.ExtensionName("AppleSauce/McGee")
	extension1 := graphsync.ExtensionData{
		Name: extensionName1,
		Data: extensionData1,
	}
	extensionData2 := testutil.RandomBytes(100)
	extensionName2 := graphsync.ExtensionName("HappyLand/Happenstance")
	extension2 := graphsync.ExtensionData{
		Name: extensionName2,
		Data: extensionData2,
	}
549 550 551

	expectedError := make(chan error, 2)
	receivedExtensionData := make(chan []byte, 2)
Hannah Howard's avatar
Hannah Howard committed
552 553
	expectedUpdateChan := make(chan []graphsync.ExtensionData, 2)
	hook := func(p peer.ID, responseData graphsync.ResponseData, hookActions graphsync.IncomingResponseHookActions) {
554
		data, has := responseData.Extension(extensionName1)
Hannah Howard's avatar
Hannah Howard committed
555
		require.True(t, has, "did not receive extension data in response")
556
		receivedExtensionData <- data
Hannah Howard's avatar
Hannah Howard committed
557 558 559 560 561 562 563 564
		err := <-expectedError
		if err != nil {
			hookActions.TerminateWithError(err)
		}
		update := <-expectedUpdateChan
		if len(update) > 0 {
			hookActions.UpdateRequestWithExtensions(update...)
		}
565
	}
Hannah Howard's avatar
Hannah Howard committed
566
	responseHooks.Register(hook)
567
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector(), extension1, extension2)
568 569 570 571 572

	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]

	gsr := rr.gsr
	returnedData1, found := gsr.Extension(extensionName1)
Hannah Howard's avatar
Hannah Howard committed
573 574
	require.True(t, found)
	require.Equal(t, extensionData1, returnedData1, "did not encode first extension correctly")
575 576

	returnedData2, found := gsr.Extension(extensionName2)
Hannah Howard's avatar
Hannah Howard committed
577 578
	require.True(t, found)
	require.Equal(t, extensionData2, returnedData2, "did not encode second extension correctly")
579

580 581
	t.Run("responding to extensions", func(t *testing.T) {
		expectedData := testutil.RandomBytes(100)
Hannah Howard's avatar
Hannah Howard committed
582
		expectedUpdate := testutil.RandomBytes(100)
583 584 585 586 587 588 589 590 591 592 593 594 595
		firstResponses := []gsmsg.GraphSyncResponse{
			gsmsg.NewResponse(gsr.ID(),
				graphsync.PartialResponse, graphsync.ExtensionData{
					Name: graphsync.ExtensionMetadata,
					Data: nil,
				},
				graphsync.ExtensionData{
					Name: extensionName1,
					Data: expectedData,
				},
			),
		}
		expectedError <- nil
Hannah Howard's avatar
Hannah Howard committed
596 597 598 599 600 601
		expectedUpdateChan <- []graphsync.ExtensionData{
			{
				Name: extensionName1,
				Data: expectedUpdate,
			},
		}
602
		requestManager.ProcessResponses(peers[0], firstResponses, nil)
Hannah Howard's avatar
Hannah Howard committed
603 604 605
		var received []byte
		testutil.AssertReceive(ctx, t, receivedExtensionData, &received, "did not receive extension data")
		require.Equal(t, expectedData, received, "did not receive correct extension data from resposne")
Hannah Howard's avatar
Hannah Howard committed
606 607 608 609 610 611

		rr = readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]
		receivedUpdateData, has := rr.gsr.Extension(extensionName1)
		require.True(t, has)
		require.Equal(t, expectedUpdate, receivedUpdateData, "should have updated with correct extension")

612
		nextExpectedData := testutil.RandomBytes(100)
Hannah Howard's avatar
Hannah Howard committed
613 614
		nextExpectedUpdate1 := testutil.RandomBytes(100)
		nextExpectedUpdate2 := testutil.RandomBytes(100)
615 616 617 618 619 620 621 622 623 624 625 626 627 628

		secondResponses := []gsmsg.GraphSyncResponse{
			gsmsg.NewResponse(gsr.ID(),
				graphsync.PartialResponse, graphsync.ExtensionData{
					Name: graphsync.ExtensionMetadata,
					Data: nil,
				},
				graphsync.ExtensionData{
					Name: extensionName1,
					Data: nextExpectedData,
				},
			),
		}
		expectedError <- errors.New("a terrible thing happened")
Hannah Howard's avatar
Hannah Howard committed
629 630 631 632 633 634 635 636 637 638
		expectedUpdateChan <- []graphsync.ExtensionData{
			{
				Name: extensionName1,
				Data: nextExpectedUpdate1,
			},
			{
				Name: extensionName2,
				Data: nextExpectedUpdate2,
			},
		}
639
		requestManager.ProcessResponses(peers[0], secondResponses, nil)
Hannah Howard's avatar
Hannah Howard committed
640 641
		testutil.AssertReceive(ctx, t, receivedExtensionData, &received, "did not receive extension data")
		require.Equal(t, nextExpectedData, received, "did not receive correct extension data from resposne")
Hannah Howard's avatar
Hannah Howard committed
642 643 644 645 646 647 648 649 650

		rr = readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]
		receivedUpdateData, has = rr.gsr.Extension(extensionName1)
		require.True(t, has)
		require.Equal(t, nextExpectedUpdate1, receivedUpdateData, "should have updated with correct extension")
		receivedUpdateData, has = rr.gsr.Extension(extensionName2)
		require.True(t, has)
		require.Equal(t, nextExpectedUpdate2, receivedUpdateData, "should have updated with correct extension")

651 652 653
		testutil.VerifySingleTerminalError(requestCtx, t, returnedErrorChan)
		testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan)
	})
654
}
655 656 657 658 659 660

func TestOutgoingRequestHooks(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
661 662 663
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
	requestManager.SetDelegate(fph)
	requestManager.Startup()

	requestCtx, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	peers := testutil.GeneratePeers(1)

	blockStore := make(map[ipld.Link][]byte)
	loader, storer := testutil.NewTestStore(blockStore)
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)

	extensionName1 := graphsync.ExtensionName("blockchain")
	extension1 := graphsync.ExtensionData{
		Name: extensionName1,
		Data: nil,
	}

	hook := func(p peer.ID, r graphsync.RequestData, ha graphsync.OutgoingRequestHookActions) {
		_, has := r.Extension(extensionName1)
		if has {
Hannah Howard's avatar
Hannah Howard committed
684
			ha.UseLinkTargetNodeStyleChooser(blockChain.Chooser)
685 686 687
			ha.UsePersistenceOption("chainstore")
		}
	}
Hannah Howard's avatar
Hannah Howard committed
688
	requestHooks.Register(hook)
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

	returnedResponseChan1, returnedErrorChan1 := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector(), extension1)
	returnedResponseChan2, returnedErrorChan2 := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())

	requestRecords := readNNetworkRequests(requestCtx, t, requestRecordChan, 2)

	md := metadataForBlocks(blockChain.AllBlocks(), true)
	mdEncoded, err := metadata.EncodeMetadata(md)
	require.NoError(t, err)
	mdExt := graphsync.ExtensionData{
		Name: graphsync.ExtensionMetadata,
		Data: mdEncoded,
	}
	responses := []gsmsg.GraphSyncResponse{
		gsmsg.NewResponse(requestRecords[0].gsr.ID(), graphsync.RequestCompletedFull, mdExt),
		gsmsg.NewResponse(requestRecords[1].gsr.ID(), graphsync.RequestCompletedFull, mdExt),
	}
	requestManager.ProcessResponses(peers[0], responses, blockChain.AllBlocks())
	fal.verifyLastProcessedBlocks(ctx, t, blockChain.AllBlocks())
	fal.verifyLastProcessedResponses(ctx, t, map[graphsync.RequestID]metadata.Metadata{
		requestRecords[0].gsr.ID(): md,
		requestRecords[1].gsr.ID(): md,
	})
	fal.successResponseOn(requestRecords[0].gsr.ID(), blockChain.AllBlocks())
	fal.successResponseOn(requestRecords[1].gsr.ID(), blockChain.AllBlocks())

	blockChain.VerifyWholeChainWithTypes(requestCtx, returnedResponseChan1)
	blockChain.VerifyWholeChain(requestCtx, returnedResponseChan2)
	testutil.VerifyEmptyErrors(ctx, t, returnedErrorChan1)
	testutil.VerifyEmptyErrors(ctx, t, returnedErrorChan2)
	fal.verifyStoreUsed(t, requestRecords[0].gsr.ID(), "chainstore")
	fal.verifyStoreUsed(t, requestRecords[1].gsr.ID(), "")
}