messagequeue_test.go 13.4 KB
Newer Older
1 2 3 4
package messagequeue

import (
	"context"
5
	"fmt"
6 7 8 9 10
	"math/rand"
	"sync"
	"testing"
	"time"

Hannah Howard's avatar
Hannah Howard committed
11
	basicnode "github.com/ipld/go-ipld-prime/node/basic"
12
	"github.com/ipld/go-ipld-prime/traversal/selector/builder"
Hannah Howard's avatar
Hannah Howard committed
13
	"github.com/libp2p/go-libp2p-core/peer"
Hannah Howard's avatar
Hannah Howard committed
14
	"github.com/stretchr/testify/require"
15

Hannah Howard's avatar
Hannah Howard committed
16
	"github.com/ipfs/go-graphsync"
17 18
	gsmsg "github.com/ipfs/go-graphsync/message"
	gsnet "github.com/ipfs/go-graphsync/network"
19
	"github.com/ipfs/go-graphsync/notifications"
20
	allocator2 "github.com/ipfs/go-graphsync/responsemanager/allocator"
Hannah Howard's avatar
Hannah Howard committed
21
	"github.com/ipfs/go-graphsync/testutil"
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
)

type fakeMessageNetwork struct {
	connectError       error
	messageSenderError error
	messageSender      gsnet.MessageSender
	wait               *sync.WaitGroup
}

func (fmn *fakeMessageNetwork) ConnectTo(context.Context, peer.ID) error {
	return fmn.connectError
}

func (fmn *fakeMessageNetwork) NewMessageSender(context.Context, peer.ID) (gsnet.MessageSender, error) {
	fmn.wait.Done()
	if fmn.messageSenderError == nil {
		return fmn.messageSender, nil
	}
	return nil, fmn.messageSenderError
}

type fakeMessageSender struct {
	sendError    error
	fullClosed   chan<- struct{}
	reset        chan<- struct{}
	messagesSent chan<- gsmsg.GraphSyncMessage
}

func (fms *fakeMessageSender) SendMsg(ctx context.Context, msg gsmsg.GraphSyncMessage) error {
	fms.messagesSent <- msg
	return fms.sendError
}
func (fms *fakeMessageSender) Close() error { fms.fullClosed <- struct{}{}; return nil }
func (fms *fakeMessageSender) Reset() error { fms.reset <- struct{}{}; return nil }

