forked from martinsumner/leveled
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathleveled_cdb.erl
More file actions
3160 lines (2945 loc) · 103 KB
/
leveled_cdb.erl
File metadata and controls
3160 lines (2945 loc) · 103 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
%% -------- CDB File Clerk ---------
%%
%% This is a modified version of the cdb module provided by Tom Whitcomb.
%%
%% - https://github.com/thomaswhitcomb/erlang-cdb
%%
%% The CDB module is an implementation of the constant database format
%% described by DJ Bernstein
%%
%% - https://cr.yp.to/cdb.html
%%
%% The primary differences are:
%% - Support for incrementally writing a CDB file while keeping the hash table
%% in memory
%% - The ability to scan a database in blocks of sequence numbers
%% - The applictaion of a CRC check by default to all values
%%
%% Because of the final delta - this is incompatible with standard CDB files
%% (in that you won't be able to fetch values if the file was written by
%% another CDB writer as the CRC check is missing)
%%
%% This module provides functions to create and query a CDB (constant database).
%% A CDB implements a two-level hashtable which provides fast {key,value}
%% lookups that remain fairly constant in speed regardless of the CDBs size.
%%
%% The first level in the CDB occupies the first 255 doublewords in the file.
%% Each doubleword slot contains two values. The first is a file pointer to
%% the primary hashtable (at the end of the file) and the second value is the
%% number of entries in the hashtable. The first level table of 255 entries
%% is indexed with the lower eight bits of the hash of the input key.
%%
%% Following the 255 doublewords are the {key,value} tuples. The tuples are
%% packed in the file without regard to word boundaries. Each {key,value}
%% tuple is represented with a four byte key length, a four byte value length,
%% the actual key value followed by the actual value.
%%
%% Following the {key,value} tuples are the primary hash tables. There are
%% at most 255 hash tables. Each hash table is referenced by one of the 255
%% doubleword entries at the top of the file. For efficiency reasons, each
%% hash table is allocated twice the number of entries that it will need.
%% Each entry in the hash table is a doubleword.
%% The first word is the corresponding hash value and the second word is a
%% file pointer to the actual {key,value} tuple higher in the file.
%%
-module(leveled_cdb).
-behaviour(gen_statem).
-include("leveled.hrl").
-export([
init/1,
callback_mode/0,
terminate/3,
code_change/4
]).
%% states
-export([
starting/3,
writer/3,
rolling/3,
reader/3,
delete_pending/3
]).
-export([
cdb_open_writer/1,
cdb_open_writer/2,
cdb_open_reader/1,
cdb_open_reader/2,
cdb_reopen_reader/3,
cdb_get/2,
cdb_put/3,
cdb_put/4,
cdb_mput/2,
cdb_getpositions/2,
cdb_directfetch/3,
cdb_lastkey/1,
cdb_firstkey/1,
cdb_filename/1,
cdb_keycheck/2,
cdb_scan/4,
cdb_close/1,
cdb_complete/1,
cdb_roll/1,
cdb_returnhashtable/3,
cdb_checkhashtable/1,
cdb_destroy/1,
cdb_deletepending/1,
cdb_deletepending/3,
cdb_isrolling/1,
cdb_clerkcomplete/1,
cdb_getcachedscore/2,
cdb_putcachedscore/2,
cdb_deleteconfirmed/1
]).
-export([
finished_rolling/1,
hashtable_calc/2
]).
-define(DWORD_SIZE, 8).
-define(MAX_FILE_SIZE, 3221225472).
-define(BINARY_MODE, false).
-define(BASE_POSITION, 2048).
-define(WRITE_OPS, [binary, raw, read, write]).
-define(DELETE_TIMEOUT, 10000).
-define(GETPOS_FACTOR, 8).
-define(MAX_OBJECT_SIZE, 1000000000).
% 1GB but really should be much smaller than this
-define(MEGA, 1000000).
-define(CACHE_LIFE, 86400).
-record(state, {
hashtree,
last_position :: integer() | undefined,
% defined when writing, not required once rolled
last_key = empty,
current_count = 0 :: non_neg_integer(),
hash_index = {} :: tuple(),
filename :: string() | undefined,
% defined when starting
handle :: file:io_device() | undefined,
% defined when starting
max_size :: pos_integer(),
max_count :: pos_integer(),
binary_mode = false :: boolean(),
delete_point = 0 :: integer(),
inker :: pid() | undefined,
% undefined until delete_pending
deferred_delete = false :: boolean(),
waste_path :: string() | undefined,
% undefined has functional meaning
% - no sending to waste on delete
sync_strategy = none,
log_options = leveled_log:get_opts() ::
leveled_log:log_options(),
cached_score :: {float(), erlang:timestamp()} | undefined,
monitor = {no_monitor, 0} :: leveled_monitor:monitor()
}).
-type cdb_options() :: #cdb_options{}.
-type hashtable_index() :: tuple().
-type file_location() :: integer() | eof.
-type extract_fun() :: fun((binary()) -> any()).
%% erlfmt:ignore - issues with editors when function definitions are split
-type filter_fun() ::
fun((any(), binary(), integer(), term() | {term(), term()}, extract_fun()) ->
{stop | loop, any()}
).
-export_type([filter_fun/0]).
%%%============================================================================
%%% API
%%%============================================================================
-spec cdb_open_writer(string()) -> {ok, pid()}.
%% @doc
%% Open a file for writing using default options
cdb_open_writer(Filename) ->
%% No options passed
cdb_open_writer(Filename, #cdb_options{binary_mode = true}).
-spec cdb_open_writer(string(), cdb_options()) -> {ok, pid()}.
%% @doc
%% The filename should be a full file system reference to an existing CDB
%% file, and it will be opened and a FSM started to manage the file - with the
%% hashtree cached in memory (the file will need to be scanned to build the
%% hashtree)
cdb_open_writer(Filename, Opts) ->
{ok, Pid} = gen_statem:start_link(?MODULE, [Opts], []),
ok = gen_statem:call(Pid, {open_writer, Filename}, infinity),
{ok, Pid}.
-spec cdb_reopen_reader(string(), binary(), cdb_options()) -> {ok, pid()}.
%% @doc
%% Open an existing file that has already been moved into read-only mode. The
%% LastKey should be known, as it has been stored in the manifest. Knowing the
%% LastKey stops the file from needing to be scanned on start-up to discover
%% the LastKey.
%%
%% The LastKey is the Key of the last object added to the file - and is used to
%% determine when scans over a file have completed.
cdb_reopen_reader(Filename, LastKey, CDBopts) ->
{ok, Pid} =
gen_statem:start_link(
?MODULE,
[CDBopts#cdb_options{binary_mode = true}],
[]
),
ok = gen_statem:call(
Pid,
{open_reader, Filename, LastKey},
infinity
),
{ok, Pid}.
-spec cdb_open_reader(string()) -> {ok, pid()}.
%% @doc
%% Open an existing file that has already been moved into read-only mode.
%% Don't use this if the LastKey is known, as this requires an expensive scan
%% to discover the LastKey.
cdb_open_reader(Filename) ->
cdb_open_reader(Filename, #cdb_options{binary_mode = true}).
-spec cdb_open_reader(string(), #cdb_options{}) -> {ok, pid()}.
%% @doc
%% Open an existing file that has already been moved into read-only mode.
%% Don't use this if the LastKey is known, as this requires an expensive scan
%% to discover the LastKey.
%% Allows non-default cdb_options to be passed
cdb_open_reader(Filename, Opts) ->
{ok, Pid} = gen_statem:start_link(?MODULE, [Opts], []),
ok = gen_statem:call(Pid, {open_reader, Filename}, infinity),
{ok, Pid}.
-spec cdb_get(pid(), any()) -> {any(), any()} | missing.
%% @doc
%% Extract a Key and Value from a CDB file by passing in a Key.
cdb_get(Pid, Key) ->
gen_statem:call(Pid, {get_kv, Key}, infinity).
-spec cdb_put(pid(), any(), any()) -> ok | roll.
%% @doc
%% Put a key and value into a cdb file that is open as a writer, will fail
%% if the FSM is in any other state.
%%
%% Response can be roll - if there is no space to put this value in the file.
%% It is assumed that the response to a "roll" will be to roll the file, which
%% will close this file for writing after persisting the hashtree.
cdb_put(Pid, Key, Value) ->
cdb_put(Pid, Key, Value, false).
-spec cdb_put(pid(), any(), any(), boolean()) -> ok | roll.
%% @doc
%% See cdb_put/3. Addition of force-sync option, to be used when sync mode is
%% none to force a sync to disk on this particlar put.
cdb_put(Pid, Key, Value, Sync) ->
gen_statem:call(Pid, {put_kv, Key, Value, Sync}, infinity).
-spec cdb_mput(pid(), list()) -> ok | roll.
%% @doc
%% Add multiple keys and values in one call. The file will request a roll if
%% all of the keys and values cnanot be written (and in this case none of them
%% will). Mput is an all_or_nothing operation.
%%
%% It may be preferable to respond to roll by trying individual PUTs until
%% roll is returned again
cdb_mput(Pid, KVList) ->
gen_statem:call(Pid, {mput_kv, KVList}, infinity).
-spec cdb_getpositions(pid(), integer() | all) -> list().
%% @doc
%% Get the positions in the file of a random sample of Keys. cdb_directfetch
%% can then be used to fetch those keys. SampleSize can be an integer or the
%% atom all. To be used for sampling queries, for example to assess the
%% potential for compaction.
cdb_getpositions(Pid, SampleSize) ->
% Getting many positions from the index, especially getting all positions
% can take time (about 1s for all positions). Rather than queue all
% requests waiting for this to complete, loop over each of the 256 indexes
% outside of the FSM processing loop - to allow for other messages to be
% interleaved
case SampleSize of
all ->
FoldFun =
fun(Index, Acc) ->
PosList = cdb_getpositions_fromidx(Pid, all, Index, []),
lists:merge(Acc, lists:sort(PosList))
end,
IdxList = lists:seq(0, 255),
lists:foldl(FoldFun, [], IdxList);
S0 ->
FC = ?GETPOS_FACTOR * S0,
FoldFun =
fun({_R, Index}, Acc) ->
case length(Acc) of
FC ->
Acc;
L when L < FC ->
cdb_getpositions_fromidx(Pid, FC, Index, Acc)
end
end,
RandFun = fun(X) -> {rand:uniform(), X} end,
SeededL = lists:map(RandFun, lists:seq(0, 255)),
SortedL = lists:keysort(1, SeededL),
PosList0 = lists:foldl(FoldFun, [], SortedL),
P1 = rand:uniform(max(1, length(PosList0) - S0)),
lists:sublist(lists:sort(PosList0), P1, S0)
end.
cdb_getpositions_fromidx(Pid, SampleSize, Index, Acc) ->
gen_statem:call(
Pid,
{get_positions, SampleSize, Index, Acc},
infinity
).
-spec cdb_directfetch(pid(), list(), key_only | key_size | key_value_check) ->
list().
%% @doc
%% Info can be key_only, key_size (size being the size of the value) or
%% key_value_check (with the check part indicating if the CRC is correct for
%% the value)
cdb_directfetch(Pid, PositionList, Info) ->
gen_statem:call(Pid, {direct_fetch, PositionList, Info}, infinity).
-spec cdb_close(pid()) -> ok.
%% @doc
%% RONSEAL
cdb_close(Pid) ->
gen_statem:call(Pid, cdb_close, infinity).
-spec cdb_deleteconfirmed(pid()) -> ok.
%% @doc
%% Delete has been confirmed, so close (state should be delete_pending)
cdb_deleteconfirmed(Pid) ->
gen_statem:cast(Pid, delete_confirmed).
-spec cdb_complete(pid()) -> {ok, string()}.
%% @doc
%% Persists the hashtable to the end of the file, to close it for further
%% writing then exit. Returns the filename that was saved.
cdb_complete(Pid) ->
gen_statem:call(Pid, cdb_complete, infinity).
-spec cdb_roll(pid()) -> ok.
%% @doc
%% Persists the hashtable to the end of the file, to close it for further
%% writing but do not exit, this will continue to service requests in the
%% rolling state whilst the hashtable is being written, and will become a
%% reader (read-only) CDB file process on completion
cdb_roll(Pid) ->
gen_statem:cast(Pid, cdb_roll).
-spec cdb_returnhashtable(pid(), list(), binary()) -> ok.
%% @doc
%% Used for handling the return of a calulcated hashtable from a spawnded
%% process - the building of the hashtable should not block the servicing of
%% requests. Returned is the binary for writing and the IndexList
%% [{Index, CurrPos, IndexLength}] which can be used to locate the slices of
%% the hashtree within that binary
cdb_returnhashtable(Pid, IndexList, HashTreeBin) ->
gen_statem:call(Pid, {return_hashtable, IndexList, HashTreeBin}, infinity).
-spec cdb_checkhashtable(pid()) -> boolean().
%% @doc
%% Hash the hashtable been written for this file?
cdb_checkhashtable(Pid) ->
% only used in tests - so OK to be call
gen_statem:call(Pid, check_hashtable).
-spec cdb_destroy(pid()) -> ok.
%% @doc
%% If the file is in a delete_pending state close (and will destroy)
cdb_destroy(Pid) ->
gen_statem:cast(Pid, destroy).
cdb_deletepending(Pid) ->
% Only used in unit tests
cdb_deletepending(Pid, 0, no_poll).
-spec cdb_deletepending(pid(), integer(), pid() | no_poll) -> ok.
%% @doc
%% Puts the file in a delete_pending state. From that state the Inker will be
%% polled to discover if the Manifest SQN at which the file is deleted now
%% means that the file can safely be destroyed (as there are no snapshots with
%% any outstanding dependencies).
%% Passing no_poll means there's no inker to poll, and the process will close
%% on timeout rather than poll.
cdb_deletepending(Pid, ManSQN, Inker) ->
gen_statem:cast(Pid, {delete_pending, ManSQN, Inker}).
-spec cdb_scan(
pid(), filter_fun(), any(), integer() | undefined
) ->
{integer() | eof, any()}.
%% @doc
%% cdb_scan returns {LastPosition, Acc}. Use LastPosition as StartPosiiton to
%% continue from that point (calling function has to protect against) double
%% counting.
%%
%% LastPosition could be the atom complete when the last key processed was at
%% the end of the file. last_key must be defined in LoopState.
cdb_scan(Pid, FilterFun, InitAcc, StartPosition) ->
gen_statem:call(
Pid,
{cdb_scan, FilterFun, InitAcc, StartPosition},
infinity
).
-spec cdb_lastkey(pid()) -> leveled_codec:journal_key() | empty.
%% @doc
%% Get the last key to be added to the file (which will have the highest
%% sequence number)
cdb_lastkey(Pid) ->
gen_statem:call(Pid, cdb_lastkey, infinity).
-spec cdb_firstkey(pid()) -> any().
cdb_firstkey(Pid) ->
gen_statem:call(Pid, cdb_firstkey, infinity).
-spec cdb_filename(pid()) -> string().
%% @doc
%% Get the filename of the database
cdb_filename(Pid) ->
gen_statem:call(Pid, cdb_filename, infinity).
-spec cdb_keycheck(pid(), any()) -> probably | missing.
%% @doc
%% Check to see if the key is probably present, will return either
%% probably or missing. Does not do a definitive check
cdb_keycheck(Pid, Key) ->
gen_statem:call(Pid, {key_check, Key}, infinity).
-spec cdb_isrolling(pid()) -> boolean().
%% @doc
%% Check to see if a cdb file is still rolling
cdb_isrolling(Pid) ->
gen_statem:call(Pid, cdb_isrolling, infinity).
-spec cdb_clerkcomplete(pid()) -> ok.
%% @doc
%% When an Inker's clerk has finished with a CDB process, then it will call
%% complete. Currently this will prompt hibernation, as the CDB process may
%% not be needed for a period.
cdb_clerkcomplete(Pid) ->
gen_statem:cast(Pid, clerk_complete).
-spec cdb_getcachedscore(pid(), erlang:timestamp()) -> undefined | float().
%% @doc
%% Return the cached score for a CDB file
cdb_getcachedscore(Pid, Now) ->
gen_statem:call(Pid, {get_cachedscore, Now}, infinity).
-spec cdb_putcachedscore(pid(), float()) -> ok.
%% @doc
%% Return the cached score for a CDB file
cdb_putcachedscore(Pid, Score) ->
gen_statem:call(Pid, {put_cachedscore, Score}, infinity).
%%%============================================================================
%%% gen_server callbacks
%%%============================================================================
init([Opts]) ->
MaxSize =
case Opts#cdb_options.max_size of
undefined ->
?MAX_FILE_SIZE;
MS ->
MS
end,
MaxCount =
case Opts#cdb_options.max_count of
undefined ->
?MAX_FILE_SIZE div 1000;
MC ->
MC
end,
{ok, starting, #state{
max_size = MaxSize,
max_count = MaxCount,
binary_mode = Opts#cdb_options.binary_mode,
waste_path = Opts#cdb_options.waste_path,
sync_strategy = Opts#cdb_options.sync_strategy,
log_options = Opts#cdb_options.log_options,
monitor = Opts#cdb_options.monitor
}}.
callback_mode() ->
state_functions.
starting({call, From}, {open_writer, Filename}, State) ->
leveled_log:save(State#state.log_options),
?STD_LOG(cdb01, [Filename]),
{LastPosition, HashTree, LastKey} = open_active_file(Filename),
{WriteOps, UpdStrategy} = set_writeops(State#state.sync_strategy),
?STD_LOG(cdb13, [WriteOps]),
{ok, Handle} = file:open(Filename, WriteOps),
State0 = State#state{
handle = Handle,
current_count = size_hashtree(HashTree),
sync_strategy = UpdStrategy,
last_position = LastPosition,
last_key = LastKey,
filename = Filename,
hashtree = HashTree
},
{next_state, writer, State0, [{reply, From, ok}, hibernate]};
starting({call, From}, {open_reader, Filename}, State) ->
leveled_log:save(State#state.log_options),
?STD_LOG(cdb02, [Filename]),
{Monitor, _} = State#state.monitor,
leveled_monitor:add_stat(Monitor, {n_active_journal_files_update, +1}),
{Handle, Index, LastKey} = open_for_readonly(Filename, false),
State0 = State#state{
handle = Handle,
last_key = LastKey,
filename = Filename,
hash_index = Index
},
{next_state, reader, State0, [{reply, From, ok}, hibernate]};
starting({call, From}, {open_reader, Filename, LastKey}, State) ->
leveled_log:save(State#state.log_options),
?STD_LOG(cdb02, [Filename]),
{Monitor, _} = State#state.monitor,
leveled_monitor:add_stat(Monitor, {n_active_journal_files_update, +1}),
{Handle, Index, LastKey} = open_for_readonly(Filename, LastKey),
State0 = State#state{
handle = Handle,
last_key = LastKey,
filename = Filename,
hash_index = Index
},
{next_state, reader, State0, [{reply, From, ok}, hibernate]}.
writer(
{call, From}, {get_kv, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
{keep_state_and_data, [
{reply, From,
get_mem(
Key,
IO,
State#state.hashtree,
State#state.binary_mode
)}
]};
writer(
{call, From}, {key_check, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
{keep_state_and_data, [
{reply, From,
get_mem(
Key,
IO,
State#state.hashtree,
State#state.binary_mode,
loose_presence
)}
]};
writer(
{call, From},
{put_kv, Key, Value, Sync},
State = #state{last_position = LP, handle = IO}
) when
?IS_DEF(last_position), ?IS_DEF(IO)
->
NewCount = State#state.current_count + 1,
case NewCount >= State#state.max_count of
true ->
{keep_state_and_data, [{reply, From, roll}]};
false ->
Result =
put(
IO,
Key,
Value,
{LP, State#state.hashtree},
State#state.binary_mode,
State#state.max_size,
State#state.last_key == empty
),
case Result of
roll ->
%% Key and value could not be written
{keep_state_and_data, [{reply, From, roll}]};
{UpdHandle, NewPosition, HashTree} ->
ok =
case {State#state.sync_strategy, Sync} of
{riak_sync, _} ->
file:datasync(UpdHandle);
{none, true} ->
file:datasync(UpdHandle);
_ ->
ok
end,
{keep_state,
State#state{
handle = UpdHandle,
current_count = NewCount,
last_position = NewPosition,
last_key = Key,
hashtree = HashTree
},
[{reply, From, ok}]}
end
end;
writer({call, From}, {mput_kv, []}, _State) ->
{keep_state_and_data, [{reply, From, ok}]};
writer(
{call, From},
{mput_kv, KVList},
State = #state{last_position = LP, handle = IO}
) when
?IS_DEF(last_position), ?IS_DEF(IO)
->
NewCount = State#state.current_count + length(KVList),
TooMany = NewCount >= State#state.max_count,
NotEmpty = State#state.current_count > 0,
case (TooMany and NotEmpty) of
true ->
{keep_state_and_data, [{reply, From, roll}]};
false ->
Result =
mput(
IO,
KVList,
{LP, State#state.hashtree},
State#state.binary_mode,
State#state.max_size
),
case Result of
roll ->
%% Keys and values could not be written
{keep_state_and_data, [{reply, From, roll}]};
{UpdHandle, NewPosition, HashTree, LastKey} ->
{keep_state,
State#state{
handle = UpdHandle,
current_count = NewCount,
last_position = NewPosition,
last_key = LastKey,
hashtree = HashTree
},
[{reply, From, ok}]}
end
end;
writer(
{call, From}, cdb_complete, State = #state{filename = FN}
) when
?IS_DEF(FN)
->
NewName = determine_new_filename(FN),
ok = close_file(
State#state.handle,
State#state.hashtree,
State#state.last_position
),
ok = rename_for_read(FN, NewName),
{stop_and_reply, normal, [{reply, From, {ok, NewName}}]};
writer({call, From}, Event, State) ->
handle_sync_event(Event, From, State);
writer(
cast, cdb_roll, State = #state{last_position = LP}
) when
?IS_DEF(LP)
->
{Monitor, _} = State#state.monitor,
leveled_monitor:add_stat(Monitor, {n_active_journal_files_update, +1}),
ok =
leveled_iclerk:clerk_hashtablecalc(
State#state.hashtree, LP, self()
),
{next_state, rolling, State}.
rolling(
{call, From}, {get_kv, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
{keep_state_and_data, [
{reply, From,
get_mem(
Key,
IO,
State#state.hashtree,
State#state.binary_mode
)}
]};
rolling(
{call, From}, {key_check, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
{keep_state_and_data, [
{reply, From,
get_mem(
Key,
IO,
State#state.hashtree,
State#state.binary_mode,
loose_presence
)}
]};
rolling(
{call, From},
{get_positions, _SampleSize, _Index, SampleAcc},
_State
) ->
{keep_state_and_data, [{reply, From, SampleAcc}]};
rolling(
{call, From},
{return_hashtable, IndexList, HashTreeBin},
State = #state{filename = FN}
) when
?IS_DEF(FN)
->
SW = os:timestamp(),
Handle = State#state.handle,
{ok, BasePos} = file:position(Handle, State#state.last_position),
NewName = determine_new_filename(FN),
ok = perform_write_hash_tables(Handle, HashTreeBin, BasePos),
ok = write_top_index_table(Handle, BasePos, IndexList),
file:close(Handle),
ok = rename_for_read(FN, NewName),
?STD_LOG(cdb03, [NewName]),
ets:delete(State#state.hashtree),
{NewHandle, Index, LastKey} =
open_for_readonly(NewName, State#state.last_key),
State0 = State#state{
handle = NewHandle,
last_key = LastKey,
filename = NewName,
hash_index = Index
},
case State#state.deferred_delete of
true ->
{
next_state,
delete_pending,
State0,
[{reply, From, ok}, ?DELETE_TIMEOUT]
};
false ->
?TMR_LOG(cdb18, [], SW),
{next_state, reader, State0, [{reply, From, ok}, hibernate]}
end;
rolling({call, From}, check_hashtable, _State) ->
{keep_state_and_data, [{reply, From, false}]};
rolling({call, From}, cdb_isrolling, _State) ->
{keep_state_and_data, [{reply, From, true}]};
rolling({call, From}, Event, State) ->
handle_sync_event(Event, From, State);
rolling(cast, {delete_pending, ManSQN, Inker}, State) ->
{keep_state, State#state{
delete_point = ManSQN, inker = Inker, deferred_delete = true
}}.
reader(
{call, From}, {get_kv, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
Result =
get_withcache(
IO,
Key,
State#state.hash_index,
State#state.binary_mode,
State#state.monitor
),
{keep_state_and_data, [{reply, From, Result}]};
reader({call, From}, {key_check, Key}, State) ->
Result =
get_withcache(
State#state.handle,
Key,
State#state.hash_index,
loose_presence,
State#state.binary_mode,
{no_monitor, 0}
),
{keep_state_and_data, [{reply, From, Result}]};
reader({call, From}, {get_positions, SampleSize, Index, Acc}, State) ->
{Pos, Count} = element(Index + 1, State#state.hash_index),
UpdAcc = scan_index_returnpositions(State#state.handle, Pos, Count, Acc),
case SampleSize of
all ->
{keep_state_and_data, [{reply, From, UpdAcc}]};
_ ->
{keep_state_and_data, [
{reply, From, lists:sublist(UpdAcc, SampleSize)}
]}
end;
reader(
{call, From},
{direct_fetch, PositionList, Info},
State = #state{handle = IO}
) when
?IS_DEF(IO)
->
FilterFalseKey =
fun(Tpl) ->
case element(1, Tpl) of
false ->
false;
_Key ->
{true, Tpl}
end
end,
case Info of
key_only ->
FM =
lists:filtermap(
fun(P) ->
FilterFalseKey(extract_key(IO, P))
end,
PositionList
),
MapFun = fun(T) -> element(1, T) end,
{keep_state_and_data, [{reply, From, lists:map(MapFun, FM)}]};
key_size ->
FilterFun = fun(P) -> FilterFalseKey(extract_key_size(IO, P)) end,
{keep_state_and_data, [
{reply, From, lists:filtermap(FilterFun, PositionList)}
]};
key_value_check ->
BM = State#state.binary_mode,
MapFun = fun(P) -> extract_key_value_check(IO, P, BM) end,
% direct_fetch will occur in batches, so it doesn't make sense to
% hibernate the process that is likely to be used again. However,
% a significant amount of unused binary references may have
% accumulated, so push a GC at this point
gen_statem:reply(From, lists:map(MapFun, PositionList)),
garbage_collect(),
{keep_state_and_data, []}
end;
reader(
{call, From}, cdb_complete, State = #state{filename = FN, handle = IO}
) when
?IS_DEF(FN), ?IS_DEF(IO)
->
?STD_LOG(cdb05, [FN, reader, cdb_ccomplete]),
ok = file:close(IO),
{stop_and_reply, normal, [{reply, From, {ok, FN}}], State#state{
handle = undefined
}};
reader({call, From}, check_hashtable, _State) ->
{keep_state_and_data, [{reply, From, true}]};
reader({call, From}, Event, State) ->
handle_sync_event(Event, From, State);
reader(cast, {delete_pending, 0, no_poll}, State) ->
{next_state, delete_pending, State#state{delete_point = 0}};
reader(cast, {delete_pending, ManSQN, Inker}, State) ->
{next_state, delete_pending,
State#state{delete_point = ManSQN, inker = Inker}, ?DELETE_TIMEOUT};
reader(cast, clerk_complete, _State) ->
{keep_state_and_data, [hibernate]}.
delete_pending(
{call, From}, {get_kv, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
Result =
get_withcache(
IO,
Key,
State#state.hash_index,
State#state.binary_mode,
State#state.monitor
),
{keep_state_and_data, [{reply, From, Result}, ?DELETE_TIMEOUT]};
delete_pending(
{call, From}, {key_check, Key}, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
Result =
get_withcache(
IO,
Key,
State#state.hash_index,
loose_presence,
State#state.binary_mode,
{no_monitor, 0}
),
{keep_state_and_data, [{reply, From, Result}, ?DELETE_TIMEOUT]};
delete_pending(
{call, From}, cdb_close, State = #state{handle = IO, filename = FN}
) when
?IS_DEF(FN), ?IS_DEF(IO)
->
?STD_LOG(cdb05, [FN, delete_pending, cdb_close]),
close_pendingdelete(IO, FN, State#state.waste_path),
{stop_and_reply, normal, [{reply, From, ok}]};
delete_pending({call, From}, Event, State) ->
handle_sync_event(Event, From, State);
delete_pending(
cast, delete_confirmed, State = #state{handle = IO, filename = FN}
) when
?IS_DEF(FN), ?IS_DEF(IO)
->
{Monitor, _} = State#state.monitor,
leveled_monitor:add_stat(Monitor, {n_active_journal_files_update, -1}),
?STD_LOG(cdb04, [FN, State#state.delete_point]),
close_pendingdelete(IO, FN, State#state.waste_path),
{stop, normal};
delete_pending(
cast, destroy, State = #state{handle = IO, filename = FN}
) when
?IS_DEF(FN), ?IS_DEF(IO)
->
?STD_LOG(cdb05, [FN, delete_pending, destroy]),
close_pendingdelete(IO, FN, State#state.waste_path),
{stop, normal};
delete_pending(
timeout,
_,
State = #state{delete_point = ManSQN, handle = IO, filename = FN}
) when
ManSQN > 0, ?IS_DEF(FN), ?IS_DEF(IO)
->
case is_process_alive(State#state.inker) of
true ->
ok =
leveled_inker:ink_confirmdelete(
State#state.inker, ManSQN, self()
),
{keep_state_and_data, [?DELETE_TIMEOUT]};
false ->
{Monitor, _} = State#state.monitor,
leveled_monitor:add_stat(
Monitor, {n_active_journal_files_update, -1}
),
?STD_LOG(cdb04, [FN, ManSQN]),
close_pendingdelete(IO, FN, State#state.waste_path),
{stop, normal}
end.
handle_sync_event(
{cdb_scan, FilterFun, Acc, StartPos}, From, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
{ok, EndPos0} = file:position(IO, eof),
{ok, StartPos0} =
case StartPos of
undefined ->
file:position(IO, ?BASE_POSITION);
StartPos ->
{ok, StartPos}
end,
file:position(IO, StartPos0),
MaybeEnd =
(check_last_key(State#state.last_key) == empty) or
(StartPos0 >= (EndPos0 - ?DWORD_SIZE)),
{LastPosition, Acc2} =
case MaybeEnd of
true ->
{eof, Acc};
false ->
scan_over_file(
IO,
StartPos0,
FilterFun,
Acc,
State#state.last_key
)
end,
% The scan may have created a lot of binary references, clear up the
% reference counters for this process here manually. The cdb process
% may be inactive for a period after the scan, and so GC may not kick in
% otherwise
%
% garbage_collect/0 is used in preference to hibernate, as we're generally
% scanning in batches at startup - so the process will be needed straight
% away.
gen_statem:reply(From, {LastPosition, Acc2}),
garbage_collect(),
{keep_state_and_data, []};
handle_sync_event(cdb_lastkey, From, State) ->
{keep_state_and_data, [{reply, From, State#state.last_key}]};
handle_sync_event(
cdb_firstkey, From, State = #state{handle = IO}
) when
?IS_DEF(IO)
->
{ok, EOFPos} = file:position(IO, eof),
FirstKey =
case EOFPos of
?BASE_POSITION ->
empty;
_ ->
FindFirstKeyFun =
fun(Key, _V, _P, _O, _Fun) -> {stop, Key} end,
file:position(IO, ?BASE_POSITION),
{_Pos, FirstScanKey} =
scan_over_file(
IO,
?BASE_POSITION,
FindFirstKeyFun,
empty,
State#state.last_key
),
FirstScanKey
end,
{keep_state_and_data, [{reply, From, FirstKey}]};
handle_sync_event(cdb_filename, From, State) ->
{keep_state_and_data, [{reply, From, State#state.filename}]};