-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathcrud.go
2794 lines (2413 loc) · 106 KB
/
crud.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package db
import (
"bytes"
"context"
"fmt"
"math"
"net/http"
"strings"
"time"
sgbucket "github.com/couchbase/sg-bucket"
"github.com/couchbase/sync_gateway/auth"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/channels"
"github.com/pkg/errors"
)
const (
kMaxRecentSequences = 20 // Maximum number of sequences stored in RecentSequences before pruning is triggered
kMinRecentSequences = 5 // Minimum number of sequences that should be left stored in RecentSequences during compaction
unusedSequenceWarningThreshold = 10000 // Warn when releasing more than this many sequences due to existing sequence on the document
)
// ErrForbidden is returned when the user requests a document without a revision that they do not have access to.
// this is different from a client specifically requesting a revision they know about, which are treated as a _removal.
var ErrForbidden = base.HTTPErrorf(403, "forbidden")
var ErrMissing = base.HTTPErrorf(404, "missing")
var ErrDeleted = base.HTTPErrorf(404, "deleted")
// ////// READING DOCUMENTS:
func realDocID(docid string) string {
if len(docid) > 250 {
return "" // Invalid doc IDs
}
if strings.HasPrefix(docid, "_") {
return "" // Disallow "_" prefix, which is for special docs
}
return docid
}
// GetDocument with raw returns the document from the bucket. This may perform an on-demand import.
func (c *DatabaseCollection) GetDocument(ctx context.Context, docid string, unmarshalLevel DocumentUnmarshalLevel) (doc *Document, err error) {
doc, _, err = c.GetDocumentWithRaw(ctx, docid, unmarshalLevel)
return doc, err
}
// GetDocumentWithRaw returns the document from the bucket. This may perform an on-demand import.
func (c *DatabaseCollection) GetDocumentWithRaw(ctx context.Context, docid string, unmarshalLevel DocumentUnmarshalLevel) (doc *Document, rawBucketDoc *sgbucket.BucketDocument, err error) {
key := realDocID(docid)
if key == "" {
return nil, nil, base.HTTPErrorf(400, "Invalid doc ID")
}
if c.UseXattrs() {
doc, rawBucketDoc, err = c.GetDocWithXattr(ctx, key, unmarshalLevel)
if err != nil {
return nil, nil, err
}
isSgWrite, crc32Match, _ := doc.IsSGWrite(ctx, rawBucketDoc.Body)
if crc32Match {
c.dbStats().Database().Crc32MatchCount.Add(1)
}
// If existing doc wasn't an SG Write, import the doc.
if !isSgWrite {
var importErr error
doc, importErr = c.OnDemandImportForGet(ctx, docid, rawBucketDoc.Body, rawBucketDoc.Xattrs, rawBucketDoc.Cas)
if importErr != nil {
return nil, nil, importErr
}
// nil, nil returned when ErrImportCancelled is swallowed by importDoc switch
if doc == nil {
return nil, nil, base.ErrNotFound
}
}
if !doc.HasValidSyncData() {
return nil, nil, base.HTTPErrorf(404, "Not imported")
}
} else {
rawDoc, cas, getErr := c.dataStore.GetRaw(key)
if getErr != nil {
return nil, nil, getErr
}
doc, err = unmarshalDocument(key, rawDoc)
if err != nil {
return nil, nil, err
}
if !doc.HasValidSyncData() {
// Check whether doc has been upgraded to use xattrs
upgradeDoc, _ := c.checkForUpgrade(ctx, docid, unmarshalLevel)
if upgradeDoc == nil {
return nil, nil, base.HTTPErrorf(404, "Not imported")
}
doc = upgradeDoc
}
rawBucketDoc = &sgbucket.BucketDocument{
Body: rawDoc,
Cas: cas,
}
}
return doc, rawBucketDoc, nil
}
func (c *DatabaseCollection) GetDocWithXattr(ctx context.Context, key string, unmarshalLevel DocumentUnmarshalLevel) (doc *Document, rawBucketDoc *sgbucket.BucketDocument, err error) {
rawBucketDoc = &sgbucket.BucketDocument{}
var getErr error
rawBucketDoc.Body, rawBucketDoc.Xattrs, rawBucketDoc.Cas, getErr = c.dataStore.GetWithXattrs(ctx, key, c.syncAndUserXattrKeys())
if getErr != nil {
return nil, nil, getErr
}
var unmarshalErr error
doc, unmarshalErr = c.unmarshalDocumentWithXattrs(ctx, key, rawBucketDoc.Body, rawBucketDoc.Xattrs, rawBucketDoc.Cas, unmarshalLevel)
if unmarshalErr != nil {
return nil, nil, unmarshalErr
}
return doc, rawBucketDoc, nil
}
// This gets *just* the Sync Metadata (_sync field) rather than the entire doc, for efficiency reasons.
func (c *DatabaseCollection) GetDocSyncData(ctx context.Context, docid string) (SyncData, error) {
emptySyncData := SyncData{}
key := realDocID(docid)
if key == "" {
return emptySyncData, base.HTTPErrorf(400, "Invalid doc ID")
}
if c.UseXattrs() {
// Retrieve doc and xattr from bucket, unmarshal only xattr.
// Triggers on-demand import when document xattr doesn't match cas.
rawDoc, xattrs, cas, getErr := c.dataStore.GetWithXattrs(ctx, key, c.syncAndUserXattrKeys())
if getErr != nil {
return emptySyncData, getErr
}
// Unmarshal xattr only
doc, unmarshalErr := c.unmarshalDocumentWithXattrs(ctx, docid, nil, xattrs, cas, DocUnmarshalSync)
if unmarshalErr != nil {
return emptySyncData, unmarshalErr
}
isSgWrite, crc32Match, _ := doc.IsSGWrite(ctx, rawDoc)
if crc32Match {
c.dbStats().Database().Crc32MatchCount.Add(1)
}
// If existing doc wasn't an SG Write, import the doc.
if !isSgWrite {
var importErr error
doc, importErr = c.OnDemandImportForGet(ctx, docid, rawDoc, xattrs, cas)
if importErr != nil {
return emptySyncData, importErr
}
}
return doc.SyncData, nil
} else {
// Non-xattr. Retrieve doc from bucket, unmarshal metadata only.
rawDocBytes, _, err := c.dataStore.GetRaw(key)
if err != nil {
return emptySyncData, err
}
docRoot := documentRoot{
SyncData: &SyncData{History: make(RevTree)},
}
if err := base.JSONUnmarshal(rawDocBytes, &docRoot); err != nil {
return emptySyncData, err
}
return *docRoot.SyncData, nil
}
}
// This gets *just* the Sync Metadata (_sync field) rather than the entire doc, for efficiency
// reasons. Unlike GetDocSyncData it does not check for on-demand import; this means it does not
// need to read the doc body from the bucket.
func (db *DatabaseCollection) GetDocSyncDataNoImport(ctx context.Context, docid string, level DocumentUnmarshalLevel) (syncData SyncData, err error) {
if db.UseXattrs() {
var xattrs map[string][]byte
var cas uint64
xattrs, cas, err = db.dataStore.GetXattrs(ctx, docid, []string{base.SyncXattrName})
if err == nil {
var doc *Document
doc, err = db.unmarshalDocumentWithXattrs(ctx, docid, nil, xattrs, cas, level)
if err == nil {
syncData = doc.SyncData
}
}
} else {
if level == DocUnmarshalAll || level == DocUnmarshalSync || level == DocUnmarshalHistory {
syncData.History = make(RevTree)
}
docRoot := documentRoot{
SyncData: &syncData,
}
var rawDocBytes []byte
if rawDocBytes, _, err = db.dataStore.GetRaw(docid); err == nil {
if err = base.JSONUnmarshal(rawDocBytes, &docRoot); err == nil {
// (unmarshaling populates `syncData` since `docRoot` points to it.)
if !syncData.HasValidSyncData() {
base.InfofCtx(ctx, base.KeyCRUD, "No valid sync data in doc %q; checking for xattrs", base.UD(docid))
if upgradeDoc, _ := db.checkForUpgrade(ctx, docid, level); upgradeDoc != nil {
// No valid sync data in doc, but doc has been upgraded to use xattrs
syncData = upgradeDoc.SyncData
} else {
base.WarnfCtx(ctx, "No valid sync data nor xattrs in doc %q", base.UD(docid))
err = base.HTTPErrorf(404, "Not imported")
}
}
}
}
}
return
}
// OnDemandImportForGet. Attempts to import the doc based on the provided id, contents and cas. ImportDocRaw does cas retry handling
// if the document gets updated after the initial retrieval attempt that triggered this.
func (c *DatabaseCollection) OnDemandImportForGet(ctx context.Context, docid string, rawDoc []byte, xattrs map[string][]byte, cas uint64) (docOut *Document, err error) {
isDelete := rawDoc == nil
importDb := DatabaseCollectionWithUser{DatabaseCollection: c, user: nil}
var importErr error
docOut, importErr = importDb.ImportDocRaw(ctx, docid, rawDoc, xattrs, isDelete, cas, nil, ImportOnDemand)
if importErr == base.ErrImportCancelledFilter {
// If the import was cancelled due to filter, treat as 404 not imported
return nil, base.HTTPErrorf(http.StatusNotFound, "Not imported")
} else if importErr != nil {
// Treat any other failure to perform an on-demand import as not found
base.DebugfCtx(ctx, base.KeyImport, "Unable to import doc %q during on demand import for get - will be treated as not found. Reason: %v", base.UD(docid), importErr)
return nil, base.HTTPErrorf(http.StatusNotFound, "Not found")
}
return docOut, nil
}
// GetRev returns the revision for the given docID and revID, or the current active revision if revID is empty.
func (db *DatabaseCollectionWithUser) GetRev(ctx context.Context, docID, revID string, history bool, attachmentsSince []string) (DocumentRevision, error) {
maxHistory := 0
if history {
maxHistory = math.MaxInt32
}
return db.getRev(ctx, docID, revID, maxHistory, nil)
}
// Returns the body of the current revision of a document
func (db *DatabaseCollectionWithUser) Get1xBody(ctx context.Context, docid string) (Body, error) {
return db.Get1xRevBody(ctx, docid, "", false, nil)
}
// Get Rev with all-or-none history based on specified 'history' flag
func (db *DatabaseCollectionWithUser) Get1xRevBody(ctx context.Context, docid, revid string, history bool, attachmentsSince []string) (Body, error) {
maxHistory := 0
if history {
maxHistory = math.MaxInt32
}
return db.Get1xRevBodyWithHistory(ctx, docid, revid, maxHistory, nil, attachmentsSince, false)
}
// Retrieves rev with request history specified as collection of revids (historyFrom)
func (db *DatabaseCollectionWithUser) Get1xRevBodyWithHistory(ctx context.Context, docid, revid string, maxHistory int, historyFrom []string, attachmentsSince []string, showExp bool) (Body, error) {
rev, err := db.getRev(ctx, docid, revid, maxHistory, historyFrom)
if err != nil {
return nil, err
}
// RequestedHistory is the _revisions returned in the body. Avoids mutating revision.History, in case it's needed
// during attachment processing below
requestedHistory := rev.History
if maxHistory == 0 {
requestedHistory = nil
}
if requestedHistory != nil {
_, requestedHistory = trimEncodedRevisionsToAncestor(ctx, requestedHistory, historyFrom, maxHistory)
}
return rev.Mutable1xBody(ctx, db, requestedHistory, attachmentsSince, showExp)
}
// Underlying revision retrieval used by Get1xRevBody, Get1xRevBodyWithHistory, GetRevCopy.
// Returns the revision of a document using the revision cache.
// - revid may be "", meaning the current revision.
// - maxHistory is >0 if the caller wants a revision history; it's the max length of the history.
// - historyFrom is an optional list of revIDs the client already has. If any of these are found
// in the revision's history, it will be trimmed after that revID.
// - attachmentsSince is nil to return no attachment bodies, otherwise a (possibly empty) list of
// revisions for which the client already has attachments and doesn't need bodies. Any attachment
// that hasn't changed since one of those revisions will be returned as a stub.
func (db *DatabaseCollectionWithUser) getRev(ctx context.Context, docid, revid string, maxHistory int, historyFrom []string) (revision DocumentRevision, err error) {
if revid != "" {
// Get a specific revision body and history from the revision cache
// (which will load them if necessary, by calling revCacheLoader, above)
revision, err = db.revisionCache.Get(ctx, docid, revid, RevCacheOmitDelta)
} else {
// No rev ID given, so load active revision
revision, err = db.revisionCache.GetActive(ctx, docid)
}
if err != nil {
return DocumentRevision{}, err
}
if revision.BodyBytes == nil {
if db.ForceAPIForbiddenErrors() {
base.InfofCtx(ctx, base.KeyCRUD, "Doc: %s %s is missing", base.UD(docid), base.MD(revid))
return DocumentRevision{}, ErrForbidden
}
return DocumentRevision{}, ErrMissing
}
db.collectionStats.NumDocReads.Add(1)
db.collectionStats.DocReadsBytes.Add(int64(len(revision.BodyBytes)))
// RequestedHistory is the _revisions returned in the body. Avoids mutating revision.History, in case it's needed
// during attachment processing below
requestedHistory := revision.History
if maxHistory == 0 {
requestedHistory = nil
}
if requestedHistory != nil {
_, requestedHistory = trimEncodedRevisionsToAncestor(ctx, requestedHistory, historyFrom, maxHistory)
}
isAuthorized, redactedRev := db.authorizeUserForChannels(docid, revision.RevID, revision.Channels, revision.Deleted, requestedHistory)
if !isAuthorized {
if revid == "" {
return DocumentRevision{}, ErrForbidden
}
if db.ForceAPIForbiddenErrors() {
base.InfofCtx(ctx, base.KeyCRUD, "Not authorized to view doc: %s %s", base.UD(docid), base.MD(revid))
return DocumentRevision{}, ErrForbidden
}
return redactedRev, nil
}
// If the revision is a removal cache entry (no body), but the user has access to that removal, then just
// return 404 missing to indicate that the body of the revision is no longer available.
if revision.Removed {
return DocumentRevision{}, ErrMissing
}
if revision.Deleted && revid == "" {
return DocumentRevision{}, ErrDeleted
}
return revision, nil
}
// GetDelta attempts to return the delta between fromRevId and toRevId. If the delta can't be generated,
// returns nil.
func (db *DatabaseCollectionWithUser) GetDelta(ctx context.Context, docID, fromRevID, toRevID string) (delta *RevisionDelta, redactedRev *DocumentRevision, err error) {
if docID == "" || fromRevID == "" || toRevID == "" {
return nil, nil, nil
}
fromRevision, err := db.revisionCache.Get(ctx, docID, fromRevID, RevCacheIncludeDelta)
// If the fromRevision is a removal cache entry (no body), but the user has access to that removal, then just
// return 404 missing to indicate that the body of the revision is no longer available.
// Delta can't be generated if we don't have the fromRevision body.
if fromRevision.Removed {
return nil, nil, ErrMissing
}
// If the fromRevision was a tombstone, then return error to tell delta sync to send full body replication
if fromRevision.Deleted {
return nil, nil, base.ErrDeltaSourceIsTombstone
}
// If both body and delta are not available for fromRevId, the delta can't be generated
if fromRevision.BodyBytes == nil && fromRevision.Delta == nil {
return nil, nil, err
}
// If delta is found, check whether it is a delta for the toRevID we want
if fromRevision.Delta != nil {
if fromRevision.Delta.ToRevID == toRevID {
isAuthorized, redactedBody := db.authorizeUserForChannels(docID, toRevID, fromRevision.Delta.ToChannels, fromRevision.Delta.ToDeleted, encodeRevisions(ctx, docID, fromRevision.Delta.RevisionHistory))
if !isAuthorized {
return nil, &redactedBody, nil
}
// Case 2a. 'some rev' is the rev we're interested in - return the delta
// db.DbStats.StatsDeltaSync().Add(base.StatKeyDeltaCacheHits, 1)
db.dbStats().DeltaSync().DeltaCacheHit.Add(1)
return fromRevision.Delta, nil, nil
}
}
// Delta is unavailable, but the body is available.
if fromRevision.BodyBytes != nil {
// db.DbStats.StatsDeltaSync().Add(base.StatKeyDeltaCacheMisses, 1)
db.dbStats().DeltaSync().DeltaCacheMiss.Add(1)
toRevision, err := db.revisionCache.Get(ctx, docID, toRevID, RevCacheIncludeDelta)
if err != nil {
return nil, nil, err
}
deleted := toRevision.Deleted
isAuthorized, redactedBody := db.authorizeUserForChannels(docID, toRevID, toRevision.Channels, deleted, toRevision.History)
if !isAuthorized {
return nil, &redactedBody, nil
}
if toRevision.Removed {
return nil, nil, ErrMissing
}
// If the revision we're generating a delta to is a tombstone, mark it as such and don't bother generating a delta
if deleted {
revCacheDelta := newRevCacheDelta([]byte(base.EmptyDocument), fromRevID, toRevision, deleted, nil)
db.revisionCache.UpdateDelta(ctx, docID, fromRevID, revCacheDelta)
return &revCacheDelta, nil, nil
}
// We didn't unmarshal fromBody earlier (in case we could get by with just the delta), so need do it now
var fromBodyCopy Body
if err := fromBodyCopy.Unmarshal(fromRevision.BodyBytes); err != nil {
return nil, nil, err
}
// We didn't unmarshal toBody earlier (in case we could get by with just the delta), so need do it now
var toBodyCopy Body
if err := toBodyCopy.Unmarshal(toRevision.BodyBytes); err != nil {
return nil, nil, err
}
// If attachments have changed between these revisions, we'll stamp the metadata into the bodies before diffing
// so that the resulting delta also contains attachment metadata changes
if fromRevision.Attachments != nil {
// the delta library does not handle deltas in non builtin types,
// so we need the map[string]interface{} type conversion here
DeleteAttachmentVersion(fromRevision.Attachments)
fromBodyCopy[BodyAttachments] = map[string]interface{}(fromRevision.Attachments)
}
var toRevAttStorageMeta []AttachmentStorageMeta
if toRevision.Attachments != nil {
// Flatten the AttachmentsMeta into a list of digest version pairs.
toRevAttStorageMeta = ToAttachmentStorageMeta(toRevision.Attachments)
DeleteAttachmentVersion(toRevision.Attachments)
toBodyCopy[BodyAttachments] = map[string]interface{}(toRevision.Attachments)
}
deltaBytes, err := base.Diff(fromBodyCopy, toBodyCopy)
if err != nil {
return nil, nil, err
}
revCacheDelta := newRevCacheDelta(deltaBytes, fromRevID, toRevision, deleted, toRevAttStorageMeta)
// Write the newly calculated delta back into the cache before returning
db.revisionCache.UpdateDelta(ctx, docID, fromRevID, revCacheDelta)
return &revCacheDelta, nil, nil
}
return nil, nil, nil
}
func (col *DatabaseCollectionWithUser) authorizeUserForChannels(docID, revID string, channels base.Set, isDeleted bool, history Revisions) (isAuthorized bool, redactedRev DocumentRevision) {
if col.user != nil {
if err := col.user.AuthorizeAnyCollectionChannel(col.ScopeName, col.Name, channels); err != nil {
// On access failure, return (only) the doc history and deletion/removal
// status instead of returning an error. For justification see the comment in
// the getRevFromDoc method, below
redactedRev = DocumentRevision{
DocID: docID,
RevID: revID,
History: history,
Deleted: isDeleted,
}
if isDeleted {
// Deletions are denoted by the deleted message property during 2.x replication
redactedRev.BodyBytes = []byte(base.EmptyDocument)
} else {
// ... but removals are still denoted by the _removed property in the body, even for 2.x replication
redactedRev.BodyBytes = []byte(RemovedRedactedDocument)
}
return false, redactedRev
}
}
return true, DocumentRevision{}
}
// Returns the body of a revision of a document, as well as the document's current channels
// and the user/roles it grants channel access to.
func (db *DatabaseCollectionWithUser) Get1xRevAndChannels(ctx context.Context, docID string, revID string, listRevisions bool) (bodyBytes []byte, channels channels.ChannelMap, access UserAccessMap, roleAccess UserAccessMap, flags uint8, sequence uint64, gotRevID string, removed bool, err error) {
doc, err := db.GetDocument(ctx, docID, DocUnmarshalAll)
if doc == nil {
return
}
bodyBytes, removed, err = db.get1xRevFromDoc(ctx, doc, revID, listRevisions)
if err != nil {
return
}
channels = doc.Channels
access = doc.Access
roleAccess = doc.RoleAccess
sequence = doc.Sequence
flags = doc.Flags
if revID == "" {
gotRevID = doc.CurrentRev
} else {
gotRevID = revID
}
return
}
// Returns an HTTP 403 error if the User is not allowed to access any of this revision's channels.
func (col *DatabaseCollectionWithUser) authorizeDoc(doc *Document, revid string) error {
user := col.user
if doc == nil || user == nil {
return nil // A nil User means access control is disabled
}
if revid == "" {
revid = doc.CurrentRev
}
if rev := doc.History[revid]; rev != nil {
// Authenticate against specific revision:
return col.user.AuthorizeAnyCollectionChannel(col.ScopeName, col.Name, rev.Channels)
} else {
// No such revision; let the caller proceed and return a 404
return nil
}
}
// Gets a revision of a document. If it's obsolete it will be loaded from the database if possible.
// inline "_attachments" properties in the body will be extracted and returned separately if present (pre-2.5 metadata, or backup revisions)
func (c *DatabaseCollection) getRevision(ctx context.Context, doc *Document, revid string) (bodyBytes []byte, attachments AttachmentsMeta, err error) {
bodyBytes = doc.getRevisionBodyJSON(ctx, revid, c.RevisionBodyLoader)
// No inline body, so look for separate doc:
if bodyBytes == nil {
if !doc.History.contains(revid) {
return nil, nil, ErrMissing
}
bodyBytes, err = c.getOldRevisionJSON(ctx, doc.ID, revid)
if err != nil || bodyBytes == nil {
return nil, nil, err
}
}
// optimistically grab the doc body and to store as a pre-unmarshalled version, as well as anticipating no inline attachments.
if doc.CurrentRev == revid {
attachments = doc.Attachments
}
// handle backup revision inline attachments, or pre-2.5 meta
if inlineAtts, cleanBodyBytes, _, err := extractInlineAttachments(bodyBytes); err != nil {
return nil, nil, err
} else if len(inlineAtts) > 0 {
// we found some inline attachments, so merge them with attachments, and update the bodies
attachments = mergeAttachments(inlineAtts, attachments)
bodyBytes = cleanBodyBytes
}
return bodyBytes, attachments, nil
}
// mergeAttachments copies the docAttachments map, and merges pre25Attachments into it.
// conflicting attachment names falls back to a revpos comparison - highest wins.
func mergeAttachments(pre25Attachments, docAttachments AttachmentsMeta) AttachmentsMeta {
if len(pre25Attachments)+len(docAttachments) == 0 {
return nil // noop
} else if len(pre25Attachments) == 0 {
return copyMap(docAttachments)
} else if len(docAttachments) == 0 {
return copyMap(pre25Attachments)
}
merged := make(AttachmentsMeta, len(docAttachments))
for k, v := range docAttachments {
merged[k] = v
}
// Iterate over pre-2.5 attachments, and merge with docAttachments
for attName, pre25Att := range pre25Attachments {
if docAtt, exists := docAttachments[attName]; !exists {
// we didn't have an attachment matching this name already in syncData, so we'll use the pre-2.5 attachment.
merged[attName] = pre25Att
} else {
// we had the same attachment name in docAttachments and in pre25Attachments.
// Use whichever has the highest revpos.
var pre25AttRevpos, docAttRevpos int64
if pre25AttMeta, ok := pre25Att.(map[string]interface{}); ok {
pre25AttRevpos, ok = base.ToInt64(pre25AttMeta["revpos"])
if !ok {
// pre25 revpos wasn't a number, docAttachment should win.
continue
}
}
if docAttMeta, ok := docAtt.(map[string]interface{}); ok {
// if docAttRevpos can't be converted into an int64, pre25 revpos wins, so fall through with docAttRevpos=0
docAttRevpos, _ = base.ToInt64(docAttMeta["revpos"])
}
// pre-2.5 meta has larger revpos
if pre25AttRevpos > docAttRevpos {
merged[attName] = pre25Att
}
}
}
return merged
}
// extractInlineAttachments moves any inline attachments, from backup revision bodies, or pre-2.5 "_attachments", along with a "cleaned" version of bodyBytes and body.
func extractInlineAttachments(bodyBytes []byte) (attachments AttachmentsMeta, cleanBodyBytes []byte, cleanBody Body, err error) {
if !bytes.Contains(bodyBytes, []byte(`"`+BodyAttachments+`"`)) {
// we can safely say this doesn't contain any inline attachments.
return nil, bodyBytes, nil, nil
}
var body Body
if err = body.Unmarshal(bodyBytes); err != nil {
return nil, nil, nil, err
}
bodyAtts, ok := body[BodyAttachments]
if !ok {
// no _attachments found (in a top-level property)
// probably a false-positive on the byte scan above
return nil, bodyBytes, body, nil
}
attsMap, ok := bodyAtts.(map[string]interface{})
if !ok {
// "_attachments" in body was not valid attachment metadata
return nil, bodyBytes, body, nil
}
// remove _attachments from body and marshal for clean bodyBytes.
delete(body, BodyAttachments)
bodyBytes, err = base.JSONMarshal(body)
if err != nil {
return nil, nil, nil, err
}
return attsMap, bodyBytes, body, nil
}
// Gets the body of a revision's nearest ancestor, as raw JSON (without _id or _rev.)
// If no ancestor has any JSON, returns nil but no error.
func (db *DatabaseCollectionWithUser) getAncestorJSON(ctx context.Context, doc *Document, revid string) ([]byte, error) {
for {
if revid = doc.History.getParent(revid); revid == "" {
return nil, nil
} else if body := doc.getRevisionBodyJSON(ctx, revid, db.RevisionBodyLoader); body != nil {
return body, nil
}
}
}
// Returns the body of a revision given a document struct. Checks user access.
// If the user is not authorized to see the specific revision they asked for,
// instead returns a minimal deletion or removal revision to let them know it's gone.
func (db *DatabaseCollectionWithUser) get1xRevFromDoc(ctx context.Context, doc *Document, revid string, listRevisions bool) (bodyBytes []byte, removed bool, err error) {
var attachments AttachmentsMeta
if err := db.authorizeDoc(doc, revid); err != nil {
// As a special case, you don't need channel access to see a deletion revision,
// otherwise the client's replicator can't process the deletion (since deletions
// usually aren't on any channels at all!) But don't show the full body. (See #59)
// Update: this applies to non-deletions too, since the client may have lost access to
// the channel and gotten a "removed" entry in the _changes feed. It then needs to
// incorporate that tombstone and for that it needs to see the _revisions property.
if revid == "" || doc.History[revid] == nil {
return nil, false, err
}
if doc.History[revid].Deleted {
bodyBytes = []byte(base.EmptyDocument)
} else {
bodyBytes = []byte(RemovedRedactedDocument)
removed = true
}
} else {
if revid == "" {
revid = doc.CurrentRev
if doc.History[revid].Deleted == true {
return nil, false, ErrDeleted
}
}
if bodyBytes, attachments, err = db.getRevision(ctx, doc, revid); err != nil {
return nil, false, err
}
}
kvPairs := []base.KVPair{
{Key: BodyId, Val: doc.ID},
{Key: BodyRev, Val: revid},
}
if len(attachments) > 0 {
kvPairs = append(kvPairs, base.KVPair{Key: BodyAttachments, Val: attachments})
}
if doc.History[revid].Deleted {
kvPairs = append(kvPairs, base.KVPair{Key: BodyDeleted, Val: true})
}
if listRevisions {
validatedHistory, getHistoryErr := doc.History.getHistory(revid)
if getHistoryErr != nil {
return nil, removed, getHistoryErr
}
kvPairs = append(kvPairs, base.KVPair{Key: BodyRevisions, Val: encodeRevisions(ctx, doc.ID, validatedHistory)})
}
bodyBytes, err = base.InjectJSONProperties(bodyBytes, kvPairs...)
if err != nil {
return nil, removed, err
}
return bodyBytes, removed, nil
}
// Returns the body and rev ID of the asked-for revision or the most recent available ancestor.
func (db *DatabaseCollectionWithUser) getAvailableRev(ctx context.Context, doc *Document, revid string) ([]byte, string, AttachmentsMeta, error) {
for ; revid != ""; revid = doc.History[revid].Parent {
if bodyBytes, attachments, _ := db.getRevision(ctx, doc, revid); bodyBytes != nil {
return bodyBytes, revid, attachments, nil
}
}
return nil, "", nil, ErrMissing
}
// Returns the 1x-style body of the asked-for revision or the most recent available ancestor.
func (db *DatabaseCollectionWithUser) getAvailable1xRev(ctx context.Context, doc *Document, revid string) ([]byte, error) {
bodyBytes, ancestorRevID, attachments, err := db.getAvailableRev(ctx, doc, revid)
if err != nil {
return nil, err
}
kvPairs := []base.KVPair{
{Key: BodyId, Val: doc.ID},
{Key: BodyRev, Val: ancestorRevID},
}
if ancestorRev, ok := doc.History[ancestorRevID]; ok && ancestorRev != nil && ancestorRev.Deleted {
kvPairs = append(kvPairs, base.KVPair{Key: BodyDeleted, Val: true})
}
if len(attachments) > 0 {
kvPairs = append(kvPairs, base.KVPair{Key: BodyAttachments, Val: attachments})
}
bodyBytes, err = base.InjectJSONProperties(bodyBytes, kvPairs...)
if err != nil {
return nil, err
}
return bodyBytes, nil
}
// Returns the attachments of the asked-for revision or the most recent available ancestor.
// Returns nil if no attachments or ancestors are found.
func (db *DatabaseCollectionWithUser) getAvailableRevAttachments(ctx context.Context, doc *Document, revid string) (ancestorAttachments AttachmentsMeta, foundAncestor bool) {
_, _, attachments, err := db.getAvailableRev(ctx, doc, revid)
if err != nil {
return nil, false
}
return attachments, true
}
// Moves a revision's ancestor's body out of the document object and into a separate db doc.
func (db *DatabaseCollectionWithUser) backupAncestorRevs(ctx context.Context, doc *Document, newDoc *Document) {
newBodyBytes, err := newDoc.BodyBytes(ctx)
if err != nil {
base.WarnfCtx(ctx, "Error getting body bytes when backing up ancestor revs")
return
}
// Find an ancestor that still has JSON in the document:
var json []byte
ancestorRevId := newDoc.RevID
for {
if ancestorRevId = doc.History.getParent(ancestorRevId); ancestorRevId == "" {
// No ancestors with JSON found. Check if we need to back up current rev for delta sync, then return
db.backupRevisionJSON(ctx, doc.ID, newDoc.RevID, "", newBodyBytes, nil, doc.Attachments)
return
} else if json = doc.getRevisionBodyJSON(ctx, ancestorRevId, db.RevisionBodyLoader); json != nil {
break
}
}
// Back up the revision JSON as a separate doc in the bucket:
db.backupRevisionJSON(ctx, doc.ID, newDoc.RevID, ancestorRevId, newBodyBytes, json, doc.Attachments)
// Nil out the ancestor rev's body in the document struct:
if ancestorRevId == doc.CurrentRev {
doc.RemoveBody()
} else {
doc.removeRevisionBody(ctx, ancestorRevId)
}
}
// ////// UPDATING DOCUMENTS:
func (db *DatabaseCollectionWithUser) OnDemandImportForWrite(ctx context.Context, docid string, doc *Document, deleted bool) error {
// Check whether the doc requiring import is an SDK delete
isDelete := false
if doc.Body(ctx) == nil {
isDelete = true
} else {
isDelete = deleted
}
// Use an admin-scoped database for import
importDb := DatabaseCollectionWithUser{DatabaseCollection: db.DatabaseCollection, user: nil}
importedDoc, importErr := importDb.ImportDoc(ctx, docid, doc, isDelete, nil, ImportOnDemand) // nolint:staticcheck
if importErr == base.ErrImportCancelledFilter {
// Document exists, but existing doc wasn't imported based on import filter. Treat write as insert
doc.SyncData = SyncData{History: make(RevTree)}
} else if importErr != nil {
return importErr
} else {
doc = importedDoc // nolint:staticcheck
}
return nil
}
// Updates or creates a document.
// The new body's BodyRev property must match the current revision's, if any.
func (db *DatabaseCollectionWithUser) Put(ctx context.Context, docid string, body Body) (newRevID string, doc *Document, err error) {
delete(body, BodyId)
// Get the revision ID to match, and the new generation number:
matchRev, _ := body[BodyRev].(string)
generation, _ := ParseRevID(ctx, matchRev)
if generation < 0 {
return "", nil, base.HTTPErrorf(http.StatusBadRequest, "Invalid revision ID")
}
generation++
delete(body, BodyRev)
// Not extracting it yet because we need this property around to generate a rev ID
deleted, _ := body[BodyDeleted].(bool)
expiry, err := body.ExtractExpiry()
if err != nil {
return "", nil, base.HTTPErrorf(http.StatusBadRequest, "Invalid expiry: %v", err)
}
// Create newDoc which will be used to pass around Body
newDoc := &Document{
ID: docid,
}
// Pull out attachments
newDoc.DocAttachments = GetBodyAttachments(body)
delete(body, BodyAttachments)
delete(body, BodyRevisions)
err = validateAPIDocUpdate(body)
if err != nil {
return "", nil, err
}
allowImport := db.UseXattrs()
updateRevCache := true
doc, newRevID, err = db.updateAndReturnDoc(ctx, newDoc.ID, allowImport, &expiry, nil, nil, false, updateRevCache, func(doc *Document) (resultDoc *Document, resultAttachmentData updatedAttachments, createNewRevIDSkipped bool, updatedExpiry *uint32, resultErr error) {
var isSgWrite bool
var crc32Match bool
// Is this doc an sgWrite?
if doc != nil {
isSgWrite, crc32Match, _ = doc.IsSGWrite(ctx, nil)
if crc32Match {
db.dbStats().Database().Crc32MatchCount.Add(1)
}
}
// (Be careful: this block can be invoked multiple times if there are races!)
// If the existing doc isn't an SG write, import prior to updating
if doc != nil && !isSgWrite && db.UseXattrs() {
err := db.OnDemandImportForWrite(ctx, newDoc.ID, doc, deleted)
if err != nil {
if db.ForceAPIForbiddenErrors() {
base.InfofCtx(ctx, base.KeyCRUD, "Importing doc %q prior to write caused error", base.UD(newDoc.ID))
return nil, nil, false, nil, ErrForbidden
}
return nil, nil, false, nil, err
}
}
var conflictErr error
// Make sure matchRev matches an existing leaf revision:
if matchRev == "" {
matchRev = doc.CurrentRev
if matchRev != "" {
// PUT with no parent rev given, but there is an existing current revision.
// This is OK as long as the current one is deleted.
if !doc.History[matchRev].Deleted {
conflictErr = base.HTTPErrorf(http.StatusConflict, "Document exists")
} else {
generation, _ = ParseRevID(ctx, matchRev)
generation++
}
}
} else if !doc.History.isLeaf(matchRev) || db.IsIllegalConflict(ctx, doc, matchRev, deleted, false, nil) {
conflictErr = base.HTTPErrorf(http.StatusConflict, "Document revision conflict")
}
// Make up a new _rev, and add it to the history:
bodyWithoutInternalProps, wasStripped := stripInternalProperties(body)
canonicalBytesForRevID, err := base.JSONMarshalCanonical(bodyWithoutInternalProps)
if err != nil {
return nil, nil, false, nil, err
}
// We needed to keep _deleted around in the body until we generated a rev ID, but now we can ditch it.
_, isDeleted := body[BodyDeleted]
if isDeleted {
delete(body, BodyDeleted)
}
// and now we can finally update the newDoc body to be without any special properties
newDoc.UpdateBody(body)
// If no special properties were stripped and document wasn't deleted, the canonical bytes represent the current
// body. In this scenario, store canonical bytes as newDoc._rawBody
if !wasStripped && !isDeleted {
newDoc._rawBody = canonicalBytesForRevID
}
// Handle telling the user if there is a conflict
if conflictErr != nil {
if db.ForceAPIForbiddenErrors() {
// Make sure the user has permission to modify the document before confirming doc existence
mutableBody, metaMap, newRevID, err := db.prepareSyncFn(doc, newDoc)
if err != nil {
base.InfofCtx(ctx, base.KeyCRUD, "Failed to prepare to run sync function: %v", err)
return nil, nil, false, nil, ErrForbidden
}
_, _, _, _, _, err = db.runSyncFn(ctx, doc, mutableBody, metaMap, newRevID)
if err != nil {
base.DebugfCtx(ctx, base.KeyCRUD, "Could not modify doc %q due to %s and sync func rejection: %v", base.UD(doc.ID), conflictErr, err)
return nil, nil, false, nil, ErrForbidden
}
}
return nil, nil, false, nil, conflictErr
}
// Process the attachments, and populate _sync with metadata. This alters 'body' so it has to
// be done before calling CreateRevID (the ID is based on the digest of the body.)
newAttachments, err := db.storeAttachments(ctx, doc, newDoc.DocAttachments, generation, matchRev, nil)
if err != nil {
return nil, nil, false, nil, err
}
newRev := CreateRevIDWithBytes(generation, matchRev, canonicalBytesForRevID)
if err := doc.History.addRevision(newDoc.ID, RevInfo{ID: newRev, Parent: matchRev, Deleted: deleted}); err != nil {
base.InfofCtx(ctx, base.KeyCRUD, "Failed to add revision ID: %s, for doc: %s, error: %v", newRev, base.UD(docid), err)
return nil, nil, false, nil, base.ErrRevTreeAddRevFailure
}
newDoc.RevID = newRev
newDoc.Deleted = deleted
return newDoc, newAttachments, false, nil, nil
})
return newRevID, doc, err
}
// Adds an existing revision to a document along with its history (list of rev IDs.)
func (db *DatabaseCollectionWithUser) PutExistingRev(ctx context.Context, newDoc *Document, docHistory []string, noConflicts bool, forceAllConflicts bool, existingDoc *sgbucket.BucketDocument) (doc *Document, newRevID string, err error) {
return db.PutExistingRevWithConflictResolution(ctx, newDoc, docHistory, noConflicts, nil, forceAllConflicts, existingDoc)