-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathblip_api_crud_test.go
3201 lines (2651 loc) · 114 KB
/
blip_api_crud_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 2018-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 (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/couchbase/go-blip"
"github.com/couchbase/gocb/v2"
"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"
)
// This test performs the following steps against the Sync Gateway passive blip replicator:
//
// - Setup
// - Create an httptest server listening on a port that wraps the Sync Gateway Admin Handler
// - Make a BLIP/Websocket client connection to Sync Gateway
//
// - Test
// - Verify Sync Gateway will accept the doc revision that is about to be sent
// - Send the doc revision in a rev request
// - Call changes endpoint and verify that it knows about the revision just sent
// - Call subChanges api and make sure we get expected changes back
//
// Replication Spec: https://github.com/couchbase/couchbase-lite-core/wiki/Replication-Protocol#proposechanges
func TestBlipPushRevisionInspectChanges(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
bt, err := NewBlipTesterFromSpec(t, BlipTesterSpec{allowConflicts: true, GuestEnabled: true})
assert.NoError(t, err, "Error creating BlipTester")
defer bt.Close()
// Verify Sync Gateway will accept the doc revision that is about to be sent
var changeList [][]interface{}
changesRequest := bt.newRequest()
changesRequest.SetProfile("changes")
changesRequest.SetBody([]byte(`[["1", "foo", "1-abc", false]]`)) // [sequence, docID, revID]
sent := bt.sender.Send(changesRequest)
assert.True(t, sent)
changesResponse := changesRequest.Response()
assert.Equal(t, changesRequest.SerialNumber(), changesResponse.SerialNumber())
body, err := changesResponse.Body()
assert.NoError(t, err, "Error reading changes response body")
err = base.JSONUnmarshal(body, &changeList)
require.NoError(t, err, "Error unmarshalling response body: %s", body)
require.Len(t, changeList, 1) // Should be 1 row, corresponding to the single doc that was queried in changes
changeRow := changeList[0]
assert.Len(t, changeRow, 0) // Should be empty, meaning the server is saying it doesn't have the revision yet
// Send the doc revision in a rev request
_, _, revResponse, err := bt.SendRev(
"foo",
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
assert.NoError(t, err)
_, err = revResponse.Body()
assert.NoError(t, err, "Error unmarshalling response body")
// Call changes with a hypothetical new revision, assert that it returns last pushed revision
var changeList2 [][]interface{}
changesRequest2 := bt.newRequest()
changesRequest2.SetProfile("changes")
changesRequest2.SetBody([]byte(`[["2", "foo", "2-xyz", false]]`)) // [sequence, docID, revID]
sent2 := bt.sender.Send(changesRequest2)
assert.True(t, sent2)
changesResponse2 := changesRequest2.Response()
assert.Equal(t, changesRequest2.SerialNumber(), changesResponse2.SerialNumber())
body2, err := changesResponse2.Body()
assert.NoError(t, err, "Error reading changes response body")
err = base.JSONUnmarshal(body2, &changeList2)
assert.NoError(t, err, "Error unmarshalling response body")
assert.Len(t, changeList2, 1) // Should be 1 row, corresponding to the single doc that was queried in changes
changeRow2 := changeList2[0]
assert.Len(t, changeRow2, 1) // Should have 1 item in row, which is the rev id of the previous revision pushed
assert.Equal(t, "1-abc", changeRow2[0])
// Call subChanges api and make sure we get expected changes back
receivedChangesRequestWg := sync.WaitGroup{}
// When this test sends subChanges, Sync Gateway will send a changes request that must be handled
bt.blipContext.HandlerForProfile["changes"] = func(request *blip.Message) {
log.Printf("got changes message: %+v", request)
body, err := request.Body()
log.Printf("changes body: %v, err: %v", string(body), err)
if string(body) != "null" {
// Expected changes body: [[1,"foo","1-abc"]]
changeListReceived := [][]interface{}{}
err = base.JSONUnmarshal(body, &changeListReceived)
assert.NoError(t, err, "Error unmarshalling changes received")
assert.Len(t, changeListReceived, 1)
change := changeListReceived[0] // [1,"foo","1-abc"]
assert.Len(t, change, 3)
assert.Equal(t, float64(1), change[0].(float64)) // Expect sequence to be 1, since first item in DB
assert.Equal(t, "foo", change[1]) // Doc id of pushed rev
assert.Equal(t, "1-abc", change[2]) // Rev id of pushed rev
}
if !request.NoReply() {
// Send an empty response to avoid the Sync: Invalid response to 'changes' message
response := request.Response()
emptyResponseVal := []interface{}{}
emptyResponseValBytes, err := base.JSONMarshal(emptyResponseVal)
assert.NoError(t, err, "Error marshalling response")
response.SetBody(emptyResponseValBytes)
}
receivedChangesRequestWg.Done()
}
// Send subChanges to subscribe to changes, which will cause the "changes" profile handler above to be called back
subChangesRequest := bt.newRequest()
subChangesRequest.SetProfile("subChanges")
subChangesRequest.Properties["continuous"] = "true"
sent = bt.sender.Send(subChangesRequest)
assert.True(t, sent)
// Also expect the "changes" profile handler above to be called back again with an empty request that
// will be ignored since body will be "null" hence the incrementing for the wait group by 2
receivedChangesRequestWg.Add(2)
subChangesResponse := subChangesRequest.Response()
assert.Equal(t, subChangesRequest.SerialNumber(), subChangesResponse.SerialNumber())
// Wait until we got the expected callback on the "changes" profile handler
timeoutErr := WaitWithTimeout(&receivedChangesRequestWg, time.Second*5)
assert.NoError(t, timeoutErr, "Timed out waiting")
}
// Start subChanges w/ continuous=true, batchsize=10
// Make several updates
// Wait until we get the expected updates
func TestContinuousChangesSubscription(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg, base.KeyChanges, base.KeyCache)
bt, err := NewBlipTester(t)
require.NoError(t, err, "Error creating BlipTester")
defer func() {
unsubChangesRequest := bt.newRequest()
blip.NewRequest()
unsubChangesRequest.SetProfile(db.MessageUnsubChanges)
assert.True(t, bt.sender.Send(unsubChangesRequest))
unsubChangesResponse := unsubChangesRequest.Response()
assert.Equal(t, "", unsubChangesResponse.Properties[db.BlipErrorCode])
bt.Close()
}()
// Counter/Waitgroup to help ensure that all callbacks on continuous changes handler are received
receivedChangesWg := sync.WaitGroup{}
// When this test sends subChanges, Sync Gateway will send a changes request that must be handled
lastReceivedSeq := float64(0)
var numbatchesReceived int32
nonIntegerSequenceReceived := false
changeCount := 0
bt.blipContext.HandlerForProfile["changes"] = func(request *blip.Message) {
body, err := request.Body()
require.NoError(t, err)
if string(body) != "null" {
atomic.AddInt32(&numbatchesReceived, 1)
// Expected changes body: [[1,"foo","1-abc"]]
changeListReceived := [][]interface{}{}
err = base.JSONUnmarshal(body, &changeListReceived)
assert.NoError(t, err, "Error unmarshalling changes received")
for _, change := range changeListReceived {
// The change should have three items in the array
// [1,"foo","1-abc"]
assert.Len(t, change, 3)
// Make sure sequence numbers are monotonically increasing
receivedSeq, ok := change[0].(float64)
if ok {
assert.True(t, receivedSeq > lastReceivedSeq)
lastReceivedSeq = receivedSeq
} else {
nonIntegerSequenceReceived = true
log.Printf("Unexpected non-integer sequence received: %v", change[0])
}
// Verify doc id and rev id have expected vals
docID := change[1].(string)
assert.True(t, strings.HasPrefix(docID, "foo"))
assert.Equal(t, "1-abc", change[2]) // Rev id of pushed rev
changeCount++
receivedChangesWg.Done()
}
}
if !request.NoReply() {
// Send an empty response to avoid the Sync: Invalid response to 'changes' message
response := request.Response()
emptyResponseVal := []interface{}{}
emptyResponseValBytes, err := base.JSONMarshal(emptyResponseVal)
assert.NoError(t, err, "Error marshalling response")
response.SetBody(emptyResponseValBytes)
}
}
// Send subChanges to subscribe to changes, which will cause the "changes" profile handler above to be called back
subChangesRequest := bt.newRequest()
subChangesRequest.SetProfile("subChanges")
subChangesRequest.Properties["continuous"] = "true"
subChangesRequest.Properties["batch"] = "10" // default batch size is 200, lower this to 10 to make sure we get multiple batches
subChangesRequest.SetCompressed(false)
sent := bt.sender.Send(subChangesRequest)
assert.True(t, sent)
subChangesResponse := subChangesRequest.Response()
assert.Equal(t, subChangesRequest.SerialNumber(), subChangesResponse.SerialNumber())
for i := 1; i < 1500; i++ {
// // Add a change: Send an unsolicited doc revision in a rev request
receivedChangesWg.Add(1)
_, _, revResponse, err := bt.SendRev(
fmt.Sprintf("foo-%d", i),
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
require.NoError(t, err)
_, err = revResponse.Body()
assert.NoError(t, err, "Error unmarshalling response body")
}
// Wait until all expected changes are received by change handler
require.NoError(t, WaitWithTimeout(&receivedChangesWg, time.Second*30))
// Since batch size was set to 10, and 15 docs were added, expect at _least_ 2 batches
numBatchesReceivedSnapshot := atomic.LoadInt32(&numbatchesReceived)
assert.True(t, numBatchesReceivedSnapshot >= 2)
assert.False(t, nonIntegerSequenceReceived, "Unexpected non-integer sequence seen.")
}
// Make several updates
// Start subChanges w/ continuous=false, batchsize=20
// Validate we get the expected updates and changes ends
func TestBlipOneShotChangesSubscription(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
bt, err := NewBlipTester(t)
assert.NoError(t, err, "Error creating BlipTester")
defer bt.Close()
// Counter/Waitgroup to help ensure that all callbacks on continuous changes handler are received
receivedChangesWg := sync.WaitGroup{}
receivedCaughtUpChange := false
// Build set of docids
docIdsReceived := make(map[string]bool)
for i := 1; i < 105; i++ {
docIdsReceived[fmt.Sprintf("preOneShot-%d", i)] = false
}
// When this test sends subChanges, Sync Gateway will send a changes request that must be handled
lastReceivedSeq := float64(0)
var numbatchesReceived int32
nonIntegerSequenceReceived := false
bt.blipContext.HandlerForProfile["changes"] = func(request *blip.Message) {
body, err := request.Body()
require.NoError(t, err)
if string(body) != "null" {
atomic.AddInt32(&numbatchesReceived, 1)
// Expected changes body: [[1,"foo","1-abc"]]
changeListReceived := [][]interface{}{}
err = base.JSONUnmarshal(body, &changeListReceived)
assert.NoError(t, err, "Error unmarshalling changes received")
for _, change := range changeListReceived {
// The change should have three items in the array
// [1,"foo","1-abc"]
assert.Len(t, change, 3)
// Make sure sequence numbers are monotonically increasing
receivedSeq, ok := change[0].(float64)
if ok {
assert.True(t, receivedSeq > lastReceivedSeq)
lastReceivedSeq = receivedSeq
} else {
nonIntegerSequenceReceived = true
log.Printf("Unexpected non-integer sequence received: %v", change[0])
}
// Verify doc id and rev id have expected vals
docID := change[1].(string)
assert.True(t, strings.HasPrefix(docID, "preOneShot"))
assert.Equal(t, "1-abc", change[2]) // Rev id of pushed rev
docIdsReceived[docID] = true
receivedChangesWg.Done()
}
} else {
receivedCaughtUpChange = true
receivedChangesWg.Done()
}
if !request.NoReply() {
// Send an empty response to avoid the Sync: Invalid response to 'changes' message
response := request.Response()
emptyResponseVal := []interface{}{}
emptyResponseValBytes, err := base.JSONMarshal(emptyResponseVal)
assert.NoError(t, err, "Error marshalling response")
response.SetBody(emptyResponseValBytes)
}
}
// Increment waitgroup to account for the expected 'caught up' nil changes entry.
receivedChangesWg.Add(1)
cacheWaiter := bt.DatabaseContext().NewDCPCachingCountWaiter(t)
cacheWaiter.Add(len(docIdsReceived))
// Add documents
for docID := range docIdsReceived {
// // Add a change: Send an unsolicited doc revision in a rev request
_, _, revResponse, err := bt.SendRev(
docID,
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
require.NoError(t, err)
_, err = revResponse.Body()
assert.NoError(t, err, "Error unmarshalling response body")
receivedChangesWg.Add(1)
}
// Wait for documents to be processed and available for changes
cacheWaiter.Wait()
// Send subChanges to subscribe to changes, which will cause the "changes" profile handler above to be called back
subChangesRequest := bt.newRequest()
subChangesRequest.SetProfile("subChanges")
subChangesRequest.Properties["continuous"] = "false"
subChangesRequest.Properties["batch"] = "10" // default batch size is 200, lower this to 10 to make sure we get multiple batches
subChangesRequest.SetCompressed(false)
sent := bt.sender.Send(subChangesRequest)
assert.True(t, sent)
subChangesResponse := subChangesRequest.Response()
assert.Equal(t, subChangesRequest.SerialNumber(), subChangesResponse.SerialNumber())
// Wait until all expected changes are received by change handler
// receivedChangesWg.Wait()
timeoutErr := WaitWithTimeout(&receivedChangesWg, time.Second*60)
assert.NoError(t, timeoutErr, "Timed out waiting for all changes.")
// Since batch size was set to 10, and 15 docs were added, expect at _least_ 2 batches
numBatchesReceivedSnapshot := atomic.LoadInt32(&numbatchesReceived)
assert.True(t, numBatchesReceivedSnapshot >= 2)
// Validate all expected documents were received.
for docID, received := range docIdsReceived {
if !received {
t.Errorf("Did not receive expected doc %s in changes", docID)
}
}
// Validate that the 'caught up' message was sent
assert.True(t, receivedCaughtUpChange)
// Create a few more changes, validate that they aren't sent (subChanges has been closed).
// Validated by the prefix matching in the subChanges callback, as well as waitgroup check below.
for i := 0; i < 5; i++ {
// // Add a change: Send an unsolicited doc revision in a rev request
_, _, revResponse, err := bt.SendRev(
fmt.Sprintf("postOneShot_%d", i),
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
require.NoError(t, err)
_, err = revResponse.Body()
assert.NoError(t, err, "Error unmarshalling response body")
receivedChangesWg.Add(1)
}
// Wait long enough to ensure the changes aren't being sent
expectedTimeoutErr := WaitWithTimeout(&receivedChangesWg, time.Second*1)
if expectedTimeoutErr == nil {
t.Errorf("Received additional changes after one-shot should have been closed.")
}
// Validate integer sequences
assert.False(t, nonIntegerSequenceReceived, "Unexpected non-integer sequence seen.")
}
// Test subChanges w/ docID filter
func TestBlipSubChangesDocIDFilter(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
bt, err := NewBlipTester(t)
require.NoError(t, err)
defer bt.Close()
// Counter/Waitgroup to help ensure that all callbacks on continuous changes handler are received
receivedChangesWg := sync.WaitGroup{}
receivedCaughtUpChange := false
// Build set of docids
docIDsSent := make([]string, 0)
docIDsExpected := make([]string, 0)
docIDsReceived := make(map[string]bool)
for i := 1; i <= 100; i++ {
docID := fmt.Sprintf("docIDFiltered-%d", i)
docIDsSent = append(docIDsSent, docID)
// Filter to every 5th doc
if i%5 == 0 {
docIDsExpected = append(docIDsExpected, docID)
docIDsReceived[docID] = false
}
}
// When this test sends subChanges, Sync Gateway will send a changes request that must be handled
lastReceivedSeq := float64(0)
var numbatchesReceived int32
nonIntegerSequenceReceived := false
bt.blipContext.HandlerForProfile["changes"] = func(request *blip.Message) {
body, err := request.Body()
require.NoError(t, err)
if string(body) != "null" {
atomic.AddInt32(&numbatchesReceived, 1)
// Expected changes body: [[1,"foo","1-abc"]]
changeListReceived := [][]interface{}{}
err = base.JSONUnmarshal(body, &changeListReceived)
assert.NoError(t, err, "Error unmarshalling changes received")
for _, change := range changeListReceived {
// The change should have three items in the array
// [1,"foo","1-abc"]
assert.Len(t, change, 3)
// Make sure sequence numbers are monotonically increasing
receivedSeq, ok := change[0].(float64)
if ok {
assert.True(t, receivedSeq > lastReceivedSeq)
lastReceivedSeq = receivedSeq
} else {
nonIntegerSequenceReceived = true
log.Printf("Unexpected non-integer sequence received: %v", change[0])
}
// Verify doc id and rev id have expected vals
docID := change[1].(string)
assert.True(t, strings.HasPrefix(docID, "docIDFiltered"))
assert.Equal(t, "1-abc", change[2]) // Rev id of pushed rev
log.Printf("Changes got docID: %s", docID)
// Ensure we only receive expected docs
_, isExpected := docIDsReceived[docID]
if !isExpected {
t.Errorf("Received unexpected docId: %s", docID)
} else {
// Add to received set, to ensure we get all expected docs
docIDsReceived[docID] = true
receivedChangesWg.Done()
}
}
} else {
receivedCaughtUpChange = true
receivedChangesWg.Done()
}
if !request.NoReply() {
// Send an empty response to avoid the Sync: Invalid response to 'changes' message
response := request.Response()
emptyResponseVal := []interface{}{}
emptyResponseValBytes, err := base.JSONMarshal(emptyResponseVal)
assert.NoError(t, err, "Error marshalling response")
response.SetBody(emptyResponseValBytes)
}
}
// Increment waitgroup to account for the expected 'caught up' nil changes entry.
receivedChangesWg.Add(1)
cacheWaiter := bt.DatabaseContext().NewDCPCachingCountWaiter(t)
// Add documents
for _, docID := range docIDsSent {
// // Add a change: Send an unsolicited doc revision in a rev request
_, _, revResponse, err := bt.SendRev(
docID,
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
assert.NoError(t, err)
_, err = revResponse.Body()
assert.NoError(t, err, "Error unmarshalling response body")
}
receivedChangesWg.Add(len(docIDsExpected))
// Wait for documents to be processed and available for changes
// 105 docs +
cacheWaiter.AddAndWait(len(docIDsExpected))
// TODO: Attempt a subChanges w/ continuous=true and docID filter
// Send subChanges to subscribe to changes, which will cause the "changes" profile handler above to be called back
subChangesRequest := bt.newRequest()
subChangesRequest.SetProfile("subChanges")
subChangesRequest.Properties["continuous"] = "false"
subChangesRequest.Properties["batch"] = "10" // default batch size is 200, lower this to 5 to make sure we get multiple batches
subChangesRequest.SetCompressed(false)
body := db.SubChangesBody{DocIDs: docIDsExpected}
bodyBytes, err := base.JSONMarshal(body)
assert.NoError(t, err, "Error marshalling subChanges body.")
subChangesRequest.SetBody(bodyBytes)
sent := bt.sender.Send(subChangesRequest)
assert.True(t, sent)
subChangesResponse := subChangesRequest.Response()
assert.Equal(t, subChangesRequest.SerialNumber(), subChangesResponse.SerialNumber())
// Wait until all expected changes are received by change handler
// receivedChangesWg.Wait()
timeoutErr := WaitWithTimeout(&receivedChangesWg, time.Second*15)
assert.NoError(t, timeoutErr, "Timed out waiting for all changes.")
// Since batch size was set to 10, and 15 docs were added, expect at _least_ 2 batches
numBatchesReceivedSnapshot := atomic.LoadInt32(&numbatchesReceived)
assert.True(t, numBatchesReceivedSnapshot >= 2)
// Validate all expected documents were received.
for docID, received := range docIDsReceived {
if !received {
t.Errorf("Did not receive expected doc %s in changes", docID)
}
}
// Validate that the 'caught up' message was sent
assert.True(t, receivedCaughtUpChange)
// Validate integer sequences
assert.False(t, nonIntegerSequenceReceived, "Unexpected non-integer sequence seen.")
}
// Push proposed changes and ensure that the server accepts them
//
// 1. Start sync gateway in no-conflicts mode
// 2. Send changes push request with multiple doc revisions
// 3. Make sure there are no panics
// 4. Make sure that the server responds to accept the changes (empty array)
func TestProposedChangesNoConflictsMode(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
bt, err := NewBlipTesterFromSpec(t, BlipTesterSpec{
GuestEnabled: true,
})
assert.NoError(t, err, "Error creating BlipTester")
defer bt.Close()
proposeChangesRequest := bt.newRequest()
proposeChangesRequest.SetProfile("proposeChanges")
proposeChangesRequest.SetCompressed(true)
// According to proposeChanges spec:
// proposedChanges entries are of the form: [docID, revID, serverRevID]
// where serverRevID is optional
changesBody := `
[["foo", "1-abc"],
["foo2", "1-abc"]]
`
proposeChangesRequest.SetBody([]byte(changesBody))
sent := bt.sender.Send(proposeChangesRequest)
assert.True(t, sent)
proposeChangesResponse := proposeChangesRequest.Response()
body, err := proposeChangesResponse.Body()
assert.NoError(t, err, "Error getting changes response body")
var changeList [][]interface{}
err = base.JSONUnmarshal(body, &changeList)
assert.NoError(t, err, "Error getting changes response body")
// The common case of an empty array response tells the sender to send all of the proposed revisions,
// so the changeList returned by Sync Gateway is expected to be empty
assert.Len(t, changeList, 0)
}
// Validate SG sends conflicting rev when requested
func TestProposedChangesIncludeConflictingRev(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
bt, err := NewBlipTesterFromSpec(t, BlipTesterSpec{
GuestEnabled: true,
})
assert.NoError(t, err, "Error creating BlipTester")
defer bt.Close()
// Write existing docs to server directly (not via blip)
rt := bt.restTester
resp := rt.PutDoc("conflictingInsert", `{"version":1}`)
conflictingInsertRev := resp.RevID
resp = rt.PutDoc("matchingInsert", `{"version":1}`)
matchingInsertRev := resp.RevID
resp = rt.PutDoc("conflictingUpdate", `{"version":1}`)
conflictingUpdateRev1 := resp.RevID
conflictingUpdateRev2 := rt.UpdateDocRev("conflictingUpdate", resp.RevID, `{"version":2}`)
resp = rt.PutDoc("matchingUpdate", `{"version":1}`)
matchingUpdateRev1 := resp.RevID
matchingUpdateRev2 := rt.UpdateDocRev("matchingUpdate", resp.RevID, `{"version":2}`)
resp = rt.PutDoc("newUpdate", `{"version":1}`)
newUpdateRev1 := resp.RevID
type proposeChangesCase struct {
key string
revID string
parentRevID string
expectedValue interface{}
}
proposeChangesCases := []proposeChangesCase{
proposeChangesCase{
key: "conflictingInsert",
revID: "1-abc",
parentRevID: "",
expectedValue: map[string]interface{}{"status": float64(db.ProposedRev_Conflict), "rev": conflictingInsertRev},
},
proposeChangesCase{
key: "newInsert",
revID: "1-abc",
parentRevID: "",
expectedValue: float64(db.ProposedRev_OK),
},
proposeChangesCase{
key: "matchingInsert",
revID: matchingInsertRev,
parentRevID: "",
expectedValue: float64(db.ProposedRev_Exists),
},
proposeChangesCase{
key: "conflictingUpdate",
revID: "2-abc",
parentRevID: conflictingUpdateRev1,
expectedValue: map[string]interface{}{"status": float64(db.ProposedRev_Conflict), "rev": conflictingUpdateRev2},
},
proposeChangesCase{
key: "newUpdate",
revID: "2-abc",
parentRevID: newUpdateRev1,
expectedValue: float64(db.ProposedRev_OK),
},
proposeChangesCase{
key: "matchingUpdate",
revID: matchingUpdateRev2,
parentRevID: matchingUpdateRev1,
expectedValue: float64(db.ProposedRev_Exists),
},
}
proposeChangesRequest := bt.newRequest()
proposeChangesRequest.SetProfile("proposeChanges")
proposeChangesRequest.SetCompressed(true)
proposeChangesRequest.Properties[db.ProposeChangesConflictsIncludeRev] = "true"
// proposedChanges entries are of the form: [docID, revID, parentRevID], where parentRevID is optional
proposedChanges := make([][]interface{}, 0)
for _, c := range proposeChangesCases {
changeEntry := []interface{}{
c.key,
c.revID,
}
if c.parentRevID != "" {
changeEntry = append(changeEntry, c.parentRevID)
}
proposedChanges = append(proposedChanges, changeEntry)
}
proposeChangesBody, marshalErr := json.Marshal(proposedChanges)
require.NoError(t, marshalErr)
proposeChangesRequest.SetBody(proposeChangesBody)
sent := bt.sender.Send(proposeChangesRequest)
assert.True(t, sent)
proposeChangesResponse := proposeChangesRequest.Response()
bodyReader, err := proposeChangesResponse.BodyReader()
assert.NoError(t, err, "Error getting changes response body reader")
var changeList []interface{}
decoder := base.JSONDecoder(bodyReader)
decodeErr := decoder.Decode(&changeList)
require.NoError(t, decodeErr)
for i, entry := range changeList {
assert.Equal(t, proposeChangesCases[i].expectedValue, entry)
}
}
// Connect to public port with authentication
func TestPublicPortAuthentication(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
// Create bliptester that is connected as user1, with access to the user1 channel
btUser1, err := NewBlipTesterFromSpec(t,
BlipTesterSpec{
connectingUsername: "user1",
connectingPassword: "1234",
syncFn: channels.DocChannelsSyncFunction,
})
require.NoError(t, err)
defer btUser1.Close()
// Send the user1 doc
_, _, _, err = btUser1.SendRev(
"foo",
"1-abc",
[]byte(`{"key": "val", "channels": ["user1"]}`),
blip.Properties{},
)
require.NoError(t, err, "Error sending revision")
// Create bliptester that is connected as user2, with access to the * channel
btUser2, err := NewBlipTesterFromSpecWithRT(t, &BlipTesterSpec{
connectingUsername: "user2",
connectingPassword: "1234",
connectingUserChannelGrants: []string{"*"}, // user2 has access to all channels
}, btUser1.restTester) // re-use rest tester, otherwise it will create a new underlying bucket in walrus case
require.NoError(t, err, "Error creating BlipTester")
defer btUser2.Close()
// Send the user2 doc, which is in a "random" channel, but it should be accessible due to * channel access
_, _, _, err = btUser2.SendRev(
"foo2",
"1-abcd",
[]byte(`{"key": "val", "channels": ["NBC"]}`),
blip.Properties{},
)
require.NoError(t, err, "Error sending revision")
// Assert that user1 received a single expected change
changesChannelUser1 := btUser1.WaitForNumChanges(1)
assert.Len(t, changesChannelUser1, 1)
change := changesChannelUser1[0]
AssertChangeEquals(t, change, ExpectedChange{docId: "foo", revId: "1-abc", sequence: "*", deleted: base.Ptr(false)})
// Assert that user2 received user1's change as well as it's own change
changesChannelUser2 := btUser2.WaitForNumChanges(2)
assert.Len(t, changesChannelUser2, 2)
change = changesChannelUser2[0]
AssertChangeEquals(t, change, ExpectedChange{docId: "foo", revId: "1-abc", sequence: "*", deleted: base.Ptr(false)})
change = changesChannelUser2[1]
AssertChangeEquals(t, change, ExpectedChange{docId: "foo2", revId: "1-abcd", sequence: "*", deleted: base.Ptr(false)})
}
// Connect to public port with authentication, and validate user update during a replication
func TestPublicPortAuthenticationUserUpdate(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg)
// Initialize restTester here, so that we can use custom sync function, and later modify user
syncFunction := `
function(doc, oldDoc) {
requireAccess("ABC")
}
`
rtConfig := RestTesterConfig{
SyncFn: syncFunction,
}
var rt = NewRestTester(t, &rtConfig)
defer rt.Close()
ctx := rt.Context()
// Create bliptester that is connected as user1, with no access to channel ABC
bt, err := NewBlipTesterFromSpecWithRT(t, &BlipTesterSpec{
connectingUsername: "user1",
connectingPassword: "1234",
}, rt)
assert.NoError(t, err, "Error creating BlipTester")
// Attempt to send a doc, should be rejected
_, _, _, sendErr := bt.SendRev(
"foo",
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
assert.Error(t, sendErr, "Expected error sending rev (403 sg missing channel access)")
// Set up a ChangeWaiter for this test, to block until the user change notification happens
dbc := rt.GetDatabase()
user1, err := dbc.Authenticator(ctx).GetUser("user1")
require.NoError(t, err)
userDb, err := db.GetDatabase(dbc, user1)
require.NoError(t, err)
userWaiter := userDb.NewUserWaiter()
// Update the user to grant them access to ABC
response := rt.SendAdminRequest("PUT", "/db/_user/user1", GetUserPayload(t, "user1", "", "", rt.GetSingleDataStore(), []string{"ABC"}, nil))
RequireStatus(t, response, 200)
// Wait for notification
require.True(t, db.WaitForUserWaiterChange(userWaiter))
// Attempt to send the doc again, should succeed if the blip context also received notification
_, _, _, sendErr = bt.SendRev(
"foo",
"1-abc",
[]byte(`{"key": "val"}`),
blip.Properties{},
)
assert.NoError(t, sendErr)
// Validate that the doc was written (GET request doesn't get a 404)
getResponse := rt.SendAdminRequest("GET", "/{{.keyspace}}/foo", "")
RequireStatus(t, getResponse, 200)
}
// Start subChanges w/ continuous=true, batchsize=20
// Write a doc that grants access to itself for the active replication's user
func TestContinuousChangesDynamicGrant(t *testing.T) {
base.SetUpTestLogging(t, base.LevelInfo, base.KeyHTTP, base.KeySync, base.KeySyncMsg, base.KeyChanges, base.KeyCache)
// Initialize restTester here, so that we can use custom sync function, and later modify user
syncFunction := `
function(doc, oldDoc) {
access(doc.accessUser, doc.accessChannel)
channel(doc.channels)
}
`
rtConfig := RestTesterConfig{SyncFn: syncFunction}
rt := NewRestTester(t, &rtConfig)
defer rt.Close()
// Create bliptester that is connected as user1, with no access to channel ABC
bt, err := NewBlipTesterFromSpecWithRT(t, &BlipTesterSpec{
connectingUsername: "user1",
connectingPassword: "1234",
}, rt)
assert.NoError(t, err, "Error creating BlipTester")
defer bt.Close()
// Counter/Waitgroup to help ensure that all callbacks on continuous changes handler are received
receivedChangesWg := sync.WaitGroup{}
revsFinishedWg := sync.WaitGroup{}
// When this test sends subChanges, Sync Gateway will send a changes request that must be handled
lastReceivedSeq := float64(0)
var numbatchesReceived int32
nonIntegerSequenceReceived := false
changeCount := 0
bt.blipContext.HandlerForProfile["changes"] = func(request *blip.Message) {
body, err := request.Body()
require.NoError(t, err)
responseVal := [][]interface{}{}
if string(body) != "null" {
atomic.AddInt32(&numbatchesReceived, 1)
// Expected changes body: [[1,"foo","1-abc"]]
changeListReceived := [][]interface{}{}
err = base.JSONUnmarshal(body, &changeListReceived)
assert.NoError(t, err, "Error unmarshalling changes received")
for _, change := range changeListReceived {
// The change should have three items in the array
// [1,"foo","1-abc"]
assert.Len(t, change, 3)
// Make sure sequence numbers are monotonically increasing
receivedSeq, ok := change[0].(float64)
if ok {
assert.True(t, receivedSeq > lastReceivedSeq)
lastReceivedSeq = receivedSeq
} else {
nonIntegerSequenceReceived = true
log.Printf("Unexpected non-integer sequence received: %v", change[0])
}
revID := change[2].(string)
responseVal = append(responseVal, []interface{}{revID})
changeCount++
receivedChangesWg.Done()
}
}
if !request.NoReply() {
// Send an empty response to avoid the Sync: Invalid response to 'changes' message
response := request.Response()
responseValBytes, err := base.JSONMarshal(responseVal)
assert.NoError(t, err, "Error marshalling response")
response.SetBody(responseValBytes)
}
}
// -------- Rev handler callback --------
bt.blipContext.HandlerForProfile["rev"] = func(request *blip.Message) {
defer revsFinishedWg.Done()
body, err := request.Body()
require.NoError(t, err)
var doc RestDocument
err = base.JSONUnmarshal(body, &doc)
if err != nil {
panic(fmt.Sprintf("Unexpected err: %v", err))
}
log.Printf("got rev message: %+v", doc)
_, isRemoved := doc[db.BodyRemoved]
assert.False(t, isRemoved)
}
// Send subChanges to subscribe to changes, which will cause the "changes" profile handler above to be called back
subChangesRequest := bt.newRequest()
subChangesRequest.SetProfile("subChanges")
subChangesRequest.Properties["continuous"] = "true"
subChangesRequest.Properties["batch"] = "10" // default batch size is 200, lower this to 10 to make sure we get multiple batches
subChangesRequest.SetCompressed(false)
sent := bt.sender.Send(subChangesRequest)
assert.True(t, sent)
subChangesResponse := subChangesRequest.Response()
assert.Equal(t, subChangesRequest.SerialNumber(), subChangesResponse.SerialNumber())
// Write a doc that grants user1 access to channel ABC, and doc is also in channel ABC
receivedChangesWg.Add(1)
revsFinishedWg.Add(1)
response := rt.SendAdminRequest("PUT", "/{{.keyspace}}/grantDoc", `{"accessUser":"user1", "accessChannel":"ABC", "channels":["ABC"]}`)
RequireStatus(t, response, 201)
rt.WaitForPendingChanges()
// Wait until all expected changes are received by change handler
timeoutErr := WaitWithTimeout(&receivedChangesWg, time.Second*5)
assert.NoError(t, timeoutErr, "Timed out waiting for all changes.")
revTimeoutErr := WaitWithTimeout(&revsFinishedWg, time.Second*5)