Implementing it

Until now we have an in memory key-value store, what do we have to do to make it a persistent one?

We would need to implement a new kv backend, that implements the same API as tanodb_kv_ets but using a library that persists to disk.

For this we are going to use leveled a pure erlang implementation of leveldb.

Being pure erlang means it's easy to build on any platform and easy to understand and contribute since it's all erlang!

The changes will involve making room for configurable KV backends, for that we will keep the backend module in a field called kv_mod in the vnode state:

- record ( state , { partition , kv_state , kv_mod }).

On init we will pass an extra field to the KV backend init function with the base path where it can safely store files without clashing with other vnodes in the same node:

init ([ Partition ]) -> DataPath = application : get_env ( tanodb , data_path , "." ), KvMod = tanodb_kv_leveled , { ok , KvState } = KvMod : new (#{ partition => Partition , data_path => DataPath }), { ok , #state { partition = Partition , kv_state = KvState , kv_mod = KvMod }}.

We are getting the base path to store data from an environment variable ( tanodb.data_path ), to make it configurable we need to add it to our cuttlefish schema on priv/01-tanodb.schema :

%% @doc base folder where data is stored { mapping , "paths.data" , "tanodb.data_path" , [ { datatype , directory }, { default , "{{platform_data_dir}}/vnodes" } ]}.

Then we need to replace all the places in tanodb_vnode where we used tanodb_kv_ets to use the value of kv_mod from the state record.

On rebar.config we need to add the leveled dependency, since it doesn't have any release and it's not on hex.pm we will reference the master branch from the github repo:

{ deps , [ cowboy , jsx , recon , { riak_core , { pkg , riak_core_ng }}, { leveled , { git , "https://github.com/martinsumner/leveled.git" , { branch , "master" }}} ]}.

We specify in the release to load leveled and its dependency lz4 :

{ relx , [{ release , { tanodb , "0.1.0" }, [ tanodb , cuttlefish , cowboy , { leveled , load }, { lz4 , load }, jsx , sasl ]},

At this point in time, to be able to compile leveled on Erlang 20.3, we need to add an override to remove the warnings_as_errors option in erl_opts :

{ override , leveled , [{ erl_opts , [{ platform_define , "^1[7-8]{1}" , old_rand }, { platform_define , "^R" , old_rand }, { platform_define , "^R" , no_sync }]}]}

The code for apps/tanodb/src/tanodb_kv_leveled.erl :