responsemanager_test.go 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
package responsemanager

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

	cid "github.com/ipfs/go-cid"
13
	"github.com/ipfs/go-graphsync"
14 15 16 17
	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"
18
	"github.com/ipfs/go-peertaskqueue/peertask"
19 20
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
21
	"github.com/libp2p/go-libp2p-core/peer"
22 23
)

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

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

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

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

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

Dirk McCormick's avatar
Dirk McCormick committed
77 78
func (fqq *fakeQueryQueue) ThawRound()                                    {}
func (fqq *fakeQueryQueue) TasksDone(to peer.ID, tasks ...*peertask.Task) {}
79 80 81 82 83 84 85 86 87 88 89 90

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 {
91
	requestID graphsync.RequestID
92 93 94 95 96 97
	link      ipld.Link
	data      []byte
}

type fakePeerResponseSender struct {
	sentResponses        chan sentResponse
98
	lastCompletedRequest chan graphsync.RequestID
99 100 101 102 103 104
}

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

func (fprs *fakePeerResponseSender) SendResponse(
105
	requestID graphsync.RequestID,
106 107 108 109 110 111
	link ipld.Link,
	data []byte,
) {
	fprs.sentResponses <- sentResponse{requestID, link, data}
}

112
func (fprs *fakePeerResponseSender) FinishRequest(requestID graphsync.RequestID) {
113 114 115
	fprs.lastCompletedRequest <- requestID
}

116
func (fprs *fakePeerResponseSender) FinishWithError(requestID graphsync.RequestID, status graphsync.ResponseStatusCode) {
117 118 119 120 121 122 123 124
	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)
125
	loader := testbridge.NewMockLoader(blks)
126
	ipldBridge := testbridge.NewMockIPLDBridge()
127
	requestIDChan := make(chan graphsync.RequestID, 1)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
	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")
	}
144
	requestID := graphsync.RequestID(rand.Int31())
145
	requests := []gsmsg.GraphSyncRequest{
146
		gsmsg.NewRequest(requestID, cids[0], selector, graphsync.Priority(math.MaxInt32)),
147 148
	}
	p := testutil.GeneratePeers(1)[0]
149
	responseManager.ProcessRequests(ctx, p, requests)
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 179
	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)
180
	loader := testbridge.NewMockLoader(blks)
181
	ipldBridge := testbridge.NewMockIPLDBridge()
182
	requestIDChan := make(chan graphsync.RequestID)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
	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")
	}
199
	requestID := graphsync.RequestID(rand.Int31())
200
	requests := []gsmsg.GraphSyncRequest{
201
		gsmsg.NewRequest(requestID, cids[0], selector, graphsync.Priority(math.MaxInt32)),
202 203
	}
	p := testutil.GeneratePeers(1)[0]
204
	responseManager.ProcessRequests(ctx, p, requests)
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

	// 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),
	}
228
	responseManager.ProcessRequests(ctx, p, requests)
229 230 231

	responseManager.synchronize()

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 257
	// 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
258 259 260 261 262 263 264 265 266
		}
	}
}

func TestEarlyCancellation(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 40*time.Millisecond)
	defer cancel()
	blks := testutil.GenerateBlocksOfSize(5, 20)
267
	loader := testbridge.NewMockLoader(blks)
268
	ipldBridge := testbridge.NewMockIPLDBridge()
269
	requestIDChan := make(chan graphsync.RequestID)
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
	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")
	}
287
	requestID := graphsync.RequestID(rand.Int31())
288
	requests := []gsmsg.GraphSyncRequest{
289
		gsmsg.NewRequest(requestID, cids[0], selector, graphsync.Priority(math.MaxInt32)),
290 291
	}
	p := testutil.GeneratePeers(1)[0]
292
	responseManager.ProcessRequests(ctx, p, requests)
293 294 295 296 297

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

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