batching_test.go 7.09 KB
Newer Older
1
package sources
2 3 4 5 6

import (
	"context"
	"errors"
	"fmt"
7
	"io"
8
	"testing"
9
	"time"
10

11
	"github.com/stretchr/testify/mock"
12
	"github.com/stretchr/testify/require"
13 14 15 16 17 18 19 20 21 22

	"github.com/ethereum/go-ethereum/rpc"
)

type elemCall struct {
	id  int
	err bool
}

type batchCall struct {
23 24 25 26 27 28
	elems  []elemCall
	rpcErr error
	err    string
	// Artificial delay to add before returning the call
	duration time.Duration
	makeCtx  func() context.Context
29 30 31 32 33 34
}

type batchTestCase struct {
	name  string
	items int

35
	batchSize int
36

37 38
	batchCalls  []batchCall
	singleCalls []elemCall
39 40 41 42

	mock.Mock
}

43 44 45 46
func makeTestRequest(i int) (*string, rpc.BatchElem) {
	out := new(string)
	return out, rpc.BatchElem{
		Method: "testing_foobar",
47
		Args:   []any{i},
48 49 50 51 52
		Result: out,
		Error:  nil,
	}
}

53
func (tc *batchTestCase) GetBatch(ctx context.Context, b []rpc.BatchElem) error {
54 55 56
	if ctx.Err() != nil {
		return ctx.Err()
	}
57 58 59 60 61 62 63 64
	return tc.Mock.MethodCalled("getBatch", b).Get(0).([]error)[0]
}

func (tc *batchTestCase) GetSingle(ctx context.Context, result any, method string, args ...any) error {
	if ctx.Err() != nil {
		return ctx.Err()
	}
	return tc.Mock.MethodCalled("getSingle", (*(result.(*interface{}))).(*string), method, args[0]).Get(0).([]error)[0]
65 66
}

67 68
var mockErr = errors.New("mockErr")

69
func (tc *batchTestCase) Run(t *testing.T) {
70 71 72 73
	keys := make([]int, tc.items)
	for i := 0; i < tc.items; i++ {
		keys[i] = i
	}
74

75
	makeBatchMock := func(bc batchCall) func(args mock.Arguments) {
76
		return func(args mock.Arguments) {
77
			batch := args[0].([]rpc.BatchElem)
78 79 80 81 82 83 84
			for i, elem := range batch {
				id := elem.Args[0].(int)
				expectedID := bc.elems[i].id
				require.Equal(t, expectedID, id, "batch element should match expected batch element")
				if bc.elems[i].err {
					batch[i].Error = mockErr
					*batch[i].Result.(*string) = ""
85 86
				} else {
					batch[i].Error = nil
87
					*batch[i].Result.(*string) = fmt.Sprintf("mock result id %d", id)
88 89
				}
			}
90 91
			time.Sleep(bc.duration)
		}
92
	}
93
	// mock all the results of the batch calls
94
	for _, bc := range tc.batchCalls {
95 96 97 98
		var batch []rpc.BatchElem
		for _, elem := range bc.elems {
			batch = append(batch, rpc.BatchElem{
				Method: "testing_foobar",
99
				Args:   []any{elem.id},
100 101 102 103 104
				Result: new(string),
				Error:  nil,
			})
		}
		if len(bc.elems) > 0 {
105 106 107 108 109 110 111 112 113 114 115 116 117
			tc.On("getBatch", batch).Once().Run(makeBatchMock(bc)).Return([]error{bc.rpcErr}) // wrap to preserve nil as type of error
		}
	}
	makeSingleMock := func(ec elemCall) func(args mock.Arguments) {
		return func(args mock.Arguments) {
			result := args[0].(*string)
			id := args[2].(int)
			require.Equal(t, ec.id, id, "element should match expected element")
			if ec.err {
				*result = ""
			} else {
				*result = fmt.Sprintf("mock result id %d", id)
			}
118 119
		}
	}
120 121 122 123 124 125 126 127 128
	// mock the results of unbatched calls
	for _, ec := range tc.singleCalls {
		var ret error
		if ec.err {
			ret = mockErr
		}
		tc.On("getSingle", new(string), "testing_foobar", ec.id).Once().Run(makeSingleMock(ec)).Return([]error{ret})
	}
	iter := NewIterativeBatchCall[int, *string](keys, makeTestRequest, tc.GetBatch, tc.GetSingle, tc.batchSize)
129 130 131 132 133
	for i, bc := range tc.batchCalls {
		ctx := context.Background()
		if bc.makeCtx != nil {
			ctx = bc.makeCtx()
		}
134

135 136 137 138 139 140 141 142 143 144 145 146
		err := iter.Fetch(ctx)
		if err == io.EOF {
			require.Equal(t, i, len(tc.batchCalls)-1, "EOF only on last call")
		} else {
			require.False(t, iter.Complete())
			if bc.err == "" {
				require.NoError(t, err)
			} else {
				require.ErrorContains(t, err, bc.err)
			}
		}
	}
147 148 149 150 151 152 153 154 155 156 157 158 159 160
	for i, ec := range tc.singleCalls {
		ctx := context.Background()
		err := iter.Fetch(ctx)
		if err == io.EOF {
			require.Equal(t, i, len(tc.singleCalls)-1, "EOF only on last call")
		} else {
			require.False(t, iter.Complete())
			if ec.err {
				require.Error(t, err)
			} else {
				require.NoError(t, err)
			}
		}
	}
161 162 163 164 165 166 167 168 169 170 171
	require.True(t, iter.Complete(), "batch iter should be complete after the expected calls")
	out, err := iter.Result()
	require.NoError(t, err)
	for i, v := range out {
		require.NotNil(t, v)
		require.Equal(t, fmt.Sprintf("mock result id %d", i), *v)
	}
	out2, err := iter.Result()
	require.NoError(t, err)
	require.Equal(t, out, out2, "cached result should match")
	require.Equal(t, io.EOF, iter.Fetch(context.Background()), "fetch after completion should EOF")
172 173 174 175 176 177 178

	tc.AssertExpectations(t)
}

