-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathblip_handler.go
More file actions
1572 lines (1351 loc) · 59.2 KB
/
blip_handler.go
File metadata and controls
1572 lines (1351 loc) · 59.2 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 2020-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 (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"runtime/debug"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/couchbase/go-blip"
sgbucket "github.com/couchbase/sg-bucket"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/channels"
)
// handlersByProfile defines the routes for each message profile (verb) of an incoming request to the function that handles it.
var handlersByProfile = map[string]blipHandlerFunc{
MessageGetCheckpoint: collectionBlipHandler((*blipHandler).handleGetCheckpoint),
MessageSetCheckpoint: collectionBlipHandler((*blipHandler).handleSetCheckpoint),
MessageSubChanges: userBlipHandler(collectionBlipHandler((*blipHandler).handleSubChanges)),
MessageUnsubChanges: userBlipHandler(collectionBlipHandler((*blipHandler).handleUnsubChanges)),
MessageChanges: userBlipHandler(collectionBlipHandler((*blipHandler).handleChanges)),
MessageRev: userBlipHandler(collectionBlipHandler((*blipHandler).handleRev)),
MessageNoRev: collectionBlipHandler((*blipHandler).handleNoRev),
MessageGetAttachment: userBlipHandler(collectionBlipHandler((*blipHandler).handleGetAttachment)),
MessageProveAttachment: userBlipHandler(collectionBlipHandler((*blipHandler).handleProveAttachment)),
MessageProposeChanges: collectionBlipHandler((*blipHandler).handleProposeChanges),
MessageGetRev: userBlipHandler(collectionBlipHandler((*blipHandler).handleGetRev)),
MessagePutRev: userBlipHandler(collectionBlipHandler((*blipHandler).handlePutRev)),
MessageGetCollections: userBlipHandler((*blipHandler).handleGetCollections),
}
var kConnectedClientHandlersByProfile = map[string]blipHandlerFunc{
MessageFunction: userBlipHandler((*blipHandler).handleFunction),
}
// Replication throttling
const (
// DefaultMaxConcurrentChangesBatches is the maximum number of in-flight changes batches a client is allowed to send concurrently without being throttled.
DefaultMaxConcurrentChangesBatches = 2
// DefaultMaxConcurrentRevs is the maximum number of in-flight revisions a client is allowed to send or receive concurrently without being throttled.
DefaultMaxConcurrentRevs = 5
)
type blipHandler struct {
*BlipSyncContext
db *Database // Handler-specific copy of the BlipSyncContext's blipContextDb
collection *DatabaseCollectionWithUser // Handler-specific copy of the BlipSyncContext's collection specific DB
collectionCtx *blipSyncCollectionContext // Sync-specific data for this collection
collectionIdx *int // index into BlipSyncContext.collectionMapping for the collection
loggingCtx context.Context // inherited from BlipSyncContext.loggingCtx with additional handler-only information (like keyspace)
serialNumber uint64 // This blip handler's serial number to differentiate logs w/ other handlers
}
func newBlipHandler(ctx context.Context, bc *BlipSyncContext, db *Database, serialNumber uint64) *blipHandler {
return &blipHandler{
BlipSyncContext: bc,
db: db,
loggingCtx: ctx,
serialNumber: serialNumber,
}
}
// BlipSyncContextClientType represents whether to replicate to another Sync Gateway or Couchbase Lite
type BLIPSyncContextClientType string
const (
BLIPCorrelationIDResponseHeader = "X-Correlation-ID"
BLIPSyncClientTypeQueryParam = "client"
BLIPClientTypeCBL2 BLIPSyncContextClientType = "cbl2"
BLIPClientTypeSGR2 BLIPSyncContextClientType = "sgr2"
)
type blipHandlerFunc func(*blipHandler, *blip.Message) error
var (
// CBLReconnectErrorCode is the error code that CBL will use to trigger a reconnect
CBLReconnectErrorCode = http.StatusServiceUnavailable
ErrUseProposeChanges = base.HTTPErrorf(http.StatusConflict, "Use 'proposeChanges' instead")
// ErrDatabaseWentAway is returned when a replication tries to use a closed database.
// HTTP 503 tells the client to reconnect and try again.
ErrDatabaseWentAway = base.HTTPErrorf(http.StatusServiceUnavailable, "Sync Gateway database went away - asking client to reconnect")
// ErrAttachmentNotFound is returned when the attachment that is asked by one of the peers does
// not exist in another to prove that it has the attachment during Inter-Sync Gateway Replication.
ErrAttachmentNotFound = base.HTTPErrorf(http.StatusNotFound, "attachment not found")
)
// userBlipHandler wraps another blip handler with code that reloads the user object when the user
// or the user's roles have changed, to make sure that the replication has the latest channel access grants.
// Uses a userChangeWaiter to detect changes to the user or roles. Note that in the case of a pushed document
// triggering a user access change, this happens at write time (via MarkPrincipalsChanged), and doesn't
// depend on the userChangeWaiter.
func userBlipHandler(next blipHandlerFunc) blipHandlerFunc {
return func(bh *blipHandler, bm *blip.Message) error {
// Reload user if it has changed
if err := bh.refreshUser(); err != nil {
return err
}
// Call down to the underlying handler and return it's value
return next(bh, bm)
}
}
func (bh *blipHandler) refreshUser() error {
bc := bh.BlipSyncContext
if bc.userName != "" {
// Check whether user needs to be refreshed
bc.dbUserLock.Lock()
defer bc.dbUserLock.Unlock()
userChanged := bc.userChangeWaiter.RefreshUserCount()
// If changed, refresh the user and db while holding the lock
if userChanged {
// Refresh the BlipSyncContext database
err := bc.blipContextDb.ReloadUser(bh.loggingCtx)
if err != nil {
return base.NewHTTPError(CBLReconnectErrorCode, err.Error())
}
newUser := bc.blipContextDb.User()
newUser.InitializeRoles()
bc.userChangeWaiter.RefreshUserKeys(newUser, bc.blipContextDb.MetadataKeys)
// refresh the handler's database with the new BlipSyncContext database
bh.db = bh._copyContextDatabase()
if bh.collection != nil {
bh.collection = &DatabaseCollectionWithUser{
DatabaseCollection: bh.collection.DatabaseCollection,
user: bh.db.User(),
}
}
}
}
return nil
}
// collectionBlipHandler wraps another blip handler to specify a collection
func collectionBlipHandler(next blipHandlerFunc) blipHandlerFunc {
return func(bh *blipHandler, bm *blip.Message) error {
collectionIndexStr, ok := bm.Properties[BlipCollection]
if !ok {
if !bh.db.HasDefaultCollection() {
return base.HTTPErrorf(http.StatusBadRequest, "Collection property not specified and default collection is not configured for this database")
}
if bh.collections.hasNamedCollections() {
return base.HTTPErrorf(http.StatusBadRequest, "GetCollections already occurred, subsequent messages need a Collection property")
}
var err error
bh.collection, err = bh.db.GetDefaultDatabaseCollectionWithUser()
if err != nil {
return err
}
bh.collectionCtx, err = bh.collections.get(nil)
if err != nil {
bh.collections.setNonCollectionAware(newBlipSyncCollectionContext(bh.loggingCtx, bh.collection.DatabaseCollection))
bh.collectionCtx, _ = bh.collections.get(nil)
}
bh.loggingCtx = bh.collection.AddCollectionContext(bh.BlipSyncContext.loggingCtx)
return next(bh, bm)
}
if !bh.collections.hasNamedCollections() {
return base.HTTPErrorf(http.StatusBadRequest, "Passing collection requires calling %s first", MessageGetCollections)
}
collectionIndex, err := strconv.Atoi(collectionIndexStr)
if err != nil {
return base.HTTPErrorf(http.StatusBadRequest, "collection property needs to be an int, was %q", collectionIndexStr)
}
bh.collectionIdx = &collectionIndex
bh.collectionCtx, err = bh.collections.get(&collectionIndex)
if err != nil {
return base.HTTPErrorf(http.StatusBadRequest, "%s", err)
}
bh.collection = &DatabaseCollectionWithUser{
DatabaseCollection: bh.collectionCtx.dbCollection,
user: bh.db.user,
}
bh.loggingCtx = bh.collection.AddCollectionContext(bh.BlipSyncContext.loggingCtx)
// Call down to the underlying handler and return it's value
return next(bh, bm)
}
}
// ////// CHECKPOINTS
// Received a "getCheckpoint" request
func (bh *blipHandler) handleGetCheckpoint(rq *blip.Message) error {
client := rq.Properties[BlipClient]
bh.logEndpointEntry(rq.Profile(), fmt.Sprintf("Client:%s", client))
response := rq.Response()
if response == nil {
return nil
}
value, err := bh.collection.GetSpecial(DocTypeLocal, CheckpointDocIDPrefix+client)
if err != nil {
return err
}
if value == nil {
return base.NewHTTPError(http.StatusNotFound, http.StatusText(http.StatusNotFound))
}
response.Properties[GetCheckpointResponseRev] = value[BodyRev].(string)
delete(value, BodyRev)
delete(value, BodyId)
// TODO: Marshaling here when we could use raw bytes all the way from the bucket
_ = response.SetJSONBody(value)
return nil
}
// Received a "setCheckpoint" request
func (bh *blipHandler) handleSetCheckpoint(rq *blip.Message) error {
checkpointMessage := SetCheckpointMessage{rq}
bh.logEndpointEntry(rq.Profile(), checkpointMessage.String())
var checkpoint Body
if err := checkpointMessage.ReadJSONBody(&checkpoint); err != nil {
return err
}
if revID := checkpointMessage.rev(); revID != "" {
checkpoint[BodyRev] = revID
}
revID, _, err := bh.collection.PutSpecial(DocTypeLocal, CheckpointDocIDPrefix+checkpointMessage.client(), checkpoint)
if err != nil {
return err
}
checkpointResponse := SetCheckpointResponse{checkpointMessage.Response()}
checkpointResponse.setRev(revID)
return nil
}
// ////// CHANGES
// Received a "subChanges" subscription request
func (bh *blipHandler) handleSubChanges(rq *blip.Message) error {
latestSeq := func() (SequenceID, error) {
seq, err := bh.collection.LastSequence(bh.loggingCtx)
return SequenceID{Seq: seq}, err
}
subChangesParams, err := NewSubChangesParams(bh.loggingCtx, rq, latestSeq, bh.db.Options.ChangesRequestPlus)
if err != nil {
return base.HTTPErrorf(http.StatusBadRequest, "Invalid subChanges parameters")
}
// Ensure that only _one_ subChanges subscription can be open on this blip connection at any given time. SG #3222.
collectionCtx := bh.collectionCtx
collectionCtx.changesCtxLock.Lock()
defer collectionCtx.changesCtxLock.Unlock()
if !collectionCtx.activeSubChanges.CASRetry(false, true) {
collectionStr := "default collection"
if bh.collectionIdx != nil {
collectionStr = fmt.Sprintf("collection %d", *bh.collectionIdx)
}
return fmt.Errorf("blipHandler for %s already has an outstanding subChanges. Cannot open another one", collectionStr)
}
// Create ctx if it has been cancelled
if collectionCtx.changesCtx.Err() != nil {
collectionCtx.changesCtx, collectionCtx.changesCtxCancel = context.WithCancel(bh.loggingCtx)
}
if len(subChangesParams.docIDs()) > 0 && subChangesParams.continuous() {
return base.HTTPErrorf(http.StatusBadRequest, "DocIDs filter not supported for continuous subChanges")
}
bh.logEndpointEntry(rq.Profile(), subChangesParams.String())
var channels base.Set
if filter := subChangesParams.filter(); filter == base.ByChannelFilter {
var err error
channels, err = subChangesParams.channelsExpandedSet()
if err != nil {
return base.HTTPErrorf(http.StatusBadRequest, "%s", err)
} else if len(channels) == 0 {
return base.HTTPErrorf(http.StatusBadRequest, "Empty channel list")
}
} else if filter != "" {
return base.HTTPErrorf(http.StatusBadRequest, "Unknown filter; try sync_gateway/bychannel")
}
collectionCtx.channels = channels
clientType := clientTypeCBL2
if rq.Properties["client_sgr2"] == trueProperty {
clientType = clientTypeSGR2
}
continuous := subChangesParams.continuous()
requestPlusSeq := uint64(0)
// If non-continuous, check whether requestPlus handling is set for request or via database config
if continuous == false {
useRequestPlus := subChangesParams.requestPlus()
if useRequestPlus {
seq, requestPlusErr := bh.db.GetRequestPlusSequence()
if requestPlusErr != nil {
return base.HTTPErrorf(http.StatusServiceUnavailable, "Unable to retrieve current sequence for requestPlus=true: %v", requestPlusErr)
}
requestPlusSeq = seq
}
}
bh.collectionCtx.sendReplacementRevs = subChangesParams.sendReplacementRevs()
// Start asynchronous changes goroutine
go func() {
// Pull replication stats by type
if continuous {
bh.replicationStats.SubChangesContinuousActive.Add(1)
defer bh.replicationStats.SubChangesContinuousActive.Add(-1)
bh.replicationStats.SubChangesContinuousTotal.Add(1)
} else {
bh.replicationStats.SubChangesOneShotActive.Add(1)
defer bh.replicationStats.SubChangesOneShotActive.Add(-1)
bh.replicationStats.SubChangesOneShotTotal.Add(1)
}
defer func() {
collectionCtx.changesCtxCancel()
collectionCtx.activeSubChanges.Set(false)
}()
// sendChanges runs until blip context closes, or fails due to error
startTime := time.Now()
_, err = bh.sendChanges(rq.Sender, &sendChangesOptions{
docIDs: subChangesParams.docIDs(),
since: subChangesParams.Since(),
continuous: continuous,
activeOnly: subChangesParams.activeOnly(),
batchSize: subChangesParams.batchSize(),
channels: collectionCtx.channels,
revocations: subChangesParams.revocations(),
clientType: clientType,
ignoreNoConflicts: clientType == clientTypeSGR2, // force this side to accept a "changes" message, even in no conflicts mode for SGR2.
changesCtx: collectionCtx.changesCtx,
requestPlusSeq: requestPlusSeq,
})
if err != nil {
base.DebugfCtx(bh.loggingCtx, base.KeySyncMsg, "Closing blip connection due to changes feed error %+v\n", err)
bh.ctxCancelFunc()
}
base.DebugfCtx(bh.loggingCtx, base.KeySyncMsg, "#%d: Type:%s --> Time:%v", bh.serialNumber, rq.Profile(), time.Since(startTime))
}()
auditFields := base.AuditFields{
base.AuditFieldSince: subChangesParams.Since().String(),
}
if subChangesParams.filter() != "" {
auditFields[base.AuditFieldFilter] = subChangesParams.filter()
}
if len(subChangesParams.docIDs()) > 0 {
auditFields[base.AuditFieldDocIDs] = subChangesParams.docIDs()
auditFields[base.AuditFieldFilter] = base.DocIDsFilter
}
if continuous {
auditFields[base.AuditFieldFeedType] = "continuous"
} else {
auditFields[base.AuditFieldFeedType] = "normal"
}
if len(channels) > 0 {
auditFields[base.AuditFieldChannels] = channels
}
base.Audit(bh.loggingCtx, base.AuditIDChangesFeedStarted, auditFields)
return nil
}
func (bh *blipHandler) handleUnsubChanges(rq *blip.Message) error {
collectionCtx := bh.collectionCtx
collectionCtx.changesCtxLock.Lock()
defer collectionCtx.changesCtxLock.Unlock()
collectionCtx.changesCtxCancel()
return nil
}
type clientType uint8
const (
clientTypeCBL2 clientType = iota
clientTypeSGR2
)
type sendChangesOptions struct {
docIDs []string
since SequenceID
continuous bool
activeOnly bool
batchSize int
channels base.Set
clientType clientType
revocations bool
ignoreNoConflicts bool
changesCtx context.Context
requestPlusSeq uint64
}
type changesDeletedFlag uint
const (
// Bitfield flags used to build changes deleted property below
changesDeletedFlagDeleted changesDeletedFlag = 0b001
changesDeletedFlagRevoked changesDeletedFlag = 0b010
changesDeletedFlagRemoved changesDeletedFlag = 0b100
)
func (flag changesDeletedFlag) HasFlag(deletedFlag changesDeletedFlag) bool {
return flag&deletedFlag != 0
}
// sendChanges will start a changes feed and send changes. Returns bool to indicate whether the changes feed finished and all changes were sent. The error value is only used to indicate a fatal error, where the blip connection should be terminated. If the blip connection is disconnected by the client, the error will be nil, but the boolean parameter will be false.
func (bh *blipHandler) sendChanges(sender *blip.Sender, opts *sendChangesOptions) (bool, error) {
defer func() {
if panicked := recover(); panicked != nil {
bh.replicationStats.NumHandlersPanicked.Add(1)
base.WarnfCtx(bh.loggingCtx, "[%s] PANIC sending changes: %v\n%s", bh.blipContext.ID, panicked, debug.Stack())
}
}()
base.InfofCtx(bh.loggingCtx, base.KeySync, "Sending changes since %v", opts.since)
options := ChangesOptions{
Since: opts.since,
Conflicts: false, // CBL 2.0/BLIP don't support branched rev trees (LiteCore #437)
Continuous: opts.continuous,
ActiveOnly: opts.activeOnly,
Revocations: opts.revocations,
clientType: opts.clientType,
ChangesCtx: opts.changesCtx,
RequestPlusSeq: opts.requestPlusSeq,
}
channelSet := opts.channels
if channelSet == nil {
channelSet = base.SetOf(channels.AllChannelWildcard)
}
caughtUp := false
pendingChanges := make([][]interface{}, 0, opts.batchSize)
sendPendingChangesAt := func(minChanges int) error {
if len(pendingChanges) >= minChanges {
if err := bh.sendBatchOfChanges(sender, pendingChanges, opts.ignoreNoConflicts); err != nil {
return err
}
pendingChanges = make([][]interface{}, 0, opts.batchSize)
}
return nil
}
// Create a distinct database instance for changes, to avoid races between reloadUser invocation in changes.go
// and BlipSyncContext user access.
changesDb, err := bh.copyDatabaseCollectionWithUser(bh.collectionIdx)
if err != nil {
base.WarnfCtx(bh.loggingCtx, "[%s] error sending changes: %v", bh.blipContext.ID, err)
return false, err
}
forceClose, err := generateBlipSyncChanges(bh.loggingCtx, changesDb, channelSet, options, opts.docIDs, func(changes []*ChangeEntry) error {
base.DebugfCtx(bh.loggingCtx, base.KeySync, " Sending %d changes", len(changes))
for _, change := range changes {
if !strings.HasPrefix(change.ID, "_") {
// If change is a removal and we're running with protocol V3 and change change is not a tombstone
// fall into 3.0 removal handling.
// Changes with change.Revoked=true have already evaluated UserHasDocAccess in changes.go, don't check again.
if change.allRemoved && bh.activeCBMobileSubprotocol >= CBMobileReplicationV3 && !change.Deleted && !change.Revoked && !bh.db.Options.UnsupportedOptions.BlipSendDocsWithChannelRemoval {
// If client doesn't want removals / revocations, don't send change
if !opts.revocations {
continue
}
// If the user has access to the doc through another channel don't send change
userHasAccessToDoc, err := UserHasDocAccess(bh.loggingCtx, changesDb, change.ID)
if err == nil && userHasAccessToDoc {
continue
}
// If we can't determine user access due to an error, log error and fall through to send change anyway.
// In the event of an error we should be cautious and send a revocation anyway, even if the user
// may actually have an alternate access method. This is the safer approach security-wise and
// also allows for a recovery if the user notices they are missing a doc they should have access
// to. A recovery option would be to trigger a mutation of the document for it to be sent in a
// subsequent changes request. If we were to avoid sending a removal there is no recovery
// option to then trigger that removal later on.
if err != nil {
base.WarnfCtx(bh.loggingCtx, "Unable to determine whether user has access to %s, will send removal: %v", base.UD(change.ID), err)
}
}
for _, item := range change.Changes {
changeRow := bh.buildChangesRow(change, item["rev"])
pendingChanges = append(pendingChanges, changeRow)
if err := sendPendingChangesAt(opts.batchSize); err != nil {
return err
}
}
}
}
if caughtUp || len(changes) == 0 {
if err := sendPendingChangesAt(1); err != nil {
return err
}
if !caughtUp {
caughtUp = true
// Signal to client that it's caught up
if err := bh.sendBatchOfChanges(sender, nil, opts.ignoreNoConflicts); err != nil {
return err
}
}
}
return nil
})
// On forceClose, send notify to trigger immediate exit from change waiter
if forceClose {
user := ""
if bh.db.User() != nil {
user = bh.db.User().Name()
}
bh.db.DatabaseContext.NotifyTerminatedChanges(bh.loggingCtx, user)
}
return (err == nil && !forceClose), err
}
func (bh *blipHandler) buildChangesRow(change *ChangeEntry, revID string) []interface{} {
var changeRow []interface{}
if bh.activeCBMobileSubprotocol >= CBMobileReplicationV3 {
deletedFlags := changesDeletedFlag(0)
if change.Deleted {
deletedFlags |= changesDeletedFlagDeleted
}
if change.Revoked {
deletedFlags |= changesDeletedFlagRevoked
}
if change.allRemoved {
deletedFlags |= changesDeletedFlagRemoved
}
changeRow = []interface{}{change.Seq, change.ID, revID, deletedFlags}
if deletedFlags == 0 {
changeRow = changeRow[0:3]
}
} else {
changeRow = []interface{}{change.Seq, change.ID, revID, change.Deleted}
if !change.Deleted {
changeRow = changeRow[0:3]
}
}
return changeRow
}
func (bh *blipHandler) sendBatchOfChanges(sender *blip.Sender, changeArray [][]interface{}, ignoreNoConflicts bool) error {
outrq := blip.NewRequest()
outrq.SetProfile("changes")
if ignoreNoConflicts {
outrq.Properties[ChangesMessageIgnoreNoConflicts] = trueProperty
}
if bh.collectionIdx != nil {
outrq.Properties[BlipCollection] = strconv.Itoa(*bh.collectionIdx)
}
err := outrq.SetJSONBody(changeArray)
if err != nil {
base.InfofCtx(bh.loggingCtx, base.KeyAll, "Error setting changes: %v", err)
}
if len(changeArray) > 0 {
// Check for user updates before creating the db copy for handleChangesResponse
if err := bh.refreshUser(); err != nil {
return err
}
handleChangesResponseDbCollection, err := bh.copyDatabaseCollectionWithUser(bh.collectionIdx)
if err != nil {
return err
}
sendTime := time.Now()
if !bh.sendBLIPMessage(sender, outrq) {
return ErrClosedBLIPSender
}
bh.inFlightChangesThrottle <- struct{}{}
atomic.AddInt64(&bh.changesPendingResponseCount, 1)
bh.replicationStats.SendChangesCount.Add(int64(len(changeArray)))
// Spawn a goroutine to await the client's response:
go func(bh *blipHandler, sender *blip.Sender, response *blip.Message, changeArray [][]interface{}, sendTime time.Time, dbCollection *DatabaseCollectionWithUser) {
if err := bh.handleChangesResponse(bh.loggingCtx, sender, response, changeArray, sendTime, dbCollection, bh.collectionIdx); err != nil {
base.WarnfCtx(bh.loggingCtx, "Error from bh.handleChangesResponse: %v", err)
if bh.fatalErrorCallback != nil {
bh.fatalErrorCallback(err)
}
}
// Sent all of the revs for this changes batch, allow another changes batch to be sent.
select {
case <-bh.inFlightChangesThrottle:
case <-bh.terminator:
}
atomic.AddInt64(&bh.changesPendingResponseCount, -1)
}(bh, sender, outrq.Response(), changeArray, sendTime, handleChangesResponseDbCollection)
} else {
outrq.SetNoReply(true)
if !bh.sendBLIPMessage(sender, outrq) {
return ErrClosedBLIPSender
}
}
if len(changeArray) > 0 {
sequence := changeArray[0][0].(SequenceID)
base.InfofCtx(bh.loggingCtx, base.KeySync, "Sent %d changes to client, from seq %s", len(changeArray), sequence.String())
} else {
base.InfofCtx(bh.loggingCtx, base.KeySync, "Sent all changes to client")
}
return nil
}
// Handles a "changes" request, i.e. a set of changes pushed by the client
func (bh *blipHandler) handleChanges(rq *blip.Message) error {
var ignoreNoConflicts bool
if val := rq.Properties[ChangesMessageIgnoreNoConflicts]; val != "" {
ignoreNoConflicts = val == trueProperty
}
if !ignoreNoConflicts && !bh.collection.AllowConflicts() {
return ErrUseProposeChanges
}
var changeList [][]interface{}
if err := rq.ReadJSONBody(&changeList); err != nil {
base.WarnfCtx(bh.loggingCtx, "Handle changes got error: %v", err)
return err
}
collectionCtx := bh.collectionCtx
bh.logEndpointEntry(rq.Profile(), fmt.Sprintf("#Changes:%d", len(changeList)))
if len(changeList) == 0 {
// An empty changeList is sent when a one-shot replication sends its final changes
// message, or a continuous replication catches up *for the first time*.
// Note that this doesn't mean that rev messages associated with previous changes
// messages have been fully processed
if collectionCtx.emptyChangesMessageCallback != nil {
collectionCtx.emptyChangesMessageCallback()
}
return nil
}
output := bytes.NewBuffer(make([]byte, 0, 100*len(changeList)))
output.Write([]byte("["))
jsonOutput := base.JSONEncoder(output)
nWritten := 0
nRequested := 0
// Include changes messages w/ proposeChanges stats, although CBL should only be using proposeChanges
startTime := time.Now()
bh.replicationStats.HandleChangesCount.Add(int64(len(changeList)))
defer func() {
bh.replicationStats.HandleChangesTime.Add(time.Since(startTime).Nanoseconds())
}()
// DocID+RevID -> SeqNo
expectedSeqs := make(map[IDAndRev]SequenceID, 0)
alreadyKnownSeqs := make([]SequenceID, 0)
for _, change := range changeList {
docID := change[1].(string)
revID := change[2].(string)
missing, possible := bh.collection.RevDiff(bh.loggingCtx, docID, []string{revID})
if nWritten > 0 {
output.Write([]byte(","))
}
deletedFlags := changesDeletedFlag(0)
if len(change) > 3 {
switch v := change[3].(type) {
case json.Number:
deletedIntFlag, err := v.Int64()
if err != nil {
base.ErrorfCtx(bh.loggingCtx, "Failed to parse deletedFlags: %v", err)
continue
}
deletedFlags = changesDeletedFlag(deletedIntFlag)
case bool:
deletedFlags = changesDeletedFlagDeleted
default:
base.ErrorfCtx(bh.loggingCtx, "Unknown type for deleted field in changes message: %T", v)
continue
}
}
if bh.purgeOnRemoval && bh.activeCBMobileSubprotocol >= CBMobileReplicationV3 &&
(deletedFlags.HasFlag(changesDeletedFlagRevoked) || deletedFlags.HasFlag(changesDeletedFlagRemoved)) {
err := bh.collection.Purge(bh.loggingCtx, docID, true)
if err != nil {
base.WarnfCtx(bh.loggingCtx, "Failed to purge document: %v", err)
}
bh.replicationStats.HandleRevDocsPurgedCount.Add(1)
// Fall into skip sending case
missing = nil
}
if missing == nil {
// already have this rev, tell the peer to skip sending it
output.Write([]byte("0"))
if collectionCtx.sgr2PullAlreadyKnownSeqsCallback != nil {
seq, err := ParseJSONSequenceID(seqStr(bh.loggingCtx, change[0]))
if err != nil {
base.WarnfCtx(bh.loggingCtx, "Unable to parse known sequence %q for %q / %q: %v", change[0], base.UD(docID), revID, err)
} else {
// we're not able to checkpoint a sequence we can't parse and aren't expecting so just skip the callback if we errored
alreadyKnownSeqs = append(alreadyKnownSeqs, seq)
}
}
} else {
// we want this rev, send possible ancestors to the peer
nRequested++
if len(possible) == 0 {
output.Write([]byte("[]"))
} else {
err := jsonOutput.Encode(possible)
if err != nil {
base.InfofCtx(bh.loggingCtx, base.KeyAll, "Error encoding json: %v", err)
}
}
// skip parsing seqno if we're not going to use it (no callback defined)
if collectionCtx.sgr2PullAddExpectedSeqsCallback != nil {
seq, err := ParseJSONSequenceID(seqStr(bh.loggingCtx, change[0]))
if err != nil {
// We've already asked for the doc/rev for the sequence so assume we're going to receive it... Just log this and carry on
base.WarnfCtx(bh.loggingCtx, "Unable to parse expected sequence %q for %q / %q: %v", change[0], base.UD(docID), revID, err)
} else {
expectedSeqs[IDAndRev{DocID: docID, RevID: revID}] = seq
}
}
}
nWritten++
}
output.Write([]byte("]"))
response := rq.Response()
if bh.sgCanUseDeltas {
base.DebugfCtx(bh.loggingCtx, base.KeyAll, "Setting deltas=true property on handleChanges response")
response.Properties[ChangesResponseDeltas] = trueProperty
bh.replicationStats.HandleChangesDeltaRequestedCount.Add(int64(nRequested))
}
response.SetCompressed(true)
response.SetBody(output.Bytes())
if collectionCtx.sgr2PullAddExpectedSeqsCallback != nil {
collectionCtx.sgr2PullAddExpectedSeqsCallback(expectedSeqs)
}
if collectionCtx.sgr2PullAlreadyKnownSeqsCallback != nil {
collectionCtx.sgr2PullAlreadyKnownSeqsCallback(alreadyKnownSeqs...)
}
return nil
}
// Handles a "proposeChanges" request, similar to "changes" but in no-conflicts mode
func (bh *blipHandler) handleProposeChanges(rq *blip.Message) error {
// we don't know whether this batch of changes has completed because they look like unsolicited revs to us,
// but we can stop clients swarming us with these causing CheckProposedRev work
bh.inFlightChangesThrottle <- struct{}{}
defer func() { <-bh.inFlightChangesThrottle }()
includeConflictRev := false
if val := rq.Properties[ProposeChangesConflictsIncludeRev]; val != "" {
includeConflictRev = val == trueProperty
}
var changeList [][]interface{}
if err := rq.ReadJSONBody(&changeList); err != nil {
return err
}
bh.logEndpointEntry(rq.Profile(), fmt.Sprintf("#Changes: %d", len(changeList)))
if len(changeList) == 0 {
return nil
}
output := bytes.NewBuffer(make([]byte, 0, 5*len(changeList)))
output.Write([]byte("["))
nWritten := 0
// proposeChanges stats
startTime := time.Now()
bh.replicationStats.HandleChangesCount.Add(int64(len(changeList)))
defer func() {
bh.replicationStats.HandleChangesTime.Add(time.Since(startTime).Nanoseconds())
}()
for i, change := range changeList {
docID := change[0].(string)
revID := change[1].(string)
parentRevID := ""
if len(change) > 2 {
parentRevID = change[2].(string)
}
status, currentRev := bh.collection.CheckProposedRev(bh.loggingCtx, docID, revID, parentRevID)
if status == ProposedRev_OK_IsNew {
// Remember that the doc doesn't exist locally, in order to optimize the upcoming Put:
bh.collectionCtx.notePendingInsertion(docID)
} else if status != ProposedRev_OK {
// Reject the proposed change.
// Skip writing trailing zeroes; but if we write a number afterwards we have to catch up
if nWritten > 0 {
output.Write([]byte(","))
}
for ; nWritten < i; nWritten++ {
output.Write([]byte("0,"))
}
if includeConflictRev && status == ProposedRev_Conflict {
revEntry := IncludeConflictRevEntry{Status: status, Rev: currentRev}
entryBytes, marshalErr := base.JSONMarshal(revEntry)
if marshalErr != nil {
base.WarnfCtx(bh.loggingCtx, "Unable to marshal proposeChangesEntry as includeConflictRev - falling back to status-only entry. Error: %v", marshalErr)
output.Write([]byte(strconv.FormatInt(int64(status), 10)))
}
output.Write(entryBytes)
} else {
output.Write([]byte(strconv.FormatInt(int64(status), 10)))
}
nWritten++
}
}
output.Write([]byte("]"))
response := rq.Response()
if bh.sgCanUseDeltas {
base.DebugfCtx(bh.loggingCtx, base.KeyAll, "Setting deltas=true property on proposeChanges response")
response.Properties[ChangesResponseDeltas] = trueProperty
}
response.SetCompressed(true)
response.SetBody(output.Bytes())
return nil
}
// ////// DOCUMENTS:
func (bsc *BlipSyncContext) sendRevAsDelta(ctx context.Context, sender *blip.Sender, docID, revID string, deltaSrcRevID string, seq SequenceID, knownRevs map[string]bool, maxHistory int, handleChangesResponseCollection *DatabaseCollectionWithUser, collectionIdx *int) error {
bsc.replicationStats.SendRevDeltaRequestedCount.Add(1)
revDelta, redactedRev, err := handleChangesResponseCollection.GetDelta(ctx, docID, deltaSrcRevID, revID)
if err == ErrForbidden { // nolint: gocritic // can't convert if/else if to switch since base.IsFleeceDeltaError is not switchable
return err
} else if base.IsFleeceDeltaError(err) {
// Something went wrong in the diffing library. We want to know about this!
base.WarnfCtx(ctx, "Falling back to full body replication. Error generating delta from %s to %s for key %s - err: %v", deltaSrcRevID, revID, base.UD(docID), err)
return bsc.sendRevision(ctx, sender, docID, revID, seq, knownRevs, maxHistory, handleChangesResponseCollection, collectionIdx)
} else if err == base.ErrDeltaSourceIsTombstone {
base.TracefCtx(ctx, base.KeySync, "Falling back to full body replication. Delta source %s is tombstone. Unable to generate delta to %s for key %s", deltaSrcRevID, revID, base.UD(docID))
return bsc.sendRevision(ctx, sender, docID, revID, seq, knownRevs, maxHistory, handleChangesResponseCollection, collectionIdx)
} else if err != nil {
base.DebugfCtx(ctx, base.KeySync, "Falling back to full body replication. Couldn't get delta from %s to %s for key %s - err: %v", deltaSrcRevID, revID, base.UD(docID), err)
return bsc.sendRevision(ctx, sender, docID, revID, seq, knownRevs, maxHistory, handleChangesResponseCollection, collectionIdx)
}
if redactedRev != nil {
history := toHistory(redactedRev.History, knownRevs, maxHistory)
properties := blipRevMessageProperties(history, redactedRev.Deleted, seq, "")
return bsc.sendRevisionWithProperties(ctx, sender, docID, revID, collectionIdx, redactedRev.BodyBytes, nil, properties, seq, nil)
}
if revDelta == nil {
base.DebugfCtx(ctx, base.KeySync, "Falling back to full body replication. Couldn't get delta from %s to %s for key %s", deltaSrcRevID, revID, base.UD(docID))
return bsc.sendRevision(ctx, sender, docID, revID, seq, knownRevs, maxHistory, handleChangesResponseCollection, collectionIdx)
}
resendFullRevisionFunc := func() error {
base.InfofCtx(ctx, base.KeySync, "Resending revision as full body. Peer couldn't process delta %s from %s to %s for key %s", base.UD(revDelta.DeltaBytes), deltaSrcRevID, revID, base.UD(docID))
return bsc.sendRevision(ctx, sender, docID, revID, seq, knownRevs, maxHistory, handleChangesResponseCollection, collectionIdx)
}
base.TracefCtx(ctx, base.KeySync, "docID: %s - delta: %v", base.UD(docID), base.UD(string(revDelta.DeltaBytes)))
if err := bsc.sendDelta(ctx, sender, docID, collectionIdx, deltaSrcRevID, revDelta, seq, resendFullRevisionFunc); err != nil {
return err
}
// We'll consider this one doc read for collection stats purposes, since GetDelta doesn't go through the normal getRev codepath.
handleChangesResponseCollection.collectionStats.NumDocReads.Add(1)
handleChangesResponseCollection.collectionStats.DocReadsBytes.Add(int64(len(revDelta.DeltaBytes)))
bsc.replicationStats.SendRevDeltaSentCount.Add(1)
return nil
}
func (bh *blipHandler) handleNoRev(rq *blip.Message) error {
docID, revID := rq.Properties[NorevMessageId], rq.Properties[NorevMessageRev]
var seqStr string
if bh.activeCBMobileSubprotocol <= CBMobileReplicationV2 && bh.clientType == BLIPClientTypeSGR2 {
seqStr = rq.Properties[NorevMessageSeq]
} else {
seqStr = rq.Properties[NorevMessageSequence]
}
base.InfofCtx(bh.loggingCtx, base.KeySyncMsg, "%s: norev for doc %q / %q seq:%q - error: %q - reason: %q",
rq.String(), base.UD(docID), revID, seqStr, rq.Properties[NorevMessageError], rq.Properties[NorevMessageReason])
if bh.collectionCtx.sgr2PullProcessedSeqCallback != nil {
seq, err := ParseJSONSequenceID(seqStr)
if err != nil {
base.WarnfCtx(bh.loggingCtx, "Unable to parse sequence %q from norev message: %v - not tracking for checkpointing", seqStr, err)
} else {
bh.collectionCtx.sgr2PullProcessedSeqCallback(&seq, IDAndRev{DocID: docID, RevID: revID})
}
}
// Couchbase Lite always sends noreply=true for norev profiles
// but for testing purposes, it's useful to know which handler processed the message
if !rq.NoReply() && rq.Properties[SGShowHandler] == trueProperty {
response := rq.Response()
response.Properties[SGHandler] = "handleNoRev"
}
return nil
}
type processRevStats struct {
count *base.SgwIntStat // Increments when rev processed successfully
errorCount *base.SgwIntStat
deltaRecvCount *base.SgwIntStat
bytes *base.SgwIntStat
processingTime *base.SgwIntStat
docsPurgedCount *base.SgwIntStat
throttledRevs *base.SgwIntStat
throttledRevTime *base.SgwIntStat
}
// Processes a "rev" request, i.e. client is pushing a revision body
// stats must always be provided, along with all the fields filled with valid pointers
func (bh *blipHandler) processRev(rq *blip.Message, stats *processRevStats) (err error) {
startTime := time.Now()
defer func() {
stats.processingTime.Add(time.Since(startTime).Nanoseconds())
if err == nil {
stats.count.Add(1)
} else {
stats.errorCount.Add(1)
}
}()
// throttle concurrent revs
if cap(bh.inFlightRevsThrottle) > 0 {
select {
case bh.inFlightRevsThrottle <- struct{}{}:
default:
stats.throttledRevs.Add(1)
throttleStart := time.Now()
bh.inFlightRevsThrottle <- struct{}{}
stats.throttledRevTime.Add(time.Since(throttleStart).Nanoseconds())
}
defer func() { <-bh.inFlightRevsThrottle }()
}
// addRevisionParams := newAddRevisionParams(rq)
revMessage := RevMessage{Message: rq}
// Doc metadata comes from the BLIP message metadata, not magic document properties:
docID, found := revMessage.ID()
revID, rfound := revMessage.Rev()
if !found || !rfound {
return base.HTTPErrorf(http.StatusBadRequest, "Missing docID or revID")
}
if bh.readOnly {
return base.HTTPErrorf(http.StatusForbidden, "Replication context is read-only, docID: %s, revID:%s", docID, revID)
}
base.DebugfCtx(bh.loggingCtx, base.KeySyncMsg, "#%d: Type:%s %s", bh.serialNumber, rq.Profile(), revMessage.String())
bodyBytes, err := rq.Body()
if err != nil {
return err
}