providerquerymanager_test.go 10.4 KB
Newer Older
1 2 3 4 5 6
package providerquerymanager

import (
	"context"
	"errors"
	"reflect"
7
	"sync"
8 9 10 11 12 13 14 15 16 17
	"testing"
	"time"

	"github.com/ipfs/go-bitswap/testutil"

	cid "github.com/ipfs/go-cid"
	"github.com/libp2p/go-libp2p-peer"
)

type fakeProviderNetwork struct {
18 19 20 21 22 23
	peersFound       []peer.ID
	connectError     error
	delay            time.Duration
	connectDelay     time.Duration
	queriesMadeMutex sync.RWMutex
	queriesMade      int
24 25 26 27 28 29 30 31
}

func (fpn *fakeProviderNetwork) ConnectTo(context.Context, peer.ID) error {
	time.Sleep(fpn.connectDelay)
	return fpn.connectError
}

func (fpn *fakeProviderNetwork) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
32
	fpn.queriesMadeMutex.Lock()
33
	fpn.queriesMade++
34
	fpn.queriesMadeMutex.Unlock()
35 36 37 38 39 40
	incomingPeers := make(chan peer.ID)
	go func() {
		defer close(incomingPeers)
		for _, p := range fpn.peersFound {
			time.Sleep(fpn.delay)
			select {
41 42 43 44 45
			case <-ctx.Done():
				return
			default:
			}
			select {
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
			case incomingPeers <- p:
			case <-ctx.Done():
				return
			}
		}
	}()
	return incomingPeers
}

func TestNormalSimultaneousFetch(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()
	keys := testutil.GenerateCids(2)

	sessionCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel()
68 69
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, keys[0])
	secondRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, keys[1])
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

	var firstPeersReceived []peer.ID
	for p := range firstRequestChan {
		firstPeersReceived = append(firstPeersReceived, p)
	}

	var secondPeersReceived []peer.ID
	for p := range secondRequestChan {
		secondPeersReceived = append(secondPeersReceived, p)
	}

	if len(firstPeersReceived) != len(peers) || len(secondPeersReceived) != len(peers) {
		t.Fatal("Did not collect all peers for request that was completed")
	}

85 86
	fpn.queriesMadeMutex.Lock()
	defer fpn.queriesMadeMutex.Unlock()
87 88 89
	if fpn.queriesMade != 2 {
		t.Fatal("Did not dedup provider requests running simultaneously")
	}
90

91 92 93 94 95 96 97 98 99 100 101 102 103
}

func TestDedupingProviderRequests(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()
	key := testutil.GenerateCids(1)[0]

104
	sessionCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
105
	defer cancel()
106 107
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, key)
	secondRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, key)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

	var firstPeersReceived []peer.ID
	for p := range firstRequestChan {
		firstPeersReceived = append(firstPeersReceived, p)
	}

	var secondPeersReceived []peer.ID
	for p := range secondRequestChan {
		secondPeersReceived = append(secondPeersReceived, p)
	}

	if len(firstPeersReceived) != len(peers) || len(secondPeersReceived) != len(peers) {
		t.Fatal("Did not collect all peers for request that was completed")
	}

	if !reflect.DeepEqual(firstPeersReceived, secondPeersReceived) {
		t.Fatal("Did not receive the same response to both find provider requests")
	}
126 127
	fpn.queriesMadeMutex.Lock()
	defer fpn.queriesMadeMutex.Unlock()
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	if fpn.queriesMade != 1 {
		t.Fatal("Did not dedup provider requests running simultaneously")
	}
}

func TestCancelOneRequestDoesNotTerminateAnother(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()

	key := testutil.GenerateCids(1)[0]

	// first session will cancel before done
	firstSessionCtx, firstCancel := context.WithTimeout(ctx, 3*time.Millisecond)
	defer firstCancel()
148
	firstRequestChan := providerQueryManager.FindProvidersAsync(firstSessionCtx, key)
149
	secondSessionCtx, secondCancel := context.WithTimeout(ctx, 100*time.Millisecond)
150
	defer secondCancel()
151
	secondRequestChan := providerQueryManager.FindProvidersAsync(secondSessionCtx, key)
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

	var firstPeersReceived []peer.ID
	for p := range firstRequestChan {
		firstPeersReceived = append(firstPeersReceived, p)
	}

	var secondPeersReceived []peer.ID
	for p := range secondRequestChan {
		secondPeersReceived = append(secondPeersReceived, p)
	}

	if len(secondPeersReceived) != len(peers) {
		t.Fatal("Did not collect all peers for request that was completed")
	}

	if len(firstPeersReceived) >= len(peers) {
		t.Fatal("Collected all peers on cancelled peer, should have been cancelled immediately")
	}
170 171
	fpn.queriesMadeMutex.Lock()
	defer fpn.queriesMadeMutex.Unlock()
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
	if fpn.queriesMade != 1 {
		t.Fatal("Did not dedup provider requests running simultaneously")
	}
}

