-module(glats@handler). -compile([no_auto_import, nowarn_unused_vars]). -export([handle_request/5]). -export_type([request/0, response/0, request_outcome/1, request_handler_state/1]). -type request() :: {request, gleam@map:map_(binary(), binary()), binary()}. -type response() :: {response, gleam@map:map_(binary(), binary()), gleam@option:option(binary()), binary()}. -type request_outcome(GVM) :: {reply, response(), GVM} | {stop, gleam@erlang@process:exit_reason()}. -type request_handler_state(GVN) :: {request_handler_state, gleam@erlang@process:subject(glats:connection_message()), integer(), fun((request(), GVN) -> request_outcome(GVN)), GVN}. -spec request_handler_msg( gleam@erlang@process:subject(glats:connection_message()), glats:message(), request_handler_state(GVX) ) -> gleam@otp@actor:next(request_handler_state(GVX)). request_handler_msg(Conn, Msg, State) -> case erlang:element(4, Msg) of {some, Reply_to} -> Req = {request, erlang:element(3, Msg), erlang:element(5, Msg)}, case (erlang:element(4, State))(Req, erlang:element(5, State)) of {reply, Res, New_inner} -> Pub_res = glats:publish_message( Conn, {message, Reply_to, erlang:element(2, Res), erlang:element(3, Res), erlang:element(4, Res)} ), case Pub_res of {ok, nil} -> {continue, erlang:setelement(5, State, New_inner)}; {error, Err} -> {stop, {abnormal, Err}} end; {stop, Reason} -> {stop, Reason} end; none -> {continue, State} end. -spec request_handler_loop( glats:subscription_message(), request_handler_state(GVU) ) -> gleam@otp@actor:next(request_handler_state(GVU)). request_handler_loop(Message, State) -> case Message of {received_message, Conn, _, Msg} -> request_handler_msg(Conn, Msg, State); _ -> {continue, State} end. -spec handle_request( gleam@erlang@process:subject(glats:connection_message()), GVQ, binary(), gleam@option:option(binary()), fun((request(), GVQ) -> request_outcome(GVQ)) ) -> {ok, gleam@erlang@process:subject(glats:subscription_message())} | {error, gleam@otp@actor:start_error()}. handle_request(Conn, State, Subject, Queue_group, Handler) -> gleam@otp@actor:start_spec( {spec, fun() -> Subscriber = gleam@erlang@process:new_subject(), Selector = begin _pipe = gleam_erlang_ffi:new_selector(), gleam@erlang@process:selecting( _pipe, Subscriber, fun(Msg) -> Msg end ) end, Subscription = case Queue_group of {some, Qg} -> glats:queue_subscribe(Conn, Subscriber, Subject, Qg); none -> glats:subscribe(Conn, Subscriber, Subject) end, case Subscription of {ok, Sid} -> {ready, {request_handler_state, Conn, Sid, Handler, State}, Selector}; {error, Err} -> {failed, Err} end end, 5000, fun request_handler_loop/2} ).