diff --git a/NEWS.md b/NEWS.md index 0307d58f..1762100a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,16 @@ # NEWS +Unreleased +---------- + +### Fixed + +- HTTP/1.1: closing a request that was still waiting for its response + took about a second, and the server only saw the socket close then. + The same delay applied when the process that owned the request died. + Both now take effect at once: the server sees a cancelled request go + away right away, and closing no longer blocks the caller. + 4.12.3 - 2026-11-21 ------------------- diff --git a/guides/design.md b/guides/design.md index 204d77b6..aaa6928e 100644 --- a/guides/design.md +++ b/guides/design.md @@ -67,7 +67,7 @@ is by far the largest state in the module. ### Owner Monitoring -The connection process monitors its owner: the process that checked out the connection, or for a connection opened without a pool, the process that opened it (with `stream_to`, the `stream_to` process once the async request starts). If the owner crashes, the connection terminates automatically, preventing socket leaks. An HTTP/1.1 read waiting on the server checks for this every second. `hackney_conn:set_owner/2` moves ownership to another process. +The connection process monitors its owner: the process that checked out the connection, or for a connection opened without a pool, the process that opened it (with `stream_to`, the `stream_to` process once the async request starts). If the owner crashes, the connection terminates automatically, preventing socket leaks. An HTTP/1.1 read waiting on the server notices it at once. `hackney_conn:set_owner/2` moves ownership to another process. ```erlang %% When connection is checked out diff --git a/src/hackney_conn.erl b/src/hackney_conn.erl index 6f0dc760..76a53582 100644 --- a/src/hackney_conn.erl +++ b/src/hackney_conn.erl @@ -148,10 +148,6 @@ %% HTTP/3 H3_REQUEST_CANCELLED (RFC 9114 8.1), used to reset refused streams. -define(H3_REQUEST_CANCELLED, 16#10c). -%% A blocking HTTP/1.1 read is cut into slices this long; between slices the -%% conn checks whether its owner died, so a dead owner does not keep the -%% socket open until the response comes or recv_timeout expires. --define(OWNER_CHECK_INTERVAL, 1000). %% Cap on bytes buffered from an idle HTTP/1.1 connection via #544 {active, %% once}. A well-behaved peer sends nothing while idle; the next response's %% stranded prefix is small. Past this, treat the peer as misbehaving (flooding @@ -682,10 +678,10 @@ hold(Pid) -> catch exit:_ -> {error, closed} end. -%% @doc Tell the connection that its caller is closing it, so a passive -%% read in progress (a server that never answers) ends within one -%% ?OWNER_CHECK_INTERVAL slice instead of holding the close for the whole -%% recv_timeout. A connection that is not reading ignores the notice. +%% @doc Tell the connection that its caller is closing it, so a read in +%% progress (a server that never answers) ends at once instead of holding +%% the close for the whole recv_timeout. An HTTP/1.1 connection in the +%% middle of a response stops; any other one ignores the notice. -spec abort_read(pid()) -> ok. abort_read(Pid) -> Pid ! {?MODULE, abort_read}, @@ -2201,6 +2197,16 @@ handle_common(cast, stop, _State, Data) -> %% Async stop - used by pool to avoid deadlock during sync checkin {stop, normal, Data}; +%% hackney:close/1 sends abort_read ahead of its stop. A read in progress +%% takes it in owner_recv; between two reads (async streaming, or a +%% stream_next still to come from another process) it lands here, and an +%% HTTP/1.1 conn in the middle of a response stops now rather than waiting +%% in its next read. A held conn in `connected' ignores it and goes back to +%% its pool. +handle_common(info, {?MODULE, abort_read}, State, #conn_data{protocol = http1} = Data) + when State =:= receiving; State =:= streaming; State =:= streaming_once -> + {stop, normal, Data}; + %% A request waiting for a stream gave up: its caller exited, or its wait %% ran out. handle_common(info, {'DOWN', Ref, process, _Pid, _Reason}, State, @@ -3198,43 +3204,50 @@ recv_data(#conn_data{socket = Socket} = Data) -> {ok, Bytes} end. -%% @private Passive read that still notices the owner dying or a close. -%% The read runs in slices of at most ?OWNER_CHECK_INTERVAL. Between them it -%% looks for the owner's 'DOWN', which is put back in the mailbox so the -%% state's owner-'DOWN' clause stops the conn once the error unwinds the -%% current callback, and for an abort_read/1 notice from hackney:close/1. -%% The caller is closing the conn, so the conn stops right there, as the -%% stop that close/1 sends next would, rather than after recv_timeout or -%% never (#996): terminate/3 runs, the exit is normal and no response -%% message is sent. The whole read still honours recv_timeout. +%% @private Read that notices the owner dying or a close at once. +%% The socket is armed {active, once}, so a single receive waits for the +%% data, the owner's 'DOWN' and an abort_read/1 notice from hackney:close/1 +%% alike. The 'DOWN' is put back in the mailbox so the state's owner-'DOWN' +%% clause stops the conn once the error unwinds the current callback. On the +%% notice the caller is closing the conn, so the conn stops right there, as +%% the stop that close/1 sends next would (#996): terminate/3 runs, the exit +%% is normal and no response message is sent. Each read honours +%% recv_timeout, and the socket is passive again when the read returns. owner_recv(#conn_data{transport = Transport, socket = Socket, recv_timeout = Timeout, owner_mon = OwnerMon}) -> - owner_recv(Transport, Socket, OwnerMon, recv_deadline(Timeout)). - -owner_recv(Transport, Socket, OwnerMon, Deadline) -> - Remaining = recv_remaining(Deadline), - case Transport:recv(Socket, 0, min(Remaining, ?OWNER_CHECK_INTERVAL)) of - {error, timeout} when Remaining > ?OWNER_CHECK_INTERVAL -> + {OK, Closed, Error} = Transport:messages(Socket), + case Transport:setopts(Socket, [{active, once}]) of + ok -> receive + {OK, Socket, Bin} -> + {ok, Bin}; + {Closed, Socket} -> + {error, closed}; + {Error, Socket, Reason} -> + {error, Reason}; {?MODULE, abort_read} -> exit(normal); {'DOWN', OwnerMon, process, _, _} = Down when is_reference(OwnerMon) -> + _ = Transport:setopts(Socket, [{active, false}]), self() ! Down, {error, owner_down} - after 0 -> - owner_recv(Transport, Socket, OwnerMon, Deadline) + after Timeout -> + _ = Transport:setopts(Socket, [{active, false}]), + %% Data, or a close, that arrived before the socket went + %% back to passive. + receive + {OK, Socket, Bin} -> {ok, Bin}; + {Closed, Socket} -> {error, closed}; + {Error, Socket, Reason} -> {error, Reason} + after 0 -> + {error, timeout} + end end; - Result -> - Result + {error, _} -> + %% The socket is gone: what a passive recv would have said. + {error, closed} end. -recv_deadline(infinity) -> infinity; -recv_deadline(Timeout) -> erlang:monotonic_time(millisecond) + Timeout. - -%% Atoms sort after integers, so min/2 keeps a slice when this is infinity. -recv_remaining(infinity) -> infinity; -recv_remaining(Deadline) -> max(0, Deadline - erlang:monotonic_time(millisecond)). - %% @private Determine if we should enable active mode when entering connected state %% We only want active mode for close detection when the connection is truly idle %% (returning from a completed request), not on initial connection where the server diff --git a/test/hackney_close_hang_tests.erl b/test/hackney_close_hang_tests.erl index d222856d..34153497 100644 --- a/test/hackney_close_hang_tests.erl +++ b/test/hackney_close_hang_tests.erl @@ -1,137 +1,330 @@ -%%% #996: closing a connection whose server accepted the request but never -%%% answers must not hang. close/1 used to wait for the passive read in -%%% progress to end, which on a pooled connection (no recv_timeout by -%%% default) was never. +%%% Closing an HTTP/1.1 request that waits for its response, or the death of +%%% its owner, acts at once: the conn stops with a normal exit, the server +%%% sees the socket close and the caller gets no message for the request. +%%% close/1 used to wait for the passive read in progress, which on a pooled +%%% connection was never (#996), and then for up to one second, the slice +%%% that read was cut into. -module(hackney_close_hang_tests). -include_lib("eunit/include/eunit.hrl"). -define(POOL, hackney_close_hang_pool). +%% The sliced read took about a second. This bound stays well clear of it +%% and leaves room for a slow CI host. +-define(FAST, 250). +-define(WAIT, 5000). +%% Status, headers and one chunk; the body stays open. +-define(PARTIAL, <<"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n" + "2\r\nok\r\n">>). close_hang_test_() -> {setup, fun setup/0, fun cleanup/1, - fun({_Server, Port}) -> - Url = iolist_to_binary(["https://localhost:", integer_to_list(Port), "/"]), - [{"close of a pooled async request returns promptly", - {timeout, 30, fun() -> close_async(Url, [{pool, ?POOL}]) end}}, - {"close of an unpooled async request returns before recv_timeout", - {timeout, 30, fun() -> close_async(Url, [{pool, false}]) end}}, - {"close of a pooled sync request returns promptly", - {timeout, 30, fun() -> close_sync(Url) end}}] - end}. + [{timeout, 30, + {Title ++ " (" ++ atom_to_list(Proto) ++ ")", + fun() -> with_server(Proto, Fun) end}} + || Proto <- [tcp, tls], + {Title, Fun} <- [ + {"close while the response is awaited", fun close_awaiting/1}, + {"owner killed while the response is awaited", fun owner_killed/1}, + {"a pooled conn closed while waiting is not reused", fun close_pooled/1}, + {"close during an async body", fun close_async_body/1}, + {"close during an {async, once} body", fun close_async_once_body/1}, + {"close notice between two reads", fun notice_between_reads/1}, + {"close during a streamed upload", fun close_upload/1}, + {"close of a held conn with a sync request", fun close_held_sync/1}]]}. setup() -> _ = application:ensure_all_started(hackney), _ = (try hackney_pool:stop_pool(?POOL) catch _:_ -> ok end), - ok = hackney_pool:start_pool(?POOL, [{pool_size, 2}]), - start_server(?MODULE). + ok = hackney_pool:start_pool(?POOL, [{pool_size, 2}]). -cleanup({Server, _Port}) -> +cleanup(_) -> _ = (try hackney_pool:stop_pool(?POOL) catch _:_ -> ok end), - exit(Server, shutdown), ok. -opts(Extra) -> - [{insecure, true} | Extra]. +%%==================================================================== +%% Tests +%%==================================================================== -close_async(Url, PoolOpt) -> - ok = listen(), - {ok, Conn} = hackney:get(Url, [], <<>>, opts([{async, once} | PoolOpt])), - %% The server has read the request: the conn is now blocked reading the - %% status line of a response that never comes. - ok = await_request(), +close_awaiting(Srv) -> + {ok, Conn} = hackney:get(url(Srv), [], <<>>, opts([async, {pool, false}])), + H = wait_server(Srv, request_seen), + close_fast(Srv, H, Conn). + +owner_killed(Srv) -> + Test = self(), + Owner = spawn(fun() -> + {ok, Conn} = hackney:get(url(Srv), [], <<>>, opts([async, {pool, false}])), + Test ! {conn, Conn}, + receive after infinity -> ok end + end), + Conn = receive {conn, C} -> C after ?WAIT -> error(no_conn) end, + H = wait_server(Srv, request_seen), MRef = erlang:monitor(process, Conn), - T0 = erlang:monotonic_time(millisecond), - ok = hackney:close(Conn), - Ms = erlang:monotonic_time(millisecond) - T0, - %% recv_timeout is 5000 by default: close must not wait for it. - ?assert(Ms < 3000), - receive {'DOWN', MRef, process, Conn, Reason} -> ?assertEqual(normal, Reason) - after 1000 -> ?assert(false) - end, + T0 = now_ms(), + exit(Owner, kill), + wait_down(MRef, Conn), + ?assert(now_ms() - T0 < ?FAST), + wait_closed(Srv, H, T0). + +%% The closed conn is neither handed back to the pool nor counted in use, +%% and the next request dials a new socket. +close_pooled(Srv) -> + Pool = list_to_atom("hackney_close_hang_" ++ atom_to_list(maps:get(proto, Srv))), + ok = hackney_pool:start_pool(Pool, [{pool_size, 1}]), + try + Opts = opts([async, {pool, Pool}]), + {ok, Conn} = hackney:get(url(Srv), [], <<>>, Opts), + H = wait_server(Srv, request_seen), + close_fast(Srv, H, Conn), + ok = wait_until(fun() -> + proplists:get_value(in_use_count, hackney_pool:get_stats(Pool)) =:= 0 + end), + ?assertEqual(0, proplists:get_value(free_count, hackney_pool:get_stats(Pool))), + {ok, Conn2} = hackney:get(url(Srv), [], <<>>, Opts), + ?assertNotEqual(Conn, Conn2), + H2 = wait_server(Srv, request_seen), + ?assertNotEqual(H, H2), + close_fast(Srv, H2, Conn2) + after + hackney_pool:stop_pool(Pool) + end. + +close_async_body(Srv) -> + {ok, Conn} = hackney:get(url(Srv), [], <<>>, opts([async, {pool, false}])), + H = wait_server(Srv, request_seen), + H ! {send, ?PARTIAL}, + await_headers(Conn), + await_chunk(Conn), + close_fast(Srv, H, Conn). + +%% The pull after the first chunk leaves the conn reading a body that has +%% nothing more to give. +close_async_once_body(Srv) -> + {ok, Conn} = hackney:get(url(Srv), [], <<>>, opts([{async, once}, {pool, false}])), + H = wait_server(Srv, request_seen), + H ! {send, ?PARTIAL}, + await_headers(Conn), + ok = hackney:stream_next(Conn), + await_chunk(Conn), + ok = hackney:stream_next(Conn), + close_fast(Srv, H, Conn). + +%% The notice lands while the conn is not reading and a pull comes after it, +%% as when the pull comes from another process than the one closing: the +%% conn stops on the notice instead of waiting in that read. +notice_between_reads(Srv) -> + {ok, Conn} = hackney:get(url(Srv), [], <<>>, opts([{async, once}, {pool, false}])), + H = wait_server(Srv, request_seen), + H ! {send, ?PARTIAL}, + await_headers(Conn), + ok = hackney:stream_next(Conn), + await_chunk(Conn), + MRef = erlang:monitor(process, Conn), + T0 = now_ms(), + ok = hackney_conn:abort_read(Conn), + ok = hackney:stream_next(Conn), + wait_down(MRef, Conn), + ?assert(now_ms() - T0 < ?FAST), + wait_closed(Srv, H, T0), no_stray_messages(Conn). -%% A sync request blocked on the same server, closed from another process: -%% close returns promptly and the request fails the way a stopped conn -%% always made it fail. -close_sync(Url) -> - ok = listen(), - {ok, Conn} = hackney:connect(Url, opts([{pool, ?POOL}])), - Self = self(), +close_upload(Srv) -> + {ok, Conn} = hackney:request(post, url(Srv), [], stream, opts([{pool, false}])), + ok = hackney:send_body(Conn, <<"chunk">>), + H = wait_server(Srv, request_seen), + close_fast(Srv, H, Conn). + +%% A sync request blocked on a conn held through connect/2, closed from +%% another process: the request fails the way a stopped conn always made +%% it fail. +close_held_sync(Srv) -> + {ok, Conn} = hackney:connect(url(Srv), opts([{pool, ?POOL}])), + Test = self(), Req = spawn(fun() -> - Self ! {result, hackney:send_request(Conn, {get, <<"/">>, [], <<>>})} - end), - ok = await_request(), - T0 = erlang:monotonic_time(millisecond), + Test ! {result, hackney:send_request(Conn, {get, <<"/">>, [], <<>>})} + end), + H = wait_server(Srv, request_seen), + MRef = erlang:monitor(process, Conn), + T0 = now_ms(), ok = hackney:close(Conn), - ?assert(erlang:monotonic_time(millisecond) - T0 < 3000), + ?assert(now_ms() - T0 < ?FAST), receive {result, R} -> ?assertMatch({error, _}, R) - after 3000 -> exit(Req, kill), ?assert(false) + after ?WAIT -> exit(Req, kill), error(no_result) end, - ?assertNot(is_process_alive(Conn)). + wait_down(MRef, Conn), + wait_closed(Srv, H, T0). + +%%==================================================================== +%% Helpers +%%==================================================================== + +opts(Extra) -> + [{insecure, true} | Extra]. + +%% close/1 returns at once, the conn exits normal, the server sees the +%% socket close and no message for the request reaches the caller. +close_fast(Srv, H, Conn) -> + MRef = erlang:monitor(process, Conn), + T0 = now_ms(), + ok = hackney:close(Conn), + ?assert(now_ms() - T0 < ?FAST), + wait_down(MRef, Conn), + wait_closed(Srv, H, T0), + no_stray_messages(Conn). + +wait_down(MRef, Conn) -> + receive {'DOWN', MRef, process, Conn, Reason} -> ?assertEqual(normal, Reason) + after ?WAIT -> error(conn_still_up) + end. + +wait_closed(#{tag := Tag}, H, T0) -> + receive {Tag, closed, H} -> ?assert(now_ms() - T0 < ?FAST) + after ?WAIT -> error(socket_left_open) + end. + +wait_server(#{tag := Tag}, Event) -> + receive {Tag, Event, H} -> H + after ?WAIT -> error({server_event_missing, Event}) + end. + +await_headers(Conn) -> + receive {hackney_response, Conn, {status, 200, _}} -> ok + after ?WAIT -> error(no_status) + end, + receive {hackney_response, Conn, {headers, _}} -> ok + after ?WAIT -> error(no_headers) + end. + +await_chunk(Conn) -> + receive {hackney_response, Conn, <<"ok">>} -> ok + after ?WAIT -> error(no_chunk) + end. -%% No message for a closed request reaches the caller. no_stray_messages(Conn) -> receive {hackney_response, Conn, _} = M -> ?assertEqual(none, M) after 200 -> ok end. -%% The server reports to whichever test is running: setup runs in another -%% process, so each test registers itself under ?MODULE. -listen() -> - true = register(?MODULE, self()), - ok. +wait_until(Fun) -> + wait_until(Fun, 50). + +wait_until(_Fun, 0) -> + timeout; +wait_until(Fun, N) -> + case Fun() of + true -> ok; + false -> receive after 20 -> wait_until(Fun, N - 1) end + end. + +now_ms() -> + erlang:monotonic_time(millisecond). -await_request() -> - Result = receive {server, got_request} -> ok - after 10000 -> {error, no_request} - end, - unregister(?MODULE), - Result. +url(#{proto := tcp, port := Port}) -> + iolist_to_binary(["http://127.0.0.1:", integer_to_list(Port), "/"]); +url(#{proto := tls, port := Port}) -> + iolist_to_binary(["https://127.0.0.1:", integer_to_list(Port), "/"]). %%==================================================================== -%% TLS server that reads a request, reports it, and never answers. +%% Server: reads a request and answers only when told to ({send, Bytes}). +%% It reports, with its handler pid, each request it has read and each +%% socket close, over TCP or TLS. %%==================================================================== -start_server(Notify) -> +with_server(Proto, Fun) -> + Tag = make_ref(), + Test = self(), + {L, Port} = listen(Proto), + Acceptor = spawn(fun() -> receive go -> accept_loop(Proto, L, Tag, Test) end end), + ok = listener_owner(Proto, L, Acceptor), + Acceptor ! go, + try + Fun(#{tag => Tag, port => Port, proto => Proto}) + after + exit(Acceptor, kill), + _ = close(Proto, L) + end. + +listen(tcp) -> + {ok, L} = gen_tcp:listen(0, [binary, {active, false}, {ip, {127, 0, 0, 1}}]), + {ok, Port} = inet:port(L), + {L, Port}; +listen(tls) -> Certs = cert_dir(), - {ok, LSock} = ssl:listen(0, - [{certfile, filename:join(Certs, "server.pem")}, - {keyfile, filename:join(Certs, "server.key")}, - {versions, ['tlsv1.2', 'tlsv1.3']}, - {active, false}, {mode, binary}, {reuseaddr, true}]), - {ok, {_, Port}} = ssl:sockname(LSock), - Pid = spawn(fun() -> accept_loop(LSock, Notify) end), - {Pid, Port}. - -accept_loop(LSock, Notify) -> - case ssl:transport_accept(LSock, 2000) of - {ok, TSock} -> - spawn(fun() -> - case ssl:handshake(TSock, 5000) of - {ok, Sock} -> serve(Sock, Notify, <<>>); - _ -> ok - end - end), - accept_loop(LSock, Notify); - {error, timeout} -> accept_loop(LSock, Notify); - {error, _} -> ok + {ok, L} = ssl:listen(0, [{certfile, filename:join(Certs, "server.pem")}, + {keyfile, filename:join(Certs, "server.key")}, + {versions, ['tlsv1.2', 'tlsv1.3']}, + {ip, {127, 0, 0, 1}}, + binary, {active, false}, {reuseaddr, true}]), + {ok, {_, Port}} = ssl:sockname(L), + {L, Port}. + +listener_owner(tcp, L, Pid) -> gen_tcp:controlling_process(L, Pid); +listener_owner(tls, L, Pid) -> ssl:controlling_process(L, Pid). + +close(tcp, S) -> gen_tcp:close(S); +close(tls, S) -> ssl:close(S). + +accept_loop(Proto, L, Tag, Test) -> + case accept(Proto, L) of + {ok, S} -> + H = spawn(fun() -> receive go -> handle(Proto, S, Tag, Test) end end), + ok = socket_owner(Proto, S, H), + H ! go, + accept_loop(Proto, L, Tag, Test); + {error, closed} -> + ok; + {error, _} -> + accept_loop(Proto, L, Tag, Test) + end. + +accept(tcp, L) -> + gen_tcp:accept(L); +accept(tls, L) -> + case ssl:transport_accept(L) of + {ok, T} -> ssl:handshake(T, 5000); + Error -> Error + end. + +socket_owner(tcp, S, Pid) -> gen_tcp:controlling_process(S, Pid); +socket_owner(tls, S, Pid) -> ssl:controlling_process(S, Pid). + +handle(tcp, S, Tag, Test) -> + ok = inet:setopts(S, [{active, true}]), + handle_loop(tcp, S, Tag, Test, <<>>); +handle(tls, S, Tag, Test) -> + ok = ssl:setopts(S, [{active, true}]), + handle_loop(tls, S, Tag, Test, <<>>). + +handle_loop(Proto, S, Tag, Test, Acc) -> + receive + {Data, S, Bytes} when Data =:= tcp; Data =:= ssl -> + handle_loop(Proto, S, Tag, Test, request_seen(Acc, Bytes, Tag, Test)); + {send, Bytes} -> + _ = case Proto of + tcp -> gen_tcp:send(S, Bytes); + tls -> ssl:send(S, Bytes) + end, + handle_loop(Proto, S, Tag, Test, Acc); + {Closed, S} when Closed =:= tcp_closed; Closed =:= ssl_closed -> + Test ! {Tag, closed, self()}; + {Error, S, _} when Error =:= tcp_error; Error =:= ssl_error -> + Test ! {Tag, closed, self()} end. -serve(Sock, Notify, Acc) -> - case binary:match(Acc, <<"\r\n\r\n">>) of +%% Report the request once its headers are in; `seen' afterwards. +request_seen(seen, _Bytes, _Tag, _Test) -> + seen; +request_seen(Acc, Bytes, Tag, Test) -> + Acc1 = <>, + case binary:match(Acc1, <<"\r\n\r\n">>) of nomatch -> - case ssl:recv(Sock, 0, 30000) of - {ok, Data} -> serve(Sock, Notify, <>); - {error, _} -> ok - end; + Acc1; _ -> - _ = (try Notify ! {server, got_request} catch error:badarg -> ok end), - %% Hold the connection open without answering. - _ = ssl:recv(Sock, 0, 30000), - ok + Test ! {Tag, request_seen, self()}, + seen end. cert_dir() -> diff --git a/test/hackney_direct_owner_tests.erl b/test/hackney_direct_owner_tests.erl index cac74805..fd12cf09 100644 --- a/test/hackney_direct_owner_tests.erl +++ b/test/hackney_direct_owner_tests.erl @@ -13,8 +13,8 @@ %%% hackney_conn process to go down and for the server to see its socket %%% close. %%% -%%% An HTTP/1.1 conn waiting for a response reads in slices and checks for -%%% its owner's 'DOWN' between them, so those tests keep the server silent. +%%% An HTTP/1.1 conn waiting for a response sees its owner's 'DOWN' while it +%%% reads, so those tests keep the server silent. -module(hackney_direct_owner_tests). -include_lib("eunit/include/eunit.hrl"). diff --git a/test/hackney_http2_shared_conn_tests.erl b/test/hackney_http2_shared_conn_tests.erl index 54455017..500bf1fe 100644 --- a/test/hackney_http2_shared_conn_tests.erl +++ b/test/hackney_http2_shared_conn_tests.erl @@ -221,8 +221,9 @@ close_keeps_shared_conn() -> ?assertMatch({ok, 200, _, <<"ok">>}, result(first)) end). -%% A caller with its own stream open closes the connection: that stream is -%% reset and its monitor dropped, the other caller's stream is untouched. +%% A caller with its own stream open closes the connection: the close +%% returns at once, that stream is reset and its monitor dropped, the other +%% caller's stream is untouched and the connection takes new requests. close_resets_own_stream() -> with_server([], fun(URL, Port, Opts) -> _ = sync_request(first, <>, Opts), @@ -233,17 +234,26 @@ close_resets_own_stream() -> {ok, Conn} = hackney:connect(URL, Opts), {ok, _} = hackney_conn:request_async(Conn, <<"GET">>, <<"/second">>, [], <<>>, true), - receive close -> Parent ! {closed, hackney:close(Conn)} end, + receive close -> + T0 = erlang:monotonic_time(millisecond), + R = hackney:close(Conn), + Parent ! {closed, R, erlang:monotonic_time(millisecond) - T0} + end, receive after infinity -> ok end end), _ = started(<<"/second">>), ?assert(lists:member(Closer, monitored(Conn))), Closer ! close, - receive {closed, R} -> ?assertEqual(ok, R) after 5000 -> error(no_close) end, + receive {closed, R, Ms} -> ?assertEqual(ok, R), ?assert(Ms < 250) + after 5000 -> error(no_close) + end, ?assertNot(lists:member(Closer, monitored(Conn))), ?assert(is_process_alive(Conn)), FirstHandler ! respond, ?assertMatch({ok, 200, _, <<"ok">>}, result(first)), + ?assertMatch({ok, 200, _, <<"ok">>}, + hackney:request(get, <>, [], <<>>, Opts)), + ?assertEqual(Conn, shared_conn(Opts, Port)), exit(Closer, kill) end).