Compare commits

..

2 Commits

Author SHA1 Message Date
46a4d1e015 add wheel 2025-12-16 23:44:50 +08:00
4bd53d0afb fix scanner 2025-12-16 22:25:20 +08:00
3 changed files with 73 additions and 0 deletions

View File

@ -8,6 +8,9 @@
%%%------------------------------------------------------------------- %%%-------------------------------------------------------------------
-author("anlicheng"). -author("anlicheng").
-define(PENDING_TAB, ets_dns_pending_queries).
-define(PENDING_INDEX_TAB, ets_dns_expire_index).
-record(dns_cache, { -record(dns_cache, {
%% {Qname, QType, QClass} %% {Qname, QType, QClass}
key, key,

View File

@ -0,0 +1,69 @@
-module(dns_pending_wheel).
-export([start/0, put/2, get/1, delete/1]).
-define(TTL, 5).
-define(TICK_MS, 1000).
-define(WHEEL_SIZE, (?TTL + 1)).
%%% =====================================================
%%% Public API
%%% =====================================================
start() ->
ets:new(dns_pending_data, [ordered_set, public, named_table]),
ets:new(dns_pending_wheel, [bag, public, named_table]),
start_scanner().
-spec put(Key :: any(), Val :: any()) -> ok.
put(Key, Val) ->
Tick = now_tick(),
Slot = Tick rem ?WHEEL_SIZE,
ets:insert(dns_pending_data, {Key, {Val, Tick}}),
ets:insert(dns_pending_wheel, {Slot, {Key, Tick}}),
ok.
-spec get(Key :: any()) -> error | {ok, Val :: any()}.
get(Key) ->
case ets:lookup(dns_pending_data, Key) of
[{Key, {Val, _Tick}}] ->
{ok, Val};
[] ->
error
end.
-spec delete(Key :: any()) -> ok.
delete(Key) ->
ets:delete(dns_pending_data, Key),
ok.
%%% =====================================================
%%% Internal
%%% =====================================================
start_scanner() ->
{ok, spawn_link(fun tick_loop/0)}.
%% Tick, Tick + 1
tick_loop() ->
Tick = now_tick(),
CleanSlot = (Tick + 1) rem ?WHEEL_SIZE,
spawn(fun() -> clean_slot(CleanSlot) end),
timer:sleep(?TICK_MS),
tick_loop().
clean_slot(Slot) ->
Items = ets:lookup(dns_pending_wheel, Slot),
true = ets:delete(dns_pending_wheel, Slot),
lists:foreach(fun({_, {Key, InsertTick}}) ->
case ets:lookup(dns_pending_data, Key) of
[{Key, {_Val, InsertTick}}] ->
ets:delete(dns_pending_data, Key);
_ ->
ok
end
end, Items).
-spec now_tick() -> integer().
now_tick() ->
erlang:system_time(second).

View File

@ -19,6 +19,7 @@ start(_StartType, _StartArgs) ->
%% %%
sdlan_hostname_regedit:init(), sdlan_hostname_regedit:init(),
sdlan_domain_regedit:init(), sdlan_domain_regedit:init(),
dns_pending_wheel:start(),
start_http_server(), start_http_server(),
start_tcp_server(), start_tcp_server(),