-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathdatabase_test.go
3522 lines (2941 loc) · 121 KB
/
database_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 2012-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"
"encoding/json"
"fmt"
"log"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
sgbucket "github.com/couchbase/sg-bucket"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/channels"
"github.com/robertkrimen/otto/underscore"
"github.com/stretchr/testify/assert"
)
func init() {
underscore.Disable() // It really slows down unit tests (by making otto.New take a lot longer)
}
// Note: It is important to call db.Close() on the returned database.
func setupTestDB(t testing.TB) (*Database, context.Context) {
return setupTestDBWithCacheOptions(t, DefaultCacheOptions())
}
func setupTestDBForBucket(t testing.TB, bucket *base.TestBucket) (*Database, context.Context) {
cacheOptions := DefaultCacheOptions()
dbcOptions := DatabaseContextOptions{
CacheOptions: &cacheOptions,
}
return SetupTestDBForDataStoreWithOptions(t, bucket, dbcOptions)
}
func setupTestDBForBucketDefaultCollection(t testing.TB, bucket *base.TestBucket) (*Database, context.Context) {
cacheOptions := DefaultCacheOptions()
dbcOptions := DatabaseContextOptions{
CacheOptions: &cacheOptions,
Scopes: GetScopesOptionsDefaultCollectionOnly(t),
}
return SetupTestDBForDataStoreWithOptions(t, bucket, dbcOptions)
}
func setupTestDBWithOptionsAndImport(t testing.TB, tBucket *base.TestBucket, dbcOptions DatabaseContextOptions) (*Database, context.Context) {
ctx := base.TestCtx(t)
AddOptionsFromEnvironmentVariables(&dbcOptions)
if tBucket == nil {
tBucket = base.GetTestBucket(t)
}
if dbcOptions.Scopes == nil {
dbcOptions.Scopes = GetScopesOptions(t, tBucket, 1)
}
if dbcOptions.GroupID == "" && base.IsEnterpriseEdition() {
dbcOptions.GroupID = t.Name()
}
dbCtx, err := NewDatabaseContext(ctx, "db", tBucket, true, dbcOptions)
require.NoError(t, err, "Couldn't create context for database 'db'")
ctx = dbCtx.AddDatabaseLogContext(ctx)
err = dbCtx.StartOnlineProcesses(ctx)
require.NoError(t, err)
db, err := CreateDatabase(dbCtx)
require.NoError(t, err, "Couldn't create database 'db'")
return db, addDatabaseAndTestUserContext(ctx, db)
}
func setupTestDBWithCacheOptions(t testing.TB, options CacheOptions) (*Database, context.Context) {
dbcOptions := DatabaseContextOptions{
CacheOptions: &options,
}
return SetupTestDBWithOptions(t, dbcOptions)
}
// Forces UseViews:true in the database context. Useful for testing w/ views while running
// tests against Couchbase Server
func setupTestDBWithViewsEnabled(t testing.TB) (*Database, context.Context) {
if !base.TestsDisableGSI() {
t.Skip("GSI is not compatible with views")
}
dbcOptions := DatabaseContextOptions{
UseViews: true,
Scopes: GetScopesOptionsDefaultCollectionOnly(t),
}
return SetupTestDBWithOptions(t, dbcOptions)
}
// Sets up a test bucket with _sync:seq initialized to a high value prior to database creation. Used to test
// issues with custom _sync:seq values without triggering skipped sequences between 0 and customSeq
func setupTestDBWithCustomSyncSeq(t testing.TB, customSeq uint64) (*Database, context.Context) {
ctx := base.TestCtx(t)
tBucket := base.GetTestBucket(t)
dbcOptions := DatabaseContextOptions{
Scopes: GetScopesOptions(t, tBucket, 1),
}
AddOptionsFromEnvironmentVariables(&dbcOptions)
// This may need to change when we move to a non-default metadata collection...
metadataStore := tBucket.GetMetadataStore()
log.Printf("Initializing test %s to %d", base.DefaultMetadataKeys.SyncSeqKey(), customSeq)
_, incrErr := metadataStore.Incr(base.DefaultMetadataKeys.SyncSeqKey(), customSeq, customSeq, 0)
assert.NoError(t, incrErr, fmt.Sprintf("Couldn't increment %s by %d", base.DefaultMetadataKeys.SyncSeqKey(), customSeq))
dbCtx, err := NewDatabaseContext(ctx, "db", tBucket, false, dbcOptions)
assert.NoError(t, err, "Couldn't create context for database 'db'")
ctx = dbCtx.AddDatabaseLogContext(ctx)
err = dbCtx.StartOnlineProcesses(ctx)
require.NoError(t, err)
db, err := CreateDatabase(dbCtx)
assert.NoError(t, err, "Couldn't create database 'db'")
atomic.StoreUint32(&dbCtx.State, DBOnline)
return db, addDatabaseAndTestUserContext(ctx, db)
}
func setupTestLeakyDBWithCacheOptions(t *testing.T, options CacheOptions, leakyOptions base.LeakyBucketConfig) (*Database, context.Context) {
ctx := base.TestCtx(t)
testBucket := base.GetTestBucket(t)
dbcOptions := DatabaseContextOptions{
CacheOptions: &options,
Scopes: GetScopesOptions(t, testBucket, 1),
}
AddOptionsFromEnvironmentVariables(&dbcOptions)
leakyBucket := base.NewLeakyBucket(testBucket, leakyOptions)
dbCtx, err := NewDatabaseContext(ctx, "db", leakyBucket, false, dbcOptions)
if err != nil {
testBucket.Close(ctx)
t.Fatalf("Unable to create database context: %v", err)
}
ctx = dbCtx.AddDatabaseLogContext(ctx)
err = dbCtx.StartOnlineProcesses(ctx)
if err != nil {
dbCtx.Close(ctx)
t.Fatalf("Unable to start online processes: %v", err)
}
db, err := CreateDatabase(dbCtx)
if err != nil {
dbCtx.Close(ctx)
t.Fatalf("Unable to create database: %v", err)
}
return db, addDatabaseAndTestUserContext(ctx, db)
}
func setupTestDBWithLeakyBucket(t testing.TB, leakyBucket *base.LeakyBucket) (*Database, context.Context) {
ctx := base.TestCtx(t)
testBucket, ok := leakyBucket.GetUnderlyingBucket().(*base.TestBucket)
require.True(t, ok)
dbcOptions := DatabaseContextOptions{
Scopes: GetScopesOptions(t, testBucket, 1),
}
AddOptionsFromEnvironmentVariables(&dbcOptions)
dbCtx, err := NewDatabaseContext(ctx, "db", leakyBucket, false, dbcOptions)
if err != nil {
leakyBucket.Close(ctx)
t.Fatalf("Unable to create database context: %v", err)
}
ctx = dbCtx.AddDatabaseLogContext(ctx)
err = dbCtx.StartOnlineProcesses(ctx)
if err != nil {
dbCtx.Close(ctx)
t.Fatalf("Unable to start online processes: %v", err)
}
db, err := CreateDatabase(dbCtx)
if err != nil {
dbCtx.Close(ctx)
t.Fatalf("Unable to create database: %v", err)
}
return db, addDatabaseAndTestUserContext(ctx, db)
}
func setupTestDBDefaultCollection(t testing.TB) (*Database, context.Context) {
cacheOptions := DefaultCacheOptions()
dbcOptions := DatabaseContextOptions{
Scopes: GetScopesOptionsDefaultCollectionOnly(t),
CacheOptions: &cacheOptions,
}
return SetupTestDBWithOptions(t, dbcOptions)
}
func assertHTTPError(t *testing.T, err error, status int) bool {
var httpErr *base.HTTPError
return assert.Error(t, err) &&
assert.ErrorAs(t, err, &httpErr) &&
assert.Equal(t, status, httpErr.Status)
}
func TestDatabase(t *testing.T) {
base.SetUpTestLogging(t, base.LevelDebug, base.KeyAll)
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
// Test creating & updating a document:
log.Printf("Create rev 1...")
body := Body{"key1": "value1", "key2": 1234}
rev1id, doc, err := collection.Put(ctx, "doc1", body)
body[BodyId] = doc.ID
body[BodyRev] = rev1id
assert.NoError(t, err, "Couldn't create document")
assert.Equal(t, "1-cb0c9a22be0e5a1b01084ec019defa81", rev1id)
log.Printf("Create rev 2...")
body["key1"] = "new value"
body["key2"] = int64(4321)
rev2id, _, err := collection.Put(ctx, "doc1", body)
body[BodyId] = "doc1"
body[BodyRev] = rev2id
assert.NoError(t, err, "Couldn't update document")
assert.Equal(t, "2-488724414d0ed6b398d6d2aeb228d797", rev2id)
// Retrieve the document:
log.Printf("Retrieve doc...")
gotbody, err := collection.Get1xBody(ctx, "doc1")
assert.NoError(t, err, "Couldn't get document")
AssertEqualBodies(t, body, gotbody)
log.Printf("Retrieve rev 1...")
gotbody, err = collection.Get1xRevBody(ctx, "doc1", rev1id, false, nil)
assert.NoError(t, err, "Couldn't get document with rev 1")
expectedResult := Body{"key1": "value1", "key2": 1234, BodyId: "doc1", BodyRev: rev1id}
AssertEqualBodies(t, expectedResult, gotbody)
log.Printf("Retrieve rev 2...")
gotbody, err = collection.Get1xRevBody(ctx, "doc1", rev2id, false, nil)
assert.NoError(t, err, "Couldn't get document with rev")
AssertEqualBodies(t, body, gotbody)
gotbody, err = collection.Get1xRevBody(ctx, "doc1", "bogusrev", false, nil)
status, _ := base.ErrorAsHTTPStatus(err)
assert.Equal(t, 404, status)
require.Nil(t, gotbody)
// Test the _revisions property:
log.Printf("Check _revisions...")
gotbody, err = collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
require.NoError(t, err)
revisions := gotbody[BodyRevisions].(Revisions)
assert.Equal(t, 2, revisions[RevisionsStart])
assert.Equal(t, []string{"488724414d0ed6b398d6d2aeb228d797",
"cb0c9a22be0e5a1b01084ec019defa81"}, revisions[RevisionsIds])
// Test RevDiff:
log.Printf("Check RevDiff...")
missing, possible := collection.RevDiff(ctx, "doc1",
[]string{"1-cb0c9a22be0e5a1b01084ec019defa81",
"2-488724414d0ed6b398d6d2aeb228d797"})
assert.True(t, missing == nil)
assert.True(t, possible == nil)
missing, possible = collection.RevDiff(ctx, "doc1",
[]string{"1-cb0c9a22be0e5a1b01084ec019defa81",
"3-foo"})
assert.Equal(t, []string{"3-foo"}, missing)
assert.Equal(t, []string{"2-488724414d0ed6b398d6d2aeb228d797"}, possible)
missing, possible = collection.RevDiff(ctx, "nosuchdoc",
[]string{"1-cb0c9a22be0e5a1b01084ec019defa81",
"3-foo"})
assert.Equal(t, []string{"1-cb0c9a22be0e5a1b01084ec019defa81",
"3-foo"}, missing)
assert.True(t, possible == nil)
// Test CheckProposedRev:
log.Printf("Check CheckProposedRev...")
proposedStatus, current := collection.CheckProposedRev(ctx, "doc1", "3-foo",
"2-488724414d0ed6b398d6d2aeb228d797")
assert.Equal(t, ProposedRev_OK, proposedStatus)
assert.Equal(t, "", current)
proposedStatus, current = collection.CheckProposedRev(ctx, "doc1",
"2-488724414d0ed6b398d6d2aeb228d797",
"1-xxx")
assert.Equal(t, ProposedRev_Exists, proposedStatus)
assert.Equal(t, "", current)
proposedStatus, current = collection.CheckProposedRev(ctx, "doc1",
"3-foo",
"2-bogus")
assert.Equal(t, ProposedRev_Conflict, proposedStatus)
assert.Equal(t, "2-488724414d0ed6b398d6d2aeb228d797", current)
proposedStatus, current = collection.CheckProposedRev(ctx, "doc1",
"3-foo",
"")
assert.Equal(t, ProposedRev_Conflict, proposedStatus)
assert.Equal(t, "2-488724414d0ed6b398d6d2aeb228d797", current)
proposedStatus, current = collection.CheckProposedRev(ctx, "nosuchdoc", "3-foo", "")
assert.Equal(t, ProposedRev_OK_IsNew, proposedStatus)
assert.Equal(t, "", current)
// Test PutExistingRev:
log.Printf("Check PutExistingRev...")
body[BodyRev] = "4-four"
body["key1"] = "fourth value"
body["key2"] = int64(4444)
history := []string{"4-four", "3-three", "2-488724414d0ed6b398d6d2aeb228d797",
"1-cb0c9a22be0e5a1b01084ec019defa81"}
doc, newRev, err := collection.PutExistingRevWithBody(ctx, "doc1", body, history, false)
body[BodyId] = doc.ID
body[BodyRev] = newRev
assert.NoError(t, err, "PutExistingRev failed")
// Retrieve the document:
log.Printf("Check Get...")
gotbody, err = collection.Get1xBody(ctx, "doc1")
assert.NoError(t, err, "Couldn't get document")
AssertEqualBodies(t, body, gotbody)
}
func TestGetDeleted(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
body := Body{"key1": 1234}
rev1id, _, err := collection.Put(ctx, "doc1", body)
assert.NoError(t, err, "Put")
rev2id, err := collection.DeleteDoc(ctx, "doc1", rev1id)
assert.NoError(t, err, "DeleteDoc")
// Get the deleted doc with its history; equivalent to GET with ?revs=true
body, err = collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assert.NoError(t, err, "Get1xRevBody")
expectedResult := Body{
BodyId: "doc1",
BodyRev: rev2id,
BodyDeleted: true,
BodyRevisions: Revisions{RevisionsStart: 2, RevisionsIds: []string{"bc6d97f6e97c0d034a34f8aac2bf8b44", "dfd5e19813767eeddd08270fc5f385cd"}},
}
AssertEqualBodies(t, expectedResult, body)
// Get the raw doc and make sure the sync data has the current revision
doc, err := collection.GetDocument(ctx, "doc1", DocUnmarshalAll)
assert.NoError(t, err, "Err getting doc")
assert.Equal(t, rev2id, doc.SyncData.CurrentRev)
// Try again but with a user who doesn't have access to this revision (see #179)
authenticator := auth.NewAuthenticator(db.MetadataStore, db, db.AuthenticatorOptions(ctx))
collection.user, err = authenticator.GetUser("")
assert.NoError(t, err, "GetUser")
collection.user.SetExplicitChannels(nil, 1)
body, err = collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assert.NoError(t, err, "Get1xRevBody")
AssertEqualBodies(t, expectedResult, body)
}
// Test retrieval of a channel removal revision, when the revision is not otherwise available
func TestGetRemovedAsUser(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
collection.ChannelMapper = channels.NewChannelMapper(ctx, channels.DocChannelsSyncFunction, db.Options.JavascriptTimeout)
backingStoreMap := CreateTestSingleBackingStoreMap(collection, collection.GetCollectionID())
rev1body := Body{
"key1": 1234,
"channels": []string{"ABC"},
}
rev1id, _, err := collection.Put(ctx, "doc1", rev1body)
assert.NoError(t, err, "Put")
rev2body := Body{
"key1": 1234,
"channels": []string{"NBC"},
BodyRev: rev1id,
}
rev2id, _, err := collection.Put(ctx, "doc1", rev2body)
assert.NoError(t, err, "Put Rev 2")
// Add another revision, so that rev 2 is obsolete
rev3body := Body{
"key1": 12345,
"channels": []string{"NBC"},
BodyRev: rev2id,
}
_, _, err = collection.Put(ctx, "doc1", rev3body)
assert.NoError(t, err, "Put Rev 3")
// Get the deleted doc with its history; equivalent to GET with ?revs=true, while still resident in the rev cache
body, err := collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assert.NoError(t, err, "Get1xRevBody")
rev2digest := rev2id[2:]
rev1digest := rev1id[2:]
expectedResult := Body{
"key1": 1234,
"channels": []string{"NBC"},
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2digest, rev1digest}},
BodyId: "doc1",
BodyRev: rev2id,
}
AssertEqualBodies(t, expectedResult, body)
// Manually remove the temporary backup doc from the bucket
// Manually flush the rev cache
// After expiry from the rev cache and removal of doc backup, try again
cacheHitCounter, cacheMissCounter, cacheNumItems, memoryCacheStat := db.DatabaseContext.DbStats.Cache().RevisionCacheHits, db.DatabaseContext.DbStats.Cache().RevisionCacheMisses, db.DatabaseContext.DbStats.Cache().RevisionCacheNumItems, db.DatabaseContext.DbStats.Cache().RevisionCacheTotalMemory
cacheOptions := &RevisionCacheOptions{
MaxBytes: 0,
MaxItemCount: DefaultRevisionCacheSize,
ShardCount: DefaultRevisionCacheShardCount,
}
collection.dbCtx.revisionCache = NewShardedLRURevisionCache(cacheOptions, backingStoreMap, cacheHitCounter, cacheMissCounter, cacheNumItems, memoryCacheStat)
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev2id)
assert.NoError(t, err, "Purge old revision JSON")
// Try again with a user who doesn't have access to this revision
authenticator := auth.NewAuthenticator(db.MetadataStore, db, db.AuthenticatorOptions(ctx))
collection.user, err = authenticator.GetUser("")
assert.NoError(t, err, "GetUser")
var chans channels.TimedSet
chans = channels.AtSequence(base.SetOf("ABC"), 1)
collection.user.SetExplicitChannels(chans, 1)
// Get the removal revision with its history; equivalent to GET with ?revs=true
body, err = collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
require.NoError(t, err, "Get1xRevBody")
expectedResult = Body{
BodyId: "doc1",
BodyRev: rev2id,
BodyRemoved: true,
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2digest, rev1digest}},
}
assert.Equal(t, expectedResult, body)
// Ensure revision is unavailable for a non-leaf revision that isn't available via the rev cache, and wasn't a channel removal
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev1id)
assert.NoError(t, err, "Purge old revision JSON")
_, err = collection.Get1xRevBody(ctx, "doc1", rev1id, true, nil)
assertHTTPError(t, err, 404)
}
func TestIsServerless(t *testing.T) {
testCases := []struct {
title string
serverless bool
}{
{
serverless: true,
},
{
serverless: false,
},
}
for _, testCase := range testCases {
t.Run(fmt.Sprintf("TestIsServerless with Serverless=%t", testCase.serverless), func(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
db.Options.Serverless = testCase.serverless
assert.Equal(t, testCase.serverless, db.IsServerless())
})
}
}
// Test removal handling for unavailable multi-channel revisions.
func TestGetRemovalMultiChannel(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
auth := db.Authenticator(ctx)
// Create a user who have access to both channel ABC and NBC.
userAlice, err := auth.NewUser("alice", "pass", base.SetOf("ABC", "NBC"))
require.NoError(t, err, "Error creating user")
// Create a user who have access to channel NBC.
userBob, err := auth.NewUser("bob", "pass", base.SetOf("NBC"))
require.NoError(t, err, "Error creating user")
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
collection.ChannelMapper = channels.NewChannelMapper(ctx, channels.DocChannelsSyncFunction, db.Options.JavascriptTimeout)
// Create the first revision of doc1.
rev1Body := Body{
"k1": "v1",
"channels": []string{"ABC", "NBC"},
}
rev1ID, _, err := collection.Put(ctx, "doc1", rev1Body)
require.NoError(t, err, "Error creating doc")
// Create the second revision of doc1 on channel ABC as removal from channel NBC.
rev2Body := Body{
"k2": "v2",
"channels": []string{"ABC"},
BodyRev: rev1ID,
}
rev2ID, _, err := collection.Put(ctx, "doc1", rev2Body)
require.NoError(t, err, "Error creating doc")
// Create the third revision of doc1 on channel ABC.
rev3Body := Body{
"k3": "v3",
"channels": []string{"ABC"},
BodyRev: rev2ID,
}
rev3ID, _, err := collection.Put(ctx, "doc1", rev3Body)
require.NoError(t, err, "Error creating doc")
require.NotEmpty(t, rev3ID, "Error creating doc")
// Get rev2 of the doc as a user who have access to this revision.
collection.user = userAlice
body, err := collection.Get1xRevBody(ctx, "doc1", rev2ID, true, nil)
require.NoError(t, err, "Error getting 1x rev body")
_, rev1Digest := ParseRevID(ctx, rev1ID)
_, rev2Digest := ParseRevID(ctx, rev2ID)
var interfaceListChannels []interface{}
interfaceListChannels = append(interfaceListChannels, "ABC")
bodyExpected := Body{
"k2": "v2",
"channels": interfaceListChannels,
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2Digest, rev1Digest},
},
BodyId: "doc1",
BodyRev: rev2ID,
}
require.Equal(t, bodyExpected, body)
// Get rev2 of the doc as a user who doesn't have access to this revision.
collection.user = userBob
body, err = collection.Get1xRevBody(ctx, "doc1", rev2ID, true, nil)
require.NoError(t, err, "Error getting 1x rev body")
bodyExpected = Body{
BodyRemoved: true,
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2Digest, rev1Digest},
},
BodyId: "doc1",
BodyRev: rev2ID,
}
require.Equal(t, bodyExpected, body)
// Flush the revision cache and purge the old revision backup.
db.FlushRevisionCacheForTest()
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev2ID)
require.NoError(t, err, "Error purging old revision JSON")
// Try with a user who has access to this revision.
collection.user = userAlice
body, err = collection.Get1xRevBody(ctx, "doc1", rev2ID, true, nil)
assertHTTPError(t, err, 404)
require.Nil(t, body)
// Get rev2 of the doc as a user who doesn't have access to this revision.
collection.user = userBob
body, err = collection.Get1xRevBody(ctx, "doc1", rev2ID, true, nil)
require.NoError(t, err, "Error getting 1x rev body")
bodyExpected = Body{
BodyRemoved: true,
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2Digest, rev1Digest},
},
BodyId: "doc1",
BodyRev: rev2ID,
}
require.Equal(t, bodyExpected, body)
}
// Test delta sync behavior when the fromRevision is a channel removal.
func TestDeltaSyncWhenFromRevIsChannelRemoval(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
// Create the first revision of doc1.
rev1Body := Body{
"k1": "v1",
"channels": []string{"ABC", "NBC"},
}
rev1ID, _, err := collection.Put(ctx, "doc1", rev1Body)
require.NoError(t, err, "Error creating doc")
// Create the second revision of doc1 on channel ABC as removal from channel NBC.
rev2Body := Body{
"k2": "v2",
"channels": []string{"ABC"},
BodyRev: rev1ID,
}
rev2ID, _, err := collection.Put(ctx, "doc1", rev2Body)
require.NoError(t, err, "Error creating doc")
// Create the third revision of doc1 on channel ABC.
rev3Body := Body{
"k3": "v3",
"channels": []string{"ABC"},
BodyRev: rev2ID,
}
rev3ID, _, err := collection.Put(ctx, "doc1", rev3Body)
require.NoError(t, err, "Error creating doc")
require.NotEmpty(t, rev3ID, "Error creating doc")
// Flush the revision cache and purge the old revision backup.
db.FlushRevisionCacheForTest()
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev2ID)
require.NoError(t, err, "Error purging old revision JSON")
// Request delta between rev2ID and rev3ID (toRevision "rev2ID" is channel removal)
// as a user who doesn't have access to the removed revision via any other channel.
authenticator := db.Authenticator(ctx)
user, err := authenticator.NewUser("alice", "pass", base.SetOf("NBC"))
require.NoError(t, err, "Error creating user")
collection.user = user
require.NoError(t, db.DbStats.InitDeltaSyncStats())
delta, redactedRev, err := collection.GetDelta(ctx, "doc1", rev2ID, rev3ID)
require.Equal(t, base.HTTPErrorf(404, "missing"), err)
assert.Nil(t, delta)
assert.Nil(t, redactedRev)
// Request delta between rev2ID and rev3ID (toRevision "rev2ID" is channel removal)
// as a user who has access to the removed revision via another channel.
user, err = authenticator.NewUser("bob", "pass", base.SetOf("ABC"))
require.NoError(t, err, "Error creating user")
collection.user = user
require.NoError(t, db.DbStats.InitDeltaSyncStats())
delta, redactedRev, err = collection.GetDelta(ctx, "doc1", rev2ID, rev3ID)
require.Equal(t, base.HTTPErrorf(404, "missing"), err)
assert.Nil(t, delta)
assert.Nil(t, redactedRev)
}
// Test delta sync behavior when the toRevision is a channel removal.
func TestDeltaSyncWhenToRevIsChannelRemoval(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
collection.ChannelMapper = channels.NewChannelMapper(ctx, channels.DocChannelsSyncFunction, db.Options.JavascriptTimeout)
// Create the first revision of doc1.
rev1Body := Body{
"k1": "v1",
"channels": []string{"ABC", "NBC"},
}
rev1ID, _, err := collection.Put(ctx, "doc1", rev1Body)
require.NoError(t, err, "Error creating doc")
// Create the second revision of doc1 on channel ABC as removal from channel NBC.
rev2Body := Body{
"k2": "v2",
"channels": []string{"ABC"},
BodyRev: rev1ID,
}
rev2ID, _, err := collection.Put(ctx, "doc1", rev2Body)
require.NoError(t, err, "Error creating doc")
// Create the third revision of doc1 on channel ABC.
rev3Body := Body{
"k3": "v3",
"channels": []string{"ABC"},
BodyRev: rev2ID,
}
rev3ID, _, err := collection.Put(ctx, "doc1", rev3Body)
require.NoError(t, err, "Error creating doc")
require.NotEmpty(t, rev3ID, "Error creating doc")
// Flush the revision cache and purge the old revision backup.
db.FlushRevisionCacheForTest()
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev2ID)
require.NoError(t, err, "Error purging old revision JSON")
// Request delta between rev1ID and rev2ID (toRevision "rev2ID" is channel removal)
// as a user who doesn't have access to the removed revision via any other channel.
authenticator := db.Authenticator(ctx)
user, err := authenticator.NewUser("alice", "pass", base.SetOf("NBC"))
require.NoError(t, err, "Error creating user")
collection.user = user
require.NoError(t, db.DbStats.InitDeltaSyncStats())
delta, redactedRev, err := collection.GetDelta(ctx, "doc1", rev1ID, rev2ID)
require.NoError(t, err)
assert.Nil(t, delta)
assert.Equal(t, `{"_removed":true}`, string(redactedRev.BodyBytes))
// Request delta between rev1ID and rev2ID (toRevision "rev2ID" is channel removal)
// as a user who has access to the removed revision via another channel.
user, err = authenticator.NewUser("bob", "pass", base.SetOf("ABC"))
require.NoError(t, err, "Error creating user")
collection.user = user
require.NoError(t, db.DbStats.InitDeltaSyncStats())
delta, redactedRev, err = collection.GetDelta(ctx, "doc1", rev1ID, rev2ID)
require.Equal(t, base.HTTPErrorf(404, "missing"), err)
assert.Nil(t, delta)
assert.Nil(t, redactedRev)
}
// Test retrieval of a channel removal revision, when the revision is not otherwise available
func TestGetRemoved(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
backingStoreMap := CreateTestSingleBackingStoreMap(collection, collection.GetCollectionID())
rev1body := Body{
"key1": 1234,
"channels": []string{"ABC"},
}
rev1id, _, err := collection.Put(ctx, "doc1", rev1body)
assert.NoError(t, err, "Put")
rev2body := Body{
"key1": 1234,
"channels": []string{"NBC"},
BodyRev: rev1id,
}
rev2id, _, err := collection.Put(ctx, "doc1", rev2body)
assert.NoError(t, err, "Put Rev 2")
// Add another revision, so that rev 2 is obsolete
rev3body := Body{
"key1": 12345,
"channels": []string{"NBC"},
BodyRev: rev2id,
}
_, _, err = collection.Put(ctx, "doc1", rev3body)
assert.NoError(t, err, "Put Rev 3")
// Get the deleted doc with its history; equivalent to GET with ?revs=true, while still resident in the rev cache
body, err := collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assert.NoError(t, err, "Get1xRevBody")
rev2digest := rev2id[2:]
rev1digest := rev1id[2:]
expectedResult := Body{
"key1": 1234,
"channels": []string{"NBC"},
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2digest, rev1digest}},
BodyId: "doc1",
BodyRev: rev2id,
}
AssertEqualBodies(t, expectedResult, body)
// Manually remove the temporary backup doc from the bucket
// Manually flush the rev cache
// After expiry from the rev cache and removal of doc backup, try again
cacheHitCounter, cacheMissCounter, cacheNumItems, memoryCacheStat := db.DatabaseContext.DbStats.Cache().RevisionCacheHits, db.DatabaseContext.DbStats.Cache().RevisionCacheMisses, db.DatabaseContext.DbStats.Cache().RevisionCacheNumItems, db.DatabaseContext.DbStats.Cache().RevisionCacheTotalMemory
cacheOptions := &RevisionCacheOptions{
MaxBytes: 0,
MaxItemCount: DefaultRevisionCacheSize,
ShardCount: DefaultRevisionCacheShardCount,
}
collection.dbCtx.revisionCache = NewShardedLRURevisionCache(cacheOptions, backingStoreMap, cacheHitCounter, cacheMissCounter, cacheNumItems, memoryCacheStat)
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev2id)
assert.NoError(t, err, "Purge old revision JSON")
// Get the removal revision with its history; equivalent to GET with ?revs=true
body, err = collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assertHTTPError(t, err, 404)
require.Nil(t, body)
// Ensure revision is unavailable for a non-leaf revision that isn't available via the rev cache, and wasn't a channel removal
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev1id)
assert.NoError(t, err, "Purge old revision JSON")
_, err = collection.Get1xRevBody(ctx, "doc1", rev1id, true, nil)
assertHTTPError(t, err, 404)
}
// Test retrieval of a channel removal revision, when the revision is not otherwise available
func TestGetRemovedAndDeleted(t *testing.T) {
db, ctx := setupTestDB(t)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
backingStoreMap := CreateTestSingleBackingStoreMap(collection, collection.GetCollectionID())
rev1body := Body{
"key1": 1234,
"channels": []string{"ABC"},
}
rev1id, _, err := collection.Put(ctx, "doc1", rev1body)
assert.NoError(t, err, "Put")
rev2body := Body{
"key1": 1234,
BodyDeleted: true,
BodyRev: rev1id,
}
rev2id, _, err := collection.Put(ctx, "doc1", rev2body)
assert.NoError(t, err, "Put Rev 2")
// Add another revision, so that rev 2 is obsolete
rev3body := Body{
"key1": 12345,
"channels": []string{"NBC"},
BodyRev: rev2id,
}
_, _, err = collection.Put(ctx, "doc1", rev3body)
assert.NoError(t, err, "Put Rev 3")
// Get the deleted doc with its history; equivalent to GET with ?revs=true, while still resident in the rev cache
body, err := collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assert.NoError(t, err, "Get1xRevBody")
rev2digest := rev2id[2:]
rev1digest := rev1id[2:]
expectedResult := Body{
"key1": 1234,
BodyDeleted: true,
BodyRevisions: Revisions{
RevisionsStart: 2,
RevisionsIds: []string{rev2digest, rev1digest}},
BodyId: "doc1",
BodyRev: rev2id,
}
AssertEqualBodies(t, expectedResult, body)
// Manually remove the temporary backup doc from the bucket
// Manually flush the rev cache
// After expiry from the rev cache and removal of doc backup, try again
cacheHitCounter, cacheMissCounter, cacheNumItems, memoryCacheStats := db.DatabaseContext.DbStats.Cache().RevisionCacheHits, db.DatabaseContext.DbStats.Cache().RevisionCacheMisses, db.DatabaseContext.DbStats.Cache().RevisionCacheNumItems, db.DatabaseContext.DbStats.Cache().RevisionCacheTotalMemory
cacheOptions := &RevisionCacheOptions{
MaxBytes: 0,
MaxItemCount: DefaultRevisionCacheSize,
ShardCount: DefaultRevisionCacheShardCount,
}
collection.dbCtx.revisionCache = NewShardedLRURevisionCache(cacheOptions, backingStoreMap, cacheHitCounter, cacheMissCounter, cacheNumItems, memoryCacheStats)
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev2id)
assert.NoError(t, err, "Purge old revision JSON")
// Get the deleted doc with its history; equivalent to GET with ?revs=true
body, err = collection.Get1xRevBody(ctx, "doc1", rev2id, true, nil)
assertHTTPError(t, err, 404)
require.Nil(t, body)
// Ensure revision is unavailable for a non-leaf revision that isn't available via the rev cache, and wasn't a channel removal
err = collection.PurgeOldRevisionJSON(ctx, "doc1", rev1id)
assert.NoError(t, err, "Purge old revision JSON")
_, err = collection.Get1xRevBody(ctx, "doc1", rev1id, true, nil)
assertHTTPError(t, err, 404)
}
type AllDocsEntry struct {
IDRevAndSequence
Channels []string
}
func (e AllDocsEntry) Equal(e2 AllDocsEntry) bool {
return e.DocID == e2.DocID && e.RevID == e2.RevID && e.Sequence == e2.Sequence &&
base.SetFromArray(e.Channels).Equals(base.SetFromArray(e2.Channels))
}
var options ForEachDocIDOptions
func allDocIDs(ctx context.Context, collection *DatabaseCollection) (docs []AllDocsEntry, err error) {
err = collection.ForEachDocID(ctx, func(doc IDRevAndSequence, channels []string) (bool, error) {
docs = append(docs, AllDocsEntry{
IDRevAndSequence: doc,
Channels: channels,
})
return true, nil
}, options)
return
}
func TestAllDocsOnly(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyCache)
// Lower the log max length so no more than 50 items will be kept.
cacheOptions := DefaultCacheOptions()
cacheOptions.ChannelCacheMaxLength = 50
db, ctx := setupTestDBWithCacheOptions(t, cacheOptions)
defer db.Close(ctx)
collection, ctx := GetSingleDatabaseCollectionWithUser(ctx, t, db)
collection.ChannelMapper = channels.NewChannelMapper(ctx, channels.DocChannelsSyncFunction, db.Options.JavascriptTimeout)
collectionID := collection.GetCollectionID()
// Trigger creation of the channel cache for channel "all"
_, err := db.changeCache.getChannelCache().getSingleChannelCache(ctx, channels.NewID("all", collectionID))
require.NoError(t, err)
ids := make([]AllDocsEntry, 100)
for i := 0; i < 100; i++ {
channels := []string{"all"}
if i%10 == 0 {
channels = append(channels, "KFJC")
}
body := Body{"serialnumber": int64(i), "channels": channels}
ids[i].DocID = fmt.Sprintf("alldoc-%02d", i)
revid, _, err := collection.Put(ctx, ids[i].DocID, body)
ids[i].RevID = revid
ids[i].Sequence = uint64(i + 1)
ids[i].Channels = channels
assert.NoError(t, err, "Couldn't create document")
}
alldocs, err := allDocIDs(ctx, collection.DatabaseCollection)
assert.NoError(t, err, "AllDocIDs failed")
require.Len(t, alldocs, 100)
for i, entry := range alldocs {
assert.True(t, entry.Equal(ids[i]))
}
// Now delete one document and try again:
_, err = collection.DeleteDoc(ctx, ids[23].DocID, ids[23].RevID)
assert.NoError(t, err, "Couldn't delete doc 23")
alldocs, err = allDocIDs(ctx, collection.DatabaseCollection)
assert.NoError(t, err, "AllDocIDs failed")
require.Len(t, alldocs, 99)
for i, entry := range alldocs {
j := i
if i >= 23 {
j++
}
assert.True(t, entry.Equal(ids[j]))
}
// Inspect the channel log to confirm that it's only got the last 50 sequences.
// There are 101 sequences overall, so the 1st one it has should be #52.
err = db.changeCache.waitForSequence(ctx, 101, base.DefaultWaitForSequence)
require.NoError(t, err)
changeLog, err := collection.GetChangeLog(ctx, channels.NewID("all", collectionID), 0)
require.NoError(t, err)
require.Len(t, changeLog, 50)
assert.Equal(t, "alldoc-51", changeLog[0].DocID)
// Now check the changes feed:
var options ChangesOptions
changesCtx, changesCtxCancel := context.WithCancel(base.TestCtx(t))
options.ChangesCtx = changesCtx
defer changesCtxCancel()
changes := getChanges(t, collection, channels.BaseSetOf(t, "all"), options)
require.Len(t, changes, 100)
for i, change := range changes {
docIndex := i
if i >= 23 {
docIndex++
}
if i == len(changes)-1 {
// The last entry in the changes response should be the deleted document
assert.True(t, change.Deleted)
assert.Equal(t, "alldoc-23", change.ID)
assert.Equal(t, channels.BaseSetOf(t, "all"), change.Removed)
} else {
// Verify correct ordering for all other documents
assert.Equal(t, fmt.Sprintf("alldoc-%02d", docIndex), change.ID)
}
}
// Check whether sequences are ascending for all entries in the changes response
sortedSeqAsc := func(changes []*ChangeEntry) bool {