responsemanager_test.go 8.94 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package responsemanager

import (
	"context"
	"math"
	"math/rand"
	"reflect"
	"sync"
	"testing"
	"time"

	cid "github.com/ipfs/go-cid"
	gsmsg "github.com/ipfs/go-graphsync/message"
	"github.com/ipfs/go-graphsync/responsemanager/peerresponsemanager"
	"github.com/ipfs/go-graphsync/testbridge"
	"github.com/ipfs/go-graphsync/testutil"
17
	"github.com/ipfs/go-peertaskqueue/peertask"
18 19
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
20
	"github.com/libp2p/go-libp2p-core/peer"
21 22
)

Dirk McCormick's avatar
Dirk McCormick committed
23 24 25 26 27
type taskRQ struct {
	tasks  []*peertask.Task
	target peer.ID
}

28 29 30
type fakeQueryQueue struct {
	popWait   sync.WaitGroup
	queriesLk sync.RWMutex
Dirk McCormick's avatar
Dirk McCormick committed
31
	queries   []*taskRQ
32 33
}

Dirk McCormick's avatar
Dirk McCormick committed
34
func (fqq *fakeQueryQueue) PushTasks(to peer.ID, tasks ...peertask.Task) {
35
	fqq.queriesLk.Lock()
Dirk McCormick's avatar
Dirk McCormick committed
36 37 38 39 40 41 42
	var ptrs []*peertask.Task
	for _, t := range tasks {
		ptrs = append(ptrs, &t)
	}
	fqq.queries = append(fqq.queries, &taskRQ{
		tasks:  ptrs,
		target: to,
43 44 45 46
	})
	fqq.queriesLk.Unlock()
}

Dirk McCormick's avatar
Dirk McCormick committed
47
func (fqq *fakeQueryQueue) PopTasks(targetMinWork int) (peer.ID, []*peertask.Task, int) {
48 49 50 51
	fqq.popWait.Wait()
	fqq.queriesLk.Lock()
	defer fqq.queriesLk.Unlock()
	if len(fqq.queries) == 0 {
Dirk McCormick's avatar
Dirk McCormick committed
52
		return "", nil, 0
53
	}
Dirk McCormick's avatar
Dirk McCormick committed
54
	trq := fqq.queries[0]
55
	fqq.queries = fqq.queries[1:]
Dirk McCormick's avatar
Dirk McCormick committed
56
	return trq.target, trq.tasks, 0
57 58
}

Dirk McCormick's avatar
Dirk McCormick committed
59
func (fqq *fakeQueryQueue) Remove(topic peertask.Topic, p peer.ID) {
60 61 62
	fqq.queriesLk.Lock()
	defer fqq.queriesLk.Unlock()
	for i, query := range fqq.queries {
Dirk McCormick's avatar
Dirk McCormick committed
63 64 65 66
		if query.target == p {
			for j, task := range query.tasks {
				if task.Topic == topic {
					query.tasks = append(query.tasks[:j], query.tasks[j+1:]...)
67 68
				}
			}
Dirk McCormick's avatar
Dirk McCormick committed
69
			if len(query.tasks) == 0 {
70 71 72 73 74 75
				fqq.queries = append(fqq.queries[:i], fqq.queries[i+1:]...)
			}
		}
	}
}

Dirk McCormick's avatar
Dirk McCormick committed
76 77
func (fqq *fakeQueryQueue) ThawRound()                                    {}
func (fqq *fakeQueryQueue) TasksDone(to peer.ID, tasks ...*peertask.Task) {}
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

type fakePeerManager struct {
	lastPeer           peer.ID
	peerResponseSender peerresponsemanager.PeerResponseSender
}

func (fpm *fakePeerManager) SenderForPeer(p peer.ID) peerresponsemanager.PeerResponseSender {
	fpm.lastPeer = p
	return fpm.peerResponseSender
}

type sentResponse struct {
	requestID gsmsg.GraphSyncRequestID
	link      ipld.Link
	data      []byte
}

type fakePeerResponseSender struct {
	sentResponses        chan sentResponse
	lastCompletedRequest chan gsmsg.GraphSyncRequestID
}

