-
Notifications
You must be signed in to change notification settings - Fork 0
/
leader_state_test.go
369 lines (298 loc) · 7.16 KB
/
leader_state_test.go
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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
230
231
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
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
package gonsensus
import (
"context"
"encoding/json"
"errors"
"log"
"sync"
"testing"
"time"
)
var (
errFailedToVerifyObserverCount = errors.New("failed to verify observer count after retries")
errSimulated = errors.New("simulated error")
)
func TestLeaderCallbacks(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setupMock func(*MockS3Client)
injectError func(*MockS3Client)
expectElected bool
expectDemoted bool
}{
{
name: "Successfully becomes leader",
setupMock: nil, // Start with no lock
injectError: nil,
expectElected: true,
expectDemoted: false,
},
{
name: "Fails to become leader due to existing lock",
setupMock: func(mockClient *MockS3Client) {
mockClient.mu.Lock()
defer mockClient.mu.Unlock()
lock := LockInfo{
Node: "other-node",
Timestamp: time.Now(),
Expiry: time.Now().Add(30 * time.Second),
Term: 1,
Version: "1",
}
data, err := json.Marshal(lock)
if err != nil {
log.Panic("mock setup fail")
}
mockClient.objects["locks/leader"] = data
},
injectError: nil,
expectElected: false,
expectDemoted: false,
},
{
name: "Becomes leader but then loses leadership",
setupMock: nil, // Start with no lock
injectError: func(mockClient *MockS3Client) {
mockClient.mu.Lock()
defer mockClient.mu.Unlock()
// Simulate failure during lock renewal
mockClient.putError = errSimulated
},
expectElected: true,
expectDemoted: true,
},
}
for _, tCase := range tests {
t.Run(tCase.name, func(t *testing.T) {
t.Parallel()
mockS3 := NewMockS3Client()
if tCase.setupMock != nil {
tCase.setupMock(mockS3)
}
elected := make(chan struct{}, 1)
demoted := make(chan struct{}, 1)
manager, err := NewManager(mockS3, "test-bucket", Config{
TTL: 2 * time.Second, // Short TTL for testing
PollInterval: 500 * time.Millisecond,
NodeID: "test-node",
LockPrefix: "locks/",
})
if err != nil {
t.Fatalf("failed to create manager: %v", err)
}
manager.SetCallbacks(
func(_ context.Context) error {
elected <- struct{}{}
return nil
},
func(_ context.Context) {
demoted <- struct{}{}
},
)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Start leadership monitoring in background
var wGroup sync.WaitGroup
wGroup.Add(1)
go func() {
defer wGroup.Done()
err := manager.Run(ctx)
if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("unexpected error from Run: %v", err)
}
}()
// Wait for initial election attempt
time.Sleep(1 * time.Second)
// Inject error if configured
if tCase.injectError != nil {
tCase.injectError(mockS3)
}
// Wait for callbacks
var gotElected, gotDemoted bool
// Use select to check for callbacks
checkCallbacks := func() {
select {
case <-elected:
gotElected = true
default:
}
select {
case <-demoted:
gotDemoted = true
default:
}
}
// Check multiple times over 3 seconds
for range 6 {
checkCallbacks()
time.Sleep(500 * time.Millisecond)
}
// Cancel context and wait for cleanup
cancel()
wGroup.Wait()
if gotElected != tCase.expectElected {
t.Errorf("expected elected=%v, got %v", tCase.expectElected, gotElected)
}
if gotDemoted != tCase.expectDemoted {
t.Errorf("expected demoted=%v, got %v", tCase.expectDemoted, gotDemoted)
}
})
}
}
func setupTestManager() *Manager {
return &Manager{
s3Client: NewMockS3Client(),
bucket: "test-bucket",
lockKey: "test-lock",
ttl: time.Second,
nodeID: "test-node",
lease: NewLease(), // Important: Initialize the lease
onElected: func(context.Context) error { return nil },
onDemoted: func(context.Context) {},
quorumSize: 3,
}
}
func TestLeaderState_RaceConditions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
fn func(*testing.T, *leaderState)
}{
{
name: "concurrent leader state changes",
fn: testConcurrentLeaderStateChanges,
},
{
name: "concurrent maintenance and demotion",
fn: testConcurrentMaintenanceAndDemotion,
},
{
name: "concurrent election attempts",
fn: testConcurrentElectionAttempts,
},
}
for _, testCase := range tests {
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
state := &leaderState{
manager: setupTestManager(),
}
testCase.fn(t, state)
})
}
}
func testConcurrentLeaderStateChanges(t *testing.T, state *leaderState) {
t.Helper()
var wGroup sync.WaitGroup
iterations := 100 // Reduced for faster tests
// Multiple goroutines changing leader state
for range 5 {
wGroup.Add(1)
go func() {
defer wGroup.Done()
for range iterations {
state.setLeader(true)
_ = state.getIsLeader()
state.setLeader(false)
}
}()
}
// Multiple goroutines reading leader state
for range 5 {
wGroup.Add(1)
go func() {
defer wGroup.Done()
for range iterations {
_ = state.getIsLeader()
}
}()
}
wGroup.Wait()
}
func testConcurrentMaintenanceAndDemotion(t *testing.T, state *leaderState) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
var wGroup sync.WaitGroup
wGroup.Add(2)
// Start maintenance loop
go func() {
defer wGroup.Done()
state.setLeader(true)
_ = state.runLeaderMaintenance(ctx)
}()
// Concurrent demotions
go func() {
defer wGroup.Done()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
state.handleDemotion(ctx)
}
}
}()
wGroup.Wait()
}
func testConcurrentElectionAttempts(t *testing.T, state *leaderState) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
var wGroup sync.WaitGroup
iterations := 10 // Reduced for faster tests
// Multiple goroutines trying to become leader
for range 5 {
wGroup.Add(1)
go func() {
defer wGroup.Done()
for range iterations {
select {
case <-ctx.Done():
return
default:
_ = state.tryBecomeLeader(ctx)
time.Sleep(time.Millisecond) // Add small delay to reduce contention
}
}
}()
}
// Concurrent state checks
wGroup.Add(1)
go func() {
defer wGroup.Done()
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_ = state.getIsLeader()
}
}
}()
wGroup.Wait()
}
// Additional helper test to verify basic functionality.
func TestLeaderState_BasicOperations(t *testing.T) {
t.Parallel()
state := &leaderState{
manager: setupTestManager(),
}
// Test basic leader state changes
if state.getIsLeader() {
t.Error("Expected initial state to be not leader")
}
state.setLeader(true)
if !state.getIsLeader() {
t.Error("Expected state to be leader after setting")
}
state.setLeader(false)
if state.getIsLeader() {
t.Error("Expected state to not be leader after unsetting")
}
}