%%% Copyright (c) 2014-2015, NORDUnet A/S. %%% See LICENSE for licensing information. %%% @doc Storage DB -module(storagedb). -behaviour(gen_server). %% API -export([start_link/0, stop/0]). -export([add/1, fetchnewhashes/1, lastverifiednewentry/0]). %% gen_server callbacks. -export([init/1, handle_call/3, terminate/2, handle_cast/2, handle_info/2, code_change/3]). -import(stacktrace, [call/2]). init(_Args) -> {ok, []}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> call(?MODULE, stop). lastverifiednewentry_path() -> {ok, Value} = application:get_env(plop, lastverifiednewentry_path), Value. %%%%%%%%%%%%%%%%%%%% %% Public API. fetchnewhashes(Index) -> case index:indexsize(newentries_db) of 0 -> []; Size -> index:getrange(newentries_db, Index, Size - 1) end. lastverifiednewentry() -> case atomic:readfile(lastverifiednewentry_path()) of noentry -> {0, none}; Contents -> {struct, PropList} = mochijson2:decode(Contents), Index = proplists:get_value(<<"index">>, PropList), Hash = proplists:get_value(<<"hash">>, PropList), {Index, mochihex:to_bin(binary_to_list(Hash))} end. -spec add(binary()) -> ok. add(LeafHash) -> ok = call(?MODULE, {add_nosync, LeafHash}), ok = index:sync(newentries_db), ok. %%%%%%%%%%%%%%%%%%%% %% gen_server callbacks. handle_cast(_Request, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. code_change(_OldVsn, State, _Extra) -> {ok, State}. terminate(_Reason, _State) -> io:format("~p terminating~n", [?MODULE]), ok. %%%%%%%%%%%%%%%%%%%% handle_call(stop, _From, State) -> {stop, normal, stopped, State}; handle_call({add_nosync, LeafHash}, _From, State) -> ok = index:addlast_nosync(newentries_db, LeafHash), {reply, ok, State}.