func (fprs *fakePeerResponseSender) Startup()  {}
func (fprs *fakePeerResponseSender) Shutdown() {}

func (fprs *fakePeerResponseSender) SendResponse(
	requestID gsmsg.GraphSyncRequestID,
	link ipld.Link,
	data []byte,
) {
	fprs.sentResponses <- sentResponse{requestID, link, data}
}

func (fprs *fakePeerResponseSender) FinishRequest(requestID gsmsg.GraphSyncRequestID) {
	fprs.lastCompletedRequest <- requestID
}

func (fprs *fakePeerResponseSender) FinishWithError(requestID gsmsg.GraphSyncRequestID, status gsmsg.GraphSyncResponseStatusCode) {
	fprs.lastCompletedRequest <- requestID
}

func TestIncomingQuery(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 40*time.Millisecond)
	defer cancel()
	blks := testutil.GenerateBlocksOfSize(5, 20)
124
	loader := testbridge.NewMockLoader(blks)
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	ipldBridge := testbridge.NewMockIPLDBridge()
	requestIDChan := make(chan gsmsg.GraphSyncRequestID, 1)
	sentResponses := make(chan sentResponse, len(blks))
	fprs := &fakePeerResponseSender{lastCompletedRequest: requestIDChan, sentResponses: sentResponses}
	peerManager := &fakePeerManager{peerResponseSender: fprs}
	queryQueue := &fakeQueryQueue{}
	responseManager := New(ctx, loader, ipldBridge, peerManager, queryQueue)
	responseManager.Startup()

	cids := make([]cid.Cid, 0, 5)
	for _, block := range blks {
		cids = append(cids, block.Cid())
	}
	selectorSpec := testbridge.NewMockSelectorSpec(cids)
	selector, err := ipldBridge.EncodeNode(selectorSpec)
	if err != nil {
		t.Fatal("error encoding selector")
	}
	requestID := gsmsg.GraphSyncRequestID(rand.Int31())
	requests := []gsmsg.GraphSyncRequest{
145
		gsmsg.NewRequest(requestID, cids[0], selector, gsmsg.GraphSyncPriority(math.MaxInt32)),
146 147
	}
	p := testutil.GeneratePeers(1)[0]
148
	responseManager.ProcessRequests(ctx, p, requests)
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
	select {
	case <-ctx.Done():
		t.Fatal("Should have completed request but didn't")
	case <-requestIDChan:
	}
	for i := 0; i < len(blks); i++ {
		select {
		case sentResponse := <-sentResponses:
			k := sentResponse.link.(cidlink.Link)
			blockIndex := testutil.IndexOf(blks, k.Cid)
			if blockIndex == -1 {
				t.Fatal("sent incorrect link")
			}
			if !reflect.DeepEqual(sentResponse.data, blks[blockIndex].RawData()) {
				t.Fatal("sent incorrect data")
			}
			if sentResponse.requestID != requestID {
				t.Fatal("incorrect response id")
			}
		case <-ctx.Done():
			t.Fatal("did not send enough responses")
		}
	}
}

func TestCancellationQueryInProgress(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 40*time.Millisecond)
	defer cancel()
	blks := testutil.GenerateBlocksOfSize(5, 20)
179
	loader := testbridge.NewMockLoader(blks)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
	ipldBridge := testbridge.NewMockIPLDBridge()
	requestIDChan := make(chan gsmsg.GraphSyncRequestID)
	sentResponses := make(chan sentResponse)
	fprs := &fakePeerResponseSender{lastCompletedRequest: requestIDChan, sentResponses: sentResponses}
	peerManager := &fakePeerManager{peerResponseSender: fprs}
	queryQueue := &fakeQueryQueue{}
	responseManager := New(ctx, loader, ipldBridge, peerManager, queryQueue)
	responseManager.Startup()

	cids := make([]cid.Cid, 0, 5)
	for _, block := range blks {
		cids = append(cids, block.Cid())
	}
	selectorSpec := testbridge.NewMockSelectorSpec(cids)
	selector, err := ipldBridge.EncodeNode(selectorSpec)
	if err != nil {
		t.Fatal("error encoding selector")
	}
	requestID := gsmsg.GraphSyncRequestID(rand.Int31())
	requests := []gsmsg.GraphSyncRequest{
200
		gsmsg.NewRequest(requestID, cids[0], selector, gsmsg.GraphSyncPriority(math.MaxInt32)),
201 202
	}
	p := testutil.GeneratePeers(1)[0]
