snapkitty
developer-tools
c++
SNAPKITTYWEST commited on
Commit
7d9899a
·
verified ·
1 Parent(s): 7b49393

Add src/hk_search_registry.erl

Browse files
Files changed (1) hide show
  1. src/hk_search_registry.erl +58 -0
src/hk_search_registry.erl ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%-------------------------------------------------------------------
2
+ %%% @doc HK-SEARCH :: job_id -> pid directory. Same rationale and
3
+ %%% shape as `hk_browser_registry'/`hk_agent_registry'; entries are
4
+ %%% removed once the owning `hk_search_job' process exits, which
5
+ %%% happens some time after the job reaches `done'/`failed' (jobs
6
+ %%% are not immediately torn down so late `describe/1' or
7
+ %%% `await_result/2' calls -- e.g. from the frontend -- still work).
8
+ %%% @end
9
+ %%%-------------------------------------------------------------------
10
+ -module(hk_search_registry).
11
+ -behaviour(gen_server).
12
+
13
+ -export([start_link/0, register/2, lookup/1, list_jobs/0]).
14
+ -export([init/1, handle_call/3, handle_cast/2, handle_info/2]).
15
+
16
+ -define(TAB, hk_search_registry_tab).
17
+
18
+ start_link() ->
19
+ hk_sup_util:start_link_retry(
20
+ fun() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []) end).
21
+
22
+ -spec register(binary(), pid()) -> ok.
23
+ register(JobId, Pid) ->
24
+ gen_server:call(?MODULE, {register, JobId, Pid}).
25
+
26
+ -spec lookup(binary()) -> {ok, pid()} | {error, not_found}.
27
+ lookup(JobId) ->
28
+ case ets:lookup(?TAB, JobId) of
29
+ [{JobId, Pid}] -> {ok, Pid};
30
+ [] -> {error, not_found}
31
+ end.
32
+
33
+ -spec list_jobs() -> [{binary(), pid()}].
34
+ list_jobs() ->
35
+ ets:tab2list(?TAB).
36
+
37
+ init([]) ->
38
+ ets:new(?TAB, [set, named_table, protected]),
39
+ {ok, #{monitors => #{}}}.
40
+
41
+ handle_call({register, JobId, Pid}, _From, State = #{monitors := Mons}) ->
42
+ ets:insert(?TAB, {JobId, Pid}),
43
+ MonRef = erlang:monitor(process, Pid),
44
+ {reply, ok, State#{monitors := Mons#{MonRef => JobId}}}.
45
+
46
+ handle_cast(_Msg, State) ->
47
+ {noreply, State}.
48
+
49
+ handle_info({'DOWN', MonRef, process, _Pid, _Reason}, State = #{monitors := Mons}) ->
50
+ case maps:take(MonRef, Mons) of
51
+ {JobId, Mons2} ->
52
+ ets:delete(?TAB, JobId),
53
+ {noreply, State#{monitors := Mons2}};
54
+ error ->
55
+ {noreply, State}
56
+ end;
57
+ handle_info(_Info, State) ->
58
+ {noreply, State}.