forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
suite.go
1217 lines (999 loc) · 38.1 KB
/
suite.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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Package test contains a backend acceptance test suite that is backend implementation independent
// each backend will use the suite to test itself
package test
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/stretchr/testify/require"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/backend"
)
var (
ErrMirrorNotSupported = errors.New("mirror mode not supported")
ErrConcurrentAccessNotSupported = errors.New("concurrent access not supported")
)
type ConstructionOptions struct {
MirrorMode bool
// ConcurrentBackend indicates that the Backend Constructor function should not
// create an entirely independent data store, but instead should create a
// new interface to the same underlying data store as `ConcurrentBackend`.
ConcurrentBackend backend.Backend
}
// ApplyOptions constructs a new `ConstructionOptions` value from a
// sensible default and then applies the supplied options to it.
func ApplyOptions(options []ConstructionOption) (*ConstructionOptions, error) {
result := ConstructionOptions{
MirrorMode: false,
}
if err := result.Apply(options); err != nil {
return nil, err
}
return &result, nil
}
// Apply applies a collection of option-setting functions to the
// receiver, modifying it in-place.
func (opts *ConstructionOptions) Apply(options []ConstructionOption) error {
for _, opt := range options {
if err := opt(opts); err != nil {
return err
}
}
return nil
}
// ConstructionOption describes a named-parameter setting function for
// configuring a ConstructionOptions instance
type ConstructionOption func(*ConstructionOptions) error
// WithMirrorMode asks the constructor to create a Backend in "mirror mode". Not
// all backends will support this.
func WithMirrorMode(mirror bool) ConstructionOption {
return func(opts *ConstructionOptions) error {
opts.MirrorMode = mirror
return nil
}
}
// WithConcurrentBackend asks the constructor to create a
func WithConcurrentBackend(target backend.Backend) ConstructionOption {
return func(opts *ConstructionOptions) error {
opts.ConcurrentBackend = target
return nil
}
}
// BlockingFakeClock simulates a fake clock by
// sleeping instead of advancing an actual fake clock.
// This is required for backend clients which cannot
// time travel via a fake clock.
type BlockingFakeClock struct {
clockwork.Clock
}
func (r BlockingFakeClock) Advance(d time.Duration) {
if d < 0 {
panic("Invalid argument, negative duration")
}
time.Sleep(d)
}
func (r BlockingFakeClock) BlockUntil(int) {
panic("Not implemented")
}
// Constructor describes a function for constructing new instances of a
// backend, with various options as required by a given test. Note that
// it's the caller's responsibility to close it when the test is finished.
type Constructor func(options ...ConstructionOption) (backend.Backend, clockwork.FakeClock, error)
// RunBackendComplianceSuite runs the entire backend compliance suite,
// creating a collection of named subtests under the context provided
// by `t`.
//
// As each test requires a new backend instance it will invoke the supplied
// `newBackend` function, which callers will use inject instances of the
// backend under test.
func RunBackendComplianceSuite(t *testing.T, newBackend Constructor) {
t.Run("CRUD", func(t *testing.T) {
testCRUD(t, newBackend)
})
t.Run("QueryRange", func(t *testing.T) {
testQueryRange(t, newBackend)
})
t.Run("DeleteRange", func(t *testing.T) {
testDeleteRange(t, newBackend)
})
t.Run("CompareAndSwap", func(t *testing.T) {
testCompareAndSwap(t, newBackend)
})
t.Run("Expiration", func(t *testing.T) {
testExpiration(t, newBackend)
})
t.Run("KeepAlive", func(t *testing.T) {
testKeepAlive(t, newBackend)
})
t.Run("Events", func(t *testing.T) {
testEvents(t, newBackend)
})
t.Run("WatchersClose", func(t *testing.T) {
testWatchersClose(t, newBackend)
})
t.Run("Locking", func(t *testing.T) {
testLocking(t, newBackend)
})
t.Run("ConcurrentOperations", func(t *testing.T) {
testConcurrentOperations(t, newBackend)
})
t.Run("Mirror", func(t *testing.T) {
testMirror(t, newBackend)
})
t.Run("FetchLimit", func(t *testing.T) {
testFetchLimit(t, newBackend)
})
t.Run("Limit", func(t *testing.T) {
testLimit(t, newBackend)
})
t.Run("ConditionalUpdate", func(t *testing.T) {
testConditionalUpdate(t, newBackend)
})
t.Run("ConditionalDelete", func(t *testing.T) {
testConditionalDelete(t, newBackend)
})
}
// RequireItems asserts that the supplied `actual` items collection matches
// the `expected` collection, in size, ordering and the key/value pairs of
// each entry.
func RequireItems(t *testing.T, expected, actual []backend.Item) {
require.Len(t, actual, len(expected))
for i := range expected {
require.Equal(t, expected[i].Key, actual[i].Key)
require.Equal(t, expected[i].Value, actual[i].Value)
require.Equal(t, expected[i].Revision, actual[i].Revision)
}
}
// testCRUD tests create read update scenarios
func testCRUD(t *testing.T, newBackend Constructor) {
uut, _, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
ctx := context.Background()
prefix := MakePrefix()
item := backend.Item{Key: prefix("/hello"), Value: []byte("world")}
// update will fail on non-existent item
_, err = uut.Update(ctx, item)
require.True(t, trace.IsNotFound(err))
lease, err := uut.Create(ctx, item)
require.NoError(t, err)
item.Revision = lease.Revision
// create will fail on existing item
_, err = uut.Create(ctx, item)
require.True(t, trace.IsAlreadyExists(err))
// get succeeds
out, err := uut.Get(ctx, item.Key)
require.NoError(t, err)
require.Equal(t, item.Value, out.Value)
require.Equal(t, item.Revision, out.Revision)
// get range succeeds
res, err := uut.GetRange(ctx, item.Key, backend.RangeEnd(item.Key), backend.NoLimit)
require.NoError(t, err)
require.Len(t, res.Items, 1)
RequireItems(t, []backend.Item{item}, res.Items)
// update succeeds
updated := backend.Item{Key: prefix("/hello"), Value: []byte("world 2")}
lease, err = uut.Update(ctx, updated)
require.NoError(t, err)
out, err = uut.Get(ctx, item.Key)
require.NoError(t, err)
require.Equal(t, updated.Value, out.Value)
require.Equal(t, lease.Revision, out.Revision)
// delete succeeds
require.NoError(t, uut.Delete(ctx, item.Key))
_, err = uut.Get(ctx, item.Key)
require.True(t, trace.IsNotFound(err))
// second delete won't find the item
err = uut.Delete(ctx, item.Key)
require.True(t, trace.IsNotFound(err))
// put new item succeeds
item = backend.Item{Key: prefix("/put"), Value: []byte("world")}
lease, err = uut.Put(ctx, item)
require.NoError(t, err)
out, err = uut.Get(ctx, item.Key)
require.NoError(t, err)
require.Equal(t, item.Value, out.Value)
require.Equal(t, lease.Revision, out.Revision)
// put with large key and binary value succeeds.
// NB: DynamoDB has a maximum overall key length of 1024 bytes, so
// we need to pick a random key size that will still fit in 1KiB
// when combined with the (currently) 33-byte prefix prepended
// by `prefix()`, so:
// (485 bytes * 2 (for hex encoding)) + 33 = 1003
// which gives us a little bit of room to spare
keyBytes := make([]byte, 485)
_, err = rand.Read(keyBytes)
require.NoError(t, err)
key := hex.EncodeToString(keyBytes)
data := make([]byte, 1024)
_, err = rand.Read(data)
require.NoError(t, err)
item = backend.Item{Key: prefix(key), Value: data}
lease, err = uut.Put(ctx, item)
require.NoError(t, err)
out, err = uut.Get(ctx, item.Key)
require.NoError(t, err)
require.Equal(t, item.Value, out.Value)
require.Equal(t, lease.Revision, out.Revision)
}
func testQueryRange(t *testing.T, newBackend Constructor) {
uut, _, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
ctx := context.Background()
prefix := MakePrefix()
outOfScope := backend.Item{Key: prefix("/a"), Value: []byte("should not show up")}
a := backend.Item{Key: prefix("/prefix/a"), Value: []byte("val a")}
b := backend.Item{Key: prefix("/prefix/b"), Value: []byte("val b")}
c1 := backend.Item{Key: prefix("/prefix/c/c1"), Value: []byte("val c1")}
c2 := backend.Item{Key: prefix("/prefix/c/c2"), Value: []byte("val c2")}
// create items and set the revisions received from the lease
for _, item := range []*backend.Item{&outOfScope, &a, &b, &c1, &c2} {
lease, err := uut.Create(ctx, *item)
require.NoError(t, err, "Failed creating value: %q => %q", item.Key, item.Value)
item.Revision = lease.Revision
}
// prefix range fetch
result, err := uut.GetRange(ctx, prefix("/prefix"), backend.RangeEnd(prefix("/prefix")), backend.NoLimit)
require.NoError(t, err)
RequireItems(t, []backend.Item{a, b, c1, c2}, result.Items)
// sub prefix range fetch
result, err = uut.GetRange(ctx, prefix("/prefix/c"), backend.RangeEnd(prefix("/prefix/c")), backend.NoLimit)
require.NoError(t, err)
RequireItems(t, []backend.Item{c1, c2}, result.Items)
// range match
result, err = uut.GetRange(ctx, prefix("/prefix/c/c1"), backend.RangeEnd(prefix("/prefix/c/cz")), backend.NoLimit)
require.NoError(t, err)
RequireItems(t, []backend.Item{c1, c2}, result.Items)
// pagination
result, err = uut.GetRange(ctx, prefix("/prefix"), backend.RangeEnd(prefix("/prefix")), 2)
require.NoError(t, err)
// expect two first records
RequireItems(t, []backend.Item{a, b}, result.Items)
// fetch next two items
result, err = uut.GetRange(ctx, backend.RangeEnd(prefix("/prefix/b")), backend.RangeEnd(prefix("/prefix")), 2)
require.NoError(t, err)
// expect two last records
RequireItems(t, []backend.Item{c1, c2}, result.Items)
// next fetch is empty
result, err = uut.GetRange(ctx, backend.RangeEnd(prefix("/prefix/c/c2")), backend.RangeEnd(prefix("/prefix")), 2)
require.NoError(t, err)
require.Empty(t, result.Items)
}
// testDeleteRange tests delete items by range
func testDeleteRange(t *testing.T, newBackend Constructor) {
uut, _, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
ctx := context.Background()
prefix := MakePrefix()
a := backend.Item{Key: prefix("/prefix/a"), Value: []byte("val a")}
b := backend.Item{Key: prefix("/prefix/b"), Value: []byte("val b")}
c1 := backend.Item{Key: prefix("/prefix/c/c1"), Value: []byte("val c1")}
c2 := backend.Item{Key: prefix("/prefix/c/c2"), Value: []byte("val c2")}
for _, item := range []*backend.Item{&a, &b, &c1, &c2} {
lease, err := uut.Create(ctx, *item)
require.NoError(t, err, "Failed creating value: %q => %q", item.Key, item.Value)
item.Revision = lease.Revision
}
err = uut.DeleteRange(ctx, prefix("/prefix/c"), backend.RangeEnd(prefix("/prefix/c")))
require.NoError(t, err)
// make sure items with "/prefix/c" are gone
result, err := uut.GetRange(ctx, prefix("/prefix"), backend.RangeEnd(prefix("/prefix")), backend.NoLimit)
require.NoError(t, err)
RequireItems(t, []backend.Item{a, b}, result.Items)
}
// testCompareAndSwap tests compare and swap functionality
func testCompareAndSwap(t *testing.T, newBackend Constructor) {
uut, clock, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
prefix := MakePrefix()
ctx := context.Background()
expires := clock.Now().UTC().Add(time.Hour)
key := prefix("one")
// compare and swap on non-existing value will fail
_, err = uut.CompareAndSwap(ctx, backend.Item{Key: key, Value: []byte("1"), Revision: "1"}, backend.Item{Key: prefix("one"), Value: []byte("2"), Revision: "1"})
require.True(t, trace.IsCompareFailed(err))
// create value and try again...
lease, err := uut.Create(ctx, backend.Item{Key: key, Value: []byte("1"), Expires: expires})
require.NoError(t, err)
// success CAS!
lease, err = uut.CompareAndSwap(ctx, backend.Item{Key: key, Value: []byte("1"), Revision: lease.Revision, Expires: expires}, backend.Item{Key: prefix("one"), Value: []byte("2"), Revision: lease.Revision, Expires: expires})
require.NoError(t, err)
out, err := uut.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, []byte("2"), out.Value)
require.Equal(t, lease.Revision, out.Revision)
// value has been updated - not '1' anymore
_, err = uut.CompareAndSwap(ctx, backend.Item{Key: key, Value: []byte("1"), Revision: lease.Revision}, backend.Item{Key: prefix("one"), Value: []byte("3"), Revision: lease.Revision})
require.True(t, trace.IsCompareFailed(err))
// existing value has not been changed by the failed CAS operation
out, err = uut.Get(ctx, key)
require.NoError(t, err)
require.Equal(t, []byte("2"), out.Value)
for i := 0; i < 10; i++ {
i := i
var wg sync.WaitGroup
wg.Add(1)
errs := make(chan error, 2)
go func(value byte) {
defer wg.Done()
_, err := uut.CompareAndSwap(ctx, backend.Item{Key: key, Value: out.Value, Revision: out.Revision}, backend.Item{Key: key, Value: []byte{value}})
errs <- err
}(byte(i + 10))
wg.Add(1)
go func(value byte) {
defer wg.Done()
_, err := uut.CompareAndSwap(ctx, backend.Item{Key: key, Value: out.Value, Revision: out.Revision}, backend.Item{Key: key, Value: []byte{value}})
errs <- err
}(byte(i + 100))
// validate that only a single failure occurred
var failed int
for i := 0; i < 2; i++ {
err := <-errs
if err != nil {
t.Log(err.Error())
failed++
}
}
require.Equal(t, 1, failed)
// validate that the value for the key was updated - we
// don't care which CAS above won only that one of them
// succeeded.
item, err := uut.Get(ctx, key)
require.NoError(t, err)
require.NotEqual(t, out.Value, item.Value)
out = item
}
}
// testExpiration tests scenario with expiring values
func testExpiration(t *testing.T, newBackend Constructor) {
uut, clock, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
prefix := MakePrefix()
ctx := context.Background()
itemA := backend.Item{Key: prefix("a"), Value: []byte("val1"), Expires: clock.Now().UTC().Add(time.Hour)}
leaseA, err := uut.Put(ctx, itemA)
require.NoError(t, err)
itemA.Revision = leaseA.Revision
itemB := backend.Item{Key: prefix("b"), Value: []byte("val1"), Expires: clock.Now().UTC().Add(time.Second)}
_, err = uut.Put(ctx, itemB)
require.NoError(t, err)
clock.Advance(4 * time.Second)
res, err := uut.GetRange(ctx, prefix(""), backend.RangeEnd(prefix("")), backend.NoLimit)
require.NoError(t, err)
RequireItems(t, []backend.Item{itemA}, res.Items)
}
// addSeconds adds seconds with a seconds precision
// always rounding up to the next second,
// because TTL engines are usually 1 second precision
func addSeconds(t time.Time, seconds int64) time.Time {
return time.Unix(t.UTC().Unix()+seconds+1, 0)
}
// testKeepAlive tests keep alive API
func testKeepAlive(t *testing.T, newBackend Constructor) {
const eventTimeout = 10 * time.Second
uut, clock, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
prefix := MakePrefix()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// When I create a new watcher...
watcher, err := uut.NewWatcher(ctx, backend.Watch{Prefixes: [][]byte{prefix("")}})
require.NoError(t, err)
defer func() { require.NoError(t, watcher.Close()) }()
// ...expect that the event channel contains the original `init` message
// sent when the Firestore client was set up.
requireEvent(t, watcher, types.OpInit, nil, eventTimeout)
// Make sure that nothing breaks even if the value we are KeepAlive-ing is
// somewhat big; PostgreSQL starts optimizing values if their compressed
// form doesn't fit within 8KiB, so we use 16KiB of uncompressible data
var bigValue [16384]byte
rand.Read(bigValue[:])
// When I create an item that expires in 10 seconds and add it to the DB
expiresAt := addSeconds(clock.Now(), 10)
item, lease := AddItem(ctx, t, uut, prefix("key"), string(bigValue[:]), expiresAt)
event := requireEvent(t, watcher, types.OpPut, prefix("key"), eventTimeout)
require.Equal(t, bigValue[:], event.Item.Value)
require.WithinDuration(t, expiresAt, event.Item.Expires, 2*time.Second)
// move the current slightly forward, but still *before* the item's
// expiry time
clock.Advance(2 * time.Second)
// Move the item's expiration further in the future using a KeepAlive
updatedAt := addSeconds(clock.Now(), 60)
err = uut.KeepAlive(ctx, lease, updatedAt)
require.NoError(t, err)
// Since the backend translates absolute expiration timestamp to a TTL
// and collecting events takes arbitrary time, the expiration timestamps
// on the collected events might have a slight skew
event = requireEvent(t, watcher, types.OpPut, prefix("key"), eventTimeout)
require.Equal(t, bigValue[:], event.Item.Value)
require.WithinDuration(t, updatedAt, event.Item.Expires, 2*time.Second)
err = uut.Delete(context.TODO(), item.Key)
require.NoError(t, err)
_, err = uut.Get(context.TODO(), item.Key)
require.True(t, trace.IsNotFound(err))
// keep alive on deleted or expired object should fail
err = uut.KeepAlive(context.TODO(), lease, updatedAt.Add(1*time.Second))
require.True(t, trace.IsNotFound(err))
}
// testEvents tests scenarios with event watches
func testEvents(t *testing.T, newBackend Constructor) {
const eventTimeout = 10 * time.Second
var ttlDeleteTimeout = eventTimeout
// TELEPORT_BACKEND_TEST_TTL_DELETE_TIMEOUT may be set to extend the time waited
// for TTL deletion to occur. This is useful for backends where TTL deletion is
// handled externally and may take longer than the default of 10 seconds.
if d, err := time.ParseDuration(os.Getenv("TELEPORT_BACKEND_TEST_TTL_DELETE_TIMEOUT")); err == nil {
ttlDeleteTimeout = d
t.Logf("TTL delete timeout overridden by envvar: %s", d)
}
uut, clock, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
prefix := MakePrefix()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Create a new watcher for the test prefix.
watcher, err := uut.NewWatcher(ctx, backend.Watch{Prefixes: [][]byte{prefix("")}})
require.NoError(t, err)
defer func() { require.NoError(t, watcher.Close()) }()
// Make sure INIT event is emitted.
requireEvent(t, watcher, types.OpInit, nil, eventTimeout)
// Add item to backend.
item := &backend.Item{Key: prefix("b"), Value: []byte("val"), Expires: clock.Now().UTC().Add(time.Hour)}
lease, err := uut.Put(ctx, *item)
require.NoError(t, err)
// Make sure item was added into backend.
item, err = uut.Get(ctx, item.Key)
require.NoError(t, err)
require.Equal(t, lease.Revision, item.Revision)
// Make sure a PUT event is emitted.
e := requireEvent(t, watcher, types.OpPut, item.Key, eventTimeout)
require.Equal(t, item.Value, e.Item.Value)
// Delete item from backend.
err = uut.Delete(ctx, item.Key)
require.NoError(t, err)
// Make sure item is no longer in backend.
_, err = uut.Get(ctx, item.Key)
require.True(t, trace.IsNotFound(err), "Item should have been be deleted")
// Make sure a DELETE event is emitted.
requireEvent(t, watcher, types.OpDelete, item.Key, eventTimeout)
// Add item to backend with a 1 second TTL.
item = &backend.Item{
Key: prefix("c"),
Value: []byte("val"),
Expires: clock.Now().UTC().Add(time.Second),
}
lease, err = uut.Put(ctx, *item)
require.NoError(t, err)
// Make sure item was added into backend.
item, err = uut.Get(ctx, item.Key)
require.NoError(t, err)
require.Equal(t, lease.Revision, item.Revision)
// Make sure a PUT event is emitted.
e = requireEvent(t, watcher, types.OpPut, item.Key, eventTimeout)
require.Equal(t, item.Value, e.Item.Value)
// Wait a few seconds for the item to expire.
clock.Advance(3 * time.Second)
// Make sure item has been removed.
_, err = uut.Get(ctx, item.Key)
require.Error(t, err)
// Make sure a DELETE event is emitted.
requireEvent(t, watcher, types.OpDelete, item.Key, ttlDeleteTimeout)
}
// testFetchLimit tests fetch max items size limit.
func testFetchLimit(t *testing.T, newBackend Constructor) {
uut, _, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
prefix := MakePrefix()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Allocate 65KB buffer.
buff := make([]byte, 1<<16)
itemsCount := 20
// Fill the backend with events that total size is greater than 1MB (65KB * 20 > 1MB).
for i := 0; i < itemsCount; i++ {
item := &backend.Item{Key: prefix(fmt.Sprintf("/db/database%d", i)), Value: buff}
_, err = uut.Put(ctx, *item)
require.NoError(t, err)
}
result, err := uut.GetRange(ctx, prefix("/db"), backend.RangeEnd(prefix("/db")), backend.NoLimit)
require.NoError(t, err)
require.Len(t, result.Items, itemsCount)
}
// testLimit tests limit.
func testLimit(t *testing.T, newBackend Constructor) {
uut, clock, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
prefix := MakePrefix()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
item := &backend.Item{
Key: prefix("/db/database_tail_item"),
Value: []byte("data"),
Expires: clock.Now().Add(10 * time.Minute),
}
_, err = uut.Put(ctx, *item)
require.NoError(t, err)
for i := 0; i < 10; i++ {
item := &backend.Item{
Key: prefix(fmt.Sprintf("/db/database%d", i)),
Value: []byte("data"),
Expires: clock.Now().Add(time.Second * 3),
}
_, err = uut.Put(ctx, *item)
require.NoError(t, err)
}
clock.Advance(time.Second * 5)
item = &backend.Item{
Key: prefix("/db/database_head_item"),
Value: []byte("data"),
Expires: clock.Now().Add(10 * time.Minute),
}
_, err = uut.Put(ctx, *item)
require.NoError(t, err)
result, err := uut.GetRange(ctx, prefix("/db"), backend.RangeEnd(prefix("/db")), 2)
require.NoError(t, err)
require.Len(t, result.Items, 2)
}
// requireEvent asserts that a given event type with the given key is emitted
// by a watcher within the supplied timeout, returning that event for further
// inspection if successful.
func requireEvent(t *testing.T, watcher backend.Watcher, eventType types.OpType, key []byte, timeout time.Duration) backend.Event {
t.Helper()
select {
case e := <-watcher.Events():
require.Equal(t, eventType, e.Type)
require.Equal(t, key, e.Item.Key)
return e
case <-watcher.Done():
require.FailNow(t, "Watcher has unexpectedly closed.")
case <-time.After(timeout):
require.FailNowf(t, "Timed out", "Timed out after %v waiting for event %v", timeout.String(), eventType.String())
}
return backend.Event{}
}
// requireNoEvent asserts that no events of any kind are emitted by the given
// watcher in the supplied timeframe.
func requireNoEvent(t *testing.T, watcher backend.Watcher, timeout time.Duration) {
select {
case e := <-watcher.Events():
require.FailNowf(t, "Unexpected event", "%s %q => %q", e.Type, e.Item.Key, e.Item.Value)
case <-watcher.Done():
require.FailNow(t, "Watcher has unexpectedly closed.")
case <-time.After(timeout):
return // Success!
}
}
// WatchersClose tests scenarios with watches close
func testWatchersClose(t *testing.T, newBackend Constructor) {
uut, _, err := newBackend()
require.NoError(t, err)
// The test function explicitly closes the UUT backend, so we only
// want this deferred call for emergency cleanup, rather than part
// of the tests itself. This is why we're not checking the error
// here as it will almost always fail with something like "already
// closed"
defer uut.Close()
prefix := MakePrefix()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
watcher, err := uut.NewWatcher(ctx, backend.Watch{Prefixes: [][]byte{prefix("")}})
require.NoError(t, err)
// cancel context -> get watcher to close
cancel()
select {
case <-watcher.Done():
case <-time.After(time.Second):
require.FailNow(t, "Timeout waiting for watcher to close")
}
// closing backend should close associated watcher too
watcher, err = uut.NewWatcher(context.Background(), backend.Watch{Prefixes: [][]byte{prefix("")}})
require.NoError(t, err)
require.NoError(t, uut.Close())
select {
case <-watcher.Done():
case <-time.After(time.Second):
require.FailNow(t, "Timeout waiting for watcher to close")
}
}
// testLocking tests locking logic
func testLocking(t *testing.T, newBackend Constructor) {
tok1 := "token1"
tok2 := "token2"
ttl := 5 * time.Second
uut, clock, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uut.Close()) }()
// If all this takes more than a minute then something external to the test
// has probably gone bad (e.g. db server has ceased to exist), so it's
// probably best to bail out with a sensible error (& call stack) rather
// than wait for the test to time out
ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Minute)
defer cancel()
// Manually drive the clock at ~10x speed to make sure anyone waiting on it
// will eventually be woken. This will automatically be stopped when the
// test exits thanks to the deferred cancel above.
go func() {
t := time.NewTicker(100 * time.Millisecond)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
clock.Advance(1 * time.Second)
}
}
}()
// some bookkeeping to make sure that any errors that happen asynchronously
// will be tracked and bubble back to fail this test. Note that this will
// also ensure that the `uut` Backend will remain alive until all async
// operations have completed.
asyncOps := sync.WaitGroup{}
asyncErrs := make(chan error, 10)
requireNoAsyncErrors := func() {
requireWaitGroupToFinish(ctx, t, &asyncOps)
select {
case err := <-asyncErrs:
require.NoError(t, err)
default:
// Happy path - there were no async errors!
}
}
defer requireNoAsyncErrors()
// Given a lock named `tok1` on the backend...
lock, err := backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok1, TTL: ttl})
require.NoError(t, err)
// When I asynchronously release the lock...
marker := int32(7)
asyncOps.Add(1)
go func() {
defer asyncOps.Done()
atomic.StoreInt32(&marker, 9)
if err := lock.Release(ctx, uut); err != nil {
asyncErrs <- err
}
}()
// ...and simultaneously attempt to create a new lock with the same name
lock, err = backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok1, TTL: ttl})
// expect that the asynchronous Release() has executed - we're using the
// change in the value of the marker value as a proxy for the Release().
atomic.AddInt32(&marker, 9)
require.Equal(t, int32(18), atomic.LoadInt32(&marker))
// ...and also expect that the acquire succeeded, and will release safely.
require.NoError(t, err)
require.NoError(t, lock.Release(ctx, uut))
// Given a lock with the same name as previously-existing, manually-released lock
lock, err = backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok1, TTL: ttl})
require.NoError(t, err)
atomic.StoreInt32(&marker, 7)
// When I asynchronously release the lock...
asyncOps.Add(1)
go func() {
defer asyncOps.Done()
atomic.StoreInt32(&marker, 9)
if err := lock.Release(ctx, uut); err != nil {
asyncErrs <- err
}
}()
// ...and simultaneously try to acquire another lock with the same name
lock, err = backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok1, TTL: ttl})
// expect that the asynchronous Release() has executed - we're using the
// change in the value of the marker value as a proxy for the call to
// Release().
atomic.AddInt32(&marker, 9)
require.Equal(t, int32(18), atomic.LoadInt32(&marker))
// ...and also expect that the acquire succeeded, and will release safely.
require.NoError(t, err)
require.NoError(t, lock.Release(ctx, uut))
// Given a pair of locks named `tok1` and `tok2`
y := int32(0)
lock1, err := backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok1, TTL: ttl})
require.NoError(t, err)
lock2, err := backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok2, TTL: ttl})
require.NoError(t, err)
// When I asynchronously release the locks...
asyncOps.Add(1)
go func() {
defer asyncOps.Done()
atomic.StoreInt32(&y, 15)
if err := lock1.Release(ctx, uut); err != nil {
asyncErrs <- err
}
if err := lock2.Release(ctx, uut); err != nil {
asyncErrs <- err
}
}()
lock, err = backend.AcquireLock(ctx, backend.LockConfiguration{Backend: uut, LockName: tok1, TTL: ttl})
require.NoError(t, err)
require.Equal(t, int32(15), atomic.LoadInt32(&y))
require.NoError(t, lock.Release(ctx, uut))
}
// testConcurrentOperations tests concurrent operations on the same
// shared backend
func testConcurrentOperations(t *testing.T, newBackend Constructor) {
uutA, _, err := newBackend()
require.NoError(t, err)
defer func() { require.NoError(t, uutA.Close()) }()
uutB, _, err := newBackend(WithConcurrentBackend(uutA))
if errors.Is(err, ErrConcurrentAccessNotSupported) {
t.Skip("Backend does not support concurrent access")
}
require.NoError(t, err)
defer func() { require.NoError(t, uutB.Close()) }()
prefix := MakePrefix()
ctx := context.TODO()
value1 := "this first value should not be corrupted by concurrent ops"
value2 := "this second value should not be corrupted too"
const attempts = 50
asyncOps := sync.WaitGroup{}
asyncErrs := make(chan error, 5*attempts)
for i := 0; i < attempts; i++ {
asyncOps.Add(5)
go func(cnt int) {
defer asyncOps.Done()
_, err := uutA.Put(ctx, backend.Item{Key: prefix("key"), Value: []byte(value1)})
if err != nil {
asyncErrs <- err
}
}(i)
go func(cnt int) {
defer asyncOps.Done()
_, err := uutB.CompareAndSwap(ctx,
backend.Item{Key: prefix("key"), Value: []byte(value2)},
backend.Item{Key: prefix("key"), Value: []byte(value1)})
if err != nil && !trace.IsCompareFailed(err) {
asyncErrs <- err
}
}(i)
go func(cnt int) {
defer asyncOps.Done()
_, err := uutB.Create(ctx, backend.Item{Key: prefix("key"), Value: []byte(value2)})
if err != nil && !trace.IsAlreadyExists(err) {
asyncErrs <- err
}
}(i)
go func(cnt int) {
defer asyncOps.Done()
item, err := uutA.Get(ctx, prefix("key"))
if err != nil && !trace.IsNotFound(err) {
asyncErrs <- err
}
// make sure data is not corrupted along the way
if err == nil {
val := string(item.Value)
if val != value1 && val != value2 {
asyncErrs <- trace.Errorf(
"corruption detected. expected one of %q or %q and got %q", value1, value2, val)
}
}
}(i)
go func(cnt int) {
defer asyncOps.Done()
err := uutB.Delete(ctx, prefix("key"))
if err != nil && !trace.IsNotFound(err) {
t.Logf("Error %v", err)
asyncErrs <- err
}
}(i)
}
// Give the database some time to update. A single-node in-memory database
// will finish faster than a 3-node cluster. Some latency is expected
// since this test intentionally creates conflict on the same key. Most tests
// should complete in less than a few seconds.
timeoutCtx, timeoutCancel := context.WithTimeout(ctx, 10*time.Second)
defer timeoutCancel()
requireWaitGroupToFinish(timeoutCtx, t, &asyncOps)
select {
case e := <-asyncErrs: