-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathriak_object.erl
2089 lines (1866 loc) · 84.9 KB
/
riak_object.erl
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
%% -------------------------------------------------------------------
%%
%% riak_object: container for Riak data and metadata
%%
%% Copyright (c) 2007-2010 Basho Technologies, Inc. All Rights Reserved.
%%
%% This file is provided to you under the Apache License,
%% Version 2.0 (the "License"); you may not use this file
%% except in compliance with the License. You may obtain
%% a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing,
%% software distributed under the License is distributed on an
%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%% @doc container for Riak data and metadata
-module(riak_object).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-include("riak_kv_wm_raw.hrl").
-include("riak_object.hrl").
-export_type([riak_object/0, proxy_object/0, bucket/0, key/0, value/0, binary_version/0, index_value/0]).
-type key() :: binary().
-type bucket() :: binary() | {binary(), binary()}.
%% -type bkey() :: {bucket(), key()}.
-type value() :: term().
-ifdef(namespaced_types).
-type riak_object_dict() :: dict:dict().
-else.
-type riak_object_dict() :: dict().
-endif.
-record(r_content, {
metadata :: riak_object_dict() | list(),
value :: term()
}).
%% Used by the merge function to accumulate contents
-record(merge_acc, {
drop=orddict:new() :: orddict:orddict(),
keep=ordsets:new() :: ordsets:ordset(#r_content{}),
crdt=orddict:new() :: orddict:orddict(),
error=[] :: list(binary())
}).
%% Opaque container for Riak objects, a.k.a. riak_object()
-record(r_object, {
bucket :: bucket(),
key :: key(),
contents :: [#r_content{}],
vclock = vclock:fresh() :: vclock:vclock(),
updatemetadata=dict:store(clean, true, dict:new()) :: riak_object_dict(),
updatevalue :: term()
}).
-record(p_object, {
r_object :: riak_object(),
proxy :: tuple(),
size :: integer()}).
-opaque riak_object() :: #r_object{}.
-opaque proxy_object() :: #p_object{}.
-type merge_acc() :: #merge_acc{}.
-type r_content() :: #r_content{}.
-type index_op() :: add | remove.
-type index_value() :: integer() | binary().
-type binary_version() :: v0 | v1.
-define(MAX_KEY_SIZE, 65536).
-define(LASTMOD_LEN, 29). %% static length of rfc1123_date() type. Hard-coded in Erlang.
-define(V1_VERS, 1).
-define(MAGIC, 53). %% Magic number, as opposed to 131 for Erlang term-to-binary magic
%% Shanley's(11) + Joe's(42)
-define(EMPTY_VTAG_BIN, <<"e">>).
-export([new/3, new/4, ensure_robject/1, ancestors/1, reconcile/2, equal/2, remove_dominated/1]).
-export([increment_vclock/2, increment_vclock/3, prune_vclock/3, vclock_descends/2, all_actors/1]).
-export([actor_counter/2]).
-export([key/1, get_metadata/1, get_metadatas/1, get_values/1, get_value/1, get_dotted_values/1]).
-export([hash/1, hash/2, hash/4, approximate_size/2, proxy_size/1]).
-export([vclock_encoding_method/0, vclock/1, vclock_header/1, encode_vclock/1, decode_vclock/1]).
-export([encode_vclock/2, decode_vclock/2]).
-export([update/5, update_value/2, update_metadata/2, bucket/1, bucket_only/1, type/1, value_count/1]).
-export([get_update_metadata/1, get_update_value/1, get_contents/1]).
-export([merge/2, apply_updates/1, syntactic_merge/2]).
-export([to_json/1, from_json/1]).
-export([index_data/1, diff_index_data/2]).
-export([index_specs/1, diff_index_specs/2]).
-export([to_binary/2, from_binary/3, to_binary_version/4, binary_version/1]).
-export([summary_from_binary/1]).
-export([set_contents/2, set_vclock/2]). %% INTERNAL, only for riak_*
-export([is_robject/1, is_head/1]).
-export([update_last_modified/1, update_last_modified/2, get_last_modified/1]).
-export([strict_descendant/2, new_actor_epoch/2]).
-export([find_bestobject/1]).
-export([spoof_getdeletedobject/1]).
-ifdef(TEST).
-export([convert_object_to_headonly/3]). % Used in unit testing of get_core
-endif.
%% @doc Constructor for new riak objects.
-spec new(Bucket::bucket(), Key::key(), Value::value()) -> riak_object().
new({T, B}, K, V) when is_binary(T), is_binary(B), is_binary(K) ->
new_int({T, B}, K, V, no_initial_metadata);
new(B, K, V) when is_binary(B), is_binary(K) ->
new_int(B, K, V, no_initial_metadata).
%% @doc Constructor for new riak objects with an initial content-type.
-spec new(Bucket::bucket(), Key::key(), Value::value(),
string() | riak_object_dict() | no_initial_metadata) -> riak_object().
new({T, B}, K, V, C) when is_binary(T), is_binary(B), is_binary(K), is_list(C) ->
new_int({T, B}, K, V, dict:from_list([{?MD_CTYPE, C}]));
new(B, K, V, C) when is_binary(B), is_binary(K), is_list(C) ->
new_int(B, K, V, dict:from_list([{?MD_CTYPE, C}]));
%% @doc Constructor for new riak objects with an initial metadata dict.
%%
%% NOTE: Removed "is_tuple(MD)" guard to make Dialyzer happy. The previous clause
%% has a guard for string(), so this clause is OK without the guard.
new({T, B}, K, V, MD) when is_binary(T), is_binary(B), is_binary(K) ->
new_int({T, B}, K, V, MD);
new(B, K, V, MD) when is_binary(B), is_binary(K) ->
new_int(B, K, V, MD).
%% internal version after all validation has been done
new_int(B, K, V, MD) ->
case size(K) > ?MAX_KEY_SIZE of
true ->
throw({error,key_too_large});
false ->
case MD of
no_initial_metadata ->
Contents = [#r_content{metadata=dict:new(), value=V}],
#r_object{bucket=B,key=K,
contents=Contents,vclock=vclock:fresh()};
_ ->
Contents = [#r_content{metadata=MD, value=V}],
#r_object{bucket=B,key=K,updatemetadata=MD,
contents=Contents,vclock=vclock:fresh()}
end
end.
-spec is_robject(any()) -> boolean()|proxy.
%% Is this a recognised riak object
%% true - riak object
%% proxy - a proxy for a riak object
%% false - something else, hopefully just needs converting from binary
is_robject(#r_object{}) ->
true;
is_robject(#p_object{}) ->
proxy;
is_robject(_) ->
false.
%% @doc Ensure the incoming term is a riak_object.
-spec ensure_robject(any()) -> riak_object().
ensure_robject(Obj = #r_object{}) -> Obj.
%% @doc Deep (expensive) comparison of Riak objects.
-spec equal(riak_object(), riak_object()) -> true | false.
equal(Obj1,Obj2) ->
(Obj1#r_object.bucket =:= Obj2#r_object.bucket)
andalso (Obj1#r_object.key =:= Obj2#r_object.key)
andalso vclock:equal(vclock(Obj1),vclock(Obj2))
andalso equal2(Obj1,Obj2).
equal2(Obj1,Obj2) ->
UM1 = lists:keysort(1, dict:to_list(Obj1#r_object.updatemetadata)),
UM2 = lists:keysort(1, dict:to_list(Obj2#r_object.updatemetadata)),
(UM1 =:= UM2)
andalso (Obj1#r_object.updatevalue =:= Obj2#r_object.updatevalue)
andalso begin
Cont1 = lists:sort(Obj1#r_object.contents),
Cont2 = lists:sort(Obj2#r_object.contents),
equal_contents(Cont1,Cont2)
end.
equal_contents([],[]) -> true;
equal_contents(_,[]) -> false;
equal_contents([],_) -> false;
equal_contents([C1|R1],[C2|R2]) ->
MD1 = lists:keysort(1, dict:to_list(C1#r_content.metadata)),
MD2 = lists:keysort(1, dict:to_list(C2#r_content.metadata)),
(MD1 =:= MD2)
andalso (C1#r_content.value =:= C2#r_content.value)
andalso equal_contents(R1,R2).
%% @doc Given a list of riak_object()s, return the objects that are pure
%% ancestors of other objects in the list, if any. The changes in the
%% objects returned by this function are guaranteed to be reflected in
%% the other objects in Objects, and can safely be discarded from the list
%% without losing data.
-spec ancestors([riak_object()]) -> [riak_object()].
ancestors(pure_baloney_to_fool_dialyzer) ->
[#r_object{vclock = vclock:fresh()}];
ancestors(Objects) ->
[ O2 || O1 <- Objects, O2 <- Objects, strict_descendant(O1, O2) ].
%% @doc returns true if the `riak_object()' at `O1' is a strict
%% descendant of that at `O2'. This means that the first object
%% causally dominates the second.
%% @see vclock:dominates/2
-spec strict_descendant(riak_object(), riak_object()) -> boolean().
strict_descendant(O1, O2) ->
vclock:dominates(riak_object:vclock(O1), riak_object:vclock(O2)).
%% @doc Reconcile a list of riak objects. If AllowMultiple is true,
%% the riak_object returned may contain multiple values if Objects
%% contains sibling versions (objects that could not be syntactically
%% merged). If AllowMultiple is false, the riak_object returned will
%% contain the value of the most-recently-updated object, as per the
%% X-Riak-Last-Modified header.
-spec reconcile([riak_object()], boolean()) -> riak_object().
reconcile(Objects, AllowMultiple) ->
RObj = reconcile(remove_dominated(Objects)),
case AllowMultiple of
false ->
Contents = [most_recent_content(RObj#r_object.contents)],
RObj#r_object{contents=Contents};
true ->
RObj
end.
%% @doc remove all Objects from the list that are causally
%% dominated by any other object in the list. Only concurrent /
%% conflicting objects will remain.
remove_dominated(Objects) ->
All = sets:from_list(Objects),
Del = sets:from_list(ancestors(Objects)),
sets:to_list(sets:subtract(All, Del)).
%% @doc Take a list of {Idx, {ok, Object}} tuples that have been the
%% result of HEAD requests or GET requests. This list MUST be in the
%% reverse order that the results are received, so that the hd of the
%% list is the latest response received, and the last element the
%% first response received.
%%
%% Works out the best answers and returns {IdxObjList, IdxHeadList} where the
%% IdxHeadList is a list of indexes and headers that may need to be updated to
%% objects before the merge can be complete, and the IdxObjList is a list of
%% vnode indexes and objects which are ready to be merged
find_bestobject(FetchedItems) ->
% Find the best object. Normally we expect this to be a score-draw in
% terms of vector clock, so in this case 'best' means an object not a
% head as the get-response can be used immediately. Then the best is
% the first received (the fastest responder) - as if there is a need
% for a follow-up fetch, we should prefer the vnode that had responded
% fastest to he HEAD (this may be local).
PredHeadFun = fun({_Idx, Rsp}) -> not is_head(Rsp) end,
{Objects, Heads} = lists:partition(PredHeadFun, FetchedItems),
%% prefer full objects to heads
FoldList = Heads ++ Objects,
%% prefer the rightmost (fastest responder)
InitialBestAnswer = lists:last(FoldList),
FoldFun =
fun({Idx, {ok, Obj}}, {IsSibling, BestAnswer}) ->
case IsSibling of
true ->
% If there are siblings could be smart about only fetching
% conflicting objects. Will be lazy, though - fetch and
% merge everything if it is a sibling
{true, [{Idx, {ok, Obj}}|BestAnswer]};
false ->
{_BestIdx, {ok, BestObj}} = BestAnswer,
case vclock:descends(vclock(BestObj), vclock(Obj)) of
true ->
{false, BestAnswer};
false ->
case vclock:descends(vclock(Obj), vclock(BestObj)) of
true ->
{false, {Idx, {ok, Obj}}};
false ->
{true, [{Idx, {ok, Obj}}|[BestAnswer]]}
end
end
end
end,
case lists:foldr(FoldFun,
{false, InitialBestAnswer},
FoldList) of
{true, IdxObjList} ->
lists:partition(PredHeadFun, IdxObjList);
{false, {BestIdx, BestObj}} ->
case is_head(BestObj) of
false ->
{[{BestIdx, BestObj}], []};
true ->
{[], [{BestIdx, BestObj}]}
end
end.
-spec is_head(any()) -> boolean().
%% @private Check if an object is simply a head response
is_head({ok, #r_object{contents=Contents}}) ->
C0 = lists:nth(1, Contents),
case C0#r_content.value of
head_only ->
true;
_ ->
false
end;
is_head({ok, #p_object{}}) ->
true;
is_head(Obj) ->
is_head({ok, Obj}).
%% @doc
%% If an object has been confirmed as deleted by riak_util:is_x_deleted, then
%% any head_only contents can be uplifted to a GET-equivalent by swapping the
%% head_only for an empty value. There is no need to fetch vales we know must
%% be empty
spoof_getdeletedobject(Obj) ->
MapFun =
fun(Content) ->
V0 =
case Content#r_content.value of
head_only -> <<>>;
V -> V
end,
Content#r_content{value = V0}
end,
Obj#r_object{contents = lists:map(MapFun, Obj#r_object.contents)}.
%% @private pairwise merge the objects in the list so that a single,
%% merged riak_object remains that contains all sibling values. Only
%% called with a list of conflicting objects. Use `remove_dominated/1'
%% to get such a list first.
reconcile(Objects) ->
lists:foldl(fun syntactic_merge/2,
hd(Objects),
tl(Objects)).
most_recent_content(AllContents) ->
hd(lists:sort(fun compare_content_dates/2, AllContents)).
compare_content_dates(C1,C2) ->
D1 = dict:fetch(<<"X-Riak-Last-Modified">>, C1#r_content.metadata),
D2 = dict:fetch(<<"X-Riak-Last-Modified">>, C2#r_content.metadata),
%% true if C1 was modifed later than C2
Cmp1 = riak_core_util:compare_dates(D1, D2),
%% true if C2 was modifed later than C1
Cmp2 = riak_core_util:compare_dates(D2, D1),
%% check for deleted objects
Del1 = dict:is_key(<<"X-Riak-Deleted">>, C1#r_content.metadata),
Del2 = dict:is_key(<<"X-Riak-Deleted">>, C2#r_content.metadata),
SameDate = (Cmp1 =:= Cmp2),
case {SameDate, Del1, Del2} of
{false, _, _} ->
Cmp1;
{true, true, false} ->
false;
{true, false, true} ->
true;
_ ->
%% Dates equal and either both present or both deleted, compare
%% by opaque contents.
C1 < C2
end.
%% @doc Merge the contents and vclocks of OldObject and NewObject.
%% Note: This function calls apply_updates on NewObject.
%% Depending on whether DVV is enabled or not, then may merge
%% dropping dotted and dominated siblings, otherwise keeps all
%% unique sibling values. NOTE: as well as being a Syntactic
%% merge, this is also now a semantic merge for CRDTs. Only
%% call with concurrent objects. Use `syntactic_merge/2' if one
%% object may strictly dominate another.
-spec merge(riak_object(), riak_object()) -> riak_object().
merge(OldObject=#r_object{}, NewObject=#r_object{}) ->
NewObj1 = apply_updates(NewObject),
Bucket = bucket(OldObject),
case riak_kv_util:get_write_once(Bucket) of
true ->
merge_write_once(OldObject, NewObj1);
_ ->
DVV = dvv_enabled(Bucket),
{Time, {CRDT, Contents}} = timer:tc(fun merge_contents/3,
[NewObject, OldObject, DVV]),
ok = riak_kv_stat:update({riak_object_merge, CRDT, Time}),
OldObject#r_object{contents=Contents,
vclock=vclock:merge([OldObject#r_object.vclock,
NewObj1#r_object.vclock]),
updatemetadata=dict:store(clean, true, dict:new()),
updatevalue=undefined}
end.
%% @doc Special case write_once merge, in the case where the write_once property is
%% set on the bucket (type). In this case, take the lesser (in lexical order)
%% of the SHA1 hash of each object.
%%
-spec merge_write_once(riak_object(), riak_object()) -> riak_object().
merge_write_once(OldObject, NewObject) ->
ok = riak_kv_stat:update(write_once_merge),
case crypto:hash(sha, term_to_binary(OldObject)) =< crypto:hash(sha, term_to_binary(NewObject)) of
true ->
OldObject;
_ ->
NewObject
end.
%% @doc Merge the r_objects contents by converting the inner dict to
%% a list, ensuring a sane order, and merging into a unique list.
merge_contents(NewObject, OldObject, false) ->
Result = lists:umerge(fun compare/2,
lists:usort(fun compare/2, NewObject#r_object.contents),
lists:usort(fun compare/2, OldObject#r_object.contents)),
{undefined, Result};
%% @private with DVV enabled, use event dots in sibling metadata to
%% remove dominated siblings and stop fake concurrency that causes
%% sibling explsion. Also, since every sibling is iterated over (some
%% twice!) why not merge CRDTs here, too?
merge_contents(NewObject, OldObject, true) ->
Bucket = bucket(NewObject),
Key = key(NewObject),
MergeAcc0 = prune_object_siblings(OldObject, vclock(NewObject)),
MergeAcc = prune_object_siblings(NewObject, vclock(OldObject), MergeAcc0),
#merge_acc{crdt=CRDT, error=Error} = MergeAcc,
riak_kv_crdt:log_merge_errors(Bucket, Key, CRDT, Error),
merge_acc_to_contents(Bucket, MergeAcc).
%% Optimisation. To save converting every meta dict to a list sorting,
%% comparing, and coverting back again, we use this optimisation, that
%% shortcuts out the meta_data comparison, if the obects aren't equal,
%% we needn't compare meta_data at all. `compare/2' is an "ordering
%% fun". Return true if A =< B, false otherwise.
%%
%% @see lists:usort/2
compare(A=#r_content{value=VA}, B=#r_content{value=VB}) ->
if VA < VB ->
true;
VA > VB ->
false;
true ->
%% values are equal, compare metadata
compare_metadata(A, B)
end.
%% Optimisation. Used by `compare/2' ordering fun. Only convert, sort,
%% and compare the meta_data dictionaries if they are the same
%% size. Called by an ordering function, this too is an ordering
%% function.
%%
%% @see compare/2
%% @see lists:usort/3
compare_metadata(#r_content{metadata=MA}, #r_content{metadata=MB}) ->
ASize = dict:size(MA),
BSize = dict:size(MB),
if ASize < BSize ->
true;
ASize > BSize ->
false;
true ->
%% same size metadata, need to do actual compare
lists:sort(dict:to_list(MA)) =< lists:sort(dict:to_list(MB))
end.
%% @private de-duplicates, removes dominated siblings, merges CRDTs
-spec prune_object_siblings(riak_object(), vclock:vclock()) -> merge_acc().
prune_object_siblings(Object, Clock) ->
prune_object_siblings(Object, Clock, #merge_acc{}).
-spec prune_object_siblings(riak_object(), vclock:vclock(), merge_acc())
-> merge_acc().
prune_object_siblings(Object, Clock, MergeAcc) ->
lists:foldl(fun(Contents, Acc) ->
fold_contents(Contents, Acc, Clock)
end,
MergeAcc,
Object#r_object.contents).
%% @private called once for each content entry for each object being
%% merged. Its job is to drop siblings that are causally dominated,
%% remove duplicate values, and merge CRDT values down to a single
%% value.
%%
%% When a Riak takes a PUT, a `dot' is generated. (See assign_dot/2)
%% for the PUT and placed in `riak_object' metadata. The cases below
%% use this `dot' to decide if a sibling value has been superceded,
%% and should therefore be dropped.
%%
%% Based on the work by Baquero et al:
%%
%% Efficient causality tracking in distributed storage systems with
%% dotted version vectors
%% http://doi.acm.org/10.1145/2332432.2332497
%% Nuno Preguiça, Carlos Bauqero, Paulo Sérgio Almeida, Victor Fonte,
%% and Ricardo Gonçalves. 2012
-spec fold_contents(r_content(), merge_acc(), vclock:vclock()) -> merge_acc().
fold_contents({r_content, Dict, Value}=C0, MergeAcc, Clock) ->
#merge_acc{drop=Drop, keep=Keep, crdt=CRDT, error=Error} = MergeAcc,
case get_dot(Dict) of
{ok, {Dot, PureDot}} ->
case {vclock:descends_dot(Clock, Dot),
is_drop_candidate(PureDot, Drop)} of
{true, true} ->
%% When the exact same dot is present in both
%% objects siblings, we keep that value. Without
%% this merging an object with itself would result
%% in an object with no values at all, since an
%% object's vector clock always dominates all its
%% dots. However, due to riak_kv#679, and
%% backup-restore it is possible for two objects
%% to have dots with the same {id, count} but
%% different timestamps (see is_drop_candidate/2
%% below), and for the referenced values to be
%% _different_ too. We need to include both dotted
%% values, and let the list sort/merge ensure that
%% only one sibling for a pair of normal dots is
%% returned. Hence get the other dots contents,
%% should be identical, but Skewed Dots mean we
%% can't guarantee that, the merge will dedupe for
%% us.
DC = get_drop_candidate(PureDot, Drop),
MergeAcc#merge_acc{keep=[C0, DC | Keep]};
{true, false} ->
%% The `dot' is dominated by the other object's
%% vclock. This means that the other object has a
%% value that is the result of a PUT that
%% reconciled this sibling value, we can therefore
%% (potentialy, see above) drop this value.
MergeAcc#merge_acc{drop=add_drop_candidate(PureDot, C0,
Drop)};
{false, _} ->
%% The other object's vclock does not contain (or
%% dominate) this sibling's `dot'. That means this
%% is a genuinely concurrent (or sibling) value
%% and should be kept for the user to reconcile.
MergeAcc#merge_acc{keep=[C0|Keep]}
end;
undefined ->
%% Both CRDTs and legacy data don't have dots. Legacy data
%% because it was written before DVV (or with DVV turned
%% off.) That means keep this sibling. We cannot know if
%% it is dominated. This is the pre-DVV behaviour.
%%
%% CRDTs values do not get a dot as they are merged by
%% Riak, not by the client. A CRDT PUT _NEVER_ overwrites
%% existing values in Riak, it is always merged with
%% them. The resulting value then does not have a single
%% event origin. Instead it is a merge of many events. In
%% DVVSets (referenced above) there is an `anonymous list'
%% for values that have no single event. In Riak we
%% already have that, by having an `undefined' dot. We
%% could store all the dots for a CRDT as a clock, but it
%% would need complex logic to prune.
%%
%% Since there are no dots for CRDT values, there can be
%% sibling values on disk. Which is a concern for sibling
%% explosion scenarios. To avoid such scenarios we call
%% out to CRDT logic to merge CRDTs into a single value
%% here.
case riak_kv_crdt:merge_value({Dict, Value}, {CRDT, [], []}) of
{CRDT, [], [E]} ->
%% An error occurred trying to merge this sibling
%% value. This means it was CRDT with some
%% corruption of the binary format, or maybe a
%% user's opaque binary that happens to match the
%% CRDT binary start tag. Either way, gather the
%% error for later logging.
MergeAcc#merge_acc{error=[E | Error]};
{CRDT, [{Dict, Value}], E} when is_list(E)->
%% The sibling value was not a CRDT, but a
%% (legacy?) un-dotted user opaque value. Add it
%% to the list of values to keep.
MergeAcc#merge_acc{keep=[C0|Keep], error=E ++ Error};
{CRDT2, [], []} ->
%% The sibling was a CRDT and the CRDT accumulator
%% has been updated.
MergeAcc#merge_acc{crdt=CRDT2}
end
end.
%% Store a pure dot and it's contents as a possible candidate to be
%% dropped.
%%
%% @see is_drop_candidate/2
add_drop_candidate(Dot, Contents, Dict) ->
orddict:store(Dot, Contents, Dict).
%% Check if a pure dot is already present as a drop candidate.
is_drop_candidate(Dot, Dict) ->
orddict:is_key(Dot, Dict).
%% fetch a drop candidate by it's pure dot
get_drop_candidate(Dot, Dict) ->
orddict:fetch(Dot, Dict).
%% @private Transform a `merge_acc()' to a list of `r_content()'. The
%% merge accumulator contains a list of non CRDT (opaque) sibling
%% values (`keep') and merged CRDT values (`crdt'). Due to bucket
%% types it should really only ever contain one or the other (and the
%% accumulated CRDTs should have a single value), but it is better to
%% be safe.
-spec merge_acc_to_contents(riak_object:bucket(), merge_acc())
-> list(r_content()).
merge_acc_to_contents(Bucket, MergeAcc) ->
#merge_acc{keep=Keep, crdt=CRDTs} = MergeAcc,
%% Convert the non-CRDT sibling values back to dict metadata values.
%%
%% For improved performance, fold_contents/3 does not check for duplicates
%% when constructing the "Keep" list (eg. using an ordset), but instead
%% simply prepends kept siblings to the list. Here, we convert Keep into an
%% ordset equivalent with reverse/unique sort.
Keep2 = lists:usort(fun compare/2, lists:reverse(Keep)),
%% Iterate the set of converged CRDT values and turn them into
%% `r_content' entries. by generating their metadata entry and
%% binary encoding their contents. Bucket Types should ensure this
%% accumulator only has one entry ever.
case orddict:size(CRDTs) > 0 of
true ->
BProps = riak_core_bucket:get_bucket(Bucket),
orddict:fold(
fun(_Type, {Meta, CRDT0}, {_, Contents}) ->
CRDT = riak_kv_crdt:maybe_apply_props(BProps, CRDT0),
{riak_kv_crdt:to_mod(CRDT),
[{r_content, riak_kv_crdt:meta(Meta, CRDT),
riak_kv_crdt:to_binary(CRDT)} | Contents]}
end,
{undefined, Keep2},
CRDTs);
false ->
{undefined, Keep2}
end.
%% @private Get the dot from the passed metadata dict (if present and
%% valid). It turns out, due to weirdness, it is possible to have two
%% dots with the same id and counter, but different timestamps (backup
%% and restore, riak_kv#679). In that case, it is possible to drop
%% both dots, as both are dominted, but not equal. Here we strip the
%% timestamp component when comparing dots. A `dot' in riak_object is
%% just a {binary(), pos_integer()} pair.
%%
%% @see vclock:destructure_dot/1
-spec get_dot(riak_object_dict()) -> {ok, {vclock:vclock_node(), pos_integer()}} | undefined.
get_dot(Dict) ->
case dict:find(?DOT, Dict) of
{ok, Dot} ->
case vclock:valid_dot(Dot) of
true ->
PureDot = vclock:pure_dot(Dot),
{ok, {Dot, PureDot}};
false ->
undefined
end;
error ->
undefined
end.
%% @private used by get_dotted_values to re-use get_dot/1
get_vc_dot(Dict) ->
case get_dot(Dict) of
{ok, {Dot, _PDot}} ->
Dot;
_ -> undefined
end.
%% @doc Promote pending updates (made with the update_value() and
%% update_metadata() calls) to this riak_object.
-spec apply_updates(riak_object()) -> riak_object().
apply_updates(Object=#r_object{}) ->
VL = case Object#r_object.updatevalue of
undefined ->
[C#r_content.value || C <- Object#r_object.contents];
_ ->
[Object#r_object.updatevalue]
end,
MD = case dict:find(clean, Object#r_object.updatemetadata) of
{ok,_} ->
MDs = [C#r_content.metadata || C <- Object#r_object.contents],
case Object#r_object.updatevalue of
undefined -> MDs;
_ -> [hd(MDs)]
end;
error ->
[dict:erase(clean,Object#r_object.updatemetadata) || _X <- VL]
end,
Contents = [#r_content{metadata=M,value=V} || {M,V} <- lists:zip(MD, VL)],
Object#r_object{contents=Contents,
updatemetadata=dict:store(clean, true, dict:new()),
updatevalue=undefined}.
%% @doc Return the containing bucket for this riak_object.
-spec bucket(riak_object()|proxy_object()) -> bucket().
bucket(#r_object{bucket=Bucket}) -> Bucket;
bucket(#p_object{r_object=RObj}) -> bucket(RObj).
%% @doc Return the containing bucket for this riak_object without any type
%% information, if present.
-spec bucket_only(riak_object()|proxy_object()) -> binary().
bucket_only(#r_object{bucket={_Type, Bucket}}) -> Bucket;
bucket_only(#r_object{bucket=Bucket}) -> Bucket;
bucket_only(#p_object{r_object=RObj}) -> bucket_only(RObj).
%% @doc Return the containing bucket-type for this riak_object.
-spec type(riak_object()|proxy_object()) -> binary() | undefined.
type(#r_object{bucket={Type, _Bucket}}) -> Type;
type(#r_object{bucket=_Bucket}) -> undefined;
type(#p_object{r_object=RObj}) -> type(RObj).
%% @doc Return the key for this riak_object.
-spec key(riak_object()|proxy_object()) -> key().
key(#r_object{key=Key}) -> Key;
key(#p_object{r_object=RObj}) -> key(RObj).
%% @doc Return the vector clock for this riak_object.
-spec vclock(riak_object()|proxy_object()) -> vclock:vclock().
vclock(#r_object{vclock=VClock}) -> VClock;
vclock(#p_object{r_object=RObj}) -> vclock(RObj).
%% @doc Return the number of values (siblings) of this riak_object.
-spec value_count(riak_object()|proxy_object()) -> non_neg_integer().
value_count(#r_object{contents=Contents}) -> length(Contents);
value_count(#p_object{r_object=RObj}) -> value_count(RObj).
%% @doc Return the contents (a list of {metadata, value} tuples) for
%% this riak_object.
-spec get_contents(riak_object()|proxy_object()) -> [{riak_object_dict(), value()}].
get_contents(#r_object{contents=Contents}) ->
[{Content#r_content.metadata, Content#r_content.value} ||
Content <- Contents];
get_contents(#p_object{r_object=RObj, proxy=P}) ->
{FetchFun, Pid, FetchKey} = P,
ObjBin = FetchFun(Pid, FetchKey),
R0 = from_binary(RObj#r_object.bucket, RObj#r_object.key, ObjBin),
get_contents(R0).
%% @doc Assert that this riak_object has no siblings and return its associated
%% metadata. This function will fail with a badmatch error if the
%% object has siblings (value_count() > 1).
-spec get_metadata(riak_object()|proxy_object()) -> riak_object_dict().
get_metadata(O=#r_object{}) ->
% this blows up intentionally (badmatch) if more than one content value!
[{Metadata,_V}] = get_contents(O),
Metadata;
get_metadata(#p_object{r_object=RObj}) ->
[Content] = RObj#r_object.contents,
Content#r_content.metadata.
%% @doc Return a list of the metadata values for this riak_object.
-spec get_metadatas(riak_object()|proxy_object()) -> [riak_object_dict()].
get_metadatas(#r_object{contents=Contents}) ->
[Content#r_content.metadata || Content <- Contents];
get_metadatas(#p_object{r_object=RObj}) ->
get_metadatas(RObj).
%% @doc Return a list of object values for this riak_object.
%% If the object is a proxy will need to fetch the actual object
-spec get_values(riak_object()|proxy_object()) -> [value()].
get_values(#r_object{contents=C}) ->
[Content#r_content.value || Content <- C];
get_values(#p_object{r_object = RObj, proxy = P}) ->
{FetchFun, Pid, FetchKey} = P,
ObjBin = FetchFun(Pid, FetchKey),
R0 = from_binary(RObj#r_object.bucket, RObj#r_object.key, ObjBin),
get_values(R0).
%% @doc Return a list of object values and their dots for this riak_object.
-spec get_dotted_values(riak_object()) -> [{vclock:dot(), value()}].
get_dotted_values(#r_object{contents=C}) ->
[{get_vc_dot(Content#r_content.metadata) , Content#r_content.value} || Content <- C].
%% @doc Assert that this riak_object has no siblings and return its associated
%% value. This function will fail with a badmatch error if the object
%% has siblings (value_count() > 1).
%% If the object is a proxy will need to fetch the actual object.
-spec get_value(riak_object()|proxy_object()) -> value().
get_value(RObj=#r_object{}) ->
% this blows up intentionally (badmatch) if more than one content value!
[{_M,Value}] = get_contents(RObj),
Value;
get_value(#p_object{r_object=RObj, proxy = P}) ->
{FetchFun, Pid, FetchKey} = P,
ObjBin = FetchFun(Pid, FetchKey),
R0 = from_binary(RObj#r_object.bucket, RObj#r_object.key, ObjBin),
get_value(R0).
%% @doc calculates the canonical hash of a riak object
%% Old API which uses the version .
%% DEPRECATED
-spec hash(riak_object()) -> binary().
hash(Obj=#r_object{}) ->
case riak_kv_entropy_manager:get_version() of
0 ->
vclock_hash(Obj);
legacy ->
legacy_hash(Obj)
end.
-spec hash(bucket(), key(),
riak_object()|proxy_object()|binary(),
non_neg_integer()|legacy) -> binary().
%% @doc calculates the canonical hash of a riak object depending on version
%% May accept as input either a real object or a proxy object, or an object
%% that is still serialised in a binary form (where that serialised object
%% could be either a proxy or a riak object)
hash(_Bucket, _Key, RObj=#r_object{}, Version) ->
hash(RObj, Version);
hash(_Bucket, _Key, PObj=#p_object{}, Version) ->
hash(PObj#p_object.r_object, Version);
hash(Bucket, Key, ObjBin, Version) when is_binary(ObjBin) ->
hash(Bucket, Key, riak_object:from_binary(Bucket, Key, ObjBin), Version).
%% @doc calculates the canonical hash of a riak object depending on version
-spec hash(riak_object(), non_neg_integer() | legacy) -> binary().
hash(Obj=#r_object{}, _Version=0) ->
vclock_hash(Obj);
hash(Obj=#r_object{}, _Version) ->
legacy_hash(Obj).
%% @private return the legacy full object hash of the riak_object
-spec legacy_hash(riak_object()) -> binary().
legacy_hash(Obj=#r_object{}) ->
% Blow up if we ever try performing a legacy hash on a proxy
% object.
UpdObj = riak_object:set_vclock(Obj, lists:sort(vclock(Obj))),
Hash = erlang:phash2(to_binary(v0, UpdObj)),
term_to_binary(Hash).
%% @private return the hash of the vclock
-spec vclock_hash(riak_object()) -> binary().
vclock_hash(Obj=#r_object{}) ->
Hash = erlang:phash2(lists:sort(vclock(Obj))),
term_to_binary(Hash).
%% @doc Set the updated metadata of an object to M.
-spec update_metadata(riak_object(), riak_object_dict()) -> riak_object().
update_metadata(Object=#r_object{}, M) ->
Object#r_object{updatemetadata=dict:erase(clean, M)}.
%% @doc Set the updated value of an object to V
-spec update_value(riak_object(), value()) -> riak_object().
update_value(Object=#r_object{}, V) -> Object#r_object{updatevalue=V}.
%% @doc Return the updated metadata of this riak_object.
-spec get_update_metadata(riak_object()) -> riak_object_dict().
get_update_metadata(#r_object{updatemetadata=UM}) -> UM.
%% @doc Return the updated value of this riak_object.
-spec get_update_value(riak_object()) -> value().
get_update_value(#r_object{updatevalue=UV}) -> UV.
%% @doc INTERNAL USE ONLY. Set the vclock of riak_object O to V.
-spec set_vclock(riak_object(), vclock:vclock()) -> riak_object().
set_vclock(Object=#r_object{}, VClock) -> Object#r_object{vclock=VClock}.
%% @doc vnode uses to add a new actor epoch to the vclock, a replica
%% write showed local amnesia
-spec new_actor_epoch(riak_object(), vclock:vclock_node()) -> riak_object().
new_actor_epoch(Object=#r_object{vclock=VC}, ClientId) ->
NewClock = vclock:increment(ClientId, VC),
Object#r_object{vclock=NewClock}.
%% @doc Increment the entry for ClientId in O's vclock.
-spec increment_vclock(riak_object(), vclock:vclock_node()) -> riak_object().
increment_vclock(Object=#r_object{bucket=B}, ClientId) ->
NewClock = vclock:increment(ClientId, Object#r_object.vclock),
{ok, Dot} = vclock:get_dot(ClientId, NewClock),
assign_dot(Object#r_object{vclock=NewClock}, Dot, dvv_enabled(B)).
%% @doc Increment the entry for ClientId in O's vclock.
-spec increment_vclock(riak_object(), vclock:vclock_node(), vclock:timestamp()) -> riak_object().
increment_vclock(Object=#r_object{bucket=B}, ClientId, Timestamp) ->
NewClock = vclock:increment(ClientId, Timestamp, Object#r_object.vclock),
{ok, Dot} = vclock:get_dot(ClientId, NewClock),
%% If it is true that we only ever increment the vclock to create
%% a frontier object, then there must only ever be a single value
%% when we increment, so add the dot here.
assign_dot(Object#r_object{vclock=NewClock}, Dot, dvv_enabled(B)).
%% @doc Prune vclock
-spec prune_vclock(riak_object(), vclock:timestamp(), [proplists:property()]) ->
riak_object().
prune_vclock(Obj=#r_object{vclock=VC}, PruneTime, BucketProps) ->
VC2 = vclock:prune(VC, PruneTime, BucketProps),
Obj#r_object{vclock=VC2}.
%% @doc Does the `riak_object' descend the provided `vclock'?
-spec vclock_descends(riak_object(), vclock:vclock()) -> boolean().
vclock_descends(#r_object{vclock=ObjVC}, VC) ->
vclock:descends(ObjVC, VC).
%% @doc get the list of all actors that have touched this object.
-spec all_actors(riak_object()) -> [binary()] | [].
all_actors(#r_object{vclock=VC}) ->
vclock:all_nodes(VC).
%%$ @doc get the counter for the given actor, 0 if not present
-spec actor_counter(vclock:vclock_node(), riak_object()) ->
non_neg_integer().
actor_counter(Actor, #r_object{vclock=VC}) ->
vclock:get_counter(Actor, VC).
%% @private assign the dot to the value only if DVV is enabled. Only
%% call with a valid dot. Only assign dot when there is a single value
%% in contents.
-spec assign_dot(riak_object(), vclock:dot(), boolean()) -> riak_object().
assign_dot(Object=#r_object{}, Dot, true) ->
#r_object{contents=[C=#r_content{metadata=Meta0}]} = Object,
Object#r_object{contents=[C#r_content{metadata=dict:store(?DOT, Dot, Meta0)}]};
assign_dot(Object, _Dot, _DVVEnabled) ->
Object.
%% @private is dvv enabled on this node?
-spec dvv_enabled(bucket()) -> boolean().
dvv_enabled(Bucket) ->
BProps = riak_core_bucket:get_bucket(Bucket),
%% default to `true`, since legacy buckets should have `false` by
%% default, and typed should have `true` and `undefined` is not a
%% valid return.
proplists:get_value(dvv_enabled, BProps, true).
%% @doc Prepare a list of index specifications
%% to pass to the backend. This function is for
%% the case where there is no existing object
%% stored for a key and therefore no existing
%% index data.
-spec index_specs(riak_object()) ->
[{index_op(), binary(), index_value()}].
index_specs(Obj) ->
Indexes = index_data(Obj),
assemble_index_specs(Indexes, add).
%% @doc Prepare a list of index specifications to pass to the
%% backend. If the object passed as the first parameter does not have
%% siblings, the function will assemble specs to replace all of its
%% indexes with the indexes specified in the object passed as the
%% second parameter. If there are siblings only the unique new
%% indexes are added.
-spec diff_index_specs('undefined' | riak_object(),
'undefined' | riak_object()) ->
[{index_op(), binary(), index_value()}].
diff_index_specs(Obj, OldObj) ->
OldIndexes = index_data(OldObj),
AllIndexes = index_data(Obj),
diff_index_data(OldIndexes, AllIndexes).
-spec diff_index_data([{binary(), index_value()}],
[{binary(), index_value()}]) ->
[{index_op(), binary(), index_value()}].
diff_index_data(OldIndexes, AllIndexes) ->
OldIndexSet = ordsets:from_list(OldIndexes),
AllIndexSet = ordsets:from_list(AllIndexes),
diff_specs_core(AllIndexSet, OldIndexSet).
diff_specs_core(AllIndexSet, OldIndexSet) ->
NewIndexSet = ordsets:subtract(AllIndexSet, OldIndexSet),
RemoveIndexSet =
ordsets:subtract(OldIndexSet, AllIndexSet),
NewIndexSpecs =
assemble_index_specs(ordsets:subtract(NewIndexSet, OldIndexSet),
add),
RemoveIndexSpecs =
assemble_index_specs(RemoveIndexSet,
remove),
NewIndexSpecs ++ RemoveIndexSpecs.
%% @doc Get a list of {Index, Value} tuples from the
%% metadata of an object.
-spec index_data(riak_object()) -> [{binary(), index_value()}].
index_data(undefined) ->
[];
index_data(Obj) ->
MetaDatas = get_metadatas(Obj),
lists:flatten([dict:fetch(?MD_INDEX, MD)
|| MD <- MetaDatas,
dict:is_key(?MD_INDEX, MD)]).
%% @doc Assemble a list of index specs in the
%% form of triplets of the form
%% {IndexOperation, IndexField, IndexValue}.
-spec assemble_index_specs([{binary(), binary()}], index_op()) ->
[{index_op(), binary(), binary()}].
assemble_index_specs(Indexes, IndexOp) ->
[{IndexOp, Index, Value} || {Index, Value} <- Indexes].
%% @doc INTERNAL USE ONLY. Set the contents of riak_object to the