-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathblip_api_delta_sync_test.go
More file actions
1489 lines (1264 loc) · 54.1 KB
/
blip_api_delta_sync_test.go
File metadata and controls
1489 lines (1264 loc) · 54.1 KB
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 2022-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 rest
import (
"encoding/base64"
"net/http"
"testing"
"github.com/couchbase/go-blip"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/channels"
"github.com/couchbase/sync_gateway/db"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestBlipDeltaSyncPushAttachment tests updating a doc that has an attachment with a delta that doesn't modify the attachment.
func TestBlipDeltaSyncPushAttachment(t *testing.T) {
if !base.IsEnterpriseEdition() {
t.Skip("Delta test requires EE")
}
rtConfig := &RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: base.Ptr(true),
},
}},
GuestEnabled: true,
}
const docID = "pushAttachmentDoc"
btcRunner := NewBlipTesterClientRunner(t)
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t, rtConfig)
defer rt.Close()
btc := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer btc.Close()
btcRunner.StartPush(btc.id)
// Push first rev
version := btcRunner.AddRev(btc.id, docID, EmptyDocVersion(), []byte(`{"key":"val"}`))
rt.WaitForVersion(docID, version)
// Push second rev with an attachment (no delta yet)
attData := base64.StdEncoding.EncodeToString([]byte("attach"))
version = btcRunner.AddRev(btc.id, docID, &version, []byte(`{"key":"val","_attachments":{"myAttachment":{"data":"`+attData+`"}}}`))
rt.WaitForVersion(docID, version)
syncData := db.GetRawSyncXattr(t, rt.GetSingleDataStore(), docID)
require.Empty(t, syncData.AttachmentsPre4dot0)
require.Equal(t, db.AttachmentMap{
"myAttachment": {
Digest: "sha1-E84HH2iVirRjaYhTGJ1jYQANtcI=",
Revpos: 2,
Length: 6,
Stub: true,
Version: 2,
},
}, db.GetRawGlobalSyncAttachments(t, rt.GetSingleDataStore(), docID))
// Turn deltas on
btc.ClientDeltas = true
// Get existing body with the stub attachment, insert a new property and push as delta.
body, found := btcRunner.GetVersion(btc.id, docID, version)
require.True(t, found)
newBody, err := base.InjectJSONPropertiesFromBytes(body, base.KVPairBytes{Key: "update", Val: []byte(`true`)})
require.NoError(t, err)
version = btcRunner.AddRev(btc.id, docID, &version, newBody)
rt.WaitForVersion(docID, version)
syncData = db.GetRawSyncXattr(t, rt.GetSingleDataStore(), docID)
require.Empty(t, syncData.AttachmentsPre4dot0)
require.Equal(t, db.AttachmentMap{
"myAttachment": {
Digest: "sha1-E84HH2iVirRjaYhTGJ1jYQANtcI=",
Length: 6,
Revpos: 2,
Stub: true,
Version: 2,
},
}, db.GetRawGlobalSyncAttachments(t, rt.GetSingleDataStore(), docID))
})
}
// TestDeltaWithAttachmentJsonProperty tests pushing a delta when _attachments is present in either delta or existing doc
func TestDeltaWithAttachmentJsonProperty(t *testing.T) {
if !base.IsEnterpriseEdition() {
t.Skip("Delta test requires EE")
}
rtConfig := &RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: base.Ptr(true),
},
}},
GuestEnabled: true,
}
doc1ID := t.Name() + "_doc1"
doc2ID := t.Name() + "_doc2"
doc3ID := t.Name() + "_doc3"
doc4ID := t.Name() + "_doc4"
btcRunner := NewBlipTesterClientRunner(t)
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t, rtConfig)
defer rt.Close()
opts := &BlipTesterClientOpts{ClientDeltas: true}
btc := btcRunner.NewBlipTesterClientOptsWithRT(rt, opts)
defer btc.Close()
btcRunner.StartPush(btc.id)
attData := base64.StdEncoding.EncodeToString([]byte("attach"))
testcases := []struct {
initialBody []byte
bodyUpdate []byte
expBody []byte
docID string
hasAttachment bool
revpos int
}{
// test case: pushing delta with key update onto doc with _attachment in json value
{
docID: doc1ID,
initialBody: []byte(`{"data":"_attachments"}`),
bodyUpdate: []byte(`{"data1":"_attachments"}`),
hasAttachment: false,
},
{
// test case: pushing delta with key update onto doc with _attachment in json value and attachment defined
docID: doc2ID,
initialBody: []byte(`{"key":"_attachments","_attachments":{"myAttachment":{"data":"` + attData + `"}}}`),
bodyUpdate: []byte(`{"key1":"_attachments","_attachments":{"myAttachment":{"data":"` + attData + `"}}}`),
hasAttachment: true,
revpos: 1,
},
{
// test case: pushing delta with attachment defined onto doc with _attachment in json value
docID: doc3ID,
initialBody: []byte(`{"key":"_attachments"}`),
bodyUpdate: []byte(`{"key":"_attachments","_attachments":{"myAttachment":{"data":"` + attData + `"}}}`),
hasAttachment: true,
revpos: 2,
},
{
// test case: pushing delta with _attachment json value onto doc with attachment defined
docID: doc4ID,
initialBody: []byte(`{"key":"val","_attachments":{"myAttachment":{"data":"` + attData + `"}}}`),
bodyUpdate: []byte(`{"key":"_attachments","_attachments":{"myAttachment":{"data":"` + attData + `"}}}`),
hasAttachment: true,
revpos: 1,
},
}
for _, tc := range testcases {
// Push first rev
version := btcRunner.AddRev(btc.id, tc.docID, EmptyDocVersion(), tc.initialBody)
rt.WaitForVersion(tc.docID, version)
// Push second rev
version = btcRunner.AddRev(btc.id, tc.docID, &version, tc.bodyUpdate)
rt.WaitForVersion(tc.docID, version)
if tc.hasAttachment {
syncData := db.GetRawSyncXattr(t, rt.GetSingleDataStore(), tc.docID)
require.Empty(t, syncData.AttachmentsPre4dot0)
require.Equal(t, db.AttachmentMap{
"myAttachment": {
Digest: "sha1-E84HH2iVirRjaYhTGJ1jYQANtcI=",
Revpos: tc.revpos,
Length: 6,
Stub: true,
Version: 2,
},
}, db.GetRawGlobalSyncAttachments(t, rt.GetSingleDataStore(), tc.docID), "mismatched attachments for doc %s", tc.docID)
}
}
})
}
// Test pushing and pulling new attachments through delta sync
// 1. Create test client that have deltas enabled
// 2. Start continuous push and pull replication in client
// 3. Make sure that sync gateway is running with delta sync on, in enterprise edition
// 4. Create doc with attachment in SGW
// 5. Update doc in the test client by adding another attachment
// 6. Have that update pushed using delta sync via the continuous replication started in step 2
func TestBlipDeltaSyncPushPullNewAttachment(t *testing.T) {
if !base.IsEnterpriseEdition() {
t.Skip("Delta test requires EE")
}
rtConfig := RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: base.Ptr(true),
},
}},
GuestEnabled: true,
}
btcRunner := NewBlipTesterClientRunner(t)
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t, &rtConfig)
defer rt.Close()
btc := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer btc.Close()
btc.ClientDeltas = true
btcRunner.StartPull(btc.id)
btcRunner.StartPush(btc.id)
const docID = "doc1"
// Create doc1 rev 1-77d9041e49931ceef58a1eef5fd032e8 on SG with an attachment
bodyText := `{"greetings":[{"hi": "alice"}],"_attachments":{"hello.txt":{"data":"aGVsbG8gd29ybGQ="}}}`
// put doc directly needs to be here
version1 := rt.PutDoc(docID, bodyText)
data := btcRunner.WaitForVersion(btc.id, docID, version1)
bodyTextExpected := `{"greetings":[{"hi":"alice"}],"_attachments":{"hello.txt":{"revpos":1,"length":11,"stub":true,"digest":"sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0="}}}`
require.JSONEq(t, bodyTextExpected, string(data))
// Update the replicated doc at client by adding another attachment.
bodyText = `{"greetings":[{"hi":"alice"}],"_attachments":{"hello.txt":{"revpos":1,"length":11,"stub":true,"digest":"sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0="},"world.txt":{"data":"bGVsbG8gd29ybGQ="}}}`
version2 := btcRunner.AddRev(btc.id, docID, &version1, []byte(bodyText))
rt.WaitForVersion(docID, version2)
respBody := rt.GetDocVersion(docID, version2)
assert.Equal(t, docID, respBody[db.BodyId])
greetings := respBody["greetings"].([]any)
assert.Len(t, greetings, 1)
assert.Equal(t, map[string]any{"hi": "alice"}, greetings[0])
require.Equal(t, db.AttachmentMap{
"hello.txt": {
Revpos: 1,
Length: 11,
Stub: true,
Digest: "sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=",
},
"world.txt": {
Revpos: 2,
Length: 11,
Stub: true,
Digest: "sha1-qiF39gVoGPFzpRQkNYcY9u3wx9Y=",
},
}, db.GetAttachmentsFrom1xBody(t, respBody))
})
}
// TestBlipDeltaSyncNewAttachmentPull tests that adding a new attachment in SG and replicated via delta sync adds the attachment
// to the temporary "allowedAttachments" map.
func TestBlipDeltaSyncNewAttachmentPull(t *testing.T) {
base.LongRunningTest(t)
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: &sgUseDeltas,
},
}},
GuestEnabled: true,
}
btcRunner := NewBlipTesterClientRunner(t)
const doc1ID = "doc1"
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t, &rtConfig)
defer rt.Close()
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer client.Close()
client.ClientDeltas = true
btcRunner.StartPull(client.id)
// create doc1 rev 1-0335a345b6ffed05707ccc4cbc1b67f4
version := rt.PutDoc(doc1ID, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}]}`)
data := btcRunner.WaitForVersion(client.id, doc1ID, version)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"}]}`, string(data))
// create doc1 rev 2-10000d5ec533b29b117e60274b1e3653 on SG with the first attachment
version2 := rt.UpdateDoc(doc1ID, version, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}], "_attachments": {"hello.txt": {"data":"aGVsbG8gd29ybGQ="}}}`)
data = btcRunner.WaitForVersion(client.id, doc1ID, version2)
require.Equal(t, db.AttachmentMap{
"hello.txt": {
Revpos: 2,
Length: 11,
Stub: true,
Digest: "sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=",
},
}, db.GetAttachmentsFromInlineBody(t, data))
// Check EE is delta, and CE is full-body replication
msg := btcRunner.WaitForPullRevMessage(client.id, doc1ID, version2)
sgCanUseDeltas := base.IsEnterpriseEdition()
if sgCanUseDeltas {
// Check the request was sent with the correct deltaSrc property
client.AssertDeltaSrcProperty(t, msg, version)
// Check the request body was the actual delta
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.Equal(t, `{"_attachments":[{"hello.txt":{"digest":"sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=","length":11,"revpos":2,"stub":true}}]}`, string(msgBody))
} else {
// Check the request was NOT sent with a deltaSrc property
assert.Equal(t, "", msg.Properties[db.RevMessageDeltaSrc])
// Check the request body was NOT the delta
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.JSONEq(t, `{"_attachments":{"hello.txt":{"digest":"sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=","length":11,"revpos":2,"stub":true}}, "greetings": [{"hello": "world!"}, {"hi": "alice"}]}`, string(msgBody))
}
respBody := rt.GetDocVersion(doc1ID, version2)
assert.Equal(t, doc1ID, respBody[db.BodyId])
require.Equal(t, db.Body{
"_id": doc1ID,
"_rev": version2.RevTreeID,
"_cv": version2.CV.String(),
"greetings": []any{
map[string]any{"hello": "world!"},
map[string]any{"hi": "alice"},
},
"_attachments": map[string]any{
"hello.txt": map[string]any{
"revpos": float64(2),
"length": float64(11),
"stub": true,
"digest": "sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=",
},
},
}, respBody)
})
}
// TestBlipDeltaSyncPull tests that a simple pull replication uses deltas in EE,
// and checks that full body replication still happens in CE.
func TestBlipDeltaSyncPull(t *testing.T) {
base.LongRunningTest(t)
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := &RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: &sgUseDeltas,
},
}},
GuestEnabled: true,
}
const docID = "doc1"
var deltaSentCount int64
btcRunner := NewBlipTesterClientRunner(t)
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t,
rtConfig)
defer rt.Close()
if rt.GetDatabase().DbStats.DeltaSync() != nil {
deltaSentCount = rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value()
}
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer client.Close()
client.ClientDeltas = true
btcRunner.StartPull(client.id)
// create doc1 rev 1-0335a345b6ffed05707ccc4cbc1b67f4
version := rt.PutDoc(docID, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}]}`)
data := btcRunner.WaitForVersion(client.id, docID, version)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"}]}`, string(data))
// create doc1 rev 2-959f0e9ad32d84ff652fb91d8d0caa7e
version2 := rt.UpdateDoc(docID, version, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}, {"howdy": 1234567890123}]}`)
data = btcRunner.WaitForVersion(client.id, docID, version2)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":1234567890123}]}`, string(data))
msg := btcRunner.WaitForPullRevMessage(client.id, docID, version2)
// Check EE is delta, and CE is full-body replication
sgCanUseDeltas := base.IsEnterpriseEdition()
if sgCanUseDeltas {
// Check the request was sent with the correct deltaSrc property
client.AssertDeltaSrcProperty(t, msg, version)
// Check the request body was the actual delta
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.Equal(t, `{"greetings":{"2-":[{"howdy":1234567890123}]}}`, string(msgBody))
base.RequireWaitForStat(t, rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value, deltaSentCount+1)
} else {
// Check the request was NOT sent with a deltaSrc property
assert.Equal(t, "", msg.Properties[db.RevMessageDeltaSrc])
// Check the request body was NOT the delta
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.NotEqual(t, `{"greetings":{"2-":[{"howdy":1234567890123}]}}`, string(msgBody))
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":1234567890123}]}`, string(msgBody))
var afterDeltaSyncCount int64
if rt.GetDatabase().DbStats.DeltaSync() != nil {
afterDeltaSyncCount = rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value()
}
assert.Equal(t, deltaSentCount, afterDeltaSyncCount)
}
})
}
// TestBlipDeltaSyncPullResend tests that a simple pull replication that uses a delta a client rejects will resend the revision in full.
func TestBlipDeltaSyncPullResend(t *testing.T) {
if !base.IsEnterpriseEdition() {
t.Skip("Enterprise-only test for delta sync")
}
rtConfig := RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: base.Ptr(true),
},
}},
GuestEnabled: true,
}
btcRunner := NewBlipTesterClientRunner(t)
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t,
&rtConfig)
defer rt.Close()
docID := "doc1"
// create doc1 rev 1
docVersion1 := rt.PutDoc(docID, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}]}`)
deltaSentCount := rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value()
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer client.Close()
// reject deltas built ontop of rev 1
if client.UseHLV() {
client.rejectDeltasForSrcRev = docVersion1.CV.String()
} else {
client.rejectDeltasForSrcRev = docVersion1.RevTreeID
}
client.ClientDeltas = true
btcRunner.StartPull(client.id)
data := btcRunner.WaitForVersion(client.id, docID, docVersion1)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"}]}`, string(data))
// create doc1 rev 2
docVersion2 := rt.UpdateDoc(docID, docVersion1, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}, {"howdy": 1234567890123}]}`)
data = btcRunner.WaitForVersion(client.id, docID, docVersion2)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":1234567890123}]}`, string(data))
// Find the two rev messages. Since there will be two rev messages associated with this version, can not use
// WaitForBlipRevMessage or GetBlipRevMessage.
// The ordering of messages stored by blip client is not 100% guaranteed, so find the
// messages by type and sort by serial number.
// 1. rev with deltaSrc (rejected)
// 2. rev without deltaSrc (accepted)
expectedDocVersion2RevID := docVersion2.RevTreeID
if client.UseHLV() {
expectedDocVersion2RevID = docVersion2.CV.String()
}
var revMsgs []*blip.Message
for _, msg := range client.pullReplication.GetMessages() {
if msg.Profile() != db.RevMessageRev {
continue
}
if msg.Properties[db.RevMessageID] != docID {
continue
}
if msg.Properties[db.RevMessageRev] != expectedDocVersion2RevID {
continue
}
revMsgs = append(revMsgs, msg)
}
require.Len(t, revMsgs, 2, client.pullReplication.GetAllMessagesSummary())
var serialNumber []blip.MessageNumber
for _, msg := range revMsgs {
serialNumber = append(serialNumber, msg.SerialNumber())
}
revMsg1 := revMsgs[0]
revMsg2 := revMsgs[1]
if serialNumber[0] > serialNumber[1] {
revMsg1 = revMsgs[1]
revMsg2 = revMsgs[0]
}
// Check the request was initially sent with the correct deltaSrc property
client.AssertDeltaSrcProperty(t, revMsg1, docVersion1)
// Check the request body was the actual delta
msgBody, err := revMsg1.Body()
assert.NoError(t, err)
assert.Equal(t, `{"greetings":{"2-":[{"howdy":1234567890123}]}}`, string(msgBody))
base.RequireWaitForStat(t, rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value, deltaSentCount+1)
// Check the resent request was NOT sent with a deltaSrc property
assert.Equal(t, "", revMsg2.Properties[db.RevMessageDeltaSrc])
// Check the request body was NOT the delta
msgBody, err = revMsg2.Body()
assert.NoError(t, err)
assert.NotEqual(t, `{"greetings":{"2-":[{"howdy":1234567890123}]}}`, string(msgBody))
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":1234567890123}]}`, string(msgBody))
})
}
// TestBlipDeltaSyncPullRemoved tests a simple pull replication that drops a document out of the user's channel.
func TestBlipDeltaSyncPullRemoved(t *testing.T) {
base.LongRunningTest(t)
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := RestTesterConfig{
DatabaseConfig: &DatabaseConfig{
DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: &sgUseDeltas,
},
},
},
SyncFn: channels.DocChannelsSyncFunction,
}
btcRunner := NewBlipTesterClientRunner(t)
const docID = "doc1"
btcRunner.RunSubprotocolV2(func(t *testing.T) {
rt := NewRestTester(t,
&rtConfig)
defer rt.Close()
const alice = "alice"
rt.CreateUser(alice, []string{"public"})
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, &BlipTesterClientOpts{
Username: alice,
ClientDeltas: true,
})
defer client.Close()
btcRunner.StartPull(client.id)
// create doc1 rev 1-1513b53e2738671e634d9dd111f48de0
version := rt.PutDoc(docID, `{"channels": ["public"], "greetings": [{"hello": "world!"}]}`)
data := btcRunner.WaitForVersion(client.id, docID, version)
assert.Contains(t, string(data), `"channels":["public"]`)
assert.Contains(t, string(data), `"greetings":[{"hello":"world!"}]`)
// create doc1 rev 2-ff91e11bc1fd12bbb4815a06571859a9
version = rt.UpdateDoc(docID, version, `{"channels": ["private"], "greetings": [{"hello": "world!"}, {"hi": "bob"}]}`)
data = btcRunner.WaitForVersion(client.id, docID, version)
assert.Equal(t, `{"_removed":true}`, string(data))
msg, ok := btcRunner.GetPullRevMessage(client.id, docID, version)
require.True(t, ok)
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.Equal(t, `{"_removed":true}`, string(msgBody))
})
}
// TestBlipDeltaSyncPullTombstoned tests a simple pull replication that deletes a document.
//
// Sync Gateway: creates rev-1 and then tombstones it in rev-2
// Client: continuously pulls, pulling rev-1 as normal, and then rev-2 which should be a tombstone, even though a delta was requested
// ┌──────────────┐ ┌─────────┐ ┌─────────┐
// │ Sync Gateway ├─┤ + rev-1 ├────────────┤ - rev-2 ├────■
// └──────────────┘ └─────────┤ └─────────┤
// ┌──────────────┐ ┌─────────┼──────────────────────┼──┐
// │ Client 1 ├─┤ ▼ continuous ▼ ├─■
// └──────────────┘ └───────────────────────────────────┘
func TestBlipDeltaSyncPullTombstoned(t *testing.T) {
base.LongRunningTest(t)
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := &RestTesterConfig{
DatabaseConfig: &DatabaseConfig{
DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: &sgUseDeltas,
},
},
},
SyncFn: channels.DocChannelsSyncFunction,
}
btcRunner := NewBlipTesterClientRunner(t)
var deltaCacheHitsStart int64
var deltaCacheMissesStart int64
var deltasRequestedStart int64
var deltasSentStart int64
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t,
rtConfig)
defer rt.Close()
const alice = "alice"
rt.CreateUser(alice, []string{"public"})
if rt.GetDatabase().DbStats.DeltaSync() != nil {
deltaCacheHitsStart = rt.GetDatabase().DbStats.DeltaSync().DeltaCacheHit.Value()
deltaCacheMissesStart = rt.GetDatabase().DbStats.DeltaSync().DeltaCacheMiss.Value()
deltasRequestedStart = rt.GetDatabase().DbStats.DeltaSync().DeltasRequested.Value()
deltasSentStart = rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value()
}
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, &BlipTesterClientOpts{
Username: alice,
ClientDeltas: true,
})
defer client.Close()
btcRunner.StartPull(client.id)
const docID = "doc1"
// create doc1 rev 1-e89945d756a1d444fa212bffbbb31941
version := rt.PutDoc(docID, `{"channels": ["public"], "greetings": [{"hello": "world!"}]}`)
data := btcRunner.WaitForVersion(client.id, docID, version)
assert.Contains(t, string(data), `"channels":["public"]`)
assert.Contains(t, string(data), `"greetings":[{"hello":"world!"}]`)
// tombstone doc1 at rev 2-2db70833630b396ef98a3ec75b3e90fc
version = rt.DeleteDoc(docID, version)
data = btcRunner.WaitForVersion(client.id, docID, version)
assert.Equal(t, `{}`, string(data))
msg, ok := btcRunner.GetPullRevMessage(client.id, docID, version)
require.True(t, ok)
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.Equal(t, `{}`, string(msgBody))
assert.Equal(t, "1", msg.Properties[db.RevMessageDeleted])
var deltaCacheHitsEnd int64
var deltaCacheMissesEnd int64
var deltasRequestedEnd int64
var deltasSentEnd int64
if rt.GetDatabase().DbStats.DeltaSync() != nil {
deltaCacheHitsEnd = rt.GetDatabase().DbStats.DeltaSync().DeltaCacheHit.Value()
deltaCacheMissesEnd = rt.GetDatabase().DbStats.DeltaSync().DeltaCacheMiss.Value()
deltasRequestedEnd = rt.GetDatabase().DbStats.DeltaSync().DeltasRequested.Value()
deltasSentEnd = rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value()
}
sgCanUseDelta := base.IsEnterpriseEdition()
if sgCanUseDelta {
assert.Equal(t, deltaCacheHitsStart, deltaCacheHitsEnd)
assert.Equal(t, deltaCacheMissesStart+1, deltaCacheMissesEnd)
assert.Equal(t, deltasRequestedStart+1, deltasRequestedEnd)
assert.Equal(t, deltasSentStart, deltasSentEnd) // "_removed" docs are not counted as a delta
} else {
assert.Equal(t, deltaCacheHitsStart, deltaCacheHitsEnd)
assert.Equal(t, deltaCacheMissesStart, deltaCacheMissesEnd)
assert.Equal(t, deltasRequestedStart, deltasRequestedEnd)
assert.Equal(t, deltasSentStart, deltasSentEnd)
}
})
}
// TestBlipDeltaSyncPullTombstonedStarChan tests two clients can perform a simple pull replication that deletes a document when the user has access to the star channel.
//
// Sync Gateway: creates rev-1 and then tombstones it in rev-2
// Client 1: continuously pulls, and causes the tombstone delta for rev-2 to be cached
// Client 2: runs two one-shots, once initially to pull rev-1, and finally for rev-2 after the tombstone delta has been cached
// ┌──────────────┐ ┌─────────┐ ┌─────────┐
// │ Sync Gateway ├─┤ + rev-1 ├─┬──────────┤ - rev-2 ├─┬───────────■
// └──────────────┘ └─────────┤ │ └─────────┤ │
// ┌──────────────┐ ┌─────────┼─┼────────────────────┼─┼─────────┐
// │ Client 1 ├─┤ ▼ │ continuous ▼ │ ├─■
// └──────────────┘ └───────────┼──────────────────────┼─────────┘
// ┌──────────────┐ ┌─┼─────────┐ ┌─┼─────────┐
// │ Client 2 ├───────────┤ ▼ oneshot ├──────────┤ ▼ oneshot ├─■
// └──────────────┘ └───────────┘ └───────────┘
func TestBlipDeltaSyncPullTombstonedStarChan(t *testing.T) {
base.LongRunningTest(t)
base.SetUpTestLogging(t, base.LevelDebug, base.KeyHTTP, base.KeyCache, base.KeySync, base.KeySyncMsg)
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := &RestTesterConfig{DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{DeltaSync: &DeltaSyncConfig{Enabled: &sgUseDeltas}}}}
btcRunner := NewBlipTesterClientRunner(t)
const docID = "doc1"
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t,
rtConfig)
defer rt.Close()
const (
user1 = "client1"
user2 = "client2"
)
rt.CreateUser(user1, []string{"*"})
rt.CreateUser(user2, []string{"*"})
var deltaCacheHitsStart int64
var deltaCacheMissesStart int64
var deltasRequestedStart int64
var deltasSentStart int64
if rt.GetDatabase().DbStats.DeltaSync() != nil {
deltaCacheHitsStart = rt.GetDatabase().DbStats.DeltaSync().DeltaCacheHit.Value()
deltaCacheMissesStart = rt.GetDatabase().DbStats.DeltaSync().DeltaCacheMiss.Value()
deltasRequestedStart = rt.GetDatabase().DbStats.DeltaSync().DeltasRequested.Value()
deltasSentStart = rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value()
}
client1 := btcRunner.NewBlipTesterClientOptsWithRT(rt, &BlipTesterClientOpts{
Username: user1,
ClientDeltas: true,
})
defer client1.Close()
client2 := btcRunner.NewBlipTesterClientOptsWithRT(rt, &BlipTesterClientOpts{
Username: user2,
ClientDeltas: true,
})
defer client2.Close()
btcRunner.StartPull(client1.id)
// create doc1 rev 1-e89945d756a1d444fa212bffbbb31941
version := rt.PutDoc(docID, `{"channels": ["public"], "greetings": [{"hello": "world!"}]}`)
data := btcRunner.WaitForVersion(client1.id, docID, version)
assert.Contains(t, string(data), `"channels":["public"]`)
assert.Contains(t, string(data), `"greetings":[{"hello":"world!"}]`)
// Have client2 get only rev-1 and then stop replicating
btcRunner.StartOneshotPull(client2.id)
data = btcRunner.WaitForVersion(client2.id, docID, version)
assert.Contains(t, string(data), `"channels":["public"]`)
assert.Contains(t, string(data), `"greetings":[{"hello":"world!"}]`)
// tombstone doc1 at rev 2-2db70833630b396ef98a3ec75b3e90fc
version = rt.DeleteDoc(docID, version)
data = btcRunner.WaitForVersion(client1.id, docID, version)
assert.Equal(t, `{}`, string(data))
msg := btcRunner.WaitForPullRevMessage(client1.id, docID, version)
if !assert.Equal(t, db.MessageRev, msg.Profile()) {
t.Logf("unexpected profile for message %v in %v",
msg.SerialNumber(), client1.pullReplication.GetAllMessagesSummary())
}
msgBody, err := msg.Body()
assert.NoError(t, err)
if !assert.Equal(t, `{}`, string(msgBody)) {
t.Logf("unexpected body for message %v in %v",
msg.SerialNumber(), client1.pullReplication.GetAllMessagesSummary())
}
if !assert.Equal(t, "1", msg.Properties[db.RevMessageDeleted]) {
t.Logf("unexpected deleted property for message %v in %v",
msg.SerialNumber(), client1.pullReplication.GetAllMessagesSummary())
}
// Sync Gateway will have cached the tombstone delta, so client 2 should be able to retrieve it from the cache
btcRunner.StartOneshotPull(client2.id)
data = btcRunner.WaitForVersion(client2.id, docID, version)
assert.Equal(t, `{}`, string(data))
msg = btcRunner.WaitForPullRevMessage(client2.id, docID, version)
if !assert.Equal(t, db.MessageRev, msg.Profile()) {
t.Logf("unexpected profile for message %v in %v",
msg.SerialNumber(), client2.pullReplication.GetAllMessagesSummary())
}
msgBody, err = msg.Body()
assert.NoError(t, err)
if !assert.Equal(t, `{}`, string(msgBody)) {
t.Logf("unexpected body for message %v in %v",
msg.SerialNumber(), client2.pullReplication.GetAllMessagesSummary())
}
if !assert.Equal(t, "1", msg.Properties[db.RevMessageDeleted]) {
t.Logf("unexpected deleted property for message %v in %v",
msg.SerialNumber(), client2.pullReplication.GetAllMessagesSummary())
}
// delta stats do not exist for CE
if !base.IsEnterpriseEdition() {
return
}
if !base.TestDisableRevCache() {
base.RequireWaitForStat(t, rt.GetDatabase().DbStats.DeltaSync().DeltaCacheHit.Value, deltaCacheHitsStart+1)
base.RequireWaitForStat(t, rt.GetDatabase().DbStats.DeltaSync().DeltaCacheMiss.Value, deltaCacheMissesStart+1)
}
base.RequireWaitForStat(t, rt.GetDatabase().DbStats.DeltaSync().DeltasRequested.Value, deltasRequestedStart+2)
base.RequireWaitForStat(t, rt.GetDatabase().DbStats.DeltaSync().DeltasSent.Value, deltasSentStart+2)
})
}
// TestBlipDeltaSyncPullRevCache tests that a simple pull replication uses deltas in EE,
// Second pull validates use of rev cache for previously generated deltas.
func TestBlipDeltaSyncPullRevCache(t *testing.T) {
if !base.IsEnterpriseEdition() {
t.Skipf("Skipping enterprise-only delta sync test.")
}
if base.TestDisableRevCache() {
t.Skip("rev cache specific test")
}
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: &sgUseDeltas,
},
}},
GuestEnabled: true,
}
const docID = "doc1"
btcRunner := NewBlipTesterClientRunner(t)
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t,
&rtConfig)
defer rt.Close()
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer client.Close()
client.ClientDeltas = true
sgCanUseDeltas := base.IsEnterpriseEdition()
btcRunner.StartPull(client.id)
// create doc1 rev 1-0335a345b6ffed05707ccc4cbc1b67f4
version1 := rt.PutDoc(docID, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}]}`)
data := btcRunner.WaitForVersion(client.id, docID, version1)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"}]}`, string(data))
// Perform a one-shot pull as client 2 to pull down the first revision
client2 := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer client2.Close()
client2.ClientDeltas = true
btcRunner.StartOneshotPull(client2.id)
data = btcRunner.WaitForVersion(client2.id, docID, version1)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"}]}`, string(data))
// create doc1 rev 2-959f0e9ad32d84ff652fb91d8d0caa7e
version2 := rt.UpdateDoc(docID, version1, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}, {"howdy": "bob"}]}`)
data = btcRunner.WaitForVersion(client.id, docID, version2)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":"bob"}]}`, string(data))
msg := btcRunner.WaitForPullRevMessage(client.id, docID, version2)
// Check EE is delta
// Check the request was sent with the correct deltaSrc property
if sgCanUseDeltas {
client.AssertDeltaSrcProperty(t, msg, version1)
} else {
assert.Equal(t, "", msg.Properties[db.RevMessageDeltaSrc])
}
// Check the request body was the actual delta
msgBody, err := msg.Body()
assert.NoError(t, err)
if sgCanUseDeltas {
assert.Equal(t, `{"greetings":{"2-":[{"howdy":"bob"}]}}`, string(msgBody))
} else {
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":"bob"}]}`, string(msgBody))
}
deltaCacheHits := rt.GetDatabase().DbStats.DeltaSync().DeltaCacheHit.Value()
deltaCacheMisses := rt.GetDatabase().DbStats.DeltaSync().DeltaCacheMiss.Value()
// Run another one shot pull to get the 2nd revision - validate it comes as delta, and uses cached version
client2.ClientDeltas = true
btcRunner.StartOneshotPull(client2.id)
msg2 := btcRunner.WaitForPullRevMessage(client2.id, docID, version2)
// Check the request was sent with the correct deltaSrc property
if sgCanUseDeltas {
client2.AssertDeltaSrcProperty(t, msg2, version1)
} else {
assert.Equal(t, "", msg2.Properties[db.RevMessageDeltaSrc])
}
// Check the request body was the actual delta
msgBody2, err := msg2.Body()
assert.NoError(t, err)
if sgCanUseDeltas {
assert.Equal(t, `{"greetings":{"2-":[{"howdy":"bob"}]}}`, string(msgBody2))
} else {
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":"bob"}]}`, string(msgBody2))
}
updatedDeltaCacheHits := rt.GetDatabase().DbStats.DeltaSync().DeltaCacheHit.Value()
updatedDeltaCacheMisses := rt.GetDatabase().DbStats.DeltaSync().DeltaCacheMiss.Value()
if sgCanUseDeltas {
assert.Equal(t, deltaCacheHits+1, updatedDeltaCacheHits)
assert.Equal(t, deltaCacheMisses, updatedDeltaCacheMisses)
} else {
assert.Equal(t, deltaCacheHits, updatedDeltaCacheHits)
assert.Equal(t, deltaCacheMisses, updatedDeltaCacheMisses)
}
})
}
// TestBlipDeltaSyncPush tests that a simple push replication handles deltas in EE,
// and checks that full body replication is still supported in CE.
func TestBlipDeltaSyncPush(t *testing.T) {
base.LongRunningTest(t)
base.SetUpTestLogging(t, base.LevelDebug, base.KeyCRUD, base.KeySGTest, base.KeySyncMsg, base.KeySync)
sgUseDeltas := base.IsEnterpriseEdition()
rtConfig := RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
DeltaSync: &DeltaSyncConfig{
Enabled: &sgUseDeltas,
},
}},
GuestEnabled: true,
}
btcRunner := NewBlipTesterClientRunner(t)
const docID = "doc1"
btcRunner.Run(func(t *testing.T) {
rt := NewRestTester(t,
&rtConfig)
defer rt.Close()
client := btcRunner.NewBlipTesterClientOptsWithRT(rt, nil)
defer client.Close()
client.ClientDeltas = true
sgCanUseDeltas := base.IsEnterpriseEdition()
btcRunner.StartPull(client.id)
// create doc1 rev 1-0335a345b6ffed05707ccc4cbc1b67f4
version := rt.PutDoc(docID, `{"greetings": [{"hello": "world!"}, {"hi": "alice"}]}`)
data := btcRunner.WaitForVersion(client.id, docID, version)
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"}]}`, string(data))
// create doc1 rev 2-abc on client
newRev := btcRunner.AddRev(client.id, docID, &version, []byte(`{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":"bob"}]}`))
btcRunner.StartPushWithOpts(client.id, BlipTesterPushOptions{Continuous: false})
// Check EE is delta, and CE is full-body replication
msg := btcRunner.WaitForPushRevMessage(client.id, docID, newRev)
if base.IsEnterpriseEdition() && sgCanUseDeltas {
// Check the request was sent with the correct deltaSrc property
client.AssertDeltaSrcProperty(t, msg, version)
// Check the request body was the actual delta
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.Equal(t, `{"greetings":{"2-":[{"howdy":"bob"}]}}`, string(msgBody))
collection, ctx := rt.GetSingleTestDatabaseCollection()
// Validate that generation of a delta didn't mutate the revision body in the revision cache
docRev, cacheErr := collection.GetRevisionCacheForTest().Get(ctx, "doc1", "1-0335a345b6ffed05707ccc4cbc1b67f4", db.RevCacheLoadBackupRev)
assert.NoError(t, cacheErr)
assert.NotContains(t, docRev.BodyBytes, "bob")
} else {
// Check the request was NOT sent with a deltaSrc property
assert.Equal(t, "", msg.Properties[db.RevMessageDeltaSrc])
// Check the request body was NOT the delta
msgBody, err := msg.Body()
assert.NoError(t, err)
assert.NotEqual(t, `{"greetings":{"2-":[{"howdy":"bob"}]}}`, string(msgBody))
assert.Equal(t, `{"greetings":[{"hello":"world!"},{"hi":"alice"},{"howdy":"bob"}]}`, string(msgBody))
}
// wait for response body, indicating rev was written to server
_ = msg.Response()
respBody := rt.GetDocVersion(docID, newRev)
assert.Equal(t, "doc1", respBody[db.BodyId])
greetings := respBody["greetings"].([]any)
assert.Len(t, greetings, 3)