feat(erlang): create version-specific worker pools from db config

This commit is contained in:
Alice39s 2026-06-28 00:07:09 +09:00
parent 241831a6f0
commit c911ca1290
No known key found for this signature in database
GPG Key ID: 0E0AA11C3939DDDD
3 changed files with 47 additions and 10 deletions

View File

@ -11,6 +11,9 @@
{poolargs, [ {poolargs, [
{size, 1}, {size, 1},
{max_overflow, 5} {max_overflow, 5}
]},
{db, [
{ipv4, "ip2region.xdb"}
]} ]}
]}, ]},
{modules, []}, {modules, []},

View File

@ -18,7 +18,6 @@
start_link() -> start_link() ->
{ok, SupPid} = supervisor:start_link({local, ?SERVER}, ?MODULE, []), {ok, SupPid} = supervisor:start_link({local, ?SERVER}, ?MODULE, []),
{ok, _PoolPid} = start_ip2region_pool(SupPid),
{ok, SupPid}. {ok, SupPid}.
%% sup_flags() = #{strategy => strategy(), % optional %% sup_flags() = #{strategy => strategy(), % optional
@ -35,7 +34,7 @@ init([]) ->
SupFlags = #{strategy => one_for_one, SupFlags = #{strategy => one_for_one,
intensity => 10, intensity => 10,
period => 5}, period => 5},
ChildSpecs = [], ChildSpecs = pool_child_specs(),
{ok, {SupFlags, ChildSpecs}}. {ok, {SupFlags, ChildSpecs}}.
%% internal functions %% internal functions
@ -60,10 +59,28 @@ ensure_table(Name, Opts) ->
_ -> ok _ -> ok
end. end.
start_ip2region_pool(Sup) -> pool_child_specs() ->
{ok, DbConfig} = application:get_env(db),
{ok, PoolArgsCfg} = application:get_env(poolargs), {ok, PoolArgsCfg} = application:get_env(poolargs),
PoolName = ?IP2REGION_POOL, Versions = [Version || {Version, _File} <- DbConfig],
PoolArgs = [{strategy, fifo}, {name, {local, PoolName}}, {worker_module, ip2region_worker} | PoolArgsCfg], UseLegacyName = (Versions == [ipv4]),
WorkerArgs = [], lists:foldl(
ChildSpecs = poolboy:child_spec(PoolName, PoolArgs, WorkerArgs), fun({ipv4, File}, Acc) when UseLegacyName ->
supervisor:start_child(Sup, ChildSpecs). [make_pool_spec(?IP2REGION_POOL, ipv4, File, PoolArgsCfg) | Acc];
({ipv4, File}, Acc) ->
[make_pool_spec(?IP2REGION_POOL_V4, ipv4, File, PoolArgsCfg) | Acc];
({ipv6, File}, Acc) ->
[make_pool_spec(?IP2REGION_POOL_V6, ipv6, File, PoolArgsCfg) | Acc];
(_, Acc) ->
Acc
end, [], DbConfig).
make_pool_spec(PoolName, Version, File, PoolArgsCfg) ->
PoolArgs = [
{strategy, fifo},
{name, {local, PoolName}},
{worker_module, ip2region_worker}
| PoolArgsCfg
],
WorkerArgs = [{xdb_file, File}, {version, Version}],
poolboy:child_spec(PoolName, PoolArgs, WorkerArgs).

View File

@ -0,0 +1,17 @@
-module(ip2region_sup_test).
-include_lib("eunit/include/eunit.hrl").
-include("ip2region.hrl").
pools_started_test() ->
application:stop(ip2region),
application:unload(ip2region),
ok = application:load(ip2region),
{ok, Cwd} = file:get_cwd(),
V6File = filename:join([Cwd, "..", "..", "data", "ip2region_v6.xdb"]),
ok = application:set_env(ip2region, db, [
{ipv4, "ip2region.xdb"},
{ipv6, V6File}
]),
application:ensure_started(ip2region),
?assert(is_pid(whereis(?IP2REGION_POOL_V4))),
?assert(is_pid(whereis(?IP2REGION_POOL_V6))).