cache_tab-1.0.21/0000755000232200023220000000000013605316475014044 5ustar debalancedebalancecache_tab-1.0.21/LICENSE.txt0000644000232200023220000002613613605316475015677 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.21/README.md0000644000232200023220000000562413605316475015332 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 -pa deps/*/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.21/rebar.config.script0000644000232200023220000000772113605316475017640 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-2019 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|_] = 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.21/CHANGELOG.md0000644000232200023220000000337313605316475015663 0ustar debalancedebalance# Version 1.0.21 * Updating p1_utils to version 1.0.17. # Version 1.0.20 * Updating p1_utils to version 1.0.16. * Make it possible to set type of the ets\_cache * Add cache support for grow-only counters * Export ets\_cache:tag() type # Version 1.0.19 * Updating p1_utils to version 1.0.15. * Expand ets\_cache API # Version 1.0.18 * Updating p1_utils to version 1.0.14. * Add contribution guide # Version 1.0.17 * Add ets\_cache:insert/3,4 functions # Version 1.0.16 * Updating p1_utils to version 1.0.13. # Version 1.0.15 * Updating p1_utils to version 6ff85e8. * Don't compile ets\_cache to native code * Use rand:unifor instead of crypto module # Version 1.0.14 * Updating p1_utils to version 1.0.12. # Version 1.0.13 * Updating p1_utils to version 1.0.11. * Fix compilation with rebar3 # 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.21/Makefile0000644000232200023220000000017513605316475015507 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.21/c_src/0000755000232200023220000000000013605316475015135 5ustar debalancedebalancecache_tab-1.0.21/c_src/ets_cache.c0000644000232200023220000000727313605316475017230 0ustar debalancedebalance/* * Author: Evgeny Khramtsov * Created : 26 Apr 2017 by Evgeny Khramtsov * * * Copyright (C) 2002-2019 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.21/src/0000755000232200023220000000000013605316475014633 5ustar debalancedebalancecache_tab-1.0.21/src/ets_cache_options.erl0000644000232200023220000000324313605316475021032 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% Created : 24 Apr 2017 by Evgeny Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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.21/src/cache_tab_sup.erl0000644000232200023220000000335513605316475020125 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab_sup.erl %%% Author : Evgeniy Khramtsov %%% Description : Cache tables supervisor %%% %%% Created : 30 Aug 2010 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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.21/src/cache_tab.app.src0000644000232200023220000000304513605316475020016 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : cache_tab.app.src %%% Author : Evgeniy Khramtsov %%% Purpose : Application package description %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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.21"}, {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"]}, {links, [{"Github", "https://github.com/processone/cache_tab"}]}]}. %% Local Variables: %% mode: erlang %% End: %% vim: set filetype=erlang tabstop=8: cache_tab-1.0.21/src/cache_tab.erl0000644000232200023220000003604413605316475017237 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab.erl %%% Author : Evgeniy Khramtsov %%% Description : Caching key-value table %%% %%% Created : 29 Aug 2010 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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.21/src/cache_tab_app.erl0000644000232200023220000000640413605316475020074 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : cache_tab_app.erl %%% Author : Evgeniy Khramtsov %%% Description : Cache tab application %%% %%% Created : 8 May 2013 by Evgeniy Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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.21/src/ets_cache.erl0000644000232200023220000005312613605316475017264 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% Created : 12 Apr 2017 by Evgeny Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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([start_link/2]). -export([new/1, new/2, delete/1]). -export([delete/2, delete/3, match_delete/2, match_delete/3]). -export([lookup/2, lookup/3]). -export([insert/3, insert/4, insert_new/3, insert_new/4]). -export([update/4, update/5]). -export([incr/3, incr/4]). -export([setopts/2, all/0, info/1, info/2]). -export([clear/1, clear/2, clean/1, clean/2]). -export([filter/2, fold/3]). -export([untag/1]). %% 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]). -compile(no_native). -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 tag() :: cache | nocache. -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, set | ordered_set | bag | duplicate_bag}. -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{}. -export_type([tag/0]). %%%=================================================================== %%% 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). -spec match_delete(atom(), any()) -> ok. match_delete(Name, Match) -> match_delete(Name, Match, [node()]). -spec match_delete(atom(), any(), [atom()]) -> ok. match_delete(Name, Match, Nodes) -> lists:foreach( fun(Node) when Node /= node() -> send({Name, Node}, {match_delete, Match}); (_MyNode) -> ets_match_delete(Name, Match) end, Nodes). -spec insert(atom(), any(), any()) -> boolean(). insert(Name, Key, Val) -> insert(Name, Key, Val, [node()]). -spec insert(atom(), any(), any(), [node()]) -> boolean(). insert(Name, Key, Val, Nodes) -> insert(replace, Name, Key, Val, Nodes). -spec insert_new(atom(), any(), any()) -> boolean(). insert_new(Name, Key, Val) -> insert(Name, Key, Val, [node()]). -spec insert_new(atom(), any(), any(), [node()]) -> boolean(). insert_new(Name, Key, Val, Nodes) -> insert(new, Name, Key, Val, Nodes). -spec lookup(atom(), any()) -> {ok, any()} | any(). lookup(Name, Key) -> lookup(Name, Key, error). -spec lookup(atom(), any(), read_fun() | term()) -> {ok, any()} | any(). lookup(Name, Key, Return) -> try ets:lookup(Name, Key) of [{_, Val, _} = Obj] -> delete_if_expired(Name, Obj), Val; [] when is_function(Return) -> Ver = get_counter(Name), case case Return() of {ok, _} = Ret -> {cache, Ret}; error -> {cache, error}; {error, notfound} -> {cache, error}; {cache, _} = Ret -> Ret; {nocache, _} = Ret -> Ret; Other -> {nocache, Other} end of {nocache, Val} -> Val; {cache, Val} -> case get_counter(Name) of Ver -> do_insert(new, Name, {Key, Val, current_time()}); _ -> ok end, Val end; [] -> Return catch _:badarg when is_function(Return) -> untag(Return()); _:badarg -> Return 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 -> case case UpdateFun() of ok -> {cache, Val}; {ok, _} = Ret -> {cache, Ret}; error -> {cache, error}; {error, notfound} -> {cache, error}; {cache, _} = Ret -> Ret; {nocache, _} = Ret -> Ret; Other -> {nocache, Other} end of {nocache, NewVal} -> NewVal; {cache, NewVal} -> 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 incr(atom(), any(), non_neg_integer()) -> ok. incr(Name, Key, Incr) -> incr(Name, Key, Incr, [node()]). -spec incr(atom(), any(), non_neg_integer(), [node()]) -> ok. incr(Name, Key, Incr, Nodes) -> Obj = {Key, Incr, current_time()}, lists:foreach( fun(Node) when Node /= node() -> send({Name, Node}, {incr, Obj}); (_) -> do_insert(incr, Name, Obj) end, Nodes). -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; ({type, _}) -> 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. -spec untag(term()) -> term(). untag({cache, Val}) -> Val; untag({nocache, Val}) -> Val; untag(Val) -> Val. 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), Type = proplists:get_value(type, Opts, set), ets:new(Name, [named_table, public, {read_concurrency, true}, Type]), 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, Op, {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(Op, Tab, New); false -> ok end; [] -> do_insert(Op, Tab, New) end, {noreply, State}; handle_info({incr, Obj}, #state{tab = Tab} = State) -> do_insert(incr, Tab, Obj), {noreply, State}; handle_info({delete, Key}, #state{tab = Tab} = State) -> ets_delete(Tab, Key), {noreply, State}; handle_info({match_delete, Match}, #state{tab = Tab} = State) -> ets_match_delete(Tab, Match), {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. -spec insert(new | replace, atom(), any(), any(), [node()]) -> boolean(). insert(Op, Name, Key, Val, Nodes) -> CurrTime = current_time(), Obj = {Key, {ok, Val}, CurrTime}, lists:foldl( fun(Node, Result) when Node /= node() -> send({Name, Node}, {insert, Op, Obj}), Result; (_, _) -> try ets:lookup(Name, Key) of [Old] -> case delete_if_expired(Name, Old, CurrTime) of true -> do_insert(Op, Name, Obj); false -> false end; [] -> do_insert(Op, Name, Obj) catch _:badarg -> false end end, false, Nodes). 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); incr -> incr_counter(Name), {Key, Incr, Time} = Obj, ets:update_counter(Name, Key, {2, Incr}), ets:update_element(Name, Key, {3, Time}) 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; {type, Type} when Type == set; Type == ordered_set; Type == bag; Type == duplicate_bag -> Opt; _ -> erlang:error({bad_option, Opt}) end; (cache_missed) -> {cache_missed, true}; (Opt) -> erlang:error({bad_option, Opt}) 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() -> erlang:system_time(millisecond). -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 = timer:minutes(1) + p1_rand:uniform(timer:minutes(4)), 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_match_delete(atom(), any()) -> boolean(). ets_match_delete(Tab, Match) -> try incr_counter(Tab), ets:match_delete(Tab, {Match, '_', '_'}) 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.21/rebar.config0000644000232200023220000000275213605316475016334 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-2019 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.17"}}}]}. {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.21/CODE_OF_CONDUCT.md0000644000232200023220000000643313605316475016651 0ustar debalancedebalance# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@process-one.net. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq cache_tab-1.0.21/include/0000755000232200023220000000000013605316475015467 5ustar debalancedebalancecache_tab-1.0.21/include/ets_cache.hrl0000644000232200023220000000201413605316475020111 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% @author Evgeny Khramtsov %%% Created : 24 Apr 2017 by Evgeny Khramtsov %%% %%% %%% Copyright (C) 2002-2019 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.21/test/0000755000232200023220000000000013605316475015023 5ustar debalancedebalancecache_tab-1.0.21/test/cache_tab_test.erl0000644000232200023220000002003513605316475020457 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-2019 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)). cache_tab-1.0.21/CONTRIBUTING.md0000644000232200023220000001362313605316475016302 0ustar debalancedebalance# Contributing We'd love for you to contribute to our source code and to make our project even better than it is today! Here are the guidelines we'd like you to follow: * [Code of Conduct](#coc) * [Questions and Problems](#question) * [Issues and Bugs](#issue) * [Feature Requests](#feature) * [Issue Submission Guidelines](#submit) * [Pull Request Submission Guidelines](#submit-pr) * [Signing the CLA](#cla) ## Code of Conduct Help us keep our community open-minded and inclusive. Please read and follow our [Code of Conduct][coc]. ## Questions, Bugs, Features ### Got a Question or Problem? Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests. You've got much better chances of getting your question answered on dedicated support platforms, the best being [Stack Overflow][stackoverflow]. Stack Overflow is a much better place to ask questions since: - there are thousands of people willing to help on Stack Overflow - questions and answers stay available for public viewing so your question / answer might help someone else - Stack Overflow's voting system assures that the best answers are prominently visible. To save your and our time, we will systematically close all issues that are requests for general support and redirect people to the section you are reading right now. ### Found an Issue or Bug? If you find a bug in the source code, you can help us by submitting an issue to our [GitHub Repository][github]. Even better, you can submit a Pull Request with a fix. ### Missing a Feature? You can request a new feature by submitting an issue to our [GitHub Repository][github-issues]. If you would like to implement a new feature then consider what kind of change it is: * **Major Changes** that you wish to contribute to the project should be discussed first in an [GitHub issue][github-issues] that clearly outlines the changes and benefits of the feature. * **Small Changes** can directly be crafted and submitted to the [GitHub Repository][github] as a Pull Request. See the section about [Pull Request Submission Guidelines](#submit-pr). ## Issue Submission Guidelines Before you submit your issue search the archive, maybe your question was already answered. If your issue appears to be a bug, and hasn't been reported, open a new issue. Help us to maximize the effort we can spend fixing issues and adding new features, by not reporting duplicate issues. The "[new issue][github-new-issue]" form contains a number of prompts that you should fill out to make it easier to understand and categorize the issue. ## Pull Request Submission Guidelines By submitting a pull request for a code or doc contribution, you need to have the right to grant your contribution's copyright license to ProcessOne. Please check [ProcessOne CLA][cla] for details. Before you submit your pull request consider the following guidelines: * Search [GitHub][github-pr] for an open or closed Pull Request that relates to your submission. You don't want to duplicate effort. * Make your changes in a new git branch: ```shell git checkout -b my-fix-branch master ``` * Test your changes and, if relevant, expand the automated test suite. * Create your patch commit, including appropriate test cases. * If the changes affect public APIs, change or add relevant documentation. * Commit your changes using a descriptive commit message. ```shell git commit -a ``` Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. * Push your branch to GitHub: ```shell git push origin my-fix-branch ``` * In GitHub, send a pull request to `master` branch. This will trigger the continuous integration and run the test. We will also notify you if you have not yet signed the [contribution agreement][cla]. * If you find that the continunous integration has failed, look into the logs to find out if your changes caused test failures, the commit message was malformed etc. If you find that the tests failed or times out for unrelated reasons, you can ping a team member so that the build can be restarted. * If we suggest changes, then: * Make the required updates. * Test your changes and test cases. * Commit your changes to your branch (e.g. `my-fix-branch`). * Push the changes to your GitHub repository (this will update your Pull Request). You can also amend the initial commits and force push them to the branch. ```shell git rebase master -i git push origin my-fix-branch -f ``` This is generally easier to follow, but separate commits are useful if the Pull Request contains iterations that might be interesting to see side-by-side. That's it! Thank you for your contribution! ## Signing the Contributor License Agreement (CLA) Upon submitting a Pull Request, we will ask you to sign our CLA if you haven't done so before. It's a quick process, we promise, and you will be able to do it all online You can read [ProcessOne Contribution License Agreement][cla] in PDF. This is part of the legal framework of the open-source ecosystem that adds some red tape, but protects both the contributor and the company / foundation behind the project. It also gives us the option to relicense the code with a more permissive license in the future. [coc]: https://github.com/processone/cache_tab/blob/master/CODE_OF_CONDUCT.md [stackoverflow]: https://stackoverflow.com/ [github]: https://github.com/processone/cache_tab [github-issues]: https://github.com/processone/cache_tab/issues [github-new-issue]: https://github.com/processone/cache_tab/issues/new [github-pr]: https://github.com/processone/cache_tab/pulls [cla]: https://www.process-one.net/resources/ejabberd-cla.pdf [license]: https://github.com/processone/cache_tab/blob/master/LICENSE.txt