203
	responseManager.ProcessRequests(ctx, p, requests)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

	// read one block
	select {
	case sentResponse := <-sentResponses:
		k := sentResponse.link.(cidlink.Link)
		blockIndex := testutil.IndexOf(blks, k.Cid)
		if blockIndex == -1 {
			t.Fatal("sent incorrect link")
		}
		if !reflect.DeepEqual(sentResponse.data, blks[blockIndex].RawData()) {
			t.Fatal("sent incorrect data")
		}
		if sentResponse.requestID != requestID {
			t.Fatal("incorrect response id")
		}
	case <-ctx.Done():
		t.Fatal("did not send responses")
	}

	// send a cancellation
	requests = []gsmsg.GraphSyncRequest{
		gsmsg.CancelRequest(requestID),
	}
227
	responseManager.ProcessRequests(ctx, p, requests)
228 229 230

	responseManager.synchronize()

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	// at this point we should receive at most one more block, then traversal
	// should complete
	additionalMessageCount := 0
drainqueue:
	for {
		select {
		case <-ctx.Done():
			t.Fatal("Should have completed request but didn't")
		case sentResponse := <-sentResponses:
			if additionalMessageCount > 0 {
				t.Fatal("should not send any more responses")
			}
			k := sentResponse.link.(cidlink.Link)
			blockIndex := testutil.IndexOf(blks, k.Cid)
			if blockIndex == -1 {
				t.Fatal("sent incorrect link")
			}
			if !reflect.DeepEqual(sentResponse.data, blks[blockIndex].RawData()) {
				t.Fatal("sent incorrect data")
			}
			if sentResponse.requestID != requestID {
				t.Fatal("incorrect response id")
			}
			additionalMessageCount++
		case <-requestIDChan:
			break drainqueue
257 258 259 260 261 262 263 264 265
		}
	}
}

func TestEarlyCancellation(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 40*time.Millisecond)
	defer cancel()
	blks := testutil.GenerateBlocksOfSize(5, 20)
266
	loader := testbridge.NewMockLoader(blks)
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
	ipldBridge := testbridge.NewMockIPLDBridge()
	requestIDChan := make(chan gsmsg.GraphSyncRequestID)
	sentResponses := make(chan sentResponse)
	fprs := &fakePeerResponseSender{lastCompletedRequest: requestIDChan, sentResponses: sentResponses}
	peerManager := &fakePeerManager{peerResponseSender: fprs}
	queryQueue := &fakeQueryQueue{}
	queryQueue.popWait.Add(1)
	responseManager := New(ctx, loader, ipldBridge, peerManager, queryQueue)
	responseManager.Startup()

	cids := make([]cid.Cid, 0, 5)
	for _, block := range blks {
		cids = append(cids, block.Cid())
	}
	selectorSpec := testbridge.NewMockSelectorSpec(cids)
	selector, err := ipldBridge.EncodeNode(selectorSpec)
	if err != nil {
		t.Fatal("error encoding selector")
	}
	requestID := gsmsg.GraphSyncRequestID(rand.Int31())
	requests := []gsmsg.GraphSyncRequest{
288
		gsmsg.NewRequest(requestID, cids[0], selector, gsmsg.GraphSyncPriority(math.MaxInt32)),
289 290
	}
	p := testutil.GeneratePeers(1)[0]
291
	responseManager.ProcessRequests(ctx, p, requests)
292 293 294 295 296

	// send a cancellation
	requests = []gsmsg.GraphSyncRequest{
		gsmsg.CancelRequest(requestID),
	}
297
	responseManager.ProcessRequests(ctx, p, requests)
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

	responseManager.synchronize()

	// unblock popping from queue
	queryQueue.popWait.Done()

	// verify no responses processed
	select {
	case <-ctx.Done():
	case <-sentResponses:
		t.Fatal("should not send any more responses")
	case <-requestIDChan:
		t.Fatal("should not send have completed response")
	}
}