cache_tab-1.0.12/0000755000232200023220000000000013204521352014027 5ustar debalancedebalancecache_tab-1.0.12/LICENSE.txt0000644000232200023220000002613613204521352015662 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.12/README.md0000644000232200023220000000560513204521352015314 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.12/rebar.config.script0000644000232200023220000000773313204521352017626 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : rebar.config.script %%% Author : Evgeniy Khramtsov %%% Purpose : Rebar build script. Compliant with rebar and rebar3. %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% Copyright (C) 2002-2017 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. %%% %%%---------------------------------------------------------------------- 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, JobId = case os:getenv("TRAVIS_JOB_ID") of false -> ""; V -> V end, 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, ModCfgS = fun(Cfg, Keys, Val) -> ModCfg0(ModCfg0, Cfg, Keys, fun(_V) -> Val end, "") end, FilterConfig = fun(F, Cfg, [{Path, true, ModFun, Default} | Tail]) -> F(F, ModCfg0(ModCfg0, Cfg, Path, ModFun, Default), Tail); (F, Cfg, [_ | Tail]) -> F(F, Cfg, Tail); (F, Cfg, []) -> Cfg end, AppendStr = fun(Append) -> fun("") -> Append; (Val) -> Val ++ " " ++ Append end end, AppendList = fun(Append) -> fun(Val) -> Val ++ Append end end, Rebar3DepsFilter = fun(DepsList) -> lists:map(fun({DepName,_, {git,_, {tag,Version}}}) -> {DepName, Version}; (Dep) -> Dep end, DepsList) end, GlobalDepsFilter = fun(Deps) -> DepNames = lists:map(fun({DepName, _, _}) -> DepName; ({DepName, _}) -> DepName end, Deps), lists:filtermap(fun(Dep) -> case code:lib_dir(Dep) of {error, _} -> {true,"Unable to locate dep '"++atom_to_list(Dep)++"' in system deps."}; _ -> false end end, DepNames) end, Rules = [ {[deps], IsRebar3, Rebar3DepsFilter, []}, {[plugins], IsRebar3, AppendList([rebar3_hex, pc]), []}, {[provider_hooks], IsRebar3, AppendList([{pre, [ {compile, {pc, compile}}, {clean, {pc, clean}} ]}]), []}, {[deps], os:getenv("TRAVIS") == "true", AppendList([{coveralls, ".*", {git, "https://github.com/markusn/coveralls-erl.git", "master"}}]), []}, {[post_hooks], os:getenv("TRAVIS") == "true", AppendList([{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"}]), []}, {[deps], os:getenv("USE_GLOBAL_DEPS") /= false, GlobalDepsFilter, []} ], Config = FilterConfig(FilterConfig, CONFIG, Rules), %io:format("Rules:~n~p~n~nCONFIG:~n~p~n~nConfig:~n~p~n", [Rules, CONFIG, Config]), Config. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: cache_tab-1.0.12/CHANGELOG.md0000644000232200023220000000172213204521352015642 0ustar debalancedebalance# Version 1.0.12 * Treat {error, notfound} callback result as a lookup mismatch # Version 1.0.11 * Updating p1_utils to version 1.0.10. # Version 1.0.10 * Fix hex packaging # Version 1.0.9 * Make sure we publish include dir on hex.pm # Version 1.0.8 * Make rebar.config.script more structured and fix problem with coveralls * Add new cache implementation on top of ETS * Introduce lookup/2 insert/3,4 insert_new/3,4 calls * Export clear/2 * Store ets_cache options globally * Add start/0 and stop/0 functions for convenience * Rewrite ets_cache module * Fix info/1 * Don't crash if counter doesn't exist # Version 1.0.7 * Use p1_utils v1.0.7 # Version 1.0.6 * Add dirty_dist_insert and dirty_dist_delete calls (Alexey Shchepin) # Version 1.0.5 * Use p1_utils v1.0.6 (Christophe Romain) # Version 1.0.4 * Use p1_utils v1.0.5 (Mickaël Rémond) # Version 1.0.3 * Use p1_utils v1.0.4 (Mickaël Rémond) # Version 1.0.2 * Use p1_utils v1.0.3 (Mickaël Rémond) cache_tab-1.0.12/Makefile0000644000232200023220000000017513204521352015472 0ustar debalancedebalanceall: src src: rebar get-deps compile clean: rebar clean test: all rebar -v skip_deps=true eunit .PHONY: clean src all cache_tab-1.0.12/c_src/0000755000232200023220000000000013204521352015120 5ustar debalancedebalancecache_tab-1.0.12/c_src/ets_cache.c0000644000232200023220000000727313204521352017213 0ustar debalancedebalance/* * Author: Evgeny Khramtsov * Created : 26 Apr 2017 by Evgeny Khramtsov * * * Copyright (C) 2002-2017 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. * */ #include #include #include #include #define MAX_UINT64 ((ErlNifUInt64) -1) static unsigned int max_counters = 0; static unsigned int counters_num = 0; static ErlNifUInt64 *counters = NULL; static ErlNifMutex *counters_lock = NULL; static int load(ErlNifEnv* env, void** priv, ERL_NIF_TERM max) { size_t size; if (enif_get_uint(env, max, &max_counters)) { size = sizeof(ErlNifUInt64) * max_counters; if ((counters = enif_alloc(size))) { memset(counters, -1, size); counters_num = 0; counters_lock = enif_mutex_create("counters_lock"); return 0; } } return ENOMEM; } static void unload(ErlNifEnv* env, void* priv) { if (counters_lock) enif_mutex_destroy(counters_lock); if (counters) enif_free(counters); } static ERL_NIF_TERM new_counter(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { unsigned int counter; enif_mutex_lock(counters_lock); if (counters_num < max_counters) { counter = counters_num++; counters[counter] = 0; enif_mutex_unlock(counters_lock); return enif_make_tuple2(env, enif_make_atom(env, "ok"), enif_make_ulong(env, counter)); } else { for (counter = 0; counter < max_counters; counter++) { if (counters[counter] == MAX_UINT64) { counters[counter] = 0; enif_mutex_unlock(counters_lock); return enif_make_tuple2(env, enif_make_atom(env, "ok"), enif_make_ulong(env, counter)); } } enif_mutex_unlock(counters_lock); return enif_make_tuple2(env, enif_make_atom(env, "error"), enif_make_tuple2(env, enif_make_atom(env, "system_limit"), enif_make_uint(env, max_counters))); } } static ERL_NIF_TERM delete_counter(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { unsigned int counter; if (enif_get_uint(env, argv[0], &counter)) if (counter < max_counters) { counters[counter] = MAX_UINT64; return enif_make_atom(env, "ok"); } return enif_make_badarg(env); } static ERL_NIF_TERM incr_counter(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { unsigned int counter; if (enif_get_uint(env, argv[0], &counter)) if (counter < max_counters) { if (counters[counter] != MAX_UINT64) return enif_make_uint64(env, __sync_add_and_fetch(counters + counter, 1)); } return enif_make_badarg(env); } static ERL_NIF_TERM get_counter(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { unsigned int counter; ErlNifUInt64 val; if (enif_get_uint(env, argv[0], &counter)) if (counter < max_counters) { val = counters[counter]; if (val != MAX_UINT64) return enif_make_uint64(env, val); } return enif_make_badarg(env); } static ErlNifFunc nif_funcs[] = { {"new_counter_nif", 0, new_counter}, {"delete_counter_nif", 1, delete_counter}, {"incr_counter_nif", 1, incr_counter}, {"get_counter_nif", 1, get_counter} }; ERL_NIF_INIT(ets_cache, nif_funcs, load, NULL, NULL, unload) cache_tab-1.0.12/src/0000755000232200023220000000000013204521352014616 5ustar debalancedebalancecache_tab-1.0.12/src/ets_cache_options.erl0000644000232200023220000000324313204521352021015 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% Created : 24 Apr 2017 by Evgeny Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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(ets_cache_options). %% API -export([max_size/1, life_time/1, cache_missed/1, counter/1]). %%%=================================================================== %%% API %%%=================================================================== -spec max_size(atom()) -> {ok, pos_integer() | infinity}. max_size(_) -> {ok, infinity}. -spec life_time(atom()) -> {ok, pos_integer() | infinity}. life_time(_) -> {ok, infinity}. -spec cache_missed(atom()) -> {ok, boolean()}. cache_missed(_) -> {ok, true}. -spec counter(non_neg_integer()) -> {ok, non_neg_integer()} | undefined. counter(_) -> undefined. %%%=================================================================== %%% Internal functions %%%=================================================================== cache_tab-1.0.12/src/cache_tab_sup.erl0000644000232200023220000000335513204521352020110 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab_sup.erl %%% Author : Evgeniy Khramtsov %%% Description : Cache tables supervisor %%% %%% Created : 30 Aug 2010 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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.12/src/cache_tab.app.src0000644000232200023220000000310613204521352017777 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : cache_tab.app.src %%% Author : Evgeniy Khramtsov %%% Purpose : Application package description %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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.12"}, {modules, []}, {registered, []}, {applications, [kernel, stdlib]}, {mod, {cache_tab_app,[]}}, %% hex.pm packaging: {files, ["src/", "include/", "c_src/ets_cache.c", "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.12/src/cache_tab.erl0000644000232200023220000003604413204521352017222 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab.erl %%% Author : Evgeniy Khramtsov %%% Description : Caching key-value table %%% %%% Created : 29 Aug 2010 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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/0, stop/0]). -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_insert/3, dirty_dist_insert/4, dirty_delete/3, dirty_delete/2, dirty_dist_delete/3, all/0, clean/1]). %% 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() -> application:start(?MODULE). stop() -> application:stop(?MODULE). 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). dirty_delete(Tab, Key) -> ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {cache_delete, Key}, ?CALL_TIMEOUT). dirty_dist_delete(Tab, Key, F) -> F(), rpc:eval_everywhere( cache_tab_app:get_nodes() -- [node()], ?MODULE, dirty_delete, [Tab, Key]), dirty_delete(Tab, Key). 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). dirty_insert(Tab, Key, Val) -> ?GEN_SERVER:call( get_proc_by_hash(Tab, Key), {cache_insert, Key, Val}, ?CALL_TIMEOUT). dirty_dist_insert(Tab, Key, Val, F) -> F(), rpc:eval_everywhere( cache_tab_app:get_nodes() -- [node()], ?MODULE, dirty_insert, [Tab, Key, Val]), dirty_insert(Tab, Key, Val). 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() -> -p1_time_compat:system_time(micro_seconds). 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{warn = false}) -> ok; 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]). cache_tab-1.0.12/src/cache_tab_app.erl0000644000232200023220000000640413204521352020057 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab_app.erl %%% Author : Evgeniy Khramtsov %%% Description : Cache tab application %%% %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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, get_nodes/0]). -define(PG, cache_tab). -include("ets_cache.hrl"). %%%=================================================================== %%% 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} -> pg2:create(?PG), pg2:join(?PG, Pid), application:start(p1_utils), init_ets_cache_options(), {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. get_nodes() -> [node(P) || P <- pg2:get_members(?PG)]. %%%=================================================================== %%% Internal functions %%%=================================================================== init_ets_cache_options() -> p1_options:start_link(ets_cache_options), p1_options:insert(ets_cache_options, max_size, global, ?DEFAULT_MAX_SIZE), p1_options:insert(ets_cache_options, life_time, global, ?DEFAULT_LIFE_TIME), p1_options:insert(ets_cache_options, cache_missed, global, ?DEFAULT_CACHE_MISSED). cache_tab-1.0.12/src/ets_cache.erl0000644000232200023220000004555013204521352017251 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% Created : 12 Apr 2017 by Evgeny Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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(ets_cache). -behaviour(gen_server). %% API -export([new/1, new/2, start_link/2, delete/1, delete/2, delete/3, lookup/2, lookup/3, insert_new/3, insert_new/4, update/4, update/5, setopts/2, clear/1, clear/2, clean/1, clean/2, filter/2, fold/3, all/0, info/1, info/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% Counters: for tests *only*, don't use them outside this module -export([new_counter/0, get_counter/1, incr_counter/1, delete_counter/1, new_counter_nif/0, get_counter_nif/1, incr_counter_nif/1, delete_counter_nif/1]). -on_load(load_nif/0). -include_lib("stdlib/include/ms_transform.hrl"). -record(state, {tab :: atom(), clean_timer :: reference(), counter :: counter() | undefined, cache_missed = true :: boolean(), life_time = infinity :: milli_seconds() | infinity, max_size = infinity :: pos_integer() | infinity}). -define(DEFAULT_MAX_CACHE_TABLES, 1024). -define(IS_EXPIRED(Time, LifeTime, CurrTime), (is_integer(LifeTime) andalso (Time + LifeTime =< CurrTime))). -type counter() :: non_neg_integer(). -type milli_seconds() :: pos_integer(). -type option() :: {max_size, pos_integer() | infinity} | {life_time, milli_seconds() | infinity} | {cache_missed, boolean()}. -type read_fun() :: fun(() -> {ok, any()} | error). -type update_fun() :: fun(() -> ok | {ok, any()} | error). -type filter_fun() :: fun((any(), {ok, any()} | error) -> boolean()). -type fold_fun() :: fun((any(), {ok, any()} | error, any()) -> any()). -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== start_link(Name, Opts) -> gen_server:start_link({local, Name}, ?MODULE, [Name, Opts], []). -spec new(atom()) -> ok. new(Name) -> new(Name, []). -spec new(atom(), [option()]) -> ok. new(Name, Opts) -> Opts1 = check_opts(Opts), case whereis(Name) of undefined -> Spec = {Name, {?MODULE, start_link, [Name, Opts1]}, transient, 5000, worker, [?MODULE]}, case supervisor:start_child(cache_tab_sup, Spec) of {ok, _Pid} -> ok; {error, {already_started, _}} -> setopts(Name, Opts1); {error, Err} -> erlang:error(Err) end; _ -> setopts(Name, Opts1) end. -spec setopts(atom(), [option()]) -> ok. setopts(Name, Opts) -> Opts1 = check_opts(Opts), gen_server:cast(Name, {setopts, Opts1}). -spec delete(atom()) -> ok. delete(Name) -> supervisor:terminate_child(cache_tab_sup, Name), supervisor:delete_child(cache_tab_sup, Name), ok. -spec delete(atom(), any()) -> ok. delete(Name, Key) -> delete(Name, Key, [node()]). -spec delete(atom(), any(), [atom()]) -> ok. delete(Name, Key, Nodes) -> lists:foreach( fun(Node) when Node /= node() -> send({Name, Node}, {delete, Key}); (_MyNode) -> ets_delete(Name, Key) end, Nodes). insert_new(Name, Key, Val) -> insert_new(Name, Key, Val, [node()]). insert_new(Name, Key, Val, Nodes) -> CurrTime = current_time(), Obj = {Key, {ok, Val}, CurrTime}, lists:foldl( fun(Node, Result) when Node /= node() -> send({Name, Node}, {insert_new, Obj}), Result; (_, _) -> try ets:lookup(Name, Key) of [Old] -> case delete_if_expired(Name, Old, CurrTime) of true -> do_insert(new, Name, Obj); false -> false end; [] -> do_insert(new, Name, Obj) catch _:badarg -> false end end, false, Nodes). -spec lookup(atom(), any()) -> {ok, any()} | any(). lookup(Name, Key) -> lookup(Name, Key, undefined). -spec lookup(atom(), any(), read_fun() | undefined) -> {ok, any()} | any(). lookup(Name, Key, ReadFun) -> try ets:lookup(Name, Key) of [{_, Val, _} = Obj] -> delete_if_expired(Name, Obj), Val; [] when ReadFun /= undefined -> Ver = get_counter(Name), Val = case ReadFun() of {ok, Val1} -> {ok, Val1}; error -> error; {error, notfound} -> error; Other -> {error, Other} end, case Val of {error, Reason} -> Reason; _ -> case get_counter(Name) of Ver -> do_insert(new, Name, {Key, Val, current_time()}); _ -> ok end, Val end; [] -> error catch _:badarg when ReadFun /= undefined -> ReadFun(); _:badarg -> error end. -spec update(atom(), any(), {ok, any()} | error, update_fun()) -> ok | any(). update(Name, Key, Val, UpdateFun) -> update(Name, Key, Val, UpdateFun, [node()]). -spec update(atom(), any(), {ok, any()} | error, update_fun(), [node()]) -> ok | any(). update(Name, Key, Val, UpdateFun, Nodes) -> NeedUpdate = try ets:lookup(Name, Key) of [{_, Val, _} = Obj] -> delete_if_expired(Name, Obj); _ -> true catch _:badarg -> true end, if NeedUpdate -> NewVal = case UpdateFun() of ok -> Val; {ok, Val1} -> {ok, Val1}; error -> error; {error, notfound} -> error; Other -> {error, Other} end, case NewVal of {error, Reason} -> Reason; _ -> lists:foreach( fun(Node) when Node /= node() -> send({Name, Node}, {delete, Key}); (_) -> do_insert(replace, Name, {Key, NewVal, current_time()}) end, Nodes), NewVal end; true -> Val end. -spec clear(atom()) -> ok. clear(Name) -> clear(Name, [node()]). -spec clear(atom(), [atom()]) -> ok. clear(Name, Nodes) -> lists:foreach( fun(Node) when Node /= node() -> send({Name, Node}, clear); (_MyNode) -> ets_delete_all_objects(Name) end, Nodes). -spec clean(atom()) -> ok. clean(Name) -> clean(Name, [node()]). -spec clean(atom(), [node()]) -> ok. clean(Name, Nodes) -> lists:foreach( fun(Node) -> send({Name, Node}, clean) end, Nodes). -spec filter(atom(), filter_fun()) -> non_neg_integer(). filter(Name, FilterFun) -> case whereis(Name) of undefined -> 0; _ -> {ok, LifeTime} = ets_cache_options:life_time(Name), CurrTime = current_time(), ets_safe_fixtable(Name, true), Num = do_filter(Name, FilterFun, LifeTime, CurrTime, 0, ets_first(Name)), ets_safe_fixtable(Name, false), Num end. -spec fold(fold_fun(), any(), atom()) -> any(). fold(FoldFun, Acc, Name) -> case whereis(Name) of undefined -> Acc; _ -> {ok, LifeTime} = ets_cache_options:life_time(Name), CurrTime = current_time(), ets_safe_fixtable(Name, true), NewAcc = do_fold(Name, FoldFun, LifeTime, CurrTime, Acc, ets_first(Name)), ets_safe_fixtable(Name, false), NewAcc end. -spec all() -> [atom()]. all() -> [Child || {Child, _, _, [?MODULE]} <- supervisor:which_children(cache_tab_sup)]. -spec info(atom()) -> [proplists:property()]. info(Name) -> case ets:info(Name) of undefined -> []; ETSInfo -> {ok, MaxSize} = ets_cache_options:max_size(Name), {ok, CacheMissed} = ets_cache_options:cache_missed(Name), {ok, LifeTime} = ets_cache_options:life_time(Name), [{max_size, MaxSize}, {cache_missed, CacheMissed}, {life_time, LifeTime} |lists:filtermap( fun({memory, V}) -> {true, {memory, V * erlang:system_info(wordsize)}}; ({owner, _}) -> true; ({name, _}) -> true; ({size, _}) -> true; (_) -> false end, ETSInfo)] end. -spec info(atom(), atom()) -> any(). info(Name, Option) -> Options = info(Name), case lists:keyfind(Option, 1, Options) of {_, Value} -> Value; _ -> erlang:error(badarg) end. load_nif() -> Path = p1_nif_utils:get_so_path(?MODULE, [?MODULE], atom_to_list(?MODULE)), MaxTables = get_max_tables(), case erlang:load_nif(Path, MaxTables) of ok -> ok; {error, {Reason, Text}} -> error_logger:error_msg("Failed to load NIF ~s: ~s (~p)", [Path, Text, Reason]), erlang:nif_error(Reason) end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== init([Name, Opts]) -> process_flag(trap_exit, true), ets:new(Name, [named_table, public, {read_concurrency, true}]), Counter = new_counter(), TRef = start_clean_timer(), State = #state{tab = Name, clean_timer = TRef}, {ok, do_setopts(State, [{counter, Counter}|Opts])}. handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. handle_cast({setopts, Opts}, State) -> {noreply, do_setopts(State, Opts)}; handle_cast(_Msg, State) -> {noreply, State}. handle_info({insert_new, {Key, _, CurrTime} = New}, #state{tab = Tab} = State) -> case ets:lookup(Tab, Key) of [Old] -> case delete_if_expired(Tab, Old, CurrTime) of true -> do_insert(new, Tab, New); false -> ok end; [] -> do_insert(new, Tab, New) end, {noreply, State}; handle_info({delete, Key}, #state{tab = Tab} = State) -> ets_delete(Tab, Key), {noreply, State}; handle_info(clear, #state{tab = Tab} = State) -> ets_delete_all_objects(Tab), {noreply, State}; handle_info(clean, #state{clean_timer = TRef} = State) -> clean_expired(State), NewTRef = start_clean_timer(TRef), {noreply, State#state{clean_timer = NewTRef}}; handle_info(table_overflow, #state{tab = Tab, max_size = MaxSize} = State) -> case ets:info(Tab, size) of N when N >= MaxSize -> error_logger:warning_msg( "Shrinking cache '~s' (current size = ~B, max size = ~B, " "life time = ~p, memory = ~B bytes); you should increase maximum " "cache size if this message repeats too often", [Tab, N, MaxSize, State#state.life_time, ets:info(Tab, memory) * erlang:system_info(wordsize)]), ets_delete_all_objects(Tab); _ -> ok end, {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, #state{tab = Tab}) -> delete_counter(Tab). code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== -spec check_size(atom(), pos_integer() | infinity) -> ok. check_size(_Tab, infinity) -> ok; check_size(Tab, MaxSize) -> try ets:info(Tab, size) of N when N >= MaxSize -> send({Tab, node()}, table_overflow); _ -> ok catch _:badarg -> ok end. do_insert(Op, Name, Obj) -> {ok, CacheMissed} = ets_cache_options:cache_missed(Name), {ok, MaxSize} = ets_cache_options:max_size(Name), do_insert(Op, Name, Obj, CacheMissed, MaxSize). do_insert(_Op, _Name, {_Key, error, _Time}, _CacheMissed = false, _MaxSize) -> false; do_insert(Op, Name, Obj, _CacheMissed, MaxSize) -> check_size(Name, MaxSize), try case Op of new -> ets:insert_new(Name, Obj); replace -> ets:insert(Name, Obj) end catch _:badarg -> false end. -spec do_filter(atom(), filter_fun(), pos_integer() | infinity, integer(), non_neg_integer(), any()) -> non_neg_integer(). do_filter(_Name, _FilterFun, _LifeTime, _CurrTime, Num, '$end_of_table') -> Num; do_filter(Name, FilterFun, LifeTime, CurrTime, Num, Key) -> NewNum = try ets:lookup(Name, Key) of [{Key, Val, Time}] -> if ?IS_EXPIRED(Time, LifeTime, CurrTime) -> ets_delete_object(Name, {Key, Val, Time}), Num; true -> case FilterFun(Key, Val) of true -> Num; false -> ets_delete_object(Name, {Key, Val, Time}), Num + 1 end end; _ -> Num catch _:badarg -> Num end, do_filter(Name, FilterFun, LifeTime, CurrTime, NewNum, ets_next(Name, Key)). -spec do_fold(atom(), fold_fun(), pos_integer() | infinity, integer(), any(), any()) -> any(). do_fold(_Name, _FoldFun, _LifeTime, _CurrTime, Acc, '$end_of_table') -> Acc; do_fold(Name, FoldFun, LifeTime, CurrTime, Acc, Key) -> NewAcc = try ets:lookup(Name, Key) of [{Key, Val, Time}] -> if ?IS_EXPIRED(Time, LifeTime, CurrTime) -> ets_delete_object(Name, {Key, Val, Time}), Acc; true -> FoldFun(Key, Val, Acc) end; _ -> Acc catch _:badarg -> Acc end, do_fold(Name, FoldFun, LifeTime, CurrTime, NewAcc, ets_next(Name, Key)). -spec check_opts([option()]) -> [option()]. check_opts(Opts) -> lists:map( fun({Name, Val} = Opt) -> case {Name, Val} of {max_size, Val} when is_integer(Val), Val>0 -> Opt; {max_size, infinity} -> Opt; {life_time, Val} when is_integer(Val), Val>0 -> Opt; {life_time, infinity} -> Opt; {cache_missed, Bool} when is_boolean(Bool) -> Opt; _ -> erlang:error({bad_option, Opt}) end end, Opts). -spec do_setopts(state(), [{counter, counter()} | option()]) -> state(). do_setopts(State, Opts) -> MaxSize = proplists:get_value(max_size, Opts, State#state.max_size), LifeTime = proplists:get_value(life_time, Opts, State#state.life_time), CacheMissed = proplists:get_value(cache_missed, Opts, State#state.cache_missed), Counter = proplists:get_value(counter, Opts, State#state.counter), NewState = State#state{max_size = MaxSize, counter = Counter, life_time = LifeTime, cache_missed = CacheMissed}, if State == NewState -> ok; true -> Tab = State#state.tab, p1_options:insert(ets_cache_options, max_size, Tab, MaxSize), p1_options:insert(ets_cache_options, life_time, Tab, LifeTime), p1_options:insert(ets_cache_options, cache_missed, Tab, CacheMissed), p1_options:insert(ets_cache_options, counter, Tab, Counter), p1_options:compile(ets_cache_options) end, NewState. -spec current_time() -> integer(). current_time() -> p1_time_compat:monotonic_time(milli_seconds). -spec start_clean_timer() -> reference(). start_clean_timer() -> start_clean_timer(make_ref()). -spec start_clean_timer(reference()) -> reference(). start_clean_timer(TRef) -> case erlang:cancel_timer(TRef) of false -> receive {timeout, TRef, _} -> ok after 0 -> ok end; _ -> ok end, Timeout = crypto:rand_uniform(timer:minutes(1), timer:minutes(5)), erlang:send_after(Timeout, self(), clean). -spec clean_expired(state()) -> non_neg_integer(). clean_expired(#state{tab = Tab, life_time = LifeTime}) -> CurrTime = current_time(), ets_select_delete( Tab, ets:fun2ms( fun({_, _, Time}) -> ?IS_EXPIRED(Time, LifeTime, CurrTime) end)). delete_if_expired(Name, Obj) -> case ets_cache_options:life_time(Name) of {ok, infinity} -> false; {ok, LifeTime} -> delete_if_expired(Name, Obj, current_time(), LifeTime) end. delete_if_expired(Name, Obj, CurrTime) -> {ok, LifeTime} = ets_cache_options:life_time(Name), delete_if_expired(Name, Obj, CurrTime, LifeTime). delete_if_expired(Name, {_, _, Time} = Obj, CurrTime, LifeTime) -> if ?IS_EXPIRED(Time, LifeTime, CurrTime) -> ets_delete_object(Name, Obj); true -> false end. send(Dst, Msg) -> erlang:send(Dst, Msg, [noconnect, nosuspend]). -spec ets_delete(atom(), any()) -> boolean(). ets_delete(Tab, Key) -> try incr_counter(Tab), ets:delete(Tab, Key) catch _:badarg -> false; _:{badmatch, undefined} -> false end. -spec ets_delete_object(atom(), any()) -> boolean(). ets_delete_object(Tab, Obj) -> try incr_counter(Tab), ets:delete_object(Tab, Obj) catch _:badarg -> false; _:{badmatch, undefined} -> false end. -spec ets_delete_all_objects(atom()) -> boolean(). ets_delete_all_objects(Tab) -> try incr_counter(Tab), ets:delete_all_objects(Tab) catch _:badarg -> false; _:{badmatch, undefined} -> false end. -spec ets_select_delete(atom(), fun()) -> non_neg_integer(). ets_select_delete(Tab, Fun) -> try incr_counter(Tab), ets:select_delete(Tab, Fun) catch _:badarg -> 0 end. -spec ets_first(atom()) -> any(). ets_first(Tab) -> try ets:first(Tab) catch _:badarg -> '$end_of_table' end. -spec ets_next(atom(), any()) -> any(). ets_next(Tab, Key) -> try ets:next(Tab, Key) catch _:badarg -> '$end_of_table' end. -spec ets_safe_fixtable(atom(), boolean()) -> boolean(). ets_safe_fixtable(Tab, Fix) -> try ets:safe_fixtable(Tab, Fix) catch _:badarg -> false end. get_max_tables() -> case application:get_env(cache_tab, max_cache_tables) of undefined -> ?DEFAULT_MAX_CACHE_TABLES; {ok, I} when is_integer(I), I > 0 -> I; {ok, Val} -> error_logger:error_msg( "Incorrect value of 'max_cache_tables' " "application parameter: ~p", [Val]), ?DEFAULT_MAX_CACHE_TABLES end. %%%=================================================================== %%% Counters %%%=================================================================== -spec new_counter() -> counter(). new_counter() -> case new_counter_nif() of {ok, Counter} -> Counter; {error, {system_limit, MaxTables}} -> error_logger:error_msg( "Maximum number (~B) of ETS cache tables has reached", [MaxTables]), erlang:error(system_limit) end. -spec get_counter(atom()) -> non_neg_integer(). get_counter(Name) -> {ok, Counter} = ets_cache_options:counter(Name), get_counter_nif(Counter). -spec incr_counter(atom()) -> non_neg_integer(). incr_counter(Name) -> {ok, Counter} = ets_cache_options:counter(Name), incr_counter_nif(Counter). -spec delete_counter(counter()) -> ok. delete_counter(Name) -> {ok, Counter} = ets_cache_options:counter(Name), delete_counter_nif(Counter). -spec new_counter_nif() -> {ok, counter()} | {error, {system_limit, pos_integer()}}. new_counter_nif() -> erlang:nif_error({nif_not_loaded, ?MODULE}). -spec get_counter_nif(counter()) -> non_neg_integer(). get_counter_nif(_) -> erlang:nif_error({nif_not_loaded, ?MODULE}). -spec incr_counter_nif(counter()) -> non_neg_integer(). incr_counter_nif(_) -> erlang:nif_error({nif_not_loaded, ?MODULE}). -spec delete_counter_nif(counter()) -> ok. delete_counter_nif(_) -> erlang:nif_error({nif_not_loaded, ?MODULE}). cache_tab-1.0.12/.travis.yml0000644000232200023220000000055313204521352016143 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.12/rebar.config0000644000232200023220000000275213204521352016317 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-2017 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.10"}}}]}. {port_specs, [{"priv/lib/ets_cache.so", ["c_src/ets_cache.c"]}]}. {port_env, [{"CFLAGS", "$CFLAGS -g -O2 -Wall"}]}. {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.12/include/0000755000232200023220000000000013204521352015452 5ustar debalancedebalancecache_tab-1.0.12/include/ets_cache.hrl0000644000232200023220000000201413204521352020074 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% Created : 24 Apr 2017 by Evgeny Khramtsov %%% %%% %%% Copyright (C) 2002-2017 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. %%% %%%------------------------------------------------------------------- -define(DEFAULT_MAX_SIZE, infinity). -define(DEFAULT_LIFE_TIME, infinity). -define(DEFAULT_CACHE_MISSED, true). cache_tab-1.0.12/test/0000755000232200023220000000000013204521352015006 5ustar debalancedebalancecache_tab-1.0.12/test/cache_tab_test.erl0000644000232200023220000002003513204521352020442 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-2017 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"). get_proc_num() -> case catch erlang:system_info(logical_processors) of Num when is_integer(Num) -> Num; _ -> 1 end. start_test() -> ?assertEqual(ok, application:start(cache_tab)). dirty_insert_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual(ok, cache_tab:dirty_insert(test_tbl, 1, a, fun() -> ok end)), ?assertEqual({ok, a}, cache_tab:dirty_lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). dirty_delete_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual(ok, cache_tab:dirty_insert(test_tbl, 1, a, fun() -> ok end)), ?assertEqual(ok, cache_tab:dirty_delete(test_tbl, 1, fun() -> ok end)), ?assertEqual(error, cache_tab:dirty_lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). insert_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual(ok, cache_tab:insert(test_tbl, 1, a, fun() -> ok end)), ?assertEqual({ok, a}, cache_tab:lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). double_insert_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual(ok, cache_tab:insert(test_tbl, 1, a, fun() -> ok end)), ?assertEqual({ok, a}, cache_tab:lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:insert(test_tbl, 1, a, fun() -> ok end)), ?assertEqual({ok, a}, cache_tab:lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). insert_bad_fun_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [{warn, false}])), ?assertEqual(ok, cache_tab:insert(test_tbl, 1, a, fun() -> erlang:error(test_error) end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). delete_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual(ok, cache_tab:insert(test_tbl, 1, a, fun() -> ok end)), ?assertEqual(ok, cache_tab:delete(test_tbl, 1, fun() -> ok end)), ?assertEqual(error, cache_tab:lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). delete_bad_fun_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [{warn, false}])), ?assertEqual(ok, cache_tab:delete(test_tbl, 1, fun() -> erlang:error(test_error) end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). clean_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual(ok, cache_tab:dirty_insert(test_tbl, 1, a, fun() -> ok end)), {ok, 1} = cache_tab:info(test_tbl, size), ?assertEqual(ok, cache_tab:clean(test_tbl)), {ok, 0} = cache_tab:info(test_tbl, size), ?assertEqual(ok, cache_tab:delete(test_tbl)). dirty_lookup_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual( {ok, a}, cache_tab:dirty_lookup(test_tbl, 1, fun() -> {ok, a} end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). lookup_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual( {ok, a}, cache_tab:lookup(test_tbl, 1, fun() -> {ok, a} end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). lookup_bad_fun_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [{warn, false}])), ?assertEqual( error, cache_tab:lookup(test_tbl, 1, fun() -> erlang:error(test_error) end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). tab2list_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), KeyVals = lists:zip(lists:seq(1, 10), lists:seq(1, 10)), lists:foreach( fun({K, V}) -> ?assertEqual(ok, cache_tab:insert(test_tbl, K, V, fun() -> ok end)) end, KeyVals), ?assertEqual(KeyVals, lists:sort(cache_tab:tab2list(test_tbl))), ?assertEqual(ok, cache_tab:delete(test_tbl)). all_test() -> Tabs = [tab1, tab2, tab3], lists:foreach( fun(Tab) -> ?assertEqual(ok, cache_tab:new(Tab, [])) end, Tabs), ?assertEqual(Tabs, cache_tab:all()), lists:foreach( fun(Tab) -> ?assertEqual(ok, cache_tab:delete(Tab)) end, Tabs). size_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), lists:foreach( fun(I) -> ?assertEqual(ok, cache_tab:dirty_insert(test_tbl, I, I, fun() -> ok end)) end, lists:seq(1, 10)), ?assertEqual({ok, 10}, cache_tab:info(test_tbl, size)), ?assertEqual(ok, cache_tab:delete(test_tbl)). ratio_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), lists:foreach( fun(I) -> ?assertEqual( {ok, I}, cache_tab:dirty_lookup(test_tbl, I, fun() -> {ok, I} end)), ?assertEqual( {ok, I}, cache_tab:dirty_lookup(test_tbl, I, fun() -> {ok, I} end)) end, lists:seq(1, 10)), {ok, Opts} = cache_tab:info(test_tbl, ratio), ?assertEqual(10, proplists:get_value(hits, Opts)), ?assertEqual(10, proplists:get_value(miss, Opts)), ?assertEqual(ok, cache_tab:delete(test_tbl)). all_info_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertMatch({ok, _}, cache_tab:info(test_tbl, all)), ?assertEqual(ok, cache_tab:delete(test_tbl)). wrong_option_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), ?assertEqual({error, badarg}, cache_tab:info(test_tbl, foo)), ?assertEqual(ok, cache_tab:delete(test_tbl)). collect_sum(Sum) -> receive I when is_integer(I) -> collect_sum(Sum + 1) after 0 -> Sum end. dirty_cache_missed_enabled_test() -> cache_missed_enabled(dirty_lookup). cache_missed_enabled_test() -> cache_missed_enabled(lookup). cache_missed_enabled(F) -> ?assertEqual(ok, cache_tab:new(test_tbl, [])), Self = self(), lists:foreach( fun(_) -> ?assertEqual( error, cache_tab:F( test_tbl, 1, fun() -> Self ! 1 end)) end, lists:seq(1, 10)), ?assertEqual(1, collect_sum(0)), ?assertEqual(ok, cache_tab:delete(test_tbl)). dirty_cache_missed_disabled_test() -> cache_missed_disabled(dirty_lookup). cache_missed_disabled_test() -> cache_missed_disabled(lookup). cache_missed_disabled(F) -> ?assertEqual(ok, cache_tab:new(test_tbl, [{cache_missed, false}])), Self = self(), lists:foreach( fun(_) -> ?assertEqual( error, cache_tab:F( test_tbl, 1, fun() -> Self ! 1 end)) end, lists:seq(1, 10)), ?assertEqual(10, collect_sum(0)), ?assertEqual(ok, cache_tab:delete(test_tbl)). lifetime_with_lru_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [{life_time, 1}])), ?assertEqual(ok, cache_tab:dirty_insert(test_tbl, 1, a, fun() -> ok end)), timer:sleep(timer:seconds(2)), ?assertEqual({ok, a}, cache_tab:dirty_lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)). lifetime_without_lru_test() -> ?assertEqual(ok, cache_tab:new(test_tbl, [{life_time, 1}, {lru, false}])), ?assertEqual(ok, cache_tab:dirty_insert(test_tbl, 1, a, fun() -> ok end)), timer:sleep(timer:seconds(2)), ?assertEqual(error, cache_tab:dirty_lookup(test_tbl, 1, fun() -> error end)), ?assertEqual(ok, cache_tab:delete(test_tbl)).