Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reply to fun or MFA #329

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions doc/src/manual/gun.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ Request headers.
----
req_opts() :: #{
flow => pos_integer(),
reply_to => pid()
reply_to => pid() | {module(), atom(), list()} | fun((_) -> _) | {fun(), list()}
}
----

Expand All @@ -456,7 +456,8 @@ flow control is disabled.

reply_to (`self()`)::

The pid of the process that will receive the response messages.
The pid of the process that will receive the response messages,
alternatively a function that will be called with the reponse.

=== socks_opts()

Expand Down
42 changes: 26 additions & 16 deletions src/gun.erl
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
-export([connected_ws_only/3]).
-export([closing/3]).
-export([terminate/3]).
-export([reply/2]).

-type req_headers() :: [{binary() | string() | atom(), iodata()}]
| #{binary() | string() | atom() => iodata()}.
Expand Down Expand Up @@ -198,7 +199,7 @@

-type req_opts() :: #{
flow => pos_integer(),
reply_to => pid(),
reply_to => pid() | {module(), atom(), list()} | fun((_) -> _) | {fun(), list()},
tunnel => stream_ref()
}.
-export_type([req_opts/0]).
Expand Down Expand Up @@ -1148,7 +1149,7 @@ tls_handshake(internal, {tls_handshake, HandshakeEvent, Protocols, ReplyTo},
NewProtocolName -> {NewProtocolName, #{tunnel_transport => tls}}
end,
Protocol = gun_protocols:handler(NewProtocol),
ReplyTo ! {gun_tunnel_up, self(), StreamRef, Protocol:name()},
reply(ReplyTo, {gun_tunnel_up, self(), StreamRef, Protocol:name()}),
commands([
{switch_transport, gun_tls, TLSSocket},
{switch_protocol, NewProtocol, ReplyTo}
Expand Down Expand Up @@ -1183,7 +1184,7 @@ tls_handshake(info, {gun_tls_proxy, Socket, {ok, Negotiated}, {HandshakeEvent, P
NewProtocolName -> {NewProtocolName, #{tunnel_transport => tls}}
end,
Protocol = gun_protocols:handler(NewProtocol),
ReplyTo ! {gun_tunnel_up, self(), StreamRef, Protocol:name()},
reply(ReplyTo, {gun_tunnel_up, self(), StreamRef, Protocol:name()}),
EvHandlerState = EvHandler:tls_handshake_end(HandshakeEvent#{
socket => Socket,
protocol => Protocol:name()
Expand Down Expand Up @@ -1245,7 +1246,7 @@ connected_protocol_init(internal, {connected, Retries, Socket, NewProtocol},
{next_event, internal, {retries, Retries, Reason}}};
{ok, StateName, ProtoState} ->
%% @todo Don't send gun_up and gun_down if active/1 fails here.
Owner ! {gun_up, self(), Protocol:name()},
reply(Owner, {gun_up, self(), Protocol:name()}),
State1 = State0#state{socket=Socket, protocol=Protocol, protocol_state=ProtoState},
case active(State1) of
{ok, State2} ->
Expand All @@ -1267,9 +1268,9 @@ connected_data_only(cast, Msg, _)
element(1, Msg) =:= connect; element(1, Msg) =:= ws_upgrade;
element(1, Msg) =:= ws_send ->
ReplyTo = element(2, Msg),
ReplyTo ! {gun_error, self(), {badstate,
reply(ReplyTo, {gun_error, self(), {badstate,
"This connection does not accept new requests to be opened "
"nor does it accept Websocket frames."}},
"nor does it accept Websocket frames."}}),
keep_state_and_data;
connected_data_only(Type, Event, State) ->
handle_common_connected(Type, Event, ?FUNCTION_NAME, State).
Expand All @@ -1285,8 +1286,8 @@ connected_ws_only(cast, Msg, _)
when element(1, Msg) =:= headers; element(1, Msg) =:= request; element(1, Msg) =:= data;
element(1, Msg) =:= connect; element(1, Msg) =:= ws_upgrade ->
ReplyTo = element(2, Msg),
ReplyTo ! {gun_error, self(), {badstate,
"This connection only accepts Websocket frames."}},
reply(ReplyTo, {gun_error, self(), {badstate,
"This connection only accepts Websocket frames."}}),
keep_state_and_data;
connected_ws_only(Type, Event, State) ->
handle_common_connected_no_input(Type, Event, ?FUNCTION_NAME, State).
Expand Down Expand Up @@ -1389,23 +1390,23 @@ closing(state_timeout, closing_timeout, State=#state{status=Status}) ->
%% When reconnect is disabled, fail HTTP/Websocket operations immediately.
closing(cast, {headers, ReplyTo, StreamRef, _Method, _Path, _Headers, _InitialFlow},
State=#state{opts=#{retry := 0}}) ->
ReplyTo ! {gun_error, self(), StreamRef, closing},
reply(ReplyTo, {gun_error, self(), StreamRef, closing}),
{keep_state, State};
closing(cast, {request, ReplyTo, StreamRef, _Method, _Path, _Headers, _Body, _InitialFlow},
State=#state{opts=#{retry := 0}}) ->
ReplyTo ! {gun_error, self(), StreamRef, closing},
reply(ReplyTo, {gun_error, self(), StreamRef, closing}),
{keep_state, State};
closing(cast, {connect, ReplyTo, StreamRef, _Destination, _Headers, _InitialFlow},
State=#state{opts=#{retry := 0}}) ->
ReplyTo ! {gun_error, self(), StreamRef, closing},
reply(ReplyTo, {gun_error, self(), StreamRef, closing}),
{keep_state, State};
closing(cast, {ws_upgrade, ReplyTo, StreamRef, _Path, _Headers},
State=#state{opts=#{retry := 0}}) ->
ReplyTo ! {gun_error, self(), StreamRef, closing},
reply(ReplyTo, {gun_error, self(), StreamRef, closing}),
{keep_state, State};
closing(cast, {ws_upgrade, ReplyTo, StreamRef, _Path, _Headers, _WsOpts},
State=#state{opts=#{retry := 0}}) ->
ReplyTo ! {gun_error, self(), StreamRef, closing},
reply(ReplyTo, {gun_error, self(), StreamRef, closing}),
{keep_state, State};
closing(Type, Event, State) ->
handle_common_connected(Type, Event, ?FUNCTION_NAME, State).
Expand Down Expand Up @@ -1613,8 +1614,8 @@ handle_common(cast, {set_owner, CurrentOwner, NewOwner}, _,
{keep_state, State#state{owner=NewOwner, status={up, NewOwnerRef}}};
%% We cannot change the owner when we are shutting down.
handle_common(cast, {set_owner, CurrentOwner, _}, _, #state{owner=CurrentOwner}) ->
CurrentOwner ! {gun_error, self(), {badstate,
"The owner of the connection cannot be changed when the connection is shutting down."}},
reply(CurrentOwner, {gun_error, self(), {badstate,
"The owner of the connection cannot be changed when the connection is shutting down."}}),
keep_state_and_state;
handle_common(cast, shutdown, StateName, State=#state{
status=Status, socket=Socket, transport=Transport, protocol=Protocol}) ->
Expand Down Expand Up @@ -1767,7 +1768,7 @@ disconnect(State0=#state{owner=Owner, status=Status, opts=Opts,
%% We closed the socket, discard any remaining socket events.
disconnect_flush(State1),
KilledStreams = Protocol:down(ProtoState),
Owner ! {gun_down, self(), Protocol:name(), Reason, KilledStreams},
reply(Owner, {gun_down, self(), Protocol:name(), Reason, KilledStreams}),
Retry = maps:get(retry, Opts, 5),
State2 = keepalive_cancel(State1#state{
socket=undefined, protocol=undefined, protocol_state=undefined}),
Expand Down Expand Up @@ -1844,3 +1845,12 @@ terminate(Reason, StateName, #state{event_handler=EvHandler,
reason => Reason
},
EvHandler:terminate(TerminateEvent, EvHandlerState).

reply(Pid, Reply) when is_pid(Pid) ->
Pid ! Reply;
reply({M, F, A}, Reply) when is_atom(M), is_atom(F), is_list(A) ->
apply(M, F, [Reply | A]);
reply(Fun, Reply) when is_function(Fun, 1) ->
Fun(Reply);
reply({Fun, A}, Reply) when is_list(A), is_function(Fun, length(A) + 1) ->
apply(Fun, [Reply | A]).
2 changes: 1 addition & 1 deletion src/gun_data_h.erl
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ init(ReplyTo, StreamRef, _, _, _) ->

-spec handle(fin | nofin, binary(), State) -> {done, 1, State} when State::#state{}.
handle(IsFin, Data, State=#state{reply_to=ReplyTo, stream_ref=StreamRef}) ->
ReplyTo ! {gun_data, self(), StreamRef, IsFin, Data},
gun:reply(ReplyTo, {gun_data, self(), StreamRef, IsFin, Data}),
{done, 1, State}.
50 changes: 25 additions & 25 deletions src/gun_http.erl
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ handle(Data, State=#http_state{in=body_trailer, buffer=Buffer, connection=Conn,
{Trailers, Rest} = cow_http:parse_headers(Data2),
%% @todo We probably want to pass this to gun_content_handler?
RealStreamRef = stream_ref(State, StreamRef),
ReplyTo ! {gun_trailers, self(), RealStreamRef, Trailers},
gun:reply(ReplyTo, {gun_trailers, self(), RealStreamRef, Trailers}),
ResponseEvent = #{
stream_ref => RealStreamRef,
reply_to => ReplyTo
Expand Down Expand Up @@ -319,7 +319,7 @@ handle_connect(Rest, State=#http_state{
%% @todo If the stream is cancelled we probably shouldn't finish the CONNECT setup.
_ = case Stream of
#stream{is_alive=false} -> ok;
_ -> ReplyTo ! {gun_response, self(), RealStreamRef, fin, Status, Headers}
_ -> gun:reply(ReplyTo, {gun_response, self(), RealStreamRef, fin, Status, Headers})
end,
%% @todo Figure out whether the event should trigger if the stream was cancelled.
EvHandlerState1 = EvHandler:response_headers(#{
Expand Down Expand Up @@ -355,7 +355,7 @@ handle_connect(Rest, State=#http_state{
[NewProtocol0] = maps:get(protocols, Destination, [http]),
NewProtocol = gun_protocols:add_stream_ref(NewProtocol0, RealStreamRef),
Protocol = gun_protocols:handler(NewProtocol),
ReplyTo ! {gun_tunnel_up, self(), RealStreamRef, Protocol:name()},
gun:reply(ReplyTo, {gun_tunnel_up, self(), RealStreamRef, Protocol:name()}),
{[
{origin, <<"http">>, NewHost, NewPort, connect},
{switch_protocol, NewProtocol, ReplyTo}
Expand All @@ -382,17 +382,17 @@ handle_inform(Rest, State=#http_state{
%% @todo We shouldn't ignore Rest.
{_, Upgrade0} = lists:keyfind(<<"upgrade">>, 1, Headers),
Upgrade = cow_http_hd:parse_upgrade(Upgrade0),
ReplyTo ! {gun_upgrade, self(), stream_ref(State, StreamRef), Upgrade, Headers},
gun:reply(ReplyTo, {gun_upgrade, self(), stream_ref(State, StreamRef), Upgrade, Headers}),
%% @todo We probably need to add_stream_ref?
{{switch_protocol, raw, ReplyTo}, CookieStore, EvHandlerState0}
catch _:_ ->
%% When the Upgrade header is missing or invalid we treat
%% the response as any other informational response.
ReplyTo ! {gun_inform, self(), stream_ref(State, StreamRef), Status, Headers},
gun:reply(ReplyTo, {gun_inform, self(), stream_ref(State, StreamRef), Status, Headers}),
handle(Rest, State, CookieStore, EvHandler, EvHandlerState)
end;
_ ->
ReplyTo ! {gun_inform, self(), stream_ref(State, StreamRef), Status, Headers},
gun:reply(ReplyTo, {gun_inform, self(), stream_ref(State, StreamRef), Status, Headers}),
handle(Rest, State, CookieStore, EvHandler, EvHandlerState)
end.

Expand All @@ -407,7 +407,7 @@ handle_response(Rest, State=#http_state{version=ClientVersion, opts=Opts, connec
false ->
{undefined, EvHandlerState0};
true ->
ReplyTo ! {gun_response, self(), RealStreamRef, IsFin, Status, Headers},
gun:reply(ReplyTo, {gun_response, self(), RealStreamRef, IsFin, Status, Headers}),
EvHandlerState1 = EvHandler:response_headers(#{
stream_ref => RealStreamRef,
reply_to => ReplyTo,
Expand Down Expand Up @@ -546,7 +546,7 @@ close_streams(_, [], _) ->
close_streams(State, [#stream{is_alive=false}|Tail], Reason) ->
close_streams(State, Tail, Reason);
close_streams(State, [#stream{ref=StreamRef, reply_to=ReplyTo}|Tail], Reason) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef), Reason},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef), Reason}),
close_streams(State, Tail, Reason).

%% We don't send a keep-alive when a CONNECT request was initiated.
Expand All @@ -563,8 +563,8 @@ keepalive(_State, _, EvHandlerState) ->

headers(State, StreamRef, ReplyTo, _, _, _, _, _, _, CookieStore, _, EvHandlerState)
when is_list(StreamRef) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}}),
{[], CookieStore, EvHandlerState};
headers(State=#http_state{opts=Opts, out=head},
StreamRef, ReplyTo, Method, Host, Port, Path, Headers,
Expand All @@ -584,8 +584,8 @@ headers(State=#http_state{opts=Opts, out=head},

request(State, StreamRef, ReplyTo, _, _, _, _, _, _, _, CookieStore, _, EvHandlerState)
when is_list(StreamRef) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}}),
{[], CookieStore, EvHandlerState};
request(State=#http_state{opts=Opts, out=head}, StreamRef, ReplyTo,
Method, Host, Port, Path, Headers, Body,
Expand Down Expand Up @@ -762,13 +762,13 @@ data(State=#http_state{socket=Socket, transport=Transport, version=Version,

connect(State, StreamRef, ReplyTo, _, _, _, _, _, EvHandlerState)
when is_list(StreamRef) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}}),
{[], EvHandlerState};
connect(State=#http_state{streams=Streams}, StreamRef, ReplyTo, _, _, _, _, _, EvHandlerState)
when Streams =/= [] ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"CONNECT can only be used with HTTP/1.1 when no other streams are active."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"CONNECT can only be used with HTTP/1.1 when no other streams are active."}}),
{[], EvHandlerState};
connect(State=#http_state{socket=Socket, transport=Transport, opts=Opts, version=Version},
StreamRef, ReplyTo, Destination=#{host := Host0}, _TunnelInfo, Headers0, InitialFlow0,
Expand Down Expand Up @@ -863,13 +863,13 @@ down(#http_state{streams=Streams}) ->
end || #stream{ref=Ref} <- Streams].

error_stream_closed(State, StreamRef, ReplyTo) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"The stream has already been closed."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"The stream has already been closed."}}),
ok.

error_stream_not_found(State, StreamRef, ReplyTo) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"The stream cannot be found."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"The stream cannot be found."}}),
ok.

%% Headers information retrieval.
Expand Down Expand Up @@ -959,13 +959,13 @@ end_stream(State=#http_state{streams=[_|Tail]}) ->

ws_upgrade(State, StreamRef, ReplyTo, _, _, _, _, _, CookieStore, _, EvHandlerState)
when is_list(StreamRef) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef),
{badstate, "The stream is not a tunnel."}}),
{[], CookieStore, EvHandlerState};
ws_upgrade(State=#http_state{version='HTTP/1.0'},
StreamRef, ReplyTo, _, _, _, _, _, CookieStore, _, EvHandlerState) ->
ReplyTo ! {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"Websocket cannot be used over an HTTP/1.0 connection."}},
gun:reply(ReplyTo, {gun_error, self(), stream_ref(State, StreamRef), {badstate,
"Websocket cannot be used over an HTTP/1.0 connection."}}),
{[], CookieStore, EvHandlerState};
ws_upgrade(State=#http_state{out=head}, StreamRef, ReplyTo,
Host, Port, Path, Headers0, WsOpts, CookieStore0, EvHandler, EvHandlerState0) ->
Expand Down Expand Up @@ -1047,7 +1047,7 @@ ws_handshake_end(Buffer,
end,
%% Inform the user that the upgrade was successful and switch the protocol.
RealStreamRef = stream_ref(State, StreamRef),
ReplyTo ! {gun_upgrade, self(), RealStreamRef, [<<"websocket">>], Headers},
gun:reply(ReplyTo, {gun_upgrade, self(), RealStreamRef, [<<"websocket">>], Headers}),
{switch_protocol, {ws, #{
stream_ref => RealStreamRef,
headers => Headers,
Expand Down