-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathselector_iterator_test.go
More file actions
119 lines (101 loc) · 4.21 KB
/
Copy pathselector_iterator_test.go
File metadata and controls
119 lines (101 loc) · 4.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
69
70
71
72
73
74
75
76
77
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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package sherdlock_test
import (
"context"
"runtime"
"sync"
"sync/atomic"
"testing"
"github.com/LFDT-Panurus/panurus/token/services/selector/sherdlock"
"github.com/LFDT-Panurus/panurus/token/services/selector/sherdlock/mocks"
token2 "github.com/LFDT-Panurus/panurus/token/token"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestSelectorClosesDisplacedIterators verifies that every iterator the retry
// loop replaces is closed. Previously `selectInternal` overwrote `s.cache` on
// each immediate retry without closing the iterator it displaced, leaking a
// database cursor and its pooled connection per retry. See #2019.
func TestSelectorClosesDisplacedIterators(t *testing.T) {
_, metrics := setupMetricsMocks()
mockFetcher := &mocks.FakeTokenFetcher{}
mockLocker := &mocks.FakeTokenLocker{}
var mu sync.Mutex
var iterators []*mocks.FakeIterator[*token2.UnspentTokenInWallet]
mockFetcher.UnspentTokensIteratorByStub = func(_ context.Context, _ string, _ token2.Type) (sherdlock.Iterator[*token2.UnspentTokenInWallet], error) {
it := &mocks.FakeIterator[*token2.UnspentTokenInWallet]{}
// One token, always locked by someone else, then exhausted: this drives a
// refresh of the cache on every pass through the loop.
it.NextReturnsOnCall(0, &token2.UnspentTokenInWallet{
Id: token2.ID{TxId: "tx1", Index: 0},
Type: "ABC",
Quantity: "100",
}, nil)
it.NextReturnsOnCall(1, nil, nil)
mu.Lock()
defer mu.Unlock()
iterators = append(iterators, it)
return it, nil
}
// Every token appears locked by another process, so the selector exhausts its
// immediate retries and gives up with SufficientButLockedFunds.
mockLocker.TryLockReturns(false, nil)
s := sherdlock.NewSelector(sherdlock.Logger(), mockFetcher, mockLocker, 64, metrics)
_, _, err := s.Select(t.Context(), &unitTestMockOwnerFilter{id: "alice"}, "50", "ABC")
require.Error(t, err)
mu.Lock()
defer mu.Unlock()
require.NotEmpty(t, iterators, "the retry loop must have refreshed the cache at least once")
// All but the last iterator were displaced by a refresh and must be closed.
for i, it := range iterators[:len(iterators)-1] {
assert.Equal(t, 1, it.CloseCallCount(), "displaced iterator %d was leaked", i)
}
// The last one is still the current cache; Close must release it.
require.NoError(t, s.Close())
assert.Equal(t, 1, iterators[len(iterators)-1].CloseCallCount(), "the current iterator must be closed by Close")
}
// TestSelectorCloseDuringRetryIsRaceFree runs Close concurrently with a retrying
// Select. Under `-race` this covers the unsynchronized reads and writes of
// `s.cache` inside `selectInternal`, which could also nil-dereference when Close
// won the race between the closed check and the iterator read. See #2019.
func TestSelectorCloseDuringRetryIsRaceFree(t *testing.T) {
_, metrics := setupMetricsMocks()
mockFetcher := &mocks.FakeTokenFetcher{}
mockLocker := &mocks.FakeTokenLocker{}
var created atomic.Int64
mockFetcher.UnspentTokensIteratorByStub = func(_ context.Context, _ string, _ token2.Type) (sherdlock.Iterator[*token2.UnspentTokenInWallet], error) {
created.Add(1)
it := &mocks.FakeIterator[*token2.UnspentTokenInWallet]{}
it.NextReturnsOnCall(0, &token2.UnspentTokenInWallet{
Id: token2.ID{TxId: "tx1", Index: 0},
Type: "ABC",
Quantity: "100",
}, nil)
it.NextReturnsOnCall(1, nil, nil)
return it, nil
}
mockLocker.TryLockReturns(false, nil)
s := sherdlock.NewSelector(sherdlock.Logger(), mockFetcher, mockLocker, 64, metrics)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
// Either outcome is valid: locked funds, or "already closed" if Close won.
_, _, _ = s.Select(t.Context(), &unitTestMockOwnerFilter{id: "alice"}, "50", "ABC")
}()
go func() {
defer wg.Done()
// Give the selector a chance to enter the retry loop before closing it.
for created.Load() == 0 {
runtime.Gosched()
}
_ = s.Close()
}()
wg.Wait()
// Whoever ran last, the selector ends up closed and stays closed.
_, _, err := s.Select(t.Context(), &unitTestMockOwnerFilter{id: "alice"}, "50", "ABC")
require.ErrorContains(t, err, "selector is already closed")
}