func TestStartupAndShutdown(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	peer := testutil.GeneratePeers(1)[0]
	messagesSent := make(chan gsmsg.GraphSyncMessage)
	resetChan := make(chan struct{}, 1)
	fullClosedChan := make(chan struct{}, 1)
	messageSender := &fakeMessageSender{nil, fullClosedChan, resetChan, messagesSent}
	var waitGroup sync.WaitGroup
	messageNetwork := &fakeMessageNetwork{nil, nil, messageSender, &waitGroup}
69
	allocator := allocator2.NewAllocator(1<<30, 1<<30)
70

71
	messageQueue := New(ctx, peer, messageNetwork, allocator)
72
	messageQueue.Startup()
73 74
	id := graphsync.RequestID(rand.Int31())
	priority := graphsync.Priority(rand.Int31())
Eric Myhre's avatar
Eric Myhre committed
75
	ssb := builder.NewSelectorSpecBuilder(basicnode.Prototype.Any)
76
	selector := ssb.Matcher().Node()
77
	root := testutil.GenerateCids(1)[0]
78 79

	waitGroup.Add(1)
80
	messageQueue.AllocateAndBuildMessage(0, func(b *gsmsg.Builder) {
81 82
		b.AddRequest(gsmsg.NewRequest(id, root, selector, priority))
	}, []notifications.Notifee{})
83

Hannah Howard's avatar
Hannah Howard committed
84
	testutil.AssertDoesReceive(ctx, t, messagesSent, "message was not sent")
85 86 87

	messageQueue.Shutdown()

Hannah Howard's avatar
Hannah Howard committed
88
	testutil.AssertDoesReceiveFirst(t, fullClosedChan, "message sender should be closed", resetChan, ctx.Done())
89 90
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
func TestShutdownDuringMessageSend(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	peer := testutil.GeneratePeers(1)[0]
	messagesSent := make(chan gsmsg.GraphSyncMessage)
	resetChan := make(chan struct{}, 1)
	fullClosedChan := make(chan struct{}, 1)
	messageSender := &fakeMessageSender{
		fmt.Errorf("Something went wrong"),
		fullClosedChan,
		resetChan,
		messagesSent}
	var waitGroup sync.WaitGroup
	messageNetwork := &fakeMessageNetwork{nil, nil, messageSender, &waitGroup}
107
	allocator := allocator2.NewAllocator(1<<30, 1<<30)
108

109
	messageQueue := New(ctx, peer, messageNetwork, allocator)
110
	messageQueue.Startup()
111 112
	id := graphsync.RequestID(rand.Int31())
	priority := graphsync.Priority(rand.Int31())
Eric Myhre's avatar
Eric Myhre committed
113
	ssb := builder.NewSelectorSpecBuilder(basicnode.Prototype.Any)
114
	selector := ssb.Matcher().Node()
115 116 117 118
	root := testutil.GenerateCids(1)[0]

	// setup a message and advance as far as beginning to send it
	waitGroup.Add(1)
119
	messageQueue.AllocateAndBuildMessage(0, func(b *gsmsg.Builder) {
120 121
		b.AddRequest(gsmsg.NewRequest(id, root, selector, priority))
	}, []notifications.Notifee{})
122 123 124 125 126 127 128
	waitGroup.Wait()

	// now shut down
	messageQueue.Shutdown()

	// let the message send attempt complete and fail (as it would if
	// the connection were closed)
Hannah Howard's avatar
Hannah Howard committed
129
	testutil.AssertDoesReceive(ctx, t, messagesSent, "message send not attempted")
130 131

	// verify the connection is reset after a failed send attempt
Hannah Howard's avatar
Hannah Howard committed
132
	testutil.AssertDoesReceiveFirst(t, resetChan, "message sender was not reset", fullClosedChan, ctx.Done())
133 134 135 136 137 138 139

	// now verify after it's reset, no further retries, connection
	// resets, or attempts to close the connection, cause the queue
	// should realize it's shut down and stop processing
	// FIXME: this relies on time passing -- 100 ms to be exact
	// and we should instead mock out time as a dependency
	waitGroup.Add(1)
Hannah Howard's avatar
Hannah Howard committed
140
	testutil.AssertDoesReceiveFirst(t, ctx.Done(), "further message operations should not occur", messagesSent, resetChan, fullClosedChan)
141 142
}

143 144 145 146 147 148 149 150 151 152 153 154
func TestProcessingNotification(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	peer := testutil.GeneratePeers(1)[0]
	messagesSent := make(chan gsmsg.GraphSyncMessage)
	resetChan := make(chan struct{}, 1)
	fullClosedChan := make(chan struct{}, 1)
	messageSender := &fakeMessageSender{nil, fullClosedChan, resetChan, messagesSent}
	var waitGroup sync.WaitGroup
	messageNetwork := &fakeMessageNetwork{nil, nil, messageSender, &waitGroup}
155
	allocator := allocator2.NewAllocator(1<<30, 1<<30)
156

157
	messageQueue := New(ctx, peer, messageNetwork, allocator)
158
	messageQueue.Startup()
159 160 161
	waitGroup.Add(1)
	blks := testutil.GenerateBlocksOfSize(3, 128)

162 163 164
	responseID := graphsync.RequestID(rand.Int31())
	extensionName := graphsync.ExtensionName("graphsync/awesome")
	extension := graphsync.ExtensionData{
165 166 167
		Name: extensionName,
		Data: testutil.RandomBytes(100),
	}
168
	status := graphsync.RequestCompletedFull
169 170
	expectedTopic := "testTopic"
	notifee, verifier := testutil.NewTestNotifee(expectedTopic, 5)
171
	messageQueue.AllocateAndBuildMessage(0, func(b *gsmsg.Builder) {
172 173 174
		b.AddResponseCode(responseID, status)
		b.AddExtensionData(responseID, extension)
	}, []notifications.Notifee{notifee})
175 176 177 178

	// wait for send attempt
	waitGroup.Wait()

Hannah Howard's avatar
Hannah Howard committed
179 180 181 182 183
	var message gsmsg.GraphSyncMessage
	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not send")
	receivedBlocks := message.Blocks()
	for _, block := range receivedBlocks {
		testutil.AssertContainsBlock(t, blks, block)
184
	}
Hannah Howard's avatar
Hannah Howard committed
185 186 187 188 189 190
	firstResponse := message.Responses()[0]
	extensionData, found := firstResponse.Extension(extensionName)
	require.Equal(t, responseID, firstResponse.RequestID())
	require.Equal(t, status, firstResponse.Status())
	require.True(t, found)
	require.Equal(t, extension.Data, extensionData)
191 192 193 194 195 196

	verifier.ExpectEvents(ctx, t, []notifications.Event{
		Event{Name: Queued},
		Event{Name: Sent},
	})
	verifier.ExpectClose(ctx, t)
197 198
}

199 200 201 202 203 204 205 206 207 208 209 210
func TestDedupingMessages(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	peer := testutil.GeneratePeers(1)[0]
	messagesSent := make(chan gsmsg.GraphSyncMessage)
	resetChan := make(chan struct{}, 1)
	fullClosedChan := make(chan struct{}, 1)
	messageSender := &fakeMessageSender{nil, fullClosedChan, resetChan, messagesSent}
	var waitGroup sync.WaitGroup
	messageNetwork := &fakeMessageNetwork{nil, nil, messageSender, &waitGroup}
211
	allocator := allocator2.NewAllocator(1<<30, 1<<30)
212

213
	messageQueue := New(ctx, peer, messageNetwork, allocator)
214 215
	messageQueue.Startup()
	waitGroup.Add(1)
216 217
	id := graphsync.RequestID(rand.Int31())
	priority := graphsync.Priority(rand.Int31())
Eric Myhre's avatar
Eric Myhre committed
218
	ssb := builder.NewSelectorSpecBuilder(basicnode.Prototype.Any)
219
	selector := ssb.Matcher().Node()
220
	root := testutil.GenerateCids(1)[0]
221

222
	messageQueue.AllocateAndBuildMessage(0, func(b *gsmsg.Builder) {
223 224
		b.AddRequest(gsmsg.NewRequest(id, root, selector, priority))
	}, []notifications.Notifee{})
225 226
	// wait for send attempt
	waitGroup.Wait()
227 228
	id2 := graphsync.RequestID(rand.Int31())
	priority2 := graphsync.Priority(rand.Int31())
229
	selector2 := ssb.ExploreAll(ssb.Matcher()).Node()
230
	root2 := testutil.GenerateCids(1)[0]
231 232
	id3 := graphsync.RequestID(rand.Int31())
	priority3 := graphsync.Priority(rand.Int31())
233
	selector3 := ssb.ExploreIndex(0, ssb.Matcher()).Node()
234 235
	root3 := testutil.GenerateCids(1)[0]

236
	messageQueue.AllocateAndBuildMessage(0, func(b *gsmsg.Builder) {
237 238 239
		b.AddRequest(gsmsg.NewRequest(id2, root2, selector2, priority2))
		b.AddRequest(gsmsg.NewRequest(id3, root3, selector3, priority3))
	}, []notifications.Notifee{})
240

Hannah Howard's avatar
Hannah Howard committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	var message gsmsg.GraphSyncMessage
	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not send")

	requests := message.Requests()
	require.Len(t, requests, 1, "number of requests in first message was not 1")
	request := requests[0]
	require.Equal(t, id, request.ID())
	require.False(t, request.IsCancel())
	require.Equal(t, priority, request.Priority())
	require.Equal(t, selector, request.Selector())

	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not senf")

	requests = message.Requests()
	require.Len(t, requests, 2, "number of requests in second message was not 2")
	for _, request := range requests {
		if request.ID() == id2 {
			require.False(t, request.IsCancel())
			require.Equal(t, priority2, request.Priority())
			require.Equal(t, selector2, request.Selector())
		} else if request.ID() == id3 {
			require.False(t, request.IsCancel())
			require.Equal(t, priority3, request.Priority())
			require.Equal(t, selector3, request.Selector())
		} else {
			t.Fatal("incorrect request added to message")
267 268 269
		}
	}
}
270

271
func TestSendsVeryLargeBlocksResponses(t *testing.T) {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	peer := testutil.GeneratePeers(1)[0]
	messagesSent := make(chan gsmsg.GraphSyncMessage)
	resetChan := make(chan struct{}, 1)
	fullClosedChan := make(chan struct{}, 1)
	messageSender := &fakeMessageSender{nil, fullClosedChan, resetChan, messagesSent}
	var waitGroup sync.WaitGroup
	messageNetwork := &fakeMessageNetwork{nil, nil, messageSender, &waitGroup}
	allocator := allocator2.NewAllocator(1<<30, 1<<30)

	messageQueue := New(ctx, peer, messageNetwork, allocator)
	messageQueue.Startup()
	waitGroup.Add(1)

	// generate large blocks before proceeding
	blks := testutil.GenerateBlocksOfSize(5, 1000000)
291
	messageQueue.AllocateAndBuildMessage(uint64(len(blks[0].RawData())), func(b *gsmsg.Builder) {
292 293 294 295 296 297 298 299 300 301 302
		b.AddBlock(blks[0])
	}, []notifications.Notifee{})
	waitGroup.Wait()
	var message gsmsg.GraphSyncMessage
	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not send")

	msgBlks := message.Blocks()
	require.Len(t, msgBlks, 1, "number of blks in first message was not 1")
	require.True(t, blks[0].Cid().Equals(msgBlks[0].Cid()))

	// Send 3 very large blocks
303
	messageQueue.AllocateAndBuildMessage(uint64(len(blks[1].RawData())), func(b *gsmsg.Builder) {
304 305
		b.AddBlock(blks[1])
	}, []notifications.Notifee{})
306
	messageQueue.AllocateAndBuildMessage(uint64(len(blks[2].RawData())), func(b *gsmsg.Builder) {
307 308
		b.AddBlock(blks[2])
	}, []notifications.Notifee{})
309
	messageQueue.AllocateAndBuildMessage(uint64(len(blks[3].RawData())), func(b *gsmsg.Builder) {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
		b.AddBlock(blks[3])
	}, []notifications.Notifee{})

	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not send")
	msgBlks = message.Blocks()
	require.Len(t, msgBlks, 1, "number of blks in first message was not 1")
	require.True(t, blks[1].Cid().Equals(msgBlks[0].Cid()))

	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not send")
	msgBlks = message.Blocks()
	require.Len(t, msgBlks, 1, "number of blks in first message was not 1")
	require.True(t, blks[2].Cid().Equals(msgBlks[0].Cid()))

	testutil.AssertReceive(ctx, t, messagesSent, &message, "message did not send")
	msgBlks = message.Blocks()
	require.Len(t, msgBlks, 1, "number of blks in first message was not 1")
	require.True(t, blks[3].Cid().Equals(msgBlks[0].Cid()))
}
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

func TestSendsResponsesMemoryPressure(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	p := testutil.GeneratePeers(1)[0]
	messagesSent := make(chan gsmsg.GraphSyncMessage, 0)
	resetChan := make(chan struct{}, 1)
	fullClosedChan := make(chan struct{}, 1)
	messageSender := &fakeMessageSender{nil, fullClosedChan, resetChan, messagesSent}
	var waitGroup sync.WaitGroup
	messageNetwork := &fakeMessageNetwork{nil, nil, messageSender, &waitGroup}

	// use allocator with very small limit
	allocator := allocator2.NewAllocator(1000, 1000)

	messageQueue := New(ctx, p, messageNetwork, allocator)
	messageQueue.Startup()
	waitGroup.Add(1)

	// start sending block that exceeds memory limit
	blks := testutil.GenerateBlocksOfSize(2, 999)
	messageQueue.AllocateAndBuildMessage(uint64(len(blks[0].RawData())), func(b *gsmsg.Builder) {
		b.AddBlock(blks[0])
	}, []notifications.Notifee{})

	finishes := make(chan string, 2)
	go func() {
		// attempt to send second block. Should block until memory is released
		messageQueue.AllocateAndBuildMessage(uint64(len(blks[1].RawData())), func(b *gsmsg.Builder) {
			b.AddBlock(blks[1])
		}, []notifications.Notifee{})
		finishes <- "sent message"
	}()

	// assert transaction does not complete within 200ms because it is waiting on memory
	ctx2, cancel2 := context.WithTimeout(ctx, 200*time.Millisecond)
	select {
	case <-finishes:
		t.Fatal("transaction failed to wait on memory")
	case <-ctx2.Done():
	}

	// Allow first message to complete sending
	<-messagesSent

	// assert message is now queued within 200ms
	ctx2, cancel2 = context.WithTimeout(ctx, 200*time.Millisecond)
	defer cancel2()
	select {
	case <-finishes:
		cancel2()
	case <-ctx2.Done():
		t.Fatal("timeout waiting for transaction to complete")
	}
}