requestmanager_test.go 28.1 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 TestUnencodableSelector(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 390 391
	requestManager.SetDelegate(fph)
	requestManager.Startup()

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

392 393
	s := testutil.NewUnencodableSelectorSpec()
	r := cidlink.Link{Cid: testutil.GenerateCids(1)[0]}
394
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], r, s)
395

396 397
	testutil.VerifySingleTerminalError(requestCtx, t, returnedErrorChan)
	testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan)
398
}
399 400 401 402 403

func TestFailedRequest(t *testing.T) {
	requestRecordChan := make(chan requestRecord, 2)
	fph := &fakePeerHandler{requestRecordChan}
	ctx := context.Background()
404
	fal := newFakeAsyncLoader()
Hannah Howard's avatar
Hannah Howard committed
405 406 407
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
408 409 410 411 412
	requestManager.SetDelegate(fph)
	requestManager.Startup()

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

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

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

	rr := readNNetworkRequests(requestCtx, t, requestRecordChan, 1)[0]
422
	failedResponses := []gsmsg.GraphSyncResponse{
423
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestFailedContentNotFound),
424
	}
425
	requestManager.ProcessResponses(peers[0], failedResponses, nil)
426

427 428
	testutil.VerifySingleTerminalError(requestCtx, t, returnedErrorChan)
	testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan)
429 430 431 432 433 434 435
}

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
436 437 438
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
439 440 441 442 443 444 445
	requestManager.SetDelegate(fph)
	requestManager.Startup()

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

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

	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
451 452 453 454

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

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

457
	blockChain.VerifyWholeChain(requestCtx, returnedResponseChan)
458 459 460

	// failure comes in later over network
	failedResponses := []gsmsg.GraphSyncResponse{
461
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestFailedContentNotFound),
462 463 464
	}

	requestManager.ProcessResponses(peers[0], failedResponses, nil)
465
	testutil.VerifyEmptyErrors(ctx, t, returnedErrorChan)
466 467 468 469 470 471 472 473

}

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
474 475 476
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
477 478 479 480 481 482 483
	requestManager.SetDelegate(fph)
	requestManager.Startup()

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

484
	blockStore := make(map[ipld.Link][]byte)
485
	loader, storer := testutil.NewTestStore(blockStore)
486 487
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
488 489 490 491

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

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

494
	blockChain.VerifyWholeChain(requestCtx, returnedResponseChan)
495

496
	md := encodedMetadataForBlocks(t, blockChain.AllBlocks(), true)
497
	firstResponses := []gsmsg.GraphSyncResponse{
498
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestCompletedFull, md),
499
	}
500
	requestManager.ProcessResponses(peers[0], firstResponses, blockChain.AllBlocks())
501 502

	fal.verifyNoRemainingData(t, rr.gsr.ID())
503
	testutil.VerifyEmptyErrors(ctx, t, returnedErrorChan)
504 505 506 507 508 509 510
}

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
511 512 513
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
514 515 516 517 518 519 520
	requestManager.SetDelegate(fph)
	requestManager.Startup()

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

521
	blockStore := make(map[ipld.Link][]byte)
522
	loader, storer := testutil.NewTestStore(blockStore)
523 524
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector())
525 526 527

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

528
	md := encodedMetadataForBlocks(t, blockChain.AllBlocks(), false)
529
	firstResponses := []gsmsg.GraphSyncResponse{
530
		gsmsg.NewResponse(rr.gsr.ID(), graphsync.RequestCompletedPartial, md),
531 532
	}
	requestManager.ProcessResponses(peers[0], firstResponses, nil)
533
	for _, block := range blockChain.AllBlocks() {
534 535
		fal.responseOn(rr.gsr.ID(), cidlink.Link{Cid: block.Cid()}, types.AsyncLoadResult{Data: nil, Err: fmt.Errorf("Terrible Thing")})
	}
536 537
	testutil.VerifyEmptyResponse(ctx, t, returnedResponseChan)
	errs := testutil.CollectErrors(ctx, t, returnedErrorChan)
Hannah Howard's avatar
Hannah Howard committed
538
	require.NotEqual(t, len(errs), 0, "did not send errors")
