-
Notifications
You must be signed in to change notification settings - Fork 107
/
partition_test.go
713 lines (589 loc) · 17.8 KB
/
partition_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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
package server
import (
"context"
"testing"
"time"
"github.com/Workiva/go-datastructures/queue"
lift "github.com/liftbridge-io/go-liftbridge/v2"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/require"
client "github.com/liftbridge-io/liftbridge-api/go"
proto "github.com/liftbridge-io/liftbridge/server/protocol"
)
func createServer() *Server {
config := getTestConfig("a", true, 0)
return New(config)
}
func waitForCommitQueue(t *testing.T, timeout time.Duration, size int64, partition *partition) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if partition.commitQueue.Len() == size {
return
}
time.Sleep(15 * time.Millisecond)
}
stackFatalf(t, "Commit queue did not reach size %d", size)
}
func waitForPause(t *testing.T, timeout time.Duration, partition *partition) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if partition.IsPaused() {
return
}
time.Sleep(time.Millisecond)
}
stackFatalf(t, "Partition did not pause in time")
}
// Ensure commitLoop commits messages in the queue when they have been
// replicated by all replicas in the ISR. This is done by removing committed
// messages and updating the HW. Ensure acks are not sent when the AckPolicy is
// not AckPolicy_ALL.
func TestPartitionCommitLoopCommitNoAck(t *testing.T) {
defer cleanupStorage(t)
// Start Liftbridge server.
server := createServer()
require.NoError(t, server.Start())
defer server.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b"},
Leader: "a",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.commitQueue = queue.New(5)
// Subscribe to ack inbox.
ackInbox := "ack"
sub, err := nc.SubscribeSync(ackInbox)
require.NoError(t, err)
nc.Flush()
// Put some messages in the queue.
p.commitQueue.Put(&client.Ack{Offset: 0, AckInbox: ackInbox})
p.commitQueue.Put(&client.Ack{Offset: 1, AckInbox: ackInbox})
p.commitQueue.Put(&client.Ack{Offset: 2, AckInbox: ackInbox})
// Mark 0 and 1 as fully replicated.
p.isr["a"].offset = 1
p.isr["b"].offset = 2
// Start commit loop.
stop := make(chan struct{})
go p.commitLoop(stop)
// Trigger a commit.
p.commitCheck <- struct{}{}
// Wait for messages to be committed.
waitForCommitQueue(t, 5*time.Second, 1, p)
// Stop the loop.
close(stop)
// Verify HW.
require.Equal(t, int64(1), p.log.HighWatermark())
// Ensure no acks were published.
_, err = sub.NextMsg(500 * time.Millisecond)
require.Error(t, err)
}
// Ensure commitLoop commits messages in the queue when they have been
// replicated by all replicas in the ISR. This is done by removing committed
// messages and updating the HW. Ensure acks are sent when the AckPolicy is
// AckPolicy_ALL.
func TestPartitionCommitLoopCommitAck(t *testing.T) {
defer cleanupStorage(t)
// Start Liftbridge server.
server := createServer()
require.NoError(t, server.Start())
defer server.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b"},
Leader: "a",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.commitQueue = queue.New(5)
// Subscribe to ack inbox.
ackInbox := "ack"
sub, err := nc.SubscribeSync(ackInbox)
require.NoError(t, err)
nc.Flush()
// Put some messages in the queue.
p.commitQueue.Put(&client.Ack{Offset: 0, AckInbox: ackInbox, AckPolicy: client.AckPolicy_ALL})
p.commitQueue.Put(&client.Ack{Offset: 1, AckInbox: ackInbox})
p.commitQueue.Put(&client.Ack{Offset: 2, AckInbox: ackInbox, AckPolicy: client.AckPolicy_ALL})
// Mark messages as fully replicated.
p.isr["a"].offset = 2
p.isr["b"].offset = 2
// Start commit loop.
stop := make(chan struct{})
go p.commitLoop(stop)
// Trigger a commit.
p.commitCheck <- struct{}{}
// Wait for messages to be committed.
waitForCommitQueue(t, 5*time.Second, 0, p)
// Stop the loop.
close(stop)
// Verify HW.
require.Equal(t, int64(2), p.log.HighWatermark())
// Ensure acks were published.
_, err = sub.NextMsg(5 * time.Second)
require.NoError(t, err)
_, err = sub.NextMsg(5 * time.Second)
require.NoError(t, err)
}
// Ensure commitLoop is a no-op when the commitQueue is empty.
func TestPartitionCommitLoopEmptyQueue(t *testing.T) {
defer cleanupStorage(t)
// Start Liftbridge server.
server := createServer()
require.NoError(t, server.Start())
defer server.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b"},
Leader: "a",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.commitQueue = queue.New(5)
// Subscribe to ack inbox.
ackInbox := "ack"
sub, err := nc.SubscribeSync(ackInbox)
require.NoError(t, err)
nc.Flush()
// Start commit loop.
stop := make(chan struct{})
exited := make(chan struct{})
go func() {
p.commitLoop(stop)
close(exited)
}()
// Trigger a commit.
p.commitCheck <- struct{}{}
// Stop the loop.
close(stop)
select {
case <-exited:
case <-time.After(5 * time.Second):
t.Fatal("Expected commit loop to exit")
}
// Verify HW.
require.Equal(t, int64(-1), p.log.HighWatermark())
// Ensure no acks were published.
_, err = sub.NextMsg(500 * time.Millisecond)
require.Error(t, err)
}
// Ensure commitLoop exits when the queue is disposed.
func TestPartitionCommitLoopDisposedQueue(t *testing.T) {
defer cleanupStorage(t)
// Start Liftbridge server.
server := createServer()
require.NoError(t, server.Start())
defer server.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b"},
Leader: "a",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.commitQueue = queue.New(5)
// Subscribe to ack inbox.
ackInbox := "ack"
sub, err := nc.SubscribeSync(ackInbox)
require.NoError(t, err)
nc.Flush()
// Put some messages in the queue.
p.commitQueue.Put(&client.Ack{Offset: 0, AckInbox: ackInbox})
p.commitQueue.Put(&client.Ack{Offset: 1, AckInbox: ackInbox})
p.commitQueue.Put(&client.Ack{Offset: 2, AckInbox: ackInbox})
// Mark 0 and 1 as fully replicated.
p.isr["a"].offset = 1
p.isr["b"].offset = 2
// Start commit loop.
exited := make(chan struct{})
go func() {
p.commitLoop(make(chan struct{}))
close(exited)
}()
// Dispose commit queue.
p.commitQueue.Dispose()
// Trigger a commit.
p.commitCheck <- struct{}{}
// Verify HW.
require.Equal(t, int64(-1), p.log.HighWatermark())
// Ensure no acks were published.
_, err = sub.NextMsg(500 * time.Millisecond)
require.Error(t, err)
// Ensure loop exited.
select {
case <-exited:
case <-time.After(5 * time.Second):
t.Fatal("Expected commit loop to exit")
}
}
// Ensure commitLoop does not commit messages in the queue if the ISR is below
// the minimum ISR size.
func TestPartitionCommitLoopNoCommitBelowMinISR(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
server.config.Clustering.MinISR = 2
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b"},
Leader: "a",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.commitQueue = queue.New(5)
require.NoError(t, p.RemoveFromISR("b"))
// Put some messages in the queue.
p.commitQueue.Put(&client.Ack{Offset: 0})
p.commitQueue.Put(&client.Ack{Offset: 1})
p.commitQueue.Put(&client.Ack{Offset: 2})
// Mark 0 and 1 as fully replicated.
p.isr["a"].offset = 1
// Start commit loop.
stop := make(chan struct{})
exited := make(chan struct{})
go func() {
p.commitLoop(stop)
close(exited)
}()
// Trigger a commit.
p.commitCheck <- struct{}{}
// Stop the loop.
close(stop)
// Ensure loop exited.
select {
case <-exited:
case <-time.After(5 * time.Second):
t.Fatal("Expected commit loop to exit")
}
// Verify nothing was committed.
require.Equal(t, int64(3), p.commitQueue.Len())
require.Equal(t, int64(-1), p.log.HighWatermark())
}
// Ensure RemoveFromISR returns an error if the replica is not a stream
// replica.
func TestPartitionRemoveFromISRNotReplica(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
}, false, nil)
require.NoError(t, err)
defer p.Close()
require.Error(t, p.RemoveFromISR("foo"))
}
// Ensure RemoveFromISR removes the replica from the ISR and does not trigger a
// commit check on the follower.
func TestPartitionRemoveFromISRFollower(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b", "c"},
Leader: "b",
Isr: []string{"a", "b", "c"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
require.NoError(t, p.RemoveFromISR("b"))
// Verify there is no commit check.
select {
case <-p.commitCheck:
t.Fatal("Unexpected commit check")
default:
}
require.ElementsMatch(t, []string{"a", "c"}, p.GetISR())
require.False(t, p.belowMinISR)
}
// Ensure RemoveFromISR removes the replica from the ISR and triggers a commit
// check on the leader.
func TestPartitionRemoveFromISRLeader(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b", "c"},
Leader: "a",
Isr: []string{"a", "b", "c"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.isLeading = true
require.NoError(t, p.RemoveFromISR("b"))
// Verify there is a commit check.
select {
case <-p.commitCheck:
default:
t.Fatal("Did not get expected commit check")
}
require.ElementsMatch(t, []string{"a", "c"}, p.GetISR())
require.False(t, p.belowMinISR)
p.isLeading = false
}
// Ensure RemoveFromISR removes the replica from the ISR and marks the stream
// as below the minimum ISR when the ISR shrinks below the minimum.
func TestPartitionRemoveFromISRBelowMin(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
server.config.Clustering.MinISR = 3
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b", "c"},
Leader: "b",
Isr: []string{"a", "b", "c"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
require.NoError(t, p.RemoveFromISR("b"))
require.ElementsMatch(t, []string{"a", "c"}, p.GetISR())
require.True(t, p.belowMinISR)
}
// Ensure AddToISR returns an error if the replica is not a stream replica.
func TestPartitionAddToISRNotReplica(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
}, false, nil)
require.NoError(t, err)
defer p.Close()
require.Error(t, p.AddToISR("foo"))
}
// Ensure AddToISR adds the replica to the ISR.
func TestPartitionAddToISR(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b", "c"},
Leader: "b",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
require.ElementsMatch(t, []string{"a", "b"}, p.GetISR())
require.NoError(t, p.AddToISR("c"))
require.ElementsMatch(t, []string{"a", "b", "c"}, p.GetISR())
}
// Ensure AddToISR adds the replica to the ISR and, if the stream was below the
// minimum ISR and has recovered, marks the stream ISR as recovered.
func TestPartitionAddToISRRecoverMin(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
server.config.Clustering.MinISR = 3
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b", "c"},
Leader: "b",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
p.belowMinISR = true
require.ElementsMatch(t, []string{"a", "b"}, p.GetISR())
require.NoError(t, p.AddToISR("c"))
require.ElementsMatch(t, []string{"a", "b", "c"}, p.GetISR())
require.False(t, p.belowMinISR)
}
// Ensure replicationRequestLoop's idle follower sleep is preempted when a
// partition notification is received.
func TestPartitionReplicationRequestLoopPreempt(t *testing.T) {
defer cleanupStorage(t)
// Start Liftbridge server.
config := getTestConfig("a", true, 5050)
// Set idle wait long enough that it shouldn't be reached.
config.Clustering.ReplicaMaxIdleWait = time.Hour
server := runServerWithConfig(t, config)
defer server.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b"},
Leader: "b",
Isr: []string{"a", "b"},
}, false, nil)
require.NoError(t, err)
defer p.Close()
leaderEpoch := uint64(1)
// Set up mock leader.
requests := make(chan struct{}, 2)
_, err = nc.Subscribe(p.getReplicationRequestInbox(), func(msg *nats.Msg) {
// Send empty replication response.
resp := make([]byte, 16)
proto.Encoding.PutUint64(resp, leaderEpoch)
proto.Encoding.PutUint64(resp[8:], 0)
msg.Respond(resp)
requests <- struct{}{}
})
require.NoError(t, err)
require.NoError(t, nc.Flush())
stop := make(chan struct{})
defer close(stop)
go p.replicationRequestLoop("b", leaderEpoch, stop)
select {
case <-requests:
case <-time.After(5 * time.Second):
t.Fatal("Expected replication request")
}
// Notify partition to preempt sleep.
p.Notify()
select {
case <-requests:
case <-time.After(5 * time.Second):
t.Fatal("Expected replication request")
}
}
// Ensure that a new partition can be created with custom StreamConfig.
func TestPartitionWithCustomConfigNoError(t *testing.T) {
defer cleanupStorage(t)
server := createServer()
customStreamConfig := &proto.StreamConfig{
RetentionMaxMessages: &proto.NullableInt64{Value: 1000},
}
p, err := server.newPartition(&proto.Partition{
Subject: "foo",
Stream: "foo",
Replicas: []string{"a", "b", "c"},
Leader: "b",
Isr: []string{"a", "b"},
}, false, customStreamConfig)
require.NoError(t, err)
defer p.Close()
}
// Ensure when streams.auto.pause.time is enabled, partitions automatically
// pause when idle.
func TestPartitionAutoPause(t *testing.T) {
defer cleanupStorage(t)
// Configure server.
s1Config := getTestConfig("a", true, 5050)
autoPauseTime := 100 * time.Millisecond
s1Config.Streams.AutoPauseTime = autoPauseTime
s1 := runServerWithConfig(t, s1Config)
defer s1.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
// Wait for server to elect itself leader.
getMetadataLeader(t, 10*time.Second, s1)
client, err := lift.Connect([]string{"localhost:5050"})
require.NoError(t, err)
defer client.Close()
subject := "foo"
name := "foo"
// Start publishing to stream subject to keep it active.
stop := make(chan struct{})
go func() {
for {
select {
case <-stop:
return
default:
}
nc.Publish(subject, nil)
}
}()
// Create stream
err = client.CreateStream(context.Background(), subject, name)
require.NoError(t, err)
// Stop publishing to trigger a pause.
close(stop)
before := time.Now()
waitForPause(t, 2*time.Second, s1.metadata.GetPartition(name, 0))
require.True(t, time.Since(before) > autoPauseTime)
}
// Ensure when streams.auto.pause.disable.if.subscribers is enabled, partitions
// automatically pause when idle only if there is no subscriber.
func TestPartitionAutoPauseDisableIfSubscribers(t *testing.T) {
defer cleanupStorage(t)
// Configure server.
s1Config := getTestConfig("a", true, 5050)
autoPauseTime := 100 * time.Millisecond
s1Config.Streams.AutoPauseTime = autoPauseTime
s1Config.Streams.AutoPauseDisableIfSubscribers = true
s1 := runServerWithConfig(t, s1Config)
defer s1.Stop()
// Create NATS connection.
nc, err := nats.GetDefaultOptions().Connect()
require.NoError(t, err)
defer nc.Close()
// Wait for server to elect itself leader.
getMetadataLeader(t, 10*time.Second, s1)
client, err := lift.Connect([]string{"localhost:5050"})
require.NoError(t, err)
defer client.Close()
subject := "foo"
name := "foo"
// Start publishing to stream subject to keep it active.
stop := make(chan struct{})
go func() {
for {
select {
case <-stop:
return
default:
}
nc.Publish(subject, nil)
}
}()
// Create stream
err = client.CreateStream(context.Background(), subject, name)
require.NoError(t, err)
// Subscribe to the stream.
err = client.Subscribe(context.Background(), name, func(msg *lift.Message, err error) {})
require.NoError(t, err)
// Stop publishing.
close(stop)
// Wait some time.
time.Sleep(200 * time.Millisecond)
// Check that the partition has not been paused.
partition := s1.metadata.GetPartition(name, 0)
require.False(t, partition.IsPaused())
waitForPartition(t, time.Second, name, 0)
}
// Ensure computeTick correctly computes the sleep time for the tick loop based
// on the elapsed time.
func TestComputeTick(t *testing.T) {
maxSleep := 10 * time.Second
require.Equal(t, time.Duration(0), computeTick(maxSleep, maxSleep))
require.Equal(t, time.Second, computeTick(9*time.Second, maxSleep))
require.Equal(t, 9*time.Second, computeTick(time.Second, maxSleep))
require.Equal(t, maxSleep, computeTick(15*time.Second, maxSleep))
require.Equal(t, maxSleep, computeTick(0, maxSleep))
}