cache_tab-1.0.2/0000755000232200023220000000000012650725555013765 5ustar debalancedebalancecache_tab-1.0.2/rebar.config0000644000232200023220000000256412650725555016256 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : rebar.config %%% Author : Evgeniy Khramtsov %%% Purpose : Rebar build script. Compliant with rebar and rebar3. %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%---------------------------------------------------------------------- {erl_opts, [debug_info]}. {deps, [{p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.3"}}}]}. {cover_enabled, true}. {cover_export_enabled, true}. {xref_checks, [undefined_function_calls, undefined_functions, deprecated_function_calls, deprecated_functions]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: cache_tab-1.0.2/CHANGELOG.md0000644000232200023220000000007212650725555015575 0ustar debalancedebalance# Version 1.0.2 * Use p1_utils v1.0.3 (Mickaël Rémond) cache_tab-1.0.2/test/0000755000232200023220000000000012650725555014744 5ustar debalancedebalancecache_tab-1.0.2/test/cache_tab_test.erl0000644000232200023220000000214712650725555020404 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : cache_tab_test.erl %%% Author : Mickael Remond %%% Purpose : cache_tab module tests %%% Created : 10 Dec 2015 by Mickael Remond %%% %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%---------------------------------------------------------------------- -module(cache_tab_test). -compile(export_all). -include_lib("eunit/include/eunit.hrl"). dummy_test() -> ?assertEqual(ok, ok). cache_tab-1.0.2/LICENSE.txt0000644000232200023220000002613612650725555015620 0ustar debalancedebalance Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed 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. cache_tab-1.0.2/README.md0000644000232200023220000000560512650725555015252 0ustar debalancedebalance# In-memory cache application for Erlang / Elixir apps [![Build Status](https://travis-ci.org/processone/cache_tab.svg?branch=master)](https://travis-ci.org/processone/cache_tab) [![Coverage Status](https://coveralls.io/repos/processone/cache_tab/badge.svg?branch=master&service=github)](https://coveralls.io/github/processone/cache_tab?branch=master) [![Hex version](https://img.shields.io/hexpm/v/cache_tab.svg "Hex version")](https://hex.pm/packages/cache_tab) `cache_tab` application is intended to proxy back-end operations for Key-Value insert, lookup and delete and maintain a cache of those Key-Values in-memory, to save back-end operations. Operations are intended to be atomic between back-end and cache tables. The lifetime of the cache object and the max size of the cache can be defined as table parameters to limit the size of the in-memory tables. ## Building `cache_tab` application can be build as follow: make It is a rebar-compatible OTP application. Alternatively, you can build it with rebar: rebar get-deps compile ## Usage You can start the application with the command: ``` $ erl -pa ebin/ Erlang/OTP 18 [erts-7.1] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] Eshell V7.1 (abort with ^G) 1> application:start(cache_tab). ``` Then, you can create a table for a specific type of data to cache. You can create several tables to separate your cached data. The following command will create a table named `tab_name`: ``` cache_tab:new(tab_name, [{life_time, Seconds}, {max_size, N}]). ``` The optional `life_time` option is used to define cache entry expiration. The optional `max_size` option is used to limit number of entries to add in cache. You can insert data into the cache with: ``` cache_tab:insert(tab_name, <<"key">>, <<"value">>, fun() -> do_something() end). ``` Cache inserts are designed to be able to act as a proxy to backend insert. That's the purpose of the fun called as last parameter (`do_something`). Return of the fun is ignored, but if it crashes, cache will not be stored. If value did not change compared to previous insert, the fun will not be called, saving possibly unneeded write operations You can also lookup data from the cache: ``` cache_tab:lookup(tab_name, <<"key">>, fun() -> read_value_if_not_cached() end). ``` The fun in last parameter is used to read and cache the value from your back-end if it is not already in cache. It is expected to return either `{ok, Value}` or `error`. You can delete entries from back-end and cache with command: ``` cache_tab:delete(tab_name, <<"key">>, fun() -> do_something() end), ``` Info command will report about the hits / misses to help you tune your cache size / lifetime parameters: ``` cache_tab:info(tab_name, Info). ``` Info parameter can be: `size`, `ratio` or `all`. ## Development ### Test #### Unit test You can run eunit test with the command: $ make test cache_tab-1.0.2/rebar.config.script0000644000232200023220000000743512650725555017563 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : rebar.config.script %%% Author : Mickael Remond %%% Purpose : Rebar build script. Compliant with rebar and rebar3. %%% Created : 24 Nov 2015 by Mickael Remond %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%---------------------------------------------------------------------- ModCfg0 = fun(F, Cfg, [Key|Tail], Op, Default) -> {OldVal,PartCfg} = case lists:keytake(Key, 1, Cfg) of {value, {_, V1}, V2} -> {V1, V2}; false -> {if Tail == [] -> Default; true -> [] end, Cfg} end, case Tail of [] -> [{Key, Op(OldVal)} | PartCfg]; _ -> [{Key, F(F, OldVal, Tail, Op, Default)} | PartCfg] end end, ModCfg = fun(Cfg, Keys, Op, Default) -> ModCfg0(ModCfg0, Cfg, Keys, Op, Default) end. %% Rebar3 support for hex.pm support: %% - Transform dependencies specification to use hex.pm packages: %% deps of the form: {Name, _Vsn, {git, _URL, {tag, Version}}} %% are expected to refer to package and are rewritten for rebar3 as: %% {Name, Version} %% - Add rebar3_hex plugin IsRebar3 = case application:get_key(rebar, vsn) of {ok, VSN} -> [VSN1 | _] = string:tokens(VSN, "-"), [Maj, Min, Patch] = string:tokens(VSN1, "."), (list_to_integer(Maj) >= 3); undefined -> lists:keymember(mix, 1, application:loaded_applications()) end, Cfg2 = case IsRebar3 of true -> DepsFun = fun(DepsList) -> lists:map(fun({DepName,_, {git,_, {tag,Version}}}) -> {DepName, Version}; (Dep) -> Dep end, DepsList) end, RB1 = ModCfg(CONFIG, [deps], DepsFun, []), ModCfg(RB1, [plugins], fun(V) -> V ++ [rebar3_hex] end, []); false -> CONFIG end, %% When running Travis test, upload test coverage result to coveralls: Config = case os:getenv("TRAVIS") of "true" -> JobId = os:getenv("TRAVIS_JOB_ID"), Cfg3 = ModCfg(Cfg2, [deps], fun(V) -> [{coveralls, ".*", {git, "https://github.com/markusn/coveralls-erl.git", "master"}}|V] end, []), ModCfg(Cfg3, [post_hooks], fun(V) -> V ++ [{eunit, "echo '\n%%! -pa .eunit/ deps/coveralls/ebin\nmain(_)->{ok,F}=file:open(\"erlang.json\",[write]),io:fwrite(F,\"~s\",[coveralls:convert_file(\".eunit/cover.coverdata\", \""++JobId++"\", \"travis-ci\")]).' > getcover.erl"}, {eunit, "escript ./getcover.erl"}] end, []); _ -> Cfg2 end, Config. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: cache_tab-1.0.2/.travis.yml0000644000232200023220000000055312650725555016101 0ustar debalancedebalancesudo: false language: erlang before_install: - pip install --user cpp-coveralls coveralls-merge install: - rebar get-deps script: rebar compile xref && rebar skip_deps=true eunit otp_release: - 17.1 - 17.5 - 18.1 after_success: - coveralls --exclude lib --exclude tests --gcov-options '\-lp' --dump c.json - coveralls-merge c.json erlang.json cache_tab-1.0.2/src/0000755000232200023220000000000012650725555014554 5ustar debalancedebalancecache_tab-1.0.2/src/cache_tab.erl0000644000232200023220000004260312650725555017156 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab.erl %%% Author : Evgeniy Khramtsov %%% Description : Caching key-value table %%% %%% Created : 29 Aug 2010 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%------------------------------------------------------------------- -module(cache_tab). -define(GEN_SERVER, gen_server). -behaviour(?GEN_SERVER). %% API -export([start_link/4, new/2, delete/1, delete/3, lookup/3, insert/4, info/2, tab2list/1, setopts/2, dirty_lookup/3, dirty_insert/4, dirty_delete/3, all/0, clean/1, test/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {tab = treap:empty(), name, size = 0, owner, max_size, life_time, warn, hits = 0, miss = 0, procs_num, cache_missed, lru, shrink_size}). -define(PROCNAME, ?MODULE). -define(CALL_TIMEOUT, 60000). %% Defaults -define(MAX_SIZE, 1000). -define(WARN, true). -define(CACHE_MISSED, true). -define(LRU, true). -define(LIFETIME, 600). %% 10 minutes %%==================================================================== %% API %%==================================================================== start_link(Proc, Tab, Opts, Owner) -> ?GEN_SERVER:start_link( {local, Proc}, ?MODULE, [Tab, Opts, get_proc_num(), Owner], []). new(Tab, Opts) -> Res = lists:flatmap( fun(Proc) -> Spec = {{Tab, Proc}, {?MODULE, start_link, [Proc, Tab, Opts, self()]}, permanent, brutal_kill, worker, [?MODULE]}, case supervisor:start_child(cache_tab_sup, Spec) of {ok, _Pid} -> [ok]; R -> [R] end end, get_all_procs(Tab)), case lists:filter(fun(ok) -> false; (_) -> true end, Res) of [] -> ok; Err -> {error, Err} end. clean(Tab) -> lists:foreach( fun(Proc) -> ?GEN_SERVER:call(Proc, clean, ?CALL_TIMEOUT) end, get_all_procs(Tab)). delete(Tab) -> lists:foreach( fun(Proc) -> supervisor:terminate_child(cache_tab_sup, {Tab, Proc}), supervisor:delete_child(cache_tab_sup, {Tab, Proc}) end, get_all_procs(Tab)). delete(Tab, Key, F) -> ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {delete, Key, F}, ?CALL_TIMEOUT). dirty_delete(Tab, Key, F) -> F(), ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {cache_delete, Key}, ?CALL_TIMEOUT). lookup(Tab, Key, F) -> ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {lookup, Key, F}, ?CALL_TIMEOUT). dirty_lookup(Tab, Key, F) -> Proc = get_proc_by_hash(Tab, Key), case ?GEN_SERVER:call(Proc, {cache_lookup, Key}, ?CALL_TIMEOUT) of {ok, '$cached_mismatch'} -> error; {ok, Val} -> {ok, Val}; _ -> {Result, NewVal} = case F() of {ok, Val} -> {{ok, Val}, Val}; _ -> {error, '$cached_mismatch'} end, ?GEN_SERVER:call( Proc, {cache_insert, Key, NewVal}, ?CALL_TIMEOUT), Result end. insert(Tab, Key, Val, F) -> ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {insert, Key, Val, F}, ?CALL_TIMEOUT). dirty_insert(Tab, Key, Val, F) -> F(), ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {cache_insert, Key, Val}, ?CALL_TIMEOUT). info(Tab, Info) -> case lists:map( fun(Proc) -> ?GEN_SERVER:call(Proc, {info, Info}, ?CALL_TIMEOUT) end, get_all_procs(Tab)) of Res when Info == size -> {ok, lists:sum(Res)}; Res when Info == all -> {ok, Res}; Res when Info == ratio -> {H, M} = lists:foldl( fun({Hits, Miss}, {HitsAcc, MissAcc}) -> {HitsAcc + Hits, MissAcc + Miss} end, {0, 0}, Res), {ok, [{hits, H}, {miss, M}]}; _ -> {error, badarg} end. setopts(Tab, Opts) -> lists:foreach( fun(Proc) -> ?GEN_SERVER:call(Proc, {setopts, Opts}, ?CALL_TIMEOUT) end, get_all_procs(Tab)). tab2list(Tab) -> lists:flatmap( fun(Proc) -> ?GEN_SERVER:call(Proc, tab2list, ?CALL_TIMEOUT) end, get_all_procs(Tab)). all() -> lists:usort( [Tab || {{Tab, _}, _, _, _} <- supervisor:which_children(cache_tab_sup)]). %%==================================================================== %% gen_server callbacks %%==================================================================== init([Tab, Opts, N, Pid]) -> State = #state{procs_num = N, owner = Pid, name = Tab}, {ok, do_setopts(State, Opts)}. handle_call({lookup, Key, F}, _From, #state{tab = T} = State) -> CleanPrio = clean_priority(State#state.life_time), case treap:lookup(Key, T) of {ok, Prio, Val} when (State#state.lru == true) or (Prio =< CleanPrio) -> Hits = State#state.hits, NewState = treap_update(Key, Val, State#state{hits = Hits + 1}), case Val of '$cached_mismatch' -> {reply, error, NewState}; _ -> {reply, {ok, Val}, NewState} end; _ -> case catch F() of {ok, Val} -> Miss = State#state.miss, NewState = treap_insert(Key, Val, State), {reply, {ok, Val}, NewState#state{miss = Miss + 1}}; {'EXIT', Reason} -> print_error(lookup, [Key], Reason, State), {reply, error, State}; _ -> Miss = State#state.miss, NewState = State#state{miss = Miss + 1}, if State#state.cache_missed -> {reply, error, treap_insert(Key, '$cached_mismatch', NewState)}; true -> {reply, error, NewState} end end end; handle_call({cache_lookup, Key}, _From, #state{tab = T} = State) -> CleanPrio = clean_priority(State#state.life_time), case treap:lookup(Key, T) of {ok, Prio, Val} when (State#state.lru == true) or (Prio =< CleanPrio) -> Hits = State#state.hits, NewState = treap_update(Key, Val, State#state{hits = Hits + 1}), {reply, {ok, Val}, NewState}; _ -> Miss = State#state.miss, NewState = State#state{miss = Miss + 1}, {reply, error, NewState} end; handle_call({insert, Key, Val, F}, _From, #state{tab = T} = State) -> case treap:lookup(Key, T) of {ok, _Prio, Val} -> {reply, ok, treap_update(Key, Val, State)}; _ -> case catch F() of {'EXIT', Reason} -> print_error(insert, [Key, Val], Reason, State), {reply, ok, State}; _ -> {reply, ok, treap_insert(Key, Val, State)} end end; handle_call({cache_insert, _, '$cached_mismatch'}, _From, #state{cache_missed = false} = State) -> {reply, ok, State}; handle_call({cache_insert, Key, Val}, _From, State) -> {reply, ok, treap_insert(Key, Val, State)}; handle_call({delete, Key, F}, _From, State) -> NewState = treap_delete(Key, State), case catch F() of {'EXIT', Reason} -> print_error(delete, [Key], Reason, State); _ -> ok end, {reply, ok, NewState}; handle_call({cache_delete, Key}, _From, State) -> NewState = treap_delete(Key, State), {reply, ok, NewState}; handle_call({info, Info}, _From, State) -> Res = case Info of size -> State#state.size; ratio -> {State#state.hits, State#state.miss}; all -> [{max_size, State#state.max_size}, {life_time, State#state.life_time}, {shrink_size, State#state.shrink_size}, {size, State#state.size}, {owner, State#state.owner}, {hits, State#state.hits}, {miss, State#state.miss}, {cache_missed, State#state.cache_missed}, {lru, State#state.lru}, {warn, State#state.warn}]; _ -> badarg end, {reply, Res, State}; handle_call(tab2list, _From, #state{tab = T} = State) -> Res = treap:fold( fun({Key, _, Val}, Acc) -> [{Key, Val}|Acc] end, [], T), {reply, Res, State}; handle_call({setopts, Opts}, _From, State) -> {reply, ok, do_setopts(State, Opts)}; handle_call(clean, _From, State) -> {reply, ok, State#state{tab = treap:empty(), size = 0}}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- do_setopts(#state{procs_num = N} = State, Opts) -> MaxSize = case {proplists:get_value(max_size, Opts), State#state.max_size} of {MS, _} when is_integer(MS), MS > 0 -> round(MS/N); {unlimited, _} -> unlimited; {_, undefined} -> round(?MAX_SIZE/N); {_, MS} -> MS end, LifeTime = case {proplists:get_value(life_time, Opts), State#state.life_time} of {LT, _} when is_integer(LT), LT > 0 -> LT*1000*1000; {unlimited, _} -> unlimited; {_, undefined} -> ?LIFETIME*1000*1000; {_, LT} -> LT end, ShrinkSize = case {proplists:get_value(shrink_size, Opts), State#state.shrink_size} of {SS, _} when is_integer(SS), SS > 0 -> round(SS/N); _ when is_integer(MaxSize) -> round(MaxSize/2); _ -> unlimited end, Warn = case {proplists:get_value(warn, Opts), State#state.warn} of {true, _} -> true; {false, _} -> false; {_, undefined} -> ?WARN; {_, W} -> W end, CacheMissed = case proplists:get_value( cache_missed, Opts, State#state.cache_missed) of false -> false; true -> true; _ -> ?CACHE_MISSED end, LRU = case proplists:get_value( lru, Opts, State#state.lru) of false -> false; true -> true; _ -> ?LRU end, State#state{max_size = MaxSize, warn = Warn, life_time = LifeTime, cache_missed = CacheMissed, lru = LRU, shrink_size = ShrinkSize}. get_proc_num() -> case catch erlang:system_info(logical_processors) of Num when is_integer(Num) -> Num; _ -> 1 end. get_proc_by_hash(Tab, Term) -> N = erlang:phash2(Term, get_proc_num()) + 1, get_proc(Tab, N). get_proc(Tab, N) -> list_to_atom(atom_to_list(?PROCNAME) ++ "_" ++ atom_to_list(Tab) ++ "_" ++ integer_to_list(N)). get_all_procs(Tab) -> [get_proc(Tab, N) || N <- lists:seq(1, get_proc_num())]. now_priority() -> {MSec, Sec, USec} = now(), -((MSec*1000000 + Sec)*1000000 + USec). clean_priority(LifeTime) -> if is_integer(LifeTime) -> now_priority() + LifeTime; true -> unlimited end. treap_update(Key, Val, #state{tab = T, lru = LRU} = State) -> if LRU -> Priority = now_priority(), NewT = treap:insert(Key, Priority, Val, T), State#state{tab = NewT}; true -> State end. treap_insert(Key, Val, State) -> State1 = clean_treap(State), #state{size = Size} = State2 = shrink_treap(State1), T = State2#state.tab, case treap:lookup(Key, T) of {ok, _, Val} -> treap_update(Key, Val, State2); {ok, _, _} -> NewT = treap:insert(Key, now_priority(), Val, T), State2#state{tab = NewT}; _ -> NewT = treap:insert(Key, now_priority(), Val, T), State2#state{tab = NewT, size = Size+1} end. treap_delete(Key, #state{tab = T, size = Size} = State) -> case treap:lookup(Key, T) of {ok, _, _} -> NewT = treap:delete(Key, T), clean_treap(State#state{tab = NewT, size = Size-1}); _ -> State end. clean_treap(#state{tab = T, size = Size, life_time = LifeTime} = State) -> if is_integer(LifeTime) -> Priority = now_priority(), {Cleaned, NewT} = clean_treap(T, Priority + LifeTime, 0), State#state{size = Size - Cleaned, tab = NewT}; true -> State end. clean_treap(Treap, CleanPriority, N) -> case treap:is_empty(Treap) of true -> {N, Treap}; false -> {_Key, Priority, _Value} = treap:get_root(Treap), if Priority > CleanPriority -> clean_treap(treap:delete_root(Treap), CleanPriority, N+1); true -> {N, Treap} end end. shrink_treap(#state{tab = T, max_size = MaxSize, shrink_size = ShrinkSize, warn = Warn, size = Size} = State) when Size >= MaxSize -> if Warn -> error_logger:warning_msg( "shrinking table:~n" "** Table: ~p~n" "** Processes Number: ~p~n" "** Max Size: ~p items~n" "** Shrink Size: ~p items~n" "** Life Time: ~p microseconds~n" "** Hits/Miss: ~p/~p~n" "** Owner: ~p~n" "** Cache Missed: ~p~n" "** Instruction: you have to tune cacheing options" " if this message repeats too frequently~n", [State#state.name, State#state.procs_num, MaxSize, ShrinkSize, State#state.life_time, State#state.hits, State#state.miss, State#state.owner, State#state.cache_missed]); true -> ok end, {Shrinked, NewT} = shrink_treap(T, ShrinkSize, 0), State#state{tab = NewT, size = Size - Shrinked}; shrink_treap(State) -> State. shrink_treap(T, ShrinkSize, ShrinkSize) -> {ShrinkSize, T}; shrink_treap(T, ShrinkSize, N) -> case treap:is_empty(T) of true -> {N, T}; false -> shrink_treap(treap:delete_root(T), ShrinkSize, N+1) end. print_error(Operation, Args, Reason, State) -> error_logger:error_msg( "callback failed:~n" "** Tab: ~p~n" "** Owner: ~p~n" "** Operation: ~p~n" "** Args: ~p~n" "** Reason: ~p~n", [State#state.name, State#state.owner, Operation, Args, Reason]). %%-------------------------------------------------------------------- %%% Tests %%-------------------------------------------------------------------- -define(lookup, dirty_lookup). -define(delete, dirty_delete). -define(insert, dirty_insert). %%-define(lookup, lookup). %%-define(delete, delete). %%-define(insert, insert). test() -> LifeTime = 2, ok = new(test_tbl, [{life_time, LifeTime}, {max_size, unlimited}]), check([]), ok = ?insert(test_tbl, "key", "value", fun() -> ok end), check([{"key", "value"}]), {ok, "value"} = ?lookup(test_tbl, "key", fun() -> error end), check([{"key", "value"}]), io:format("** waiting for ~p seconds to check if LRU works fine...~n", [LifeTime+1]), timer:sleep(timer:seconds(LifeTime+1)), ok = ?insert(test_tbl, "key1", "value1", fun() -> ok end), check([{"key1", "value1"}]), ok = ?delete(test_tbl, "key1", fun() -> ok end), {ok, "value"} = ?lookup(test_tbl, "key", fun() -> {ok, "value"} end), check([{"key", "value"}]), ok = ?delete(test_tbl, "key", fun() -> ok end), check([]), %% io:format("** testing buggy callbacks...~n"), %% delete(test_tbl, "key", fun() -> erlang:error(badarg) end), %% insert(test_tbl, "key", "val", fun() -> erlang:error(badarg) end), %% lookup(test_tbl, "key", fun() -> erlang:error(badarg) end), check([]), delete(test_tbl), test1(). test1() -> MaxSize = 10, ok = new(test_tbl, [{max_size, MaxSize}, {shrink_size, 1}, {warn, false}]), lists:foreach( fun(N) -> ok = ?insert(test_tbl, N, N, fun() -> ok end) end, lists:seq(1, MaxSize*get_proc_num())), {ok, MaxSize} = info(test_tbl, size), delete(test_tbl), test2(). test2() -> LifeTime = 2, ok = new(test_tbl, [{life_time, LifeTime}, {max_size, unlimited}, {lru, false}]), check([]), ok = ?insert(test_tbl, "key", "value", fun() -> ok end), {ok, "value"} = ?lookup(test_tbl, "key", fun() -> error end), check([{"key", "value"}]), io:format("** waiting for ~p seconds to check if non-LRU works fine...~n", [LifeTime+1]), timer:sleep(timer:seconds(LifeTime+1)), error = ?lookup(test_tbl, "key", fun() -> error end), check([{"key", '$cached_mismatch'}]), ok = ?insert(test_tbl, "key", "value1", fun() -> ok end), check([{"key", "value1"}]), delete(test_tbl), io:format("** testing speed, this may take a while...~n"), test3(1000), test3(10000), test3(100000), test3(1000000). test3(Iter) -> ok = new(test_tbl, [{max_size, unlimited}, {life_time, unlimited}]), L = lists:seq(1, Iter), T1 = now(), lists:foreach( fun(N) -> ok = ?insert(test_tbl, N, N, fun() -> ok end) end, L), io:format("** average insert (size = ~p): ~p usec~n", [Iter, round(timer:now_diff(now(), T1)/Iter)]), T2 = now(), lists:foreach( fun(N) -> {ok, N} = ?lookup(test_tbl, N, fun() -> ok end) end, L), io:format("** average lookup (size = ~p): ~p usec~n", [Iter, round(timer:now_diff(now(), T2)/Iter)]), {ok, Iter} = info(test_tbl, size), delete(test_tbl). check(List) -> Size = length(List), {ok, Size} = info(test_tbl, size), List = tab2list(test_tbl). cache_tab-1.0.2/src/cache_tab_sup.erl0000644000232200023220000000335512650725555020046 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab_sup.erl %%% Author : Evgeniy Khramtsov %%% Description : Cache tables supervisor %%% %%% Created : 30 Aug 2010 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%------------------------------------------------------------------- -module(cache_tab_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%==================================================================== %% API functions %%==================================================================== start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%==================================================================== %% Supervisor callbacks %%==================================================================== init([]) -> {ok, {{one_for_one,10,1}, []}}. %%==================================================================== %% Internal functions %%==================================================================== cache_tab-1.0.2/src/cache_tab.app.src0000644000232200023220000000304412650725555017736 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : cache_tab.app.src %%% Author : Evgeniy Khramtsov %%% Purpose : Application package description %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%---------------------------------------------------------------------- {application, cache_tab, [{description, "In-memory cache Erlang / Elixir library"}, {vsn, "1.0.2"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib]}, {mod, {cache_tab_app,[]}}, %% hex.pm packaging: {files, ["src/", "rebar.config", "rebar.config.script", "README.md", "LICENSE.txt"]}, {licenses, ["Apache 2.0"]}, {maintainers, ["ProcessOne"]}, {links, [{"Github", "https://github.com/processone/cache_tab"}]}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: cache_tab-1.0.2/src/cache_tab_app.erl0000644000232200023220000000530712650725555020016 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab_app.erl %%% Author : Evgeniy Khramtsov %%% Description : Cache tab application %%% %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2015 ProcessOne, SARL. All Rights Reserved. %%% %%% Licensed 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. %%% %%%------------------------------------------------------------------- -module(cache_tab_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% Application callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called whenever an application is started using %% application:start/[1,2], and should start the processes of the %% application. If the application is structured according to the OTP %% design principles as a supervision tree, this means starting the %% top supervisor of the tree. %% %% @spec start(StartType, StartArgs) -> {ok, Pid} | %% {ok, Pid, State} | %% {error, Reason} %% StartType = normal | {takeover, Node} | {failover, Node} %% StartArgs = term() %% @end %%-------------------------------------------------------------------- start(_StartType, _StartArgs) -> case cache_tab_sup:start_link() of {ok, Pid} -> {ok, Pid}; Error -> Error end. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called whenever an application has stopped. It %% is intended to be the opposite of Module:start/2 and should do %% any necessary cleaning up. The return value is ignored. %% %% @spec stop(State) -> void() %% @end %%-------------------------------------------------------------------- stop(_State) -> ok. %%%=================================================================== %%% Internal functions %%%=================================================================== cache_tab-1.0.2/Makefile0000644000232200023220000000012312650725555015421 0ustar debalancedebalanceall: src src: rebar get-deps compile clean: rebar clean .PHONY: clean src all