forked from samcamwilliams/HyperBEAM
-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathhb_cache.erl
More file actions
1699 lines (1623 loc) · 67.5 KB
/
Copy pathhb_cache.erl
File metadata and controls
1699 lines (1623 loc) · 67.5 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
%%% @doc A cache of AO-Core protocol messages and compute results.
%%%
%%% HyperBEAM stores all paths in key value stores, abstracted by the `hb_store'
%%% module. Each store has its own storage backend, but each works with simple
%%% key-value pairs. Each store can write binary keys at paths, and link between
%%% paths.
%%%
%%% There are three layers to HyperBEAMs internal data representation on-disk:
%%%
%%% 1. The raw binary data, written to the store at the hash of the content.
%%% Storing binary paths in this way effectively deduplicates the data.
%%% 2. The hashpath-graph of all content, stored as a set of links between
%%% hashpaths, their keys, and the data that underlies them. This allows
%%% all messages to share the same hashpath space, such that all requests
%%% from users additively fill-in the hashpath space, minimizing duplicated
%%% compute.
%%% 3. Messages, referrable by their IDs (committed or uncommitted). These are
%%% stored as a set of links commitment IDs and the uncommitted message.
%%%
%%% Before writing a message to the store, we convert it to Type-Annotated
%%% Binary Messages (TABMs), such that each of the keys in the message is
%%% either a map or a direct binary.
%%%
%%% Nested keys are lazily loaded from the stores, such that large deeply
%%% nested messages where only a small part of the data is actually used are
%%% not loaded into memory unnecessarily. In order to ensure that a message is
%%% loaded from the cache after a `read', we can use the `ensure_loaded/1' and
%%% `ensure_all_loaded/1' functions. Ensure loaded will load the exact value
%%% that has been requested, while ensure all loaded will load the entire
%%% structure of the message into memory.
%%%
%%% Lazily loadable `links' are expressed as a tuple of the following form:
%%% `{link, ID, LinkOpts}', where `ID' is the path to the data in the store,
%%% and `LinkOpts' is a map of suggested options to use when loading the data.
%%% In particular, this module ensures to stash the `store' option in `LinkOpts',
%%% such that the `read' function can use the correct store without having to
%%% search unnecessarily. By providing an `Opts' argument to `ensure_loaded' or
%%% `ensure_all_loaded', the caller can specify additional options to use when
%%% loading the data -- overriding the suggested options in the link.
-module(hb_cache).
-export([read_all_commitments/2]).
-export([ensure_loaded/1, ensure_loaded/2, ensure_all_loaded/1, ensure_all_loaded/2]).
-export([read/2, read_resolved/3, resolved_address/3]).
-export([write/2, write_binary/3, write_hashpath/2, write_resolved/4]).
-export([link/3]).
-export([match/2, list/2, list_numbered/2]).
-export([test_unsigned/1, test_signed/1]).
-include("include/hb.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(MATCH_PREFIX, <<"~match@1.0">>).
-define(DIRECT_VALUE_LENGTH, 60).
%% @doc Ensure that a value is loaded from the cache if it is an ID or a link.
%% If it is not loadable we raise an error. If the value is a message, we will
%% load only the first `layer' of it: Representing all nested messages inside
%% the result as links. If the value has an associated `type' key in the extra
%% options, we apply it to the read value, 'lazily' recreating a `structured@1.0'
%% form.
ensure_loaded(Msg) ->
ensure_loaded(Msg, #{}).
ensure_loaded(Msg, Opts) ->
ensure_loaded([], Msg, Opts).
ensure_loaded(Ref, {Status, Msg}, Opts) when Status == ok; Status == error ->
{Status, ensure_loaded(Ref, Msg, Opts)};
ensure_loaded(Ref,
Lk = {link, ID, LkOpts = #{ <<"type">> := <<"link">>, <<"lazy">> := Lazy }},
RawOpts) ->
% The link is to a submessage; either in lazy (unresolved) form, or direct
% form.
UnscopedOpts = hb_util:deep_merge(RawOpts, LkOpts, RawOpts),
Opts = hb_store:scope(UnscopedOpts, hb_opts:get(scope, local, LkOpts)),
_Store = hb_opts:get(store, no_viable_store, Opts),
?event_debug(debug_cache,
{loading_multi_link,
{link, ID},
{link_opts, LkOpts},
{store, _Store}
}
),
CacheReadResult =
case hb_opts:get(commitment, undefined, Opts) of
true ->
do_read_commitment(ID, hb_util:deep_merge(Opts, LkOpts, Opts));
_ ->
hb_cache:read(ID, hb_util:deep_merge(Opts, LkOpts, Opts))
end,
case CacheReadResult of
{ok, Next} ->
?event_debug(debug_cache,
{loaded,
{link, ID},
{store, _Store}
}),
case Lazy of
true ->
% We have resolved the ID of the submessage, so we continue
% to load the submessage itself.
ensure_loaded(
{link,
Next,
#{
<<"type">> => <<"link">>,
<<"lazy">> => false
}
},
Opts
);
false ->
% The already had the ID of the submessage, so now we have
% the data, we simply return it.
Next
end;
{error, not_found} ->
report_ensure_loaded_not_found(Ref, Lk, Opts)
end;
ensure_loaded(Ref, Link = {link, ID, LinkOpts = #{ <<"lazy">> := true }}, RawOpts) ->
% If the user provided their own options, we merge them and _overwrite_
% the options that are already set in the link.
UnscopedOpts = hb_util:deep_merge(RawOpts, LinkOpts, RawOpts),
Opts = hb_store:scope(UnscopedOpts, hb_opts:get(scope, local, LinkOpts)),
CacheReadResult =
case hb_opts:get(commitment, undefined, Opts) of
true ->
do_read_commitment(ID, Opts);
_ ->
read(ID, Opts)
end,
case CacheReadResult of
{ok, LoadedMsg} ->
?event_debug(debug_caching,
{lazy_loaded,
{link, ID},
{msg, LoadedMsg},
{link_opts, LinkOpts}
}
),
case hb_maps:get(<<"type">>, LinkOpts, undefined, Opts) of
undefined -> LoadedMsg;
Type -> hb_util:decode(Type, LoadedMsg)
end;
{error, not_found} ->
report_ensure_loaded_not_found(Ref, Link, Opts)
end;
ensure_loaded(Ref, {link, ID, LinkOpts}, Opts) ->
ensure_loaded(Ref, {link, ID, LinkOpts#{ <<"lazy">> => true}}, Opts);
ensure_loaded(_Ref, Msg, _Opts) when not ?IS_LINK(Msg) ->
Msg.
%% @doc Report that a value was not found in the cache. If a key is provided,
%% we report that the key was not found, otherwise we report that the link was
%% not found.
report_ensure_loaded_not_found(Ref, Lk, Opts) ->
?event(link_error, {link_not_resolvable, {ref, Ref}, {link, Lk}, {opts, Opts}}),
throw(
{necessary_message_not_found,
hb_path:to_binary(lists:reverse(Ref)),
hb_link:format_unresolved(Lk, Opts, 0)
}
).
%% @doc Ensure that all of the components of a message (whether a map, list,
%% or immediate value) are recursively fully loaded from the stores into memory.
%% This is a catch-all function that is useful in situations where ensuring a
%% message contains no links is important, but it carries potentially extreme
%% performance costs.
ensure_all_loaded(Msg) ->
ensure_all_loaded(Msg, #{}).
ensure_all_loaded(Msg, Opts) ->
ensure_all_loaded([], Msg, Opts).
ensure_all_loaded(Ref, Link, Opts) when ?IS_LINK(Link) ->
ensure_all_loaded(Ref, ensure_loaded(Ref, Link, Opts), Opts);
ensure_all_loaded(Ref, Msg, Opts) when is_map(Msg) ->
maps:map(fun(K, V) -> ensure_all_loaded([K|Ref], V, Opts) end, Msg);
ensure_all_loaded(Ref, Msg, Opts) when is_list(Msg) ->
lists:map(
fun({N, V}) -> ensure_all_loaded([N|Ref], V, Opts) end,
hb_util:number(Msg)
);
ensure_all_loaded(Ref, Msg, Opts) ->
ensure_loaded(Ref, Msg, Opts).
%% @doc List all items in a directory, assuming they are numbered.
list_numbered(Path, Opts) ->
SlotDir = hb_path:to_binary(Path),
[ hb_util:int(Name) || Name <- list(SlotDir, Opts) ].
%% @doc List all items under a given path.
list(Path, Opts) when is_map(Opts) and not is_map_key(<<"store-module">>, Opts) ->
case hb_opts:get(store, no_viable_store, Opts) of
not_found -> [];
Store ->
list(Path, Store, Opts)
end;
list(Path, Store) ->
list(Path, Store, #{}).
list(Path, Store, Opts) ->
case hb_store:read(Store, Path, Opts) of
{composite, Names} -> lists:map(fun child_name/1, Names);
_ -> []
end.
%% @doc Match a template message against the cache, returning a list of IDs
%% that match the template. We match on the binary representation of values,
%% rather than their types explicitly, such that 'AO-Types' keys that are
%% only partial matches do not cause the match to fail. If the `match_index' key
%% is set, indicating the presence and usage of the `~match@1.0` device, we use
%% it to find the matching messages. This lowers the complexity class of the
%% match to `O(keys * log(cache_size))` instead of `O(cache_size)`.
match(MatchSpec, Opts) ->
ReadMode = hb_opts:get(cache_read_mode, normal, Opts),
NormalizedSpec = normalize_match_spec(MatchSpec, ReadMode, Opts),
case (ReadMode == raw) orelse
(hb_opts:get(match_index, false, Opts) == false)
of
true -> store_match(NormalizedSpec, Opts);
false ->
case
hb_ao:raw(
<<"match@1.0">>,
<<"all">>,
NormalizedSpec,
#{},
Opts
)
of
{ok, Matches} when length(Matches) > 0 -> {ok, Matches};
_ -> {error, not_found}
end
end.
%% @doc Normalize match values for store reverse-index lookups.
normalize_match_spec(MatchSpec, raw, Opts) ->
maps:without([<<"ao-types">>], hb_ao:normalize_keys(MatchSpec, Opts));
normalize_match_spec(MatchSpec, _ReadMode, Opts) ->
Spec = hb_message:convert(MatchSpec, tabm, <<"structured@1.0">>, Opts),
maps:without([<<"ao-types">>], hb_ao:normalize_keys(Spec, Opts)).
%% @doc Match using the store's reverse index.
store_match(NormalizedSpec, Opts) ->
ConvertedMatchSpec =
maps:map(
fun(Key, Value) -> store_match_value(Key, Value, Opts) end,
NormalizedSpec
),
case hb_store:match(
hb_opts:get(store, no_viable_store, Opts),
ConvertedMatchSpec,
Opts
) of
{ok, []} -> {error, not_found};
{ok, Matches} -> {ok, Matches};
_ -> {error, not_found}
end.
%% @doc Generate the path at which a binary value should be stored.
generate_binary_path(Bin, Opts) ->
Hashpath = hb_path:hashpath(Bin, Opts),
<<"data/", Hashpath/binary>>.
%% @doc Write a message to the cache. For raw binaries, we write the data at
%% the hashpath of the data (by default the SHA2-256 hash of the data). We link
%% the unattended ID's hashpath for the keys (including `/commitments') on the
%% message to the underlying data and recurse. We then link each commitment ID
%% to the uncommitted message, such that any of the committed or uncommitted IDs
%% can be read, and once in memory all of the commitments are available. For
%% deep messages, the commitments will also be read, such that the ID of the
%% outer message (which does not include its commitments) will be built upon
%% the commitments of the inner messages. We do not, however, store the IDs from
%% commitments on signed _inner_ messages. We may wish to revisit this.
write(RawMsg, Opts) when is_map(RawMsg) ->
% Reattach only cache-owned freshness after private keys are filtered.
PrivCreatedAt = case maps:find(<<"priv-created-at">>, RawMsg) of
{ok, CreatedAt} ->
case is_immediate_value(<<"priv-created-at">>, CreatedAt) of
true -> #{ <<"priv-created-at">> => CreatedAt };
false -> #{}
end;
error -> #{}
end,
PublicRawMsg = maps:remove(<<"priv-created-at">>, RawMsg),
hb_message:paranoid_verify(cache_write, PublicRawMsg, Opts),
{ok, Msg} = hb_message:with_only_committed(PublicRawMsg, Opts),
PublicTABM = hb_message:convert(Msg, tabm, <<"structured@1.0">>, Opts),
TABM = maps:merge(PublicTABM, PrivCreatedAt),
?event_debug(debug_cache, {writing_full_message, {msg, TABM}}),
try
do_write_message(
TABM,
hb_opts:get(store, no_viable_store, Opts),
Opts
)
catch
Type:Reason:Stacktrace ->
?event(error,
{cache_write_error,
{type, Type},
{reason, Reason},
{stacktrace, {trace, Stacktrace}}
},
Opts
),
erlang:raise(Type, Reason, Stacktrace)
end;
write(List, Opts) when is_list(List) ->
write(hb_message:convert(List, tabm, <<"structured@1.0">>, Opts), Opts);
write(Bin, Opts) when is_binary(Bin) ->
do_write_message(Bin, hb_opts:get(store, no_viable_store, Opts), Opts).
do_write_message(Bin, Store, Opts) when is_binary(Bin) ->
% Write the binary in the store at its calculated content-hash.
% Return the path.
Path = generate_binary_path(Bin, Opts),
hb_store:write(Store, #{ Path => Bin }, Opts),
%lists:map(fun(ID) -> hb_store:make_link(Store, Path, ID) end, AllIDs),
{ok, Path};
do_write_message(List, Store, Opts) when is_list(List) ->
do_write_message(
hb_message:convert(List, tabm, <<"structured@1.0">>, Opts),
Store,
Opts
);
do_write_message(Msg, Store, Opts) when is_map(Msg) ->
{ok, UncommittedID, Ops} = write_message_ops(Msg, Opts),
run_write_ops(Store, Ops, Opts),
{ok, UncommittedID}.
write_message_ops(Bin, Opts) when is_binary(Bin) ->
Path = generate_binary_path(Bin, Opts),
{ok, Path, [{write, Path, Bin}]};
write_message_ops(List, Opts) when is_list(List) ->
write_message_ops(
hb_message:convert(List, tabm, <<"structured@1.0">>, Opts),
Opts
);
write_message_ops(Msg, Opts) when is_map(Msg) ->
?event_debug(debug_cache, {writing_message, Msg}),
UncommittedID =
hb_message:id(Msg, none, Opts#{ <<"linkify-mode">> => discard }),
AllIDs = calculate_all_ids(Msg, UncommittedID, Opts),
AltIDs = AllIDs -- [UncommittedID],
MsgHashpathAlg = hb_path:hashpath_alg(Msg, Opts),
?event_debug(debug_cache,
{writing_message,
{id, UncommittedID},
{alt_ids, AltIDs},
{original, Msg}
}
),
KeyOps =
maps:fold(
fun(Key, Value, Acc) ->
write_key_ops(UncommittedID, Key, MsgHashpathAlg, Value, Opts, Acc)
end,
[{group, UncommittedID}],
maps:without([<<"priv">>], Msg)
),
MatchOps =
case match_store(Opts) of
[] -> KeyOps;
_ -> [{match, AllIDs, Msg} | KeyOps]
end,
Ops =
lists:foldl(
fun(AltID, Acc) ->
?event_debug(debug_cache,
{linking_commitment,
{uncommitted_id, UncommittedID},
{committed_id, AltID}
}
),
[{link, AltID, UncommittedID} | Acc]
end,
MatchOps,
AltIDs
),
{ok, UncommittedID, lists:reverse(Ops)}.
write_key_ops(Base, <<"commitments">>, _HPAlg, RawCommitments, Opts, Acc) ->
Commitments = prepare_commitments(RawCommitments, Opts),
CommitmentsBase = commitment_path(Base, Opts),
?event(
{writing_commitments,
{base, Base},
{commitments_message, Commitments},
{commitments_base, CommitmentsBase}
}
),
Acc1 = [{group, CommitmentsBase} | Acc],
Acc2 =
maps:fold(
fun(BaseCommID, Commitment, InnerAcc) ->
?event_debug(debug_cache, {writing_commitment, {commitment, Commitment}}),
{ok, CommMsgID, CommOps} = write_message_ops(Commitment, Opts),
[
{link, <<CommitmentsBase/binary, "/", BaseCommID/binary>>, CommMsgID}
| prepend_reversed(CommOps, InnerAcc)
]
end,
Acc1,
Commitments
),
[{link, <<Base/binary, "/commitments">>, CommitmentsBase} | Acc2];
write_key_ops(Base, Key, HPAlg, Value, Opts, Acc) ->
KeyHashPath =
hb_path:hashpath(
Base,
hb_path:to_binary(Key),
HPAlg,
Opts
),
case is_immediate_value(Key, Value) of
true ->
[{write, KeyHashPath, encode_immediate_value(Value)} | Acc];
false ->
{ok, Path, ValueOps} = write_message_ops(Value, Opts),
[
{link, KeyHashPath, Path}
| prepend_reversed(ValueOps, Acc)
]
end.
%% @doc True when `Value' should be stored at `Key''s path instead of linked
%% through `data/'.
is_immediate_value(Key, Value) ->
is_binary(Value) andalso
byte_size(Value) < ?DIRECT_VALUE_LENGTH andalso
not hb_link:is_link_key(Key).
%% @doc Encode an immediate value so it cannot be confused with cache markers.
%% Most values are stored unchanged. Literal marker-looking values get a single
%% `raw:' prefix, so decoding removes exactly one layer and preserves literal
%% values that start with `link:' or `raw:'.
encode_immediate_value(<<"group">>) -> <<"raw:group">>;
encode_immediate_value(<<"link:", _/binary>> = Value) -> <<"raw:", Value/binary>>;
encode_immediate_value(<<"raw:", _/binary>> = Value) -> <<"raw:", Value/binary>>;
encode_immediate_value(Value) -> Value.
%% @doc Decode a value read from a message key path. Linked payloads under
%% `data/' are not immediate values, so leave them byte-for-byte intact.
decode_immediate_value(<<"data/", _/binary>>, Value) -> Value;
decode_immediate_value(_Path, <<"raw:", Value/binary>>) -> Value;
decode_immediate_value(_Path, Value) -> Value.
store_match_value(Key, Bin, Opts) when is_binary(Bin) ->
case is_immediate_value(Key, Bin) of
true -> encode_immediate_value(Bin);
false -> <<"link:", (generate_binary_path(Bin, Opts))/binary>>
end;
store_match_value(_Key, Map, Opts) when is_map(Map) ->
<<"link:",
(hb_message:id(
Map,
none,
Opts#{ <<"linkify-mode">> => discard }
))/binary
>>;
store_match_value(Key, List, Opts) when is_list(List) ->
case io_lib:printable_unicode_list(List) of
true ->
store_match_value(Key, iolist_to_binary(List), Opts);
false ->
store_match_value(
Key,
hb_message:convert(List, tabm, <<"structured@1.0">>, Opts),
Opts
)
end;
store_match_value(Key, Other, Opts) ->
store_match_value(Key, hb_path:to_binary(Other), Opts).
prepend_reversed(Ops, Acc) ->
lists:foldl(fun(Op, InnerAcc) -> [Op | InnerAcc] end, Acc, Ops).
run_write_ops(Store, Ops, Opts) ->
run_write_ops(Store, Ops, Opts, []).
run_write_ops(Store, [], Opts, Pending) ->
flush_write_ops(Store, Pending, Opts);
run_write_ops(Store, [{match, IDs, Msg} | Rest], Opts, Pending) ->
flush_write_ops(Store, Pending, Opts),
write_match_index(IDs, Msg, Opts),
run_write_ops(Store, Rest, Opts, []);
run_write_ops(Store, [Op | Rest], Opts, Pending) ->
run_write_ops(Store, Rest, Opts, [Op | Pending]).
flush_write_ops(_Store, [], _Opts) ->
ok;
flush_write_ops(Store, Pending, Opts) ->
apply_write_ops(Store, lists:reverse(Pending), Opts).
%% @doc Apply a list of write/group/link operations through the store's existing
%% interfaces, collapsing a message's per-key store round-trips into a small
%% constant number of calls: the group markers, then all values in a single
%% `write' map, then all links in a single `link' map. Links stay links -- the
%% store decides how to represent them -- so this is store-agnostic.
apply_write_ops(Store, Ops, Opts) ->
{Groups, Writes, Links} =
lists:foldl(
fun({group, Path}, {Gs, Ws, Ls}) ->
{[Path | Gs], Ws, Ls};
({write, Path, Value}, {Gs, Ws, Ls}) ->
{Gs, Ws#{ Path => Value }, Ls};
({link, New, Existing}, {Gs, Ws, Ls}) ->
{Gs, Ws, Ls#{ New => Existing }}
end,
{[], #{}, #{}},
Ops
),
lists:foreach(
fun(Group) -> hb_store:group(Store, Group, Opts) end,
lists:reverse(Groups)
),
case map_size(Writes) of
0 -> ok;
_ -> hb_store:write(Store, Writes, Opts)
end,
case map_size(Links) of
0 -> ok;
_ -> hb_store:link(Store, Links, Opts)
end,
ok.
%% @doc Write all message keys to the optional match index.
write_match_index(IDs, Base, Opts) ->
case match_store(Opts) of
[] -> {skip, <<"No store configured for match index.">>};
Store ->
IndexBase = hb_message:uncommitted(hb_private:reset(Base)),
Ops =
hb_maps:fold(
fun(RawKey, Value, Acc) ->
Key = hb_ao:normalize_key(RawKey),
ValuePath = match_value_path(Value, Opts),
MatchAddress = match_address(Key, ValuePath),
lists:foldl(
fun(ID, InnerAcc) ->
Address = match_address_id(MatchAddress, ID),
[{write, Address, <<"">>} | InnerAcc]
end,
[{group, MatchAddress} | Acc],
IDs
)
end,
[],
IndexBase
),
apply_write_ops(Store, lists:reverse(Ops), Opts)
end.
%% @doc Select the store that should receive reverse match-index writes.
%% A local `match-index' option wins when present. Otherwise, a local
%% `store' means "write this message and its match index to the same
%% caller-provided store". If neither is present, use the global node
%% `match-index' setting. The selected value is interpreted as:
%% `false' disables index writes, `true' uses the normal configured
%% store, and a store definition/list writes the index there.
match_store(Opts) ->
LocalMatchIndex = maps:get(<<"match-index">>, Opts, undefined),
LocalStore = maps:get(<<"store">>, Opts, undefined),
GlobalMatchIndex = hb_opts:get(match_index, false, #{ <<"only">> => global }),
MatchIndexStore =
case {LocalMatchIndex, LocalStore} of
{false, _} ->
false;
{[], _} ->
[];
{undefined, undefined} ->
GlobalMatchIndex;
{undefined, _} ->
LocalStore;
{Local, Store}
when Store =/= undefined andalso
Local =:= GlobalMatchIndex ->
Store;
{Local, _} ->
Local
end,
case MatchIndexStore of
false -> [];
true -> hb_opts:get(store, [], Opts);
ResolvedStore when is_list(ResolvedStore) -> ResolvedStore;
ResolvedStore -> [ResolvedStore]
end.
%% @doc Calculate the address of a key-value pair in the match index.
match_address(Key, Value) ->
KeyBin = match_bin(Key),
ValueBin = match_bin(Value),
iolist_to_binary([?MATCH_PREFIX, "&", KeyBin, "=", ValueBin]).
match_address_id(Address, ID) ->
IDBin = match_bin(ID),
<<Address/binary, "/", IDBin/binary>>.
%% @doc Normalize a match-index path part.
match_bin(Bin) when is_binary(Bin) -> Bin;
match_bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom);
match_bin(Int) when is_integer(Int) -> integer_to_binary(Int);
match_bin(Float) when is_float(Float) -> float_to_binary(Float, [compact]);
match_bin(List) when is_list(List) ->
try iolist_to_binary(List)
catch _:_ -> term_to_binary(List)
end;
match_bin(Other) ->
term_to_binary(Other).
%% @doc Return the path representation used by cache key-value links.
match_value_path(Bin, Opts) when is_binary(Bin) ->
generate_binary_path(Bin, Opts);
match_value_path(Map, Opts) when is_map(Map) ->
hb_message:id(Map, none, Opts#{ <<"linkify-mode">> => discard });
match_value_path(List, Opts) when is_list(List) ->
case io_lib:printable_unicode_list(List) of
true ->
match_value_path(iolist_to_binary(List), Opts);
false ->
match_value_path(
hb_message:convert(List, tabm, <<"structured@1.0">>, Opts),
Opts
)
end;
match_value_path(Other, Opts) ->
match_value_path(hb_path:to_binary(Other), Opts).
%% @doc The `structured@1.0` encoder does not typically encode `commitments`,
%% subsequently, when we encounter a commitments message we prepare its contents
%% separately, then write each to the store.
prepare_commitments(RawCommitments, Opts) ->
Commitments = ensure_all_loaded(RawCommitments, Opts),
maps:map(
fun(_, StructuredCommitment) ->
hb_message:convert(StructuredCommitment, tabm, Opts)
end,
Commitments
).
%% @doc Generate the commitment path for a given base path.
commitment_path(Base, Opts) ->
hb_path:hashpath(<<Base/binary, "/commitments">>, Opts).
%% @doc Calculate the IDs for a message.
calculate_all_ids(Bin, _UncommittedID, _Opts) when is_binary(Bin) -> [];
calculate_all_ids(Msg, UncommittedID, Opts) ->
CommIDs =
hb_maps:keys(
hb_maps:get(<<"commitments">>, Msg, #{}, Opts),
Opts
),
?event_debug({calculating_ids, {msg, Msg}, {comm_ids, CommIDs}}),
case length(CommIDs) of
0 ->
% With no commitments the `all' id is the uncommitted id we already
% computed; skip re-serializing the message to recompute it.
[UncommittedID];
_ ->
All = hb_message:id(Msg, all, Opts#{ <<"linkify-mode">> => discard }),
case lists:member(All, CommIDs) of
true -> CommIDs;
false -> [All | CommIDs]
end
end.
%% @doc Write a hashpath and its message to the store and link it.
write_hashpath(Msg = #{ <<"priv">> := #{ <<"hashpath">> := HP } }, Opts) ->
write_hashpath(HP, Msg, Opts);
write_hashpath(MsgWithoutHP, Opts) ->
write(MsgWithoutHP, Opts).
write_hashpath(HP, Msg, Opts) when is_binary(HP) or is_list(HP) ->
Store = hb_opts:get(store, no_viable_store, Opts),
?event_debug({writing_hashpath, {hashpath, HP}, {msg, Msg}, {store, Store}}),
{ok, Path} = write(Msg, Opts),
hb_store:link(Store, #{ hb_path:to_binary(HP) => Path }, Opts),
{ok, Path}.
%% @doc Write a raw binary keys into the store and link it at a given hashpath.
write_binary(Hashpath, Bin, Opts) ->
write_binary(Hashpath, Bin, hb_opts:get(store, no_viable_store, Opts), Opts).
write_binary(Hashpath, Bin, Store, Opts) ->
?event_debug({writing_binary, {hashpath, Hashpath}, {bin, Bin}, {store, Store}}),
{ok, Path} = do_write_message(Bin, Store, Opts),
hb_store:link(Store, #{ hb_path:to_binary(Hashpath) => Path }, Opts),
{ok, Path}.
%% @doc Write a resolved message with its private cache creation timestamp.
write_resolved(CacheAddress, Msg, CreatedAt, Opts) ->
write_hashpath(
CacheAddress,
Msg#{
<<"priv-created-at">> =>
integer_to_binary(hb_util:int(CreatedAt))
},
Opts
).
%% @doc Read the message at a path. Returns in `structured@1.0' format: Either
%% a richly typed map or a direct binary. If `cache-read-mode' is `raw',
%% composite reads return lazy links without decoding `ao-types'.
read(Path, Opts) ->
Store = hb_opts:get(store, no_viable_store, Opts),
case {
store_read(Path, Store, Opts),
hb_opts:get(cache_read_mode, normal, Opts)
} of
{{ok, Res}, raw} ->
{ok, Res};
{{ok, Res}, _} ->
hb_message:paranoid_verify(cache_read, Res, Opts),
{ok, Res};
{Other, _} ->
Other
end.
do_read_commitment(Path, Opts) ->
store_read(Path, hb_opts:get(store, no_viable_store, Opts), Opts).
%% @doc Load all of the commitments for a message into memory.
read_all_commitments(Msg, Opts) ->
LocalOpts = hb_store:scope(Opts, local),
UncommittedID = hb_message:id(Msg, none, Opts#{ <<"linkify-mode">> => discard }),
CurrentCommitments = hb_maps:get(<<"commitments">>, Msg, #{}, Opts),
AlreadyLoaded = hb_maps:keys(CurrentCommitments, Opts),
CommitmentsPath = hb_path:to_binary([UncommittedID, <<"commitments">>]),
FoundCommitments =
case hb_store:list(CommitmentsPath, LocalOpts) of
{ok, CommitmentIDs} ->
lists:filtermap(
fun(CommitmentID) ->
ShouldLoad = not lists:member(CommitmentID, AlreadyLoaded),
ResolvedCommPath = hb_path:to_binary([CommitmentsPath, CommitmentID]),
case
ShouldLoad andalso
do_read_commitment(ResolvedCommPath, LocalOpts)
of
{ok, Commitment} ->
{
true,
{
CommitmentID,
ensure_all_loaded(
Commitment,
Opts#{ <<"commitment">> => true }
)
}
};
_ ->
false
end
end,
CommitmentIDs
);
_ ->
[]
end,
NewCommitments =
hb_maps:merge(
CurrentCommitments,
maps:from_list(FoundCommitments)
),
Msg#{ <<"commitments">> => NewCommitments }.
%% @doc List all of the subpaths of a given path and return a map of keys and
%% links to the subpaths, including their types.
store_read(Path, Store, Opts) ->
store_read(Path, Path, Store, Opts).
store_read(_Target, _Path, no_viable_store, _) ->
{error, not_found};
store_read(Target, <<"data/", _/binary>> = PathBin, Store, Opts) ->
read_resolved_path(Target, PathBin, Store, Opts);
store_read(Target, Path, Store, Opts) ->
PathBin = hb_path:to_binary(Path),
case hb_store:resolve(Store, PathBin, Opts) of
{ok, ResolvedFullPath} ->
?event_debug({reading,
{original_path, {string, PathBin}},
{fully_resolved_path, ResolvedFullPath},
{store, Store}
}),
read_resolved_path(Target, ResolvedFullPath, Store, Opts);
{error, _} = Error ->
Error;
{failure, _} = Failure ->
Failure
end.
%% @doc Read a path whose intermediate links are already resolved, skipping the
%% redundant per-segment `hb_store:resolve' round-trip.
read_resolved_path(_Target, _Path, no_viable_store, _) ->
{error, not_found};
read_resolved_path(Target, ResolvedFullPath, Store, Opts) ->
case hb_store:read(Store, ResolvedFullPath, Opts) of
{ok, Bin} ->
?event_debug({reading_data, ResolvedFullPath}),
{ok, decode_immediate_value(ResolvedFullPath, Bin)};
{composite, Children} ->
?event_debug({reading_composite, ResolvedFullPath}),
Subpaths =
[
hb_util:bin(child_name(Child))
||
Child <- Children
],
?event(
{listed,
{original_path, Target},
{subpaths, {explicit, Subpaths}}
}
),
Msg =
case hb_opts:get(cache_read_mode, normal, Opts) of
raw ->
maps:from_list(
[
{
Subpath,
{link,
hb_path:to_binary([ResolvedFullPath, Subpath]),
#{ <<"lazy">> => true, <<"store">> => Store }
}
}
||
Subpath <- Subpaths,
Subpath =/= <<"ao-types">>
]
);
_ ->
Values =
maps:from_list([
{hb_util:bin(Subpath), Value}
||
{Subpath, Value} <- Children
]),
prepare_typed_values(
Target,
ResolvedFullPath,
Subpaths,
Values,
Store,
Opts
)
end,
?event(
{completed_read,
{resolved_path, ResolvedFullPath},
{explicit, Msg}
}
),
{ok, Msg};
{error, _} = Error ->
Error;
{failure, _} = Failure ->
Failure
end.
%% @doc Normalize a composite child entry to its subpath name, dropping any
%% inline value the prefix read supplied alongside it.
child_name({Subpath, _Value}) -> Subpath;
child_name(Subpath) -> Subpath.
%% @doc Prepare child values using `ao-types' where present. Immediate values
%% are returned directly; linked values remain lazy.
prepare_typed_values(Target, RootPath, Subpaths, Values, Store, Opts) ->
{ok, Implicit, Types} = read_ao_types(RootPath, Subpaths, Values, Store, Opts),
Res =
maps:from_list(lists:filtermap(
fun(<<"ao-types">>) -> false;
(<<"commitments">>) ->
% List the commitments for this message, and load them into
% memory. If there no commitments at the path, we exclude
% commitments from the list of links. The `commitments' key is
% itself a link to the hashpath-addressed commitments group.
% The composite read already returned that link inline, so
% when it is present we address the commitment straight from
% the resolved group, skipping the redundant re-reads of
% `RootPath' and `RootPath/commitments' that the scan just
% materialised. Only when the inline value is absent (or is
% not the usual link) do we fall back to resolving the full
% `RootPath/commitments/Target' path from scratch.
CommPath =
case maps:get(<<"commitments">>, Values, none) of
<<"link:", CommGroup/binary>> when byte_size(CommGroup) > 0 ->
hb_path:to_binary([CommGroup, Target]);
_ ->
hb_path:to_binary(
[RootPath, <<"commitments">>, Target])
end,
?event(read_commitment,
{reading_commitment,
{target, Target},
{root_path, RootPath},
{commitments_path, CommPath}
}
),
case do_read_commitment(CommPath, Opts) of
{ok, Commitment} ->
LoadedCommitment =
ensure_all_loaded(
Commitment,
Opts#{ <<"commitment">> => true }
),
?event(read_commitment,
{found_target_commitment,
{path, CommPath},
{commitment, LoadedCommitment}
}
),
% We have commitments, so we read each commitment
% into memory, and return it as part of the message.
{
true,
{
<<"commitments">>,
#{ Target => LoadedCommitment }
}
};
_ ->
false
end;
(Subpath) ->
?event(
{returning_link,
{subpath, Subpath}
}
),
SubkeyPath = hb_path:to_binary([RootPath, Subpath]),
case hb_link:is_link_key(Subpath) of
false ->
% The key is a literal value, not a nested composite
% message. Subsequently, we return a resolvable link
% to the subpath, leaving the key as-is.
LinkOpts =
(case Types of
#{ Subpath := Type } ->
% We have an `ao-types' entry for the
% subpath, so the link carries its type
% and resolves lazily to the final value.
#{
<<"type">> => Type,
<<"lazy">> => true
};
_ ->
% No `ao-types' entry: the subpath is a
% literal value, resolved lazily.
#{
<<"lazy">> => true
}
end)#{ <<"store">> => Store },
PreparedValue =
case maps:get(Subpath, Values, none) of
<<"raw:", ImmediateValue/binary>> ->
apply_type_to_immediate(ImmediateValue, LinkOpts);
<<"link:", Path/binary>> ->
{link, Path, LinkOpts};
ImmediateValue when is_binary(ImmediateValue) ->
apply_type_to_immediate(ImmediateValue, LinkOpts);
_ ->
{link, SubkeyPath, LinkOpts}
end,
{true, {Subpath, PreparedValue}};
true ->
% The key is an encoded link, so we create a resolvable
% link to the underlying link. This requires that we
% dereference the link twice in order to get the final
% value. Returning the data this way avoids having to
% read each of the link keys themselves, which may be
% a large quantity.
{true,
{
binary:part(Subpath, 0, byte_size(Subpath) - 5),
{link, SubkeyPath, #{
<<"type">> => <<"link">>,
<<"lazy">> => true
}}
}
}
end
end,
Subpaths
)),
Merged = maps:merge(Res, Implicit),
% Convert the message to an ordered list if the ao-types indicate that it
% should be so.
case hb_maps:get(<<".">>, Types, undefined, Opts) of
<<"list">> ->
hb_util:message_to_ordered_list(Merged, Opts);
_ ->
case hb_opts:get(lazy_loading, true, Opts) of
true -> Merged;
false -> ensure_all_loaded(Merged, Opts)
end
end.
apply_type_to_immediate(Value, #{ <<"type">> := Type }) ->
hb_util:decode(Type, Value);
apply_type_to_immediate(Value, _LinkOpts) ->
Value.
%% @doc Read and parse the ao-types for a given path if it is in the supplied
%% list of subpaths, returning a map of keys and their types. Prefix reads
%% already return small inline `ao-types' values, so reuse them when present.
read_ao_types(Path, Subpaths, Values, Store, Opts) ->
?event_debug({reading_ao_types, {path, Path}, {subpaths, {explicit, Subpaths}}}),
case lists:member(<<"ao-types">>, Subpaths) of
true ->