Add src/hk_search.erl
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748%%%-------------------------------------------------------------------%%% @doc HK-SEARCH :: public entry point for starting a search job.%%%%%% Thin convenience wrapper used by `hk_agent_toolbox' (the%%% `search'/`start' tool call) and by the `/search' API handler:%%% starts a supervised `hk_search_job', registers it, kicks off the%%% pipeline, and (for callers that want a synchronous result)%%% blocks on `hk_search_job:await_result/2'. The job itself keeps%%% running and emitting events on the bus regardless of whether%%% anyone is blocked waiting on it -- `run/3' is a convenience, not%%% the only way to consume a job's progress.%%% @end%%%--------------------------------------------------------------------module(hk_search).
-export([start/3, run/3]).
-define(DEFAULT_AWAIT_TIMEOUT_MS, 20000).
%% @doc Start a job and return immediately with its id, without%% waiting for the pipeline to finish. Progress is observable via%% the event bus (`search.*' events) and `hk_search_job:describe/1'.-spec start(binary() | undefined, binary(), map()) -> {ok, binary()} | {error, term()}.start(OwnerAgentId, Query, Opts) -> JobId = hk_id:new(<<"job">>), Args = #{job_id => JobId, owner_agent_id => OwnerAgentId, query => Query, max_iterations => maps:get(max_iterations, Opts, 3)}, case hk_search_job_sup:start_job(Args) of {ok, Pid} -> ok = hk_search_registry:register(JobId, Pid), hk_search_job:run(Pid), {ok, JobId}; {error, Reason} -> {error, Reason} end.
%% @doc Start a job and block until it reaches `done'/`failed' or%% `Timeout' (default from `Opts') elapses.-spec run(binary() | undefined, binary(), map()) -> {ok, term()} | {error, term()}.run(OwnerAgentId, Query, Opts) -> case start(OwnerAgentId, Query, Opts) of {ok, JobId} -> {ok, Pid} = hk_search_registry:lookup(JobId), Timeout = maps:get(await_timeout_ms, Opts, ?DEFAULT_AWAIT_TIMEOUT_MS), hk_search_job:await_result(Pid, Timeout); {error, Reason} -> {error, Reason} end.src/hk_search.erlAdded+48