539
}
540 541 542 543 544 545

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
546 547 548
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
549 550 551 552 553 554 555
	requestManager.SetDelegate(fph)
	requestManager.Startup()

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

556
	blockStore := make(map[ipld.Link][]byte)
557
	loader, storer := testutil.NewTestStore(blockStore)
558
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 5)
559 560 561 562 563 564 565 566 567 568 569 570 571

	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,
	}
572 573 574

	expectedError := make(chan error, 2)
	receivedExtensionData := make(chan []byte, 2)
Hannah Howard's avatar
Hannah Howard committed
575 576
	expectedUpdateChan := make(chan []graphsync.ExtensionData, 2)
	hook := func(p peer.ID, responseData graphsync.ResponseData, hookActions graphsync.IncomingResponseHookActions) {
577
		data, has := responseData.Extension(extensionName1)
Hannah Howard's avatar
Hannah Howard committed
578
		require.True(t, has, "did not receive extension data in response")
579
		receivedExtensionData <- data
Hannah Howard's avatar
Hannah Howard committed
580 581 582 583 584 585 586 587
		err := <-expectedError
		if err != nil {
			hookActions.TerminateWithError(err)
		}
		update := <-expectedUpdateChan
		if len(update) > 0 {
			hookActions.UpdateRequestWithExtensions(update...)
		}
588
	}
Hannah Howard's avatar
Hannah Howard committed
589
	responseHooks.Register(hook)
590
	returnedResponseChan, returnedErrorChan := requestManager.SendRequest(requestCtx, peers[0], blockChain.TipLink, blockChain.Selector(), extension1, extension2)
591 592 593 594 595

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

	gsr := rr.gsr
	returnedData1, found := gsr.Extension(extensionName1)
Hannah Howard's avatar
Hannah Howard committed
596 597
	require.True(t, found)
	require.Equal(t, extensionData1, returnedData1, "did not encode first extension correctly")
598 599

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

603 604
	t.Run("responding to extensions", func(t *testing.T) {
		expectedData := testutil.RandomBytes(100)
Hannah Howard's avatar
Hannah Howard committed
605
		expectedUpdate := testutil.RandomBytes(100)
606 607 608 609 610 611 612 613 614 615 616 617 618
		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
619 620 621 622 623 624
		expectedUpdateChan <- []graphsync.ExtensionData{
			{
				Name: extensionName1,
				Data: expectedUpdate,
			},
		}
625
		requestManager.ProcessResponses(peers[0], firstResponses, nil)
Hannah Howard's avatar
Hannah Howard committed
626 627 628
		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
629 630 631 632 633 634

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

635
		nextExpectedData := testutil.RandomBytes(100)
Hannah Howard's avatar
Hannah Howard committed
636 637
		nextExpectedUpdate1 := testutil.RandomBytes(100)
		nextExpectedUpdate2 := testutil.RandomBytes(100)
638 639 640 641 642 643 644 645 646 647 648 649 650 651

		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
652 653 654 655 656 657 658 659 660 661
		expectedUpdateChan <- []graphsync.ExtensionData{
			{
				Name: extensionName1,
				Data: nextExpectedUpdate1,
			},
			{
				Name: extensionName2,
				Data: nextExpectedUpdate2,
			},
		}
662
		requestManager.ProcessResponses(peers[0], secondResponses, nil)
Hannah Howard's avatar
Hannah Howard committed
663 664
		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
665 666 667 668 669 670 671 672 673

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

674 675 676
		testutil.VerifySingleTerminalError(requestCtx, t, returnedErrorChan)
		testutil.VerifyEmptyResponse(requestCtx, t, returnedResponseChan)
	})
677
}
678 679 680 681 682 683

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
684 685 686
	requestHooks := hooks.NewRequestHooks()
	responseHooks := hooks.NewResponseHooks()
	requestManager := New(ctx, fal, requestHooks, responseHooks)
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
	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 {
			ha.UseNodeBuilderChooser(blockChain.Chooser)
			ha.UsePersistenceOption("chainstore")
		}
	}
Hannah Howard's avatar
Hannah Howard committed
711
	requestHooks.Register(hook)
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

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