func TestCancelManagerExitsGracefully(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	managerCtx, managerCancel := context.WithTimeout(ctx, 5*time.Millisecond)
	defer managerCancel()
	providerQueryManager := New(managerCtx, fpn)
	providerQueryManager.Startup()

	key := testutil.GenerateCids(1)[0]

	sessionCtx, cancel := context.WithTimeout(ctx, 20*time.Millisecond)
	defer cancel()
193 194
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, key)
	secondRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, key)
195 196 197 198 199 200 201 202 203 204 205

	var firstPeersReceived []peer.ID
	for p := range firstRequestChan {
		firstPeersReceived = append(firstPeersReceived, p)
	}

	var secondPeersReceived []peer.ID
	for p := range secondRequestChan {
		secondPeersReceived = append(secondPeersReceived, p)
	}

206
	if len(firstPeersReceived) >= len(peers) ||
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
		len(secondPeersReceived) >= len(peers) {
		t.Fatal("Did not cancel requests in progress correctly")
	}
}

func TestPeersWithConnectionErrorsNotAddedToPeerList(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound:   peers,
		connectError: errors.New("not able to connect"),
		delay:        1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()

	key := testutil.GenerateCids(1)[0]

	sessionCtx, cancel := context.WithTimeout(ctx, 20*time.Millisecond)
	defer cancel()
227 228
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, key)
	secondRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, key)
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

	var firstPeersReceived []peer.ID
	for p := range firstRequestChan {
		firstPeersReceived = append(firstPeersReceived, p)
	}

	var secondPeersReceived []peer.ID
	for p := range secondRequestChan {
		secondPeersReceived = append(secondPeersReceived, p)
	}

	if len(firstPeersReceived) != 0 || len(secondPeersReceived) != 0 {
		t.Fatal("Did not filter out peers with connection issues")
	}

}

func TestRateLimitingRequests(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
253 254
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
255 256 257 258
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()

	keys := testutil.GenerateCids(maxInProcessRequests + 1)
259
	sessionCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
260 261 262
	defer cancel()
	var requestChannels []<-chan peer.ID
	for i := 0; i < maxInProcessRequests+1; i++ {
263
		requestChannels = append(requestChannels, providerQueryManager.FindProvidersAsync(sessionCtx, keys[i]))
264
	}
265 266
	time.Sleep(9 * time.Millisecond)
	fpn.queriesMadeMutex.Lock()
267
	if fpn.queriesMade != maxInProcessRequests {
268
		t.Logf("Queries made: %d\n", fpn.queriesMade)
269 270
		t.Fatal("Did not limit parallel requests to rate limit")
	}
271
	fpn.queriesMadeMutex.Unlock()
272 273 274 275 276
	for i := 0; i < maxInProcessRequests+1; i++ {
		for range requestChannels[i] {
		}
	}

277 278
	fpn.queriesMadeMutex.Lock()
	defer fpn.queriesMadeMutex.Unlock()
279 280 281 282
	if fpn.queriesMade != maxInProcessRequests+1 {
		t.Fatal("Did not make all seperate requests")
	}
}
283 284 285 286 287 288 289 290 291 292

func TestFindProviderTimeout(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()
293
	providerQueryManager.SetFindProviderTimeout(2 * time.Millisecond)
294 295 296 297
	keys := testutil.GenerateCids(1)

	sessionCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel()
298
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, keys[0])
299 300 301 302
	var firstPeersReceived []peer.ID
	for p := range firstRequestChan {
		firstPeersReceived = append(firstPeersReceived, p)
	}
303
	if len(firstPeersReceived) >= len(peers) {
304 305 306
		t.Fatal("Find provider request should have timed out, did not")
	}
}
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

func TestFindProviderPreCanceled(t *testing.T) {
	peers := testutil.GeneratePeers(10)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()
	providerQueryManager.SetFindProviderTimeout(100 * time.Millisecond)
	keys := testutil.GenerateCids(1)

	sessionCtx, cancel := context.WithCancel(ctx)
	cancel()
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, keys[0])
	if firstRequestChan == nil {
		t.Fatal("expected non-nil channel")
	}
	select {
	case <-firstRequestChan:
	case <-time.After(10 * time.Millisecond):
		t.Fatal("shouldn't have blocked waiting on a closed context")
	}
}
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

func TestCancelFindProvidersAfterCompletion(t *testing.T) {
	peers := testutil.GeneratePeers(2)
	fpn := &fakeProviderNetwork{
		peersFound: peers,
		delay:      1 * time.Millisecond,
	}
	ctx := context.Background()
	providerQueryManager := New(ctx, fpn)
	providerQueryManager.Startup()
	providerQueryManager.SetFindProviderTimeout(100 * time.Millisecond)
	keys := testutil.GenerateCids(1)

	sessionCtx, cancel := context.WithCancel(ctx)
	firstRequestChan := providerQueryManager.FindProvidersAsync(sessionCtx, keys[0])
	<-firstRequestChan                // wait for everything to start.
	time.Sleep(10 * time.Millisecond) // wait for the incoming providres to stop.
	cancel()                          // cancel the context.

	timer := time.NewTimer(10 * time.Millisecond)
	defer timer.Stop()
	for {
		select {
		case _, ok := <-firstRequestChan:
			if !ok {
				return
			}
		case <-timer.C:
			t.Fatal("should have finished receiving responses within timeout")
		}
	}
}