func TestFetchBatched(t *testing.T) {
	testCases := []*batchTestCase{
		{
179 180 181
			name:       "empty",
			items:      0,
			batchCalls: []batchCall{},
182 183
		},
		{
184 185 186
			name:      "simple",
			items:     4,
			batchSize: 4,
187 188 189 190 191 192 193 194
			batchCalls: []batchCall{
				{
					elems: []elemCall{
						{id: 0, err: false},
						{id: 1, err: false},
						{id: 2, err: false},
						{id: 3, err: false},
					},
195
					err: "",
196 197 198
				},
			},
		},
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
		{
			name:      "single element",
			items:     1,
			batchSize: 4,
			singleCalls: []elemCall{
				{id: 0, err: false},
			},
		},
		{
			name:      "unbatched",
			items:     4,
			batchSize: 1,
			singleCalls: []elemCall{
				{id: 0, err: false},
				{id: 1, err: false},
				{id: 2, err: false},
				{id: 3, err: false},
			},
		},
		{
			name:      "unbatched with retry",
			items:     4,
			batchSize: 1,
			singleCalls: []elemCall{
				{id: 0, err: false},
				{id: 1, err: true},
				{id: 2, err: false},
				{id: 3, err: false},
				{id: 1, err: false},
			},
		},
230
		{
231 232 233
			name:      "split",
			items:     5,
			batchSize: 3,
234 235 236 237 238 239 240
			batchCalls: []batchCall{
				{
					elems: []elemCall{
						{id: 0, err: false},
						{id: 1, err: false},
						{id: 2, err: false},
					},
241
					err: "",
242 243 244 245 246 247
				},
				{
					elems: []elemCall{
						{id: 3, err: false},
						{id: 4, err: false},
					},
248
					err: "",
249 250 251 252
				},
			},
		},
		{
253 254 255
			name:      "efficient retry",
			items:     7,
			batchSize: 2,
256 257 258 259
			batchCalls: []batchCall{
				{
					elems: []elemCall{
						{id: 0, err: false},
260
						{id: 1, err: true},
261
					},
262
					err: "1 error occurred:",
263 264 265 266
				},
				{
					elems: []elemCall{
						{id: 2, err: false},
267
						{id: 3, err: false},
268
					},
269
					err: "",
270 271
				},
				{
272 273 274
					elems: []elemCall{ // in-process before retry even happens
						{id: 4, err: false},
						{id: 5, err: false},
275
					},
276
					err: "",
277 278 279
				},
				{
					elems: []elemCall{
280 281
						{id: 6, err: false},
						{id: 1, err: false}, // includes the element to retry
282
					},
283
					err: "",
284 285 286 287
				},
			},
		},
		{
288 289 290
			name:      "repeated sequential retries",
			items:     2,
			batchSize: 2,
291 292 293
			batchCalls: []batchCall{
				{
					elems: []elemCall{
294
						{id: 0, err: true},
295 296
						{id: 1, err: true},
					},
297
					err: "2 errors occurred:",
298 299 300
				},
				{
					elems: []elemCall{
301
						{id: 0, err: false},
302 303
						{id: 1, err: true},
					},
304
					err: "1 error occurred:",
305 306 307 308 309
				},
				{
					elems: []elemCall{
						{id: 1, err: false},
					},
310
					err: "",
311 312 313 314
				},
			},
		},
		{
315
			name:      "context timeout",
316
			items:     2,
317
			batchSize: 3,
318 319
			batchCalls: []batchCall{
				{
320 321 322 323 324 325
					elems: nil,
					err:   context.Canceled.Error(),
					makeCtx: func() context.Context {
						ctx, cancel := context.WithCancel(context.Background())
						cancel()
						return ctx
326 327 328 329
					},
				},
				{
					elems: []elemCall{
330
						{id: 0, err: false},
331
						{id: 1, err: false},
332
					},
333
					err: "",
334 335 336 337 338 339 340 341
				},
			},
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, tc.Run)
	}
}