-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathrevision_cache_test.go
1588 lines (1339 loc) · 61.4 KB
/
revision_cache_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
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
/*
Copyright 2016-Present Couchbase, Inc.
Use of this software is governed by the Business Source License included in
the file licenses/BSL-Couchbase.txt. As of the Change Date specified in that
file, in accordance with the Business Source License, use of this software will
be governed by the Apache License, Version 2.0, included in the file
licenses/APL2.txt.
*/
package db
import (
"context"
"fmt"
"log"
"math/rand"
"strconv"
"sync"
"testing"
"github.com/couchbase/sync_gateway/base"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// testBackingStore always returns an empty doc at rev:"1-abc" in channel "*" except for docs not in 'notFoundDocIDs'
type testBackingStore struct {
// notFoundDocIDs is a list of doc IDs that GetDocument returns a 404 for.
notFoundDocIDs []string
getDocumentCounter *base.SgwIntStat
getRevisionCounter *base.SgwIntStat
}
func (t *testBackingStore) GetDocument(ctx context.Context, docid string, unmarshalLevel DocumentUnmarshalLevel) (doc *Document, err error) {
t.getDocumentCounter.Add(1)
for _, d := range t.notFoundDocIDs {
if docid == d {
return nil, ErrMissing
}
}
doc = NewDocument(docid)
doc._body = Body{
"testing": true,
}
doc.CurrentRev = "1-abc"
doc.History = RevTree{
doc.CurrentRev: {
Channels: base.SetOf("*"),
},
}
return doc, nil
}
func (t *testBackingStore) getRevision(ctx context.Context, doc *Document, revid string) ([]byte, AttachmentsMeta, error) {
t.getRevisionCounter.Add(1)
b := Body{
"testing": true,
BodyId: doc.ID,
BodyRev: doc.CurrentRev,
BodyRevisions: Revisions{RevisionsStart: 1},
}
bodyBytes, err := base.JSONMarshal(b)
return bodyBytes, nil, err
}
type noopBackingStore struct{}
func (*noopBackingStore) GetDocument(ctx context.Context, docid string, unmarshalLevel DocumentUnmarshalLevel) (doc *Document, err error) {
return nil, nil
}
func (*noopBackingStore) getRevision(ctx context.Context, doc *Document, revid string) ([]byte, AttachmentsMeta, error) {
return nil, nil, nil
}
// testCollectionID is a test collection ID to use for a key in the backing store map to point to a tests backing store.
// This should only be used in tests that have no database context being created.
const testCollectionID = 0
// CreateTestSingleBackingStoreMap will create map of rev cache backing stores and assign the specified backing store to collection ID specified for testing purposes
func CreateTestSingleBackingStoreMap(backingStore RevisionCacheBackingStore, collectionID uint32) map[uint32]RevisionCacheBackingStore {
backingStoreMap := make(map[uint32]RevisionCacheBackingStore)
backingStoreMap[collectionID] = backingStore
return backingStoreMap
}
// Tests the eviction from the LRURevisionCache
func TestLRURevisionCacheEviction(t *testing.T) {
cacheHitCounter, cacheMissCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&noopBackingStore{}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 0,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
ctx := base.TestCtx(t)
// Fill up the rev cache with the first 10 docs
for docID := 0; docID < 10; docID++ {
id := strconv.Itoa(docID)
cache.Put(ctx, DocumentRevision{BodyBytes: []byte(`{}`), DocID: id, RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
}
assert.Equal(t, int64(10), cacheNumItems.Value())
assert.Equal(t, int64(20), memoryBytesCounted.Value())
// Get them back out
for i := 0; i < 10; i++ {
docID := strconv.Itoa(i)
docRev, err := cache.Get(ctx, docID, "1-abc", testCollectionID, RevCacheOmitDelta)
assert.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes, "nil body for %s", docID)
assert.Equal(t, docID, docRev.DocID)
assert.Equal(t, int64(0), cacheMissCounter.Value())
assert.Equal(t, int64(i+1), cacheHitCounter.Value())
}
assert.Equal(t, int64(10), cacheNumItems.Value())
assert.Equal(t, int64(20), memoryBytesCounted.Value())
// Add 3 more docs to the now full revcache
for i := 10; i < 13; i++ {
docID := strconv.Itoa(i)
cache.Put(ctx, DocumentRevision{BodyBytes: []byte(`{}`), DocID: docID, RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
}
assert.Equal(t, int64(10), cacheNumItems.Value())
assert.Equal(t, int64(20), memoryBytesCounted.Value())
// Check that the first 3 docs were evicted
prevCacheHitCount := cacheHitCounter.Value()
for i := 0; i < 3; i++ {
docID := strconv.Itoa(i)
docRev, ok := cache.Peek(ctx, docID, "1-abc", testCollectionID)
assert.False(t, ok)
assert.Nil(t, docRev.BodyBytes)
assert.Equal(t, int64(0), cacheMissCounter.Value()) // peek incurs no cache miss if not found
assert.Equal(t, prevCacheHitCount, cacheHitCounter.Value())
}
assert.Equal(t, int64(10), cacheNumItems.Value())
assert.Equal(t, int64(20), memoryBytesCounted.Value())
// and check we can Get up to and including the last 3 we put in
for i := 0; i < 10; i++ {
id := strconv.Itoa(i + 3)
docRev, err := cache.Get(ctx, id, "1-abc", testCollectionID, RevCacheOmitDelta)
assert.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes, "nil body for %s", id)
assert.Equal(t, id, docRev.DocID)
assert.Equal(t, int64(0), cacheMissCounter.Value())
assert.Equal(t, prevCacheHitCount+int64(i)+1, cacheHitCounter.Value())
}
assert.Equal(t, int64(10), cacheNumItems.Value())
assert.Equal(t, int64(20), memoryBytesCounted.Value())
}
func TestLRURevisionCacheEvictionMemoryBased(t *testing.T) {
dbcOptions := DatabaseContextOptions{
RevisionCacheOptions: &RevisionCacheOptions{
MaxBytes: 725,
MaxItemCount: 10,
},
}
db, ctx := SetupTestDBWithOptions(t, dbcOptions)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
cacheStats := db.DbStats.Cache()
smallBody := Body{
"channels": "_default", // add channel for default sync func in default collection test runs
}
var currMem, expValue, revZeroSize int64
for i := 0; i < 10; i++ {
currMem = cacheStats.RevisionCacheTotalMemory.Value()
revSize, _ := createDocAndReturnSizeAndRev(t, ctx, fmt.Sprint(i), collection, smallBody)
if i == 0 {
revZeroSize = int64(revSize)
}
expValue = currMem + int64(revSize)
assert.Equal(t, expValue, cacheStats.RevisionCacheTotalMemory.Value())
}
// test eviction by number of items (adding new doc from createDocAndReturnSizeAndRev shouldn't take memory over threshold defined as 730 bytes)
expValue -= revZeroSize // for doc being evicted
docSize, rev := createDocAndReturnSizeAndRev(t, ctx, fmt.Sprint(11), collection, smallBody)
expValue += int64(docSize)
// assert doc 0 been evicted
docRev, ok := db.revisionCache.Peek(ctx, "0", rev, collection.GetCollectionID())
assert.False(t, ok)
assert.Nil(t, docRev.BodyBytes)
currMem = cacheStats.RevisionCacheTotalMemory.Value()
// assert total memory is as expected
assert.Equal(t, expValue, currMem)
// remove doc "1" to give headroom for memory based eviction
db.revisionCache.Remove(ctx, "1", rev, collection.GetCollectionID())
docRev, ok = db.revisionCache.Peek(ctx, "1", rev, collection.GetCollectionID())
assert.False(t, ok)
assert.Nil(t, docRev.BodyBytes)
// assert current memory from rev cache decreases by the doc size (all docs added thus far are same size)
afterRemoval := currMem - int64(docSize)
assert.Equal(t, afterRemoval, cacheStats.RevisionCacheTotalMemory.Value())
// add new doc that will trigger eviction due to taking over memory size
largeBody := Body{
"type": "test",
"doc": "testDocument",
"foo": "bar",
"lets": "test",
"larger": "document",
"for": "eviction",
"channels": "_default", // add channel for default sync func in default collection test runs
}
_, _, err := collection.Put(ctx, "12", largeBody)
require.NoError(t, err)
// assert doc "2" has been evicted even though we only have 9 items in cache with capacity of 10, so memory based
// eviction took place
docRev, ok = db.revisionCache.Peek(ctx, "2", rev, collection.GetCollectionID())
assert.False(t, ok)
assert.Nil(t, docRev.BodyBytes)
// assert that the overall memory for rev cache is not over maximum
assert.LessOrEqual(t, cacheStats.RevisionCacheTotalMemory.Value(), dbcOptions.RevisionCacheOptions.MaxBytes)
}
func TestBackingStoreMemoryCalculation(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{[]string{"doc2"}, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 205,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
ctx := base.TestCtx(t)
docRev, err := cache.Get(ctx, "doc1", "1-abc", testCollectionID, RevCacheOmitDelta)
require.NoError(t, err)
assert.Equal(t, "doc1", docRev.DocID)
assert.NotNil(t, docRev.History)
assert.NotNil(t, docRev.Channels)
currMemStat := memoryBytesCounted.Value()
// assert stats is incremented by appropriate bytes on doc rev
assert.Equal(t, docRev.MemoryBytes, currMemStat)
// Test get active code pathway of a load from bucket
docRev, err = cache.GetActive(ctx, "doc", testCollectionID)
require.NoError(t, err)
assert.Equal(t, "doc", docRev.DocID)
assert.NotNil(t, docRev.History)
assert.NotNil(t, docRev.Channels)
newMemStat := currMemStat + docRev.MemoryBytes
// assert stats is incremented by appropriate bytes on doc rev
assert.Equal(t, newMemStat, memoryBytesCounted.Value())
// test fail load event doesn't increment memory stat
docRev, err = cache.Get(ctx, "doc2", "1-abc", testCollectionID, RevCacheOmitDelta)
assertHTTPError(t, err, 404)
assert.Nil(t, docRev.BodyBytes)
assert.Equal(t, newMemStat, memoryBytesCounted.Value())
// assert length is 2 as expected
assert.Equal(t, 2, cache.lruList.Len())
memStatBeforeThirdLoad := memoryBytesCounted.Value()
// test another load from bucket but doing so should trigger memory based eviction
docRev, err = cache.Get(ctx, "doc3", "1-abc", testCollectionID, RevCacheOmitDelta)
require.NoError(t, err)
assert.Equal(t, "doc3", docRev.DocID)
assert.NotNil(t, docRev.History)
assert.NotNil(t, docRev.Channels)
// assert length is still 2 (eviction took place) + test Peek for first added doc is failure
assert.Equal(t, 2, cache.lruList.Len())
memStatAfterEviction := (memStatBeforeThirdLoad + docRev.MemoryBytes) - currMemStat
assert.Equal(t, memStatAfterEviction, memoryBytesCounted.Value())
_, ok := cache.Peek(ctx, "doc1", "1-abc", testCollectionID)
assert.False(t, ok)
}
func TestBackingStore(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{[]string{"Peter"}, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 0,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
// Get Rev for the first time - miss cache, but fetch the doc and revision to store
docRev, err := cache.Get(base.TestCtx(t), "Jens", "1-abc", testCollectionID, RevCacheOmitDelta)
assert.NoError(t, err)
assert.Equal(t, "Jens", docRev.DocID)
assert.NotNil(t, docRev.History)
assert.NotNil(t, docRev.Channels)
assert.Equal(t, int64(0), cacheHitCounter.Value())
assert.Equal(t, int64(1), cacheMissCounter.Value())
assert.Equal(t, int64(1), getDocumentCounter.Value())
assert.Equal(t, int64(1), getRevisionCounter.Value())
// Doc doesn't exist, so miss the cache, and fail when getting the doc
docRev, err = cache.Get(base.TestCtx(t), "Peter", "1-abc", testCollectionID, RevCacheOmitDelta)
assertHTTPError(t, err, 404)
assert.Nil(t, docRev.BodyBytes)
assert.Equal(t, int64(0), cacheHitCounter.Value())
assert.Equal(t, int64(2), cacheMissCounter.Value())
assert.Equal(t, int64(2), getDocumentCounter.Value())
assert.Equal(t, int64(1), getRevisionCounter.Value())
// Rev is already resident, but still issue GetDocument to check for later revisions
docRev, err = cache.Get(base.TestCtx(t), "Jens", "1-abc", testCollectionID, RevCacheOmitDelta)
assert.NoError(t, err)
assert.Equal(t, "Jens", docRev.DocID)
assert.NotNil(t, docRev.History)
assert.NotNil(t, docRev.Channels)
assert.Equal(t, int64(1), cacheHitCounter.Value())
assert.Equal(t, int64(2), cacheMissCounter.Value())
assert.Equal(t, int64(2), getDocumentCounter.Value())
assert.Equal(t, int64(1), getRevisionCounter.Value())
// Rev still doesn't exist, make sure it wasn't cached
docRev, err = cache.Get(base.TestCtx(t), "Peter", "1-abc", testCollectionID, RevCacheOmitDelta)
assertHTTPError(t, err, 404)
assert.Nil(t, docRev.BodyBytes)
assert.Equal(t, int64(1), cacheHitCounter.Value())
assert.Equal(t, int64(3), cacheMissCounter.Value())
assert.Equal(t, int64(3), getDocumentCounter.Value())
assert.Equal(t, int64(1), getRevisionCounter.Value())
}
// Ensure internal properties aren't being incorrectly stored in revision cache
func TestRevisionCacheInternalProperties(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
// Invalid _revisions property will be stripped. Should also not be present in the rev cache.
rev1body := Body{
"value": 1234,
BodyRevisions: "unexpected data",
}
rev1id, _, err := collection.Put(ctx, "doc1", rev1body)
assert.NoError(t, err, "Put")
// Get the raw document directly from the bucket, validate _revisions property isn't found
var bucketBody Body
_, err = collection.dataStore.Get("doc1", &bucketBody)
require.NoError(t, err)
_, ok := bucketBody[BodyRevisions]
if ok {
t.Error("_revisions property still present in document retrieved directly from bucket.")
}
// Get the doc while still resident in the rev cache w/ history=false, validate _revisions property isn't found
body, err := collection.Get1xRevBody(ctx, "doc1", rev1id, false, nil)
assert.NoError(t, err, "Get1xRevBody")
badRevisions, ok := body[BodyRevisions]
if ok {
t.Errorf("_revisions property still present in document retrieved from rev cache: %s", badRevisions)
}
// Get the doc while still resident in the rev cache w/ history=true, validate _revisions property is returned with expected
// properties ("start", "ids")
bodyWithHistory, err := collection.Get1xRevBody(ctx, "doc1", rev1id, true, nil)
assert.NoError(t, err, "Get1xRevBody")
validRevisions, ok := bodyWithHistory[BodyRevisions]
if !ok {
t.Errorf("Expected _revisions property not found in document retrieved from rev cache: %s", validRevisions)
}
validRevisionsMap, ok := validRevisions.(Revisions)
require.True(t, ok)
_, startOk := validRevisionsMap[RevisionsStart]
assert.True(t, startOk)
_, idsOk := validRevisionsMap[RevisionsIds]
assert.True(t, idsOk)
}
func TestBypassRevisionCache(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyAll)
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
backingStoreMap := CreateTestSingleBackingStoreMap(collection, testCollectionID)
docBody := Body{
"value": 1234,
}
key := "doc1"
rev1, _, err := collection.Put(ctx, key, docBody)
assert.NoError(t, err)
docBody["_rev"] = rev1
docBody["value"] = 5678
rev2, _, err := collection.Put(ctx, key, docBody)
assert.NoError(t, err)
bypassStat := base.SgwIntStat{}
rc := NewBypassRevisionCache(backingStoreMap, &bypassStat)
// Peek always returns false for BypassRevisionCache
_, ok := rc.Peek(ctx, key, rev1, 0)
assert.False(t, ok)
_, ok = rc.Peek(ctx, key, rev2, 0)
assert.False(t, ok)
// Get non-existing doc
_, err = rc.Get(ctx, "invalid", rev1, testCollectionID, RevCacheOmitDelta)
assert.True(t, base.IsDocNotFoundError(err))
// Get non-existing revision
_, err = rc.Get(ctx, key, "3-abc", testCollectionID, RevCacheOmitDelta)
assertHTTPError(t, err, 404)
// Get specific revision
doc, err := rc.Get(ctx, key, rev1, testCollectionID, RevCacheOmitDelta)
assert.NoError(t, err)
require.NotNil(t, doc)
assert.Equal(t, `{"value":1234}`, string(doc.BodyBytes))
// Check peek is still returning false for "Get"
_, ok = rc.Peek(ctx, key, rev1, testCollectionID)
assert.False(t, ok)
// Put no-ops
rc.Put(ctx, doc, testCollectionID)
// Check peek is still returning false for "Put"
_, ok = rc.Peek(ctx, key, rev1, testCollectionID)
assert.False(t, ok)
// Get active revision
doc, err = rc.GetActive(ctx, key, testCollectionID)
assert.NoError(t, err)
assert.Equal(t, `{"value":5678}`, string(doc.BodyBytes))
}
// Ensure attachment properties aren't being incorrectly stored in revision cache body when inserted via Put
func TestPutRevisionCacheAttachmentProperty(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyAll)
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
rev1body := Body{
"value": 1234,
BodyAttachments: map[string]interface{}{"myatt": map[string]interface{}{"content_type": "text/plain", "data": "SGVsbG8gV29ybGQh"}},
}
rev1key := "doc1"
rev1id, _, err := collection.Put(ctx, rev1key, rev1body)
assert.NoError(t, err, "Unexpected error calling collection.Put")
// Get the raw document directly from the bucket, validate _attachments property isn't found
var bucketBody Body
_, err = collection.dataStore.Get(rev1key, &bucketBody)
assert.NoError(t, err, "Unexpected error calling bucket.Get")
_, ok := bucketBody[BodyAttachments]
assert.False(t, ok, "_attachments property still present in document body retrieved from bucket: %#v", bucketBody)
// Get the raw document directly from the revcache, validate _attachments property isn't found
docRevision, ok := collection.revisionCache.Peek(ctx, rev1key, rev1id)
assert.True(t, ok)
assert.NotContains(t, docRevision.BodyBytes, BodyAttachments, "_attachments property still present in document body retrieved from rev cache: %#v", bucketBody)
_, ok = docRevision.Attachments["myatt"]
assert.True(t, ok, "'myatt' not found in revcache attachments metadata")
// db.getRev stamps _attachments back in from revcache Attachment metadata
body, err := collection.Get1xRevBody(ctx, rev1key, rev1id, false, nil)
assert.NoError(t, err, "Unexpected error calling collection.Get1xRevBody")
atts, ok := body[BodyAttachments]
assert.True(t, ok, "_attachments property was not stamped back in body during collection.Get1xRevBody: %#v", body)
attsMap, ok := atts.(AttachmentsMeta)
require.True(t, ok)
_, ok = attsMap["myatt"]
assert.True(t, ok, "'myatt' not found in attachment map")
}
// Ensure attachment properties aren't being incorrectly stored in revision cache body when inserted via PutExistingRev
func TestPutExistingRevRevisionCacheAttachmentProperty(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyAll)
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
docKey := "doc1"
rev1body := Body{
"value": 1234,
}
rev1id, _, err := collection.Put(ctx, docKey, rev1body)
assert.NoError(t, err, "Unexpected error calling collection.Put")
rev2id := "2-xxx"
rev2body := Body{
"value": 1235,
BodyAttachments: map[string]interface{}{"myatt": map[string]interface{}{"content_type": "text/plain", "data": "SGVsbG8gV29ybGQh"}},
}
_, _, err = collection.PutExistingRevWithBody(ctx, docKey, rev2body, []string{rev2id, rev1id}, false)
assert.NoError(t, err, "Unexpected error calling collection.PutExistingRev")
// Get the raw document directly from the bucket, validate _attachments property isn't found
var bucketBody Body
_, err = collection.dataStore.Get(docKey, &bucketBody)
assert.NoError(t, err, "Unexpected error calling bucket.Get")
_, ok := bucketBody[BodyAttachments]
assert.False(t, ok, "_attachments property still present in document body retrieved from bucket: %#v", bucketBody)
// Get the raw document directly from the revcache, validate _attachments property isn't found
docRevision, err := collection.revisionCache.Get(ctx, docKey, rev2id, RevCacheOmitDelta)
assert.NoError(t, err, "Unexpected error calling collection.revisionCache.Get")
assert.NotContains(t, docRevision.BodyBytes, BodyAttachments, "_attachments property still present in document body retrieved from rev cache: %#v", bucketBody)
_, ok = docRevision.Attachments["myatt"]
assert.True(t, ok, "'myatt' not found in revcache attachments metadata")
// db.getRev stamps _attachments back in from revcache Attachment metadata
body, err := collection.Get1xRevBody(ctx, docKey, rev2id, false, nil)
assert.NoError(t, err, "Unexpected error calling collection.Get1xRevBody")
atts, ok := body[BodyAttachments]
assert.True(t, ok, "_attachments property was not stamped back in body during collection.Get1xRevBody: %#v", body)
attsMap, ok := atts.(AttachmentsMeta)
require.True(t, ok)
_, ok = attsMap["myatt"]
assert.True(t, ok, "'myatt' not found in attachment map")
}
// Ensure subsequent updates to delta don't mutate previously retrieved deltas
func TestRevisionImmutableDelta(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{nil, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 0,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
firstDelta := []byte("delta")
secondDelta := []byte("modified delta")
// Trigger load into cache
_, err := cache.Get(base.TestCtx(t), "doc1", "1-abc", testCollectionID, RevCacheIncludeDelta)
assert.NoError(t, err, "Error adding to cache")
cache.UpdateDelta(base.TestCtx(t), "doc1", "1-abc", testCollectionID, RevisionDelta{ToRevID: "rev2", DeltaBytes: firstDelta})
// Retrieve from cache
retrievedRev, err := cache.Get(base.TestCtx(t), "doc1", "1-abc", testCollectionID, RevCacheIncludeDelta)
assert.NoError(t, err, "Error retrieving from cache")
assert.Equal(t, "rev2", retrievedRev.Delta.ToRevID)
assert.Equal(t, firstDelta, retrievedRev.Delta.DeltaBytes)
// Update delta again, validate data in retrievedRev isn't mutated
cache.UpdateDelta(base.TestCtx(t), "doc1", "1-abc", testCollectionID, RevisionDelta{ToRevID: "rev3", DeltaBytes: secondDelta})
assert.Equal(t, "rev2", retrievedRev.Delta.ToRevID)
assert.Equal(t, firstDelta, retrievedRev.Delta.DeltaBytes)
// Retrieve again, validate delta is correct
updatedRev, err := cache.Get(base.TestCtx(t), "doc1", "1-abc", testCollectionID, RevCacheIncludeDelta)
assert.NoError(t, err, "Error retrieving from cache")
assert.Equal(t, "rev3", updatedRev.Delta.ToRevID)
assert.Equal(t, secondDelta, updatedRev.Delta.DeltaBytes)
assert.Equal(t, "rev2", retrievedRev.Delta.ToRevID)
assert.Equal(t, firstDelta, retrievedRev.Delta.DeltaBytes)
}
func TestUpdateDeltaRevCacheMemoryStat(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{nil, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 125,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
firstDelta := []byte("delta")
secondDelta := []byte("modified delta")
thirdDelta := []byte("another delta further modified")
ctx := base.TestCtx(t)
// Trigger load into cache
docRev, err := cache.Get(ctx, "doc1", "1-abc", testCollectionID, RevCacheIncludeDelta)
assert.NoError(t, err, "Error adding to cache")
revCacheMem := memoryBytesCounted.Value()
revCacheDelta := newRevCacheDelta(firstDelta, "1-abc", docRev, false, nil)
cache.UpdateDelta(ctx, "doc1", "1-abc", testCollectionID, revCacheDelta)
// assert that rev cache memory increases by expected amount
newMem := revCacheMem + revCacheDelta.totalDeltaBytes
assert.Equal(t, newMem, memoryBytesCounted.Value())
oldDeltaSize := revCacheDelta.totalDeltaBytes
newMem = memoryBytesCounted.Value()
revCacheDelta = newRevCacheDelta(secondDelta, "1-abc", docRev, false, nil)
cache.UpdateDelta(ctx, "doc1", "1-abc", testCollectionID, revCacheDelta)
// assert the overall memory stat is correctly updated (by the diff between the old delta and the new delta)
newMem += revCacheDelta.totalDeltaBytes - oldDeltaSize
assert.Equal(t, newMem, memoryBytesCounted.Value())
revCacheDelta = newRevCacheDelta(thirdDelta, "1-abc", docRev, false, nil)
cache.UpdateDelta(ctx, "doc1", "1-abc", testCollectionID, revCacheDelta)
// assert that eviction took place and as result stat is now 0 (only item in cache was doc1)
assert.Equal(t, int64(0), memoryBytesCounted.Value())
assert.Equal(t, 0, cache.lruList.Len())
}
func TestImmediateRevCacheMemoryBasedEviction(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{nil, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 10,
}
ctx := base.TestCtx(t)
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
cache.Put(ctx, DocumentRevision{BodyBytes: []byte(`{"some":"test"}`), DocID: "doc1", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
assert.Equal(t, int64(0), memoryBytesCounted.Value())
assert.Equal(t, int64(0), cacheNumItems.Value())
cache.Upsert(ctx, DocumentRevision{BodyBytes: []byte(`{"some":"test"}`), DocID: "doc2", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
assert.Equal(t, int64(0), memoryBytesCounted.Value())
assert.Equal(t, int64(0), cacheNumItems.Value())
// assert we can still fetch this upsert doc
docRev, err := cache.Get(ctx, "doc2", "1-abc", testCollectionID, false)
require.NoError(t, err)
assert.Equal(t, "doc2", docRev.DocID)
assert.Equal(t, int64(102), docRev.MemoryBytes)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, int64(0), memoryBytesCounted.Value())
assert.Equal(t, int64(0), cacheNumItems.Value())
docRev, err = cache.Get(ctx, "doc1", "1-abc", testCollectionID, RevCacheOmitDelta)
require.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, int64(0), memoryBytesCounted.Value())
assert.Equal(t, int64(0), cacheNumItems.Value())
docRev, err = cache.GetActive(ctx, "doc1", testCollectionID)
require.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, int64(0), memoryBytesCounted.Value())
assert.Equal(t, int64(0), cacheNumItems.Value())
}
// TestShardedMemoryEviction:
// - Test adding a doc to each shard in the test
// - Assert that each shard has individual count for memory usage as expected
// - Add new doc that will take over the shard memory capacity and assert that that eviction takes place and
// all stats are as expected
func TestShardedMemoryEviction(t *testing.T) {
dbcOptions := DatabaseContextOptions{
RevisionCacheOptions: &RevisionCacheOptions{
MaxBytes: 160,
MaxItemCount: 10,
ShardCount: 2,
},
}
db, ctx := SetupTestDBWithOptions(t, dbcOptions)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
cacheStats := db.DbStats.Cache()
docBody := Body{
"channels": "_default",
}
// add doc that will be added to one shard
size, _ := createDocAndReturnSizeAndRev(t, ctx, "doc1", collection, docBody)
assert.Equal(t, int64(size), cacheStats.RevisionCacheTotalMemory.Value())
// grab this particular shard + assert that the shard memory usage is as expected
shardedCache := db.revisionCache.(*ShardedLRURevisionCache)
doc1Shard := shardedCache.getShard("doc1")
assert.Equal(t, int64(size), doc1Shard.currMemoryUsage.Value())
// add new doc in diff shard + assert that the shard memory usage is as expected
size, _ = createDocAndReturnSizeAndRev(t, ctx, "doc2", collection, docBody)
doc2Shard := shardedCache.getShard("doc2")
assert.Equal(t, int64(size), doc2Shard.currMemoryUsage.Value())
// overall mem usage should be combination oif the two added docs
assert.Equal(t, int64(size*2), cacheStats.RevisionCacheTotalMemory.Value())
// two docs should reside in cache at this time
assert.Equal(t, int64(2), cacheStats.RevisionCacheNumItems.Value())
docBody = Body{
"channels": "_default",
"some": "field",
}
// add new doc to trigger eviction and assert stats are as expected
newDocSize, _ := createDocAndReturnSizeAndRev(t, ctx, "doc3", collection, docBody)
doc3Shard := shardedCache.getShard("doc3")
assert.Equal(t, int64(newDocSize), doc3Shard.currMemoryUsage.Value())
assert.Equal(t, int64(2), cacheStats.RevisionCacheNumItems.Value())
assert.Equal(t, int64(size+newDocSize), cacheStats.RevisionCacheTotalMemory.Value())
}
// TestShardedMemoryEvictionWhenShardEmpty:
// - Test adding a doc to sharded revision cache that will immediately be evicted due to size
// - Assert that stats look as expected
func TestShardedMemoryEvictionWhenShardEmpty(t *testing.T) {
dbcOptions := DatabaseContextOptions{
RevisionCacheOptions: &RevisionCacheOptions{
MaxBytes: 100,
MaxItemCount: 10,
ShardCount: 2,
},
}
db, ctx := SetupTestDBWithOptions(t, dbcOptions)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
cacheStats := db.DbStats.Cache()
docBody := Body{
"channels": "_default",
}
// add doc that will be added to one shard
rev, _, err := collection.Put(ctx, "doc1", docBody)
require.NoError(t, err)
shardedCache := db.revisionCache.(*ShardedLRURevisionCache)
// assert that doc was not added to cache as it's too large
doc1Shard := shardedCache.getShard("doc1")
assert.Equal(t, int64(0), doc1Shard.currMemoryUsage.Value())
assert.Equal(t, int64(0), cacheStats.RevisionCacheNumItems.Value())
assert.Equal(t, int64(0), cacheStats.RevisionCacheTotalMemory.Value())
// test we can still fetch this doc
docRev, err := collection.GetRev(ctx, "doc1", rev, false, nil)
require.NoError(t, err)
assert.Equal(t, "doc1", docRev.DocID)
assert.NotNil(t, docRev.BodyBytes)
// assert rev cache is still empty
assert.Equal(t, int64(0), doc1Shard.currMemoryUsage.Value())
assert.Equal(t, int64(0), cacheStats.RevisionCacheNumItems.Value())
assert.Equal(t, int64(0), cacheStats.RevisionCacheTotalMemory.Value())
}
func TestImmediateRevCacheItemBasedEviction(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{nil, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 1,
MaxBytes: 0, // turn off memory based eviction
}
ctx := base.TestCtx(t)
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
// load up item to hit max capacity
cache.Put(ctx, DocumentRevision{BodyBytes: []byte(`{"some":"test"}`), DocID: "doc1", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
// eviction starts from here in test
cache.Put(ctx, DocumentRevision{BodyBytes: []byte(`{"some":"test"}`), DocID: "newDoc", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
assert.Equal(t, int64(15), memoryBytesCounted.Value())
assert.Equal(t, int64(1), cacheNumItems.Value())
cache.Upsert(ctx, DocumentRevision{BodyBytes: []byte(`{"some":"test"}`), DocID: "doc2", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
assert.Equal(t, int64(15), memoryBytesCounted.Value())
assert.Equal(t, int64(1), cacheNumItems.Value())
docRev, err := cache.Get(ctx, "doc3", "1-abc", testCollectionID, RevCacheOmitDelta)
require.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, int64(102), memoryBytesCounted.Value())
assert.Equal(t, int64(1), cacheNumItems.Value())
docRev, err = cache.GetActive(ctx, "doc4", testCollectionID)
require.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, int64(102), memoryBytesCounted.Value())
assert.Equal(t, int64(1), cacheNumItems.Value())
}
func TestResetRevCache(t *testing.T) {
dbcOptions := DatabaseContextOptions{
RevisionCacheOptions: &RevisionCacheOptions{
MaxBytes: 100,
MaxItemCount: 10,
},
}
db, ctx := SetupTestDBWithOptions(t, dbcOptions)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
cacheStats := db.DbStats.Cache()
// add a doc
docSize, _ := createDocAndReturnSizeAndRev(t, ctx, "doc1", collection, Body{"test": "doc"})
assert.Equal(t, int64(docSize), cacheStats.RevisionCacheTotalMemory.Value())
assert.Equal(t, int64(1), cacheStats.RevisionCacheNumItems.Value())
// re create rev cache
db.FlushRevisionCacheForTest()
// assert rev cache is reset as expected
assert.Equal(t, int64(0), cacheStats.RevisionCacheTotalMemory.Value())
assert.Equal(t, int64(0), cacheStats.RevisionCacheNumItems.Value())
}
func TestBasicOperationsOnCacheWithMemoryStat(t *testing.T) {
dbcOptions := DatabaseContextOptions{
RevisionCacheOptions: &RevisionCacheOptions{
MaxBytes: 730,
MaxItemCount: 10,
},
}
db, ctx := SetupTestDBWithOptions(t, dbcOptions)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
cacheStats := db.DbStats.Cache()
collctionID := collection.GetCollectionID()
// Test Put on new doc
docSize, revID := createDocAndReturnSizeAndRev(t, ctx, "doc1", collection, Body{"test": "doc"})
assert.Equal(t, int64(docSize), cacheStats.RevisionCacheTotalMemory.Value())
// Test Get with item in the cache
docRev, err := db.revisionCache.Get(ctx, "doc1", revID, collctionID, RevCacheOmitDelta)
require.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, int64(docSize), cacheStats.RevisionCacheTotalMemory.Value())
revIDDoc1 := docRev.RevID
// Test Get operation with load from bucket, need to first create and remove from rev cache
prevMemStat := cacheStats.RevisionCacheTotalMemory.Value()
revIDDoc2 := createThenRemoveFromRevCache(t, ctx, "doc2", db, collection)
// load from doc from bucket
docRev, err = db.revisionCache.Get(ctx, "doc2", docRev.RevID, collctionID, RevCacheOmitDelta)
require.NoError(t, err)
assert.NotNil(t, docRev.BodyBytes)
assert.Equal(t, "doc2", docRev.DocID)
assert.Greater(t, cacheStats.RevisionCacheTotalMemory.Value(), prevMemStat)
// Test Get active with item resident in cache
prevMemStat = cacheStats.RevisionCacheTotalMemory.Value()
docRev, err = db.revisionCache.GetActive(ctx, "doc2", collctionID)
require.NoError(t, err)
assert.Equal(t, "doc2", docRev.DocID)
assert.Equal(t, prevMemStat, cacheStats.RevisionCacheTotalMemory.Value())
// Test Get active with item to be loaded from bucket, need to first create and remove from rev cache
prevMemStat = cacheStats.RevisionCacheTotalMemory.Value()
revIDDoc3 := createThenRemoveFromRevCache(t, ctx, "doc3", db, collection)
docRev, err = db.revisionCache.GetActive(ctx, "doc3", collctionID)
require.NoError(t, err)
assert.Equal(t, "doc3", docRev.DocID)
assert.Greater(t, cacheStats.RevisionCacheTotalMemory.Value(), prevMemStat)
// Test Peek at item not in cache, assert stats unchanged
prevMemStat = cacheStats.RevisionCacheTotalMemory.Value()
docRev, ok := db.revisionCache.Peek(ctx, "doc4", "1-abc", collctionID)
require.False(t, ok)
assert.Nil(t, docRev.BodyBytes)
assert.Equal(t, prevMemStat, cacheStats.RevisionCacheTotalMemory.Value())
// Test Peek in cache, assert stat unchanged
docRev, ok = db.revisionCache.Peek(ctx, "doc3", revIDDoc3, collctionID)
require.True(t, ok)
assert.Equal(t, "doc3", docRev.DocID)
assert.Equal(t, prevMemStat, cacheStats.RevisionCacheTotalMemory.Value())
// Test Upsert with item in cache + assert stat is expected
docRev.CalculateBytes()
doc3Size := docRev.MemoryBytes
expMem := cacheStats.RevisionCacheTotalMemory.Value() - doc3Size
newDocRev := DocumentRevision{
DocID: "doc3",
RevID: revIDDoc3,
BodyBytes: []byte(`"some": "body"`),
}
expMem = expMem + 14 // size for above doc rev
db.revisionCache.Upsert(ctx, newDocRev, collctionID)
assert.Equal(t, expMem, cacheStats.RevisionCacheTotalMemory.Value())
// Test Upsert with item not in cache, assert stat is as expected
newDocRev = DocumentRevision{
DocID: "doc5",
RevID: "1-abc",
BodyBytes: []byte(`"some": "body"`),
}
expMem = cacheStats.RevisionCacheTotalMemory.Value() + 14 // size for above doc rev
db.revisionCache.Upsert(ctx, newDocRev, collctionID)
assert.Equal(t, expMem, cacheStats.RevisionCacheTotalMemory.Value())
// Test Remove with something in cache, assert stat decrements by expected value
db.revisionCache.Remove(ctx, "doc5", "1-abc", collctionID)
expMem -= 14
assert.Equal(t, expMem, cacheStats.RevisionCacheTotalMemory.Value())
// Test Remove with item not in cache, assert stat is unchanged
prevMemStat = cacheStats.RevisionCacheTotalMemory.Value()
db.revisionCache.Remove(ctx, "doc6", "1-abc", collctionID)
assert.Equal(t, prevMemStat, cacheStats.RevisionCacheTotalMemory.Value())
// Test Update Delta, assert stat increases as expected
revDelta := newRevCacheDelta([]byte(`"rev":"delta"`), "1-abc", newDocRev, false, nil)
expMem = prevMemStat + revDelta.totalDeltaBytes
db.revisionCache.UpdateDelta(ctx, "doc3", revIDDoc3, collctionID, revDelta)
assert.Equal(t, expMem, cacheStats.RevisionCacheTotalMemory.Value())
// Empty cache and see memory stat is 0
db.revisionCache.Remove(ctx, "doc3", revIDDoc3, collctionID)
db.revisionCache.Remove(ctx, "doc2", revIDDoc2, collctionID)
db.revisionCache.Remove(ctx, "doc1", revIDDoc1, collctionID)
// TODO: pending CBG-4135 assert rev cache had 0 items in it
assert.Equal(t, int64(0), cacheStats.RevisionCacheTotalMemory.Value())
}
// Ensure subsequent updates to delta don't mutate previously retrieved deltas
func TestSingleLoad(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{nil, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 0,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
cache.Put(base.TestCtx(t), DocumentRevision{BodyBytes: []byte(`{"test":"1234"}`), DocID: "doc123", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
_, err := cache.Get(base.TestCtx(t), "doc123", "1-abc", testCollectionID, false)
assert.NoError(t, err)
}
// Ensure subsequent updates to delta don't mutate previously retrieved deltas
func TestConcurrentLoad(t *testing.T) {
cacheHitCounter, cacheMissCounter, getDocumentCounter, getRevisionCounter, cacheNumItems, memoryBytesCounted := base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}, base.SgwIntStat{}
backingStoreMap := CreateTestSingleBackingStoreMap(&testBackingStore{nil, &getDocumentCounter, &getRevisionCounter}, testCollectionID)
cacheOptions := &RevisionCacheOptions{
MaxItemCount: 10,
MaxBytes: 0,
}
cache := NewLRURevisionCache(cacheOptions, backingStoreMap, &cacheHitCounter, &cacheMissCounter, &cacheNumItems, &memoryBytesCounted)
cache.Put(base.TestCtx(t), DocumentRevision{BodyBytes: []byte(`{"test":"1234"}`), DocID: "doc1", RevID: "1-abc", History: Revisions{"start": 1}}, testCollectionID)
// Trigger load into cache
var wg sync.WaitGroup
wg.Add(20)
for i := 0; i < 20; i++ {
go func() {
_, err := cache.Get(base.TestCtx(t), "doc1", "1-abc", testCollectionID, false)
assert.NoError(t, err)
wg.Done()
}()
}
wg.Wait()
}
func TestRevisionCacheRemove(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
rev1id, _, err := collection.Put(ctx, "doc", Body{"val": 123})
assert.NoError(t, err)
docRev, err := collection.revisionCache.Get(ctx, "doc", rev1id, true)
assert.NoError(t, err)
assert.Equal(t, rev1id, docRev.RevID)
assert.Equal(t, int64(0), db.DbStats.Cache().RevisionCacheMisses.Value())
collection.revisionCache.Remove(ctx, "doc", rev1id)
docRev, err = collection.revisionCache.Get(ctx, "doc", rev1id, true)
assert.NoError(t, err)
assert.Equal(t, rev1id, docRev.RevID)
assert.Equal(t, int64(1), db.DbStats.Cache().RevisionCacheMisses.Value())
docRev, err = collection.revisionCache.GetActive(ctx, "doc")