uwiger / gproc

Extended process registry for Erlang
Apache License 2.0
1.07k stars 232 forks source link

Support get_env plugin methods #83

Open uwiger opened 9 years ago

uwiger commented 9 years ago

Make gproc:get_env() et.al. pluggable. Also allow for alternative lookup methods to be 'caching' - i.e. if they fail to find a value, but it's found by a later alternative, it is cached also at this level. See below.

Pluggable methods are registered as shared properties, e.g.

gproc:reg_shared({p,l,getenv}, {envtest, get_env}),
gproc:reg_shared({p,l,getenvc}, {envtest, get_env})

The plugins are called as Mod:Fun(App, Key, PropertyName) (lookup) or Mod:Fun(App, Key, Value, PropertyName) (insert). The lookup function must return {ok,Value} | undefined. The insert function's return value is ignored.

Eshell V5.10.3  (abort with ^G)
1> application:start(gproc).
ok
%% Create an ETS table and register our gproc hooks.
%% Our hooks: 'getenv' only does lookup, {Module, Fun}
%%            'getenvc' does lookup, but can also cache
%%                   when called via `gproc:get_set_env/4`,
%%                   {Mod, Fun, cache}.
2> envtest:init().
true
%% Create an "external config":
3> os:putenv("ULF","Wiger").
true
%% Look up the value in gproc, search in OS env if not found:
4> gproc:get_env(l,gproc,ulf,[os_env]).
"Wiger"
%% Also look in our own "cache"
%% The callback prints that it was called (but doesn't find anything)
5> gproc:get_env(l,gproc,ulf,[{reg,getenvc},os_env]).
-- envtest:get_env(gproc, ulf, getenvc)
"Wiger"
%% Use the caching lookup method. We see that the value is cached:
6> gproc:get_set_env(l,gproc,ulf,[{reg,getenvc},os_env]).
-- envtest:get_env(gproc, ulf, getenvc)
-- envtest:get_env(gproc, ulf, "Wiger", getenvc) (CACHE!)
"Wiger"
%% Lookup the value without falling back on the OS env:
7> gproc:get_env(l,gproc,ulf,[{reg,getenvc}]).           
"Wiger"
%% Verify that the value exists in our cache:
8> ets:tab2list(envtest).
[{{gproc,ulf},"Wiger"}]

(See gproc/test/envtest.erl)