diff --git a/grpc/lib/grpc/client/adapters/gun/connection_process.ex b/grpc/lib/grpc/client/adapters/gun/connection_process.ex index 194a80e2..2d8bef51 100644 --- a/grpc/lib/grpc/client/adapters/gun/connection_process.ex +++ b/grpc/lib/grpc/client/adapters/gun/connection_process.ex @@ -1,564 +1,582 @@ -defmodule GRPC.Client.Adapters.Gun.ConnectionProcess do - @moduledoc """ - Owns long-lived Gun connections on behalf of the Gun adapter. - - This process exists so named Gun-backed channels are no longer tied to the - lifecycle of the process that happened to call `GRPC.Stub.connect/2`. - - Without this wrapper, `GRPC.Client.Connection` would need to own Gun directly - or understand Gun-specific owner messages. Keeping Gun ownership in this - adapter-local process preserves a clean adapter boundary while ensuring the - underlying Gun connection survives short-lived callers. - - Request-specific Gun messages are routed to per-stream response processes, so - this process only needs to manage connection-level lifecycle and stream - bookkeeping. - - Named channels are registered in the node-local `GRPC.Client.Registry` under - `{ref, host, port}`, so a connection is reused by every caller on the node. - - The handshake runs after `init/1` returns, and `connect/2` waits for it - outside the node-wide `GRPC.Client.Supervisor`. A slow or unreachable host - therefore doesn't hold up connects to other hosts. - """ - - use GenServer - - @deadline_cancel_grace_ms 100 - @default_await_timeout 5_000 - # Extra time for the call on top of `:await_timeout`. The connection process - # replies by the time its own timer fires, so this only covers scheduling. - @await_up_call_margin_ms 1_000 - # Gun counts a stream's `flow` in DATA frames, and a peer sends at most - # 16 KiB per frame unless the local settings raise it. - @frame_size 16_384 - - require Logger - alias GRPC.Client.Adapter - alias GRPC.Client.Adapters.Gun.StreamResponseProcess - alias GRPC.Client.Telemetry - - def connect(channel, open_opts) when is_map(open_opts) do - case DynamicSupervisor.start_child(GRPC.Client.Supervisor, child_spec(channel, open_opts)) do - {:ok, connection_process_pid} -> - await_up(connection_process_pid, open_opts) +if Code.ensure_loaded?(:gun) do + defmodule GRPC.Client.Adapters.Gun.ConnectionProcess do + @moduledoc """ + Owns long-lived Gun connections on behalf of the Gun adapter. + + This process exists so named Gun-backed channels are no longer tied to the + lifecycle of the process that happened to call `GRPC.Stub.connect/2`. + + Without this wrapper, `GRPC.Client.Connection` would need to own Gun directly + or understand Gun-specific owner messages. Keeping Gun ownership in this + adapter-local process preserves a clean adapter boundary while ensuring the + underlying Gun connection survives short-lived callers. + + Request-specific Gun messages are routed to per-stream response processes, so + this process only needs to manage connection-level lifecycle and stream + bookkeeping. + + Named channels are registered in the node-local `GRPC.Client.Registry` under + `{ref, host, port}`, so a connection is reused by every caller on the node. + + The handshake runs after `init/1` returns, and `connect/2` waits for it + outside the node-wide `GRPC.Client.Supervisor`. A slow or unreachable host + therefore doesn't hold up connects to other hosts. + """ + + use GenServer + + @deadline_cancel_grace_ms 100 + @default_await_timeout 5_000 + # Extra time for the call on top of `:await_timeout`. The connection process + # replies by the time its own timer fires, so this only covers scheduling. + @await_up_call_margin_ms 1_000 + # Gun counts a stream's `flow` in DATA frames, and a peer sends at most + # 16 KiB per frame unless the local settings raise it. + @frame_size 16_384 + + require Logger + alias GRPC.Client.Adapter + alias GRPC.Client.Adapters.Gun.StreamResponseProcess + alias GRPC.Client.Telemetry + + def connect(channel, open_opts) when is_map(open_opts) do + case DynamicSupervisor.start_child(GRPC.Client.Supervisor, child_spec(channel, open_opts)) do + {:ok, connection_process_pid} -> + await_up(connection_process_pid, open_opts) + + {:error, {:already_started, connection_process_pid}} -> + await_up(connection_process_pid, open_opts) + + {:error, reason} -> + {:error, reason} + end + end - {:error, {:already_started, connection_process_pid}} -> - await_up(connection_process_pid, open_opts) + defp await_up(connection_process_pid, open_opts) do + timeout = + Map.get(open_opts, :await_timeout, @default_await_timeout) + @await_up_call_margin_ms - {:error, reason} -> - {:error, reason} + case GenServer.call(connection_process_pid, :await_up, timeout) do + :ok -> {:ok, %{conn_pid: connection_process_pid}} + {:error, reason} -> {:error, reason} + end + catch + :exit, {reason, {GenServer, :call, _}} -> {:error, reason} end - end - defp await_up(connection_process_pid, open_opts) do - timeout = - Map.get(open_opts, :await_timeout, @default_await_timeout) + @await_up_call_margin_ms - - case GenServer.call(connection_process_pid, :await_up, timeout) do - :ok -> {:ok, %{conn_pid: connection_process_pid}} - {:error, reason} -> {:error, reason} + def disconnect(connection_process_pid) when is_pid(connection_process_pid) do + GenServer.call(connection_process_pid, :disconnect) + catch + :exit, _reason -> + :ok end - catch - :exit, {reason, {GenServer, :call, _}} -> {:error, reason} - end - def disconnect(connection_process_pid) when is_pid(connection_process_pid) do - GenServer.call(connection_process_pid, :disconnect) - catch - :exit, _reason -> - :ok - end + # Calls carrying headers or bodies go through `Adapter.call/3`, so an exit (busy or dead + # connection process) does not leak them into logs and telemetry. + def request(connection_process_pid, path, headers, body, deadline \\ :infinity) do + Adapter.call(connection_process_pid, {:request, path, headers, body, deadline}) + end - # Calls carrying headers or bodies go through `Adapter.call/3`, so an exit (busy or dead - # connection process) does not leak them into logs and telemetry. - def request(connection_process_pid, path, headers, body, deadline \\ :infinity) do - Adapter.call(connection_process_pid, {:request, path, headers, body, deadline}) - end + def open_stream(connection_process_pid, path, headers, deadline \\ :infinity) do + Adapter.call(connection_process_pid, {:open_stream, path, headers, deadline}) + end - def open_stream(connection_process_pid, path, headers, deadline \\ :infinity) do - Adapter.call(connection_process_pid, {:open_stream, path, headers, deadline}) - end + def send_data(connection_process_pid, stream_ref, fin, data) do + Adapter.call(connection_process_pid, {:send_data, stream_ref, fin, data}) + end - def send_data(connection_process_pid, stream_ref, fin, data) do - Adapter.call(connection_process_pid, {:send_data, stream_ref, fin, data}) - end + # A dead connection process has nothing left to cancel. + def cancel(connection_process_pid, stream_ref) do + GenServer.call(connection_process_pid, {:cancel, stream_ref}) + catch + :exit, _reason -> :ok + end - # A dead connection process has nothing left to cancel. - def cancel(connection_process_pid, stream_ref) do - GenServer.call(connection_process_pid, {:cancel, stream_ref}) - catch - :exit, _reason -> :ok - end + defp child_spec(channel, open_opts) do + %{ + id: {__MODULE__, owner_key(channel)}, + start: {__MODULE__, :start_link, [channel, open_opts]}, + restart: :temporary, + type: :worker, + shutdown: 5000 + } + end - defp child_spec(channel, open_opts) do - %{ - id: {__MODULE__, owner_key(channel)}, - start: {__MODULE__, :start_link, [channel, open_opts]}, - restart: :temporary, - type: :worker, - shutdown: 5000 - } - end + def start_link(channel, open_opts) do + if is_nil(channel.ref) do + GenServer.start_link(__MODULE__, {channel, open_opts}) + else + GenServer.start_link(__MODULE__, {channel, open_opts}, name: via(channel)) + end + end - def start_link(channel, open_opts) do - if is_nil(channel.ref) do - GenServer.start_link(__MODULE__, {channel, open_opts}) - else - GenServer.start_link(__MODULE__, {channel, open_opts}, name: via(channel)) + @impl GenServer + def init({%{host: host, port: port} = channel, open_opts}) do + # Pooled connections open with `ref: nil`, so the pool passes the logical ref separately + {logical_ref, open_opts} = Map.pop(open_opts, :logical_connection_ref, channel.ref) + metadata = metadata(channel, logical_ref) + Telemetry.execute(:started, %{generation: 0, active_streams: 0}, metadata) + {await_timeout, open_opts} = Map.pop(open_opts, :await_timeout, @default_await_timeout) + {response_window, open_opts} = Map.pop(open_opts, :response_window, :infinity) + + case open(host, port, open_opts) do + {:ok, gun_pid} -> + # Monitor Gun so we don't keep casting into a dead pid if Gun + # exhausts its reconnect retries (or crashes) + Process.monitor(gun_pid) + + {:ok, + %{ + channel: channel, + logical_connection_ref: logical_ref, + gun_pid: gun_pid, + flow: window_to_flow(response_window), + response_processes: %{}, + generation: 0, + max_concurrent_streams: :unknown, + status: :connecting, + waiters: [], + await_timer: Process.send_after(self(), :await_up_timeout, await_timeout) + }} + + {:error, reason} -> + connect_failed(metadata, reason) + {:stop, reason} + end end - end - @impl GenServer - def init({%{host: host, port: port} = channel, open_opts}) do - # Pooled connections open with `ref: nil`, so the pool passes the logical ref separately - {logical_ref, open_opts} = Map.pop(open_opts, :logical_connection_ref, channel.ref) - metadata = metadata(channel, logical_ref) - Telemetry.execute(:started, %{generation: 0, active_streams: 0}, metadata) - {await_timeout, open_opts} = Map.pop(open_opts, :await_timeout, @default_await_timeout) - {response_window, open_opts} = Map.pop(open_opts, :response_window, :infinity) - - case open(host, port, open_opts) do - {:ok, gun_pid} -> - # Monitor Gun so we don't keep casting into a dead pid if Gun - # exhausts its reconnect retries (or crashes) - Process.monitor(gun_pid) - - {:ok, - %{ - channel: channel, - logical_connection_ref: logical_ref, - gun_pid: gun_pid, - flow: window_to_flow(response_window), - response_processes: %{}, - generation: 0, - max_concurrent_streams: :unknown, - status: :connecting, - waiters: [], - await_timer: Process.send_after(self(), :await_up_timeout, await_timeout) - }} - - {:error, reason} -> - connect_failed(metadata, reason) - {:stop, reason} + @impl GenServer + def handle_call(:await_up, _from, %{status: :up} = state) do + {:reply, :ok, state} end - end - @impl GenServer - def handle_call(:await_up, _from, %{status: :up} = state) do - {:reply, :ok, state} - end + def handle_call(:await_up, from, %{status: :connecting} = state) do + {:noreply, %{state | waiters: [from | state.waiters]}} + end - def handle_call(:await_up, from, %{status: :connecting} = state) do - {:noreply, %{state | waiters: [from | state.waiters]}} - end + def handle_call(:disconnect, _from, %{gun_pid: gun_pid} = state) do + :ok = :gun.shutdown(gun_pid) + reply_waiters(state, {:error, :disconnected}) + {:stop, :normal, :ok, %{state | waiters: []}} + end - def handle_call(:disconnect, _from, %{gun_pid: gun_pid} = state) do - :ok = :gun.shutdown(gun_pid) - reply_waiters(state, {:error, :disconnected}) - {:stop, :normal, :ok, %{state | waiters: []}} - end + def handle_call( + {:request, path, headers, body, deadline}, + {caller_pid, _}, + %{gun_pid: gun_pid} = state + ) do + with {:ok, response_pid} <- start_response_process(), + stream_ref <- :gun.post(gun_pid, path, headers, body, req_opts(state, response_pid)), + state <- put_response_pid(state, stream_ref, response_pid, caller_pid), + :ok <- StreamResponseProcess.track(response_pid, self(), stream_ref, deadline) do + {:reply, {:ok, %{stream_ref: stream_ref, response_pid: response_pid}}, state} + else + {:error, reason} -> {:reply, {:error, reason}, state} + end + end - def handle_call( - {:request, path, headers, body, deadline}, - {caller_pid, _}, - %{gun_pid: gun_pid} = state - ) do - with {:ok, response_pid} <- start_response_process(), - stream_ref <- :gun.post(gun_pid, path, headers, body, req_opts(state, response_pid)), - state <- put_response_pid(state, stream_ref, response_pid, caller_pid), - :ok <- StreamResponseProcess.track(response_pid, self(), stream_ref, deadline) do - {:reply, {:ok, %{stream_ref: stream_ref, response_pid: response_pid}}, state} - else - {:error, reason} -> {:reply, {:error, reason}, state} + def handle_call( + {:open_stream, path, headers, deadline}, + {caller_pid, _}, + %{gun_pid: gun_pid} = state + ) do + with {:ok, response_pid} <- start_response_process(), + stream_ref <- :gun.post(gun_pid, path, headers, req_opts(state, response_pid)), + state <- put_response_pid(state, stream_ref, response_pid, caller_pid), + :ok <- StreamResponseProcess.track(response_pid, self(), stream_ref, deadline) do + {:reply, {:ok, %{stream_ref: stream_ref, response_pid: response_pid}}, state} + else + {:error, reason} -> {:reply, {:error, reason}, state} + end end - end - def handle_call( - {:open_stream, path, headers, deadline}, - {caller_pid, _}, - %{gun_pid: gun_pid} = state - ) do - with {:ok, response_pid} <- start_response_process(), - stream_ref <- :gun.post(gun_pid, path, headers, req_opts(state, response_pid)), - state <- put_response_pid(state, stream_ref, response_pid, caller_pid), - :ok <- StreamResponseProcess.track(response_pid, self(), stream_ref, deadline) do - {:reply, {:ok, %{stream_ref: stream_ref, response_pid: response_pid}}, state} - else - {:error, reason} -> {:reply, {:error, reason}, state} + def handle_call({:send_data, stream_ref, fin, data}, _from, %{gun_pid: gun_pid} = state) do + :ok = :gun.data(gun_pid, stream_ref, fin, data) + {:reply, :ok, state} end - end - def handle_call({:send_data, stream_ref, fin, data}, _from, %{gun_pid: gun_pid} = state) do - :ok = :gun.data(gun_pid, stream_ref, fin, data) - {:reply, :ok, state} - end + def handle_call({:cancel, stream_ref}, _from, state) do + {:reply, :ok, cancel_stream(state, stream_ref, nil, true)} + end - def handle_call({:cancel, stream_ref}, _from, state) do - {:reply, :ok, cancel_stream(state, stream_ref, nil, true)} - end + @impl GenServer + def handle_info( + {:gun_up, gun_pid, protocol}, + %{status: :connecting, gun_pid: gun_pid} = state + ) do + Process.cancel_timer(state.await_timer) + state = %{state | await_timer: nil} + + case protocol do + :http2 -> + Telemetry.execute( + :connected, + %{generation: 1}, + state |> metadata() |> Map.put(:reconnect, false) + ) + + reply_waiters(state, :ok) + {:noreply, %{state | status: :up, generation: 1, waiters: []}} + + proto -> + :gun.shutdown(gun_pid) + reason = "Error when opening connection: protocol #{proto} is not http2" + + Telemetry.execute( + :connect_error, + %{}, + Map.merge(metadata(state), %{stage: :http2, reason: reason}) + ) + + Telemetry.execute( + :stopped, + %{streams_terminated: 0}, + Map.put(metadata(state), :reason, reason) + ) + + fail_connect(state, reason) + end + end - @impl GenServer - def handle_info({:gun_up, gun_pid, protocol}, %{status: :connecting, gun_pid: gun_pid} = state) do - Process.cancel_timer(state.await_timer) - state = %{state | await_timer: nil} + def handle_info(:await_up_timeout, %{status: :connecting, gun_pid: gun_pid} = state) do + :gun.shutdown(gun_pid) + connect_failed(metadata(state), :timeout) + fail_connect(%{state | await_timer: nil}, :timeout) + end - case protocol do - :http2 -> - Telemetry.execute( - :connected, - %{generation: 1}, - state |> metadata() |> Map.put(:reconnect, false) - ) + def handle_info(:await_up_timeout, state), do: {:noreply, state} - reply_waiters(state, :ok) - {:noreply, %{state | status: :up, generation: 1, waiters: []}} + def handle_info({:gun_up, _gun_pid, :http2}, state) do + generation = state.generation + 1 - proto -> - :gun.shutdown(gun_pid) - reason = "Error when opening connection: protocol #{proto} is not http2" + Telemetry.execute( + :connected, + %{generation: generation}, + state |> metadata() |> Map.put(:reconnect, true) + ) - Telemetry.execute( - :connect_error, - %{}, - Map.merge(metadata(state), %{stage: :http2, reason: reason}) - ) + {:noreply, %{state | generation: generation, max_concurrent_streams: :unknown}} + end - Telemetry.execute( - :stopped, - %{streams_terminated: 0}, - Map.put(metadata(state), :reason, reason) + def handle_info({:gun_up, _gun_pid, _protocol}, state), do: {:noreply, state} + + def handle_info({:stream_expired, stream_ref, response_pid}, state) do + if response_pid(state, stream_ref) == response_pid do + # Give deadline response frames already in flight a chance to close the + # stream before Gun sends RST_STREAM. Gun 2.4 treats late HEADERS after + # a local reset as a connection error. + Process.send_after( + self(), + {:cancel_expired_stream, stream_ref}, + @deadline_cancel_grace_ms ) - fail_connect(state, reason) + {:noreply, drop_response_pid(state, stream_ref)} + else + {:noreply, state} + end end - end - def handle_info(:await_up_timeout, %{status: :connecting, gun_pid: gun_pid} = state) do - :gun.shutdown(gun_pid) - connect_failed(metadata(state), :timeout) - fail_connect(%{state | await_timer: nil}, :timeout) - end + def handle_info({:cancel_expired_stream, stream_ref}, %{gun_pid: gun_pid} = state) do + cancel_stream(gun_pid, stream_ref) + {:noreply, state} + end - def handle_info(:await_up_timeout, state), do: {:noreply, state} + def handle_info({:gun_down, _gun_pid, _protocol, reason, killed_streams}, state) do + {new_state, killed_count} = + Enum.reduce(killed_streams, {state, 0}, fn stream_ref, {acc, count} -> + if response_pid = response_pid(acc, stream_ref) do + send(response_pid, {:connection_down, reason}) + {drop_response_pid(acc, stream_ref), count + 1} + else + {acc, count} + end + end) - def handle_info({:gun_up, _gun_pid, :http2}, state) do - generation = state.generation + 1 + metadata = Map.put(metadata(state), :reason, reason) + Telemetry.execute(:down, %{streams_terminated: killed_count}, metadata) + {:noreply, %{new_state | max_concurrent_streams: :unknown}} + end - Telemetry.execute( - :connected, - %{generation: generation}, - state |> metadata() |> Map.put(:reconnect, true) - ) + def handle_info({:gun_notify, _gun_pid, :settings_changed, settings}, state) do + max = normalize_max_streams(Map.get(settings, :max_concurrent_streams, :unknown)) - {:noreply, %{state | generation: generation, max_concurrent_streams: :unknown}} - end + if max != state.max_concurrent_streams do + Telemetry.execute(:settings, %{}, Map.put(metadata(state), :max_concurrent_streams, max)) + end - def handle_info({:gun_up, _gun_pid, _protocol}, state), do: {:noreply, state} + {:noreply, %{state | max_concurrent_streams: max}} + end - def handle_info({:stream_expired, stream_ref, response_pid}, state) do - if response_pid(state, stream_ref) == response_pid do - # Give deadline response frames already in flight a chance to close the - # stream before Gun sends RST_STREAM. Gun 2.4 treats late HEADERS after - # a local reset as a connection error. - Process.send_after(self(), {:cancel_expired_stream, stream_ref}, @deadline_cancel_grace_ms) - {:noreply, drop_response_pid(state, stream_ref)} - else - {:noreply, state} + def handle_info( + {:DOWN, _monitor_ref, :process, gun_pid, reason}, + %{status: :connecting, gun_pid: gun_pid} = state + ) do + Process.cancel_timer(state.await_timer) + connect_failed(metadata(state), {:down, reason}) + fail_connect(%{state | await_timer: nil}, {:down, reason}) end - end - def handle_info({:cancel_expired_stream, stream_ref}, %{gun_pid: gun_pid} = state) do - cancel_stream(gun_pid, stream_ref) - {:noreply, state} - end + # Gun is gone for good (reconnect retries exhausted or a crash). Fail all + # in-flight streams and stop + def handle_info({:DOWN, _monitor_ref, :process, gun_pid, reason}, %{gun_pid: gun_pid} = state) do + Enum.each(state.response_processes, fn {_stream_ref, entry} -> + pid = + case entry do + %{response_pid: p} -> p + {p, _} -> p + _ -> nil + end - def handle_info({:gun_down, _gun_pid, _protocol, reason, killed_streams}, state) do - {new_state, killed_count} = - Enum.reduce(killed_streams, {state, 0}, fn stream_ref, {acc, count} -> - if response_pid = response_pid(acc, stream_ref) do - send(response_pid, {:connection_down, reason}) - {drop_response_pid(acc, stream_ref), count + 1} - else - {acc, count} + if is_pid(pid) do + send(pid, {:connection_down, reason}) end end) - metadata = Map.put(metadata(state), :reason, reason) - Telemetry.execute(:down, %{streams_terminated: killed_count}, metadata) - {:noreply, %{new_state | max_concurrent_streams: :unknown}} - end - - def handle_info({:gun_notify, _gun_pid, :settings_changed, settings}, state) do - max = normalize_max_streams(Map.get(settings, :max_concurrent_streams, :unknown)) - - if max != state.max_concurrent_streams do - Telemetry.execute(:settings, %{}, Map.put(metadata(state), :max_concurrent_streams, max)) + {:stop, {:shutdown, {:gun_down, reason}}, state} end - {:noreply, %{state | max_concurrent_streams: max}} - end - - def handle_info( - {:DOWN, _monitor_ref, :process, gun_pid, reason}, - %{status: :connecting, gun_pid: gun_pid} = state - ) do - Process.cancel_timer(state.await_timer) - connect_failed(metadata(state), {:down, reason}) - fail_connect(%{state | await_timer: nil}, {:down, reason}) - end + def handle_info({:DOWN, monitor_ref, :process, _pid, _reason}, %{gun_pid: gun_pid} = state) do + case find_stream_by_monitor(state, monitor_ref) do + {stream_ref, entry} -> + cancel_stream(gun_pid, stream_ref) + + response_pid = + case entry do + %{response_pid: pid} -> pid + {pid, _} -> pid + _ -> nil + end + + caller_monitor = + case entry do + %{caller_monitor: mon} -> mon + _ -> nil + end + + if monitor_ref == caller_monitor and is_pid(response_pid) and + Process.alive?(response_pid) do + GenServer.stop(response_pid, :normal) + end - # Gun is gone for good (reconnect retries exhausted or a crash). Fail all - # in-flight streams and stop - def handle_info({:DOWN, _monitor_ref, :process, gun_pid, reason}, %{gun_pid: gun_pid} = state) do - Enum.each(state.response_processes, fn {_stream_ref, entry} -> - pid = - case entry do - %{response_pid: p} -> p - {p, _} -> p - _ -> nil - end + {:noreply, drop_response_pid(state, stream_ref)} - if is_pid(pid) do - send(pid, {:connection_down, reason}) + nil -> + {:noreply, state} end - end) + end - {:stop, {:shutdown, {:gun_down, reason}}, state} - end + def handle_info({:gun_error, _conn_pid, stream_ref, reason}, state) do + Logger.debug( + "#{inspect(__MODULE__)} received gun_error for stream #{inspect(stream_ref)}: #{inspect(reason)}" + ) - def handle_info({:DOWN, monitor_ref, :process, _pid, _reason}, %{gun_pid: gun_pid} = state) do - case find_stream_by_monitor(state, monitor_ref) do - {stream_ref, entry} -> - cancel_stream(gun_pid, stream_ref) + {:noreply, drop_response_pid(state, stream_ref)} + end - response_pid = - case entry do - %{response_pid: pid} -> pid - {pid, _} -> pid - _ -> nil - end + def handle_info(msg, state) do + Logger.warning("#{inspect(__MODULE__)} received unexpected message: #{inspect(msg)}") + {:noreply, state} + end - caller_monitor = - case entry do - %{caller_monitor: mon} -> mon - _ -> nil - end + # A stream that has already finished is gone from Gun, which answers a cancel + # with a gun_error about the missing stream. Only reset the ones still open. + defp cancel_stream(gun_pid, stream_ref) do + case :gun.stream_info(gun_pid, stream_ref) do + {:ok, :undefined} -> :ok + {:ok, _info} -> :gun.cancel(gun_pid, stream_ref) + {:error, :not_connected} -> :ok + end + end - if monitor_ref == caller_monitor and is_pid(response_pid) and Process.alive?(response_pid) do - GenServer.stop(response_pid, :normal) - end + @impl GenServer + # A failed connect already published `:stopped` with the connect error as reason + def terminate(_reason, %{status: :failed}), do: :ok - {:noreply, drop_response_pid(state, stream_ref)} + def terminate(reason, %{response_processes: processes} = state) do + # Response processes are linked, so a crash takes them down, but a normal + # exit leaves them waiting for messages that will never come. + Enum.each(processes, fn {stream_ref, _entry} -> + send(response_pid(state, stream_ref), {:connection_down, :closed}) + end) - nil -> - {:noreply, state} - end - end + Telemetry.execute( + :stopped, + %{streams_terminated: map_size(processes)}, + Map.put(metadata(state), :reason, reason) + ) - def handle_info({:gun_error, _conn_pid, stream_ref, reason}, state) do - Logger.debug( - "#{inspect(__MODULE__)} received gun_error for stream #{inspect(stream_ref)}: #{inspect(reason)}" - ) + :ok + end - {:noreply, drop_response_pid(state, stream_ref)} - end + defp open({:local, socket_path}, _port, open_opts), do: :gun.open_unix(socket_path, open_opts) + defp open(host, port, open_opts), do: :gun.open(parse_address(host), port, open_opts) - def handle_info(msg, state) do - Logger.warning("#{inspect(__MODULE__)} received unexpected message: #{inspect(msg)}") - {:noreply, state} - end + defp parse_address(host) do + host = String.to_charlist(host) - # A stream that has already finished is gone from Gun, which answers a cancel - # with a gun_error about the missing stream. Only reset the ones still open. - defp cancel_stream(gun_pid, stream_ref) do - case :gun.stream_info(gun_pid, stream_ref) do - {:ok, :undefined} -> :ok - {:ok, _info} -> :gun.cancel(gun_pid, stream_ref) - {:error, :not_connected} -> :ok + case :inet.parse_address(host) do + {:ok, address} -> address + {:error, _} -> host + end end - end - @impl GenServer - # A failed connect already published `:stopped` with the connect error as reason - def terminate(_reason, %{status: :failed}), do: :ok - - def terminate(reason, %{response_processes: processes} = state) do - # Response processes are linked, so a crash takes them down, but a normal - # exit leaves them waiting for messages that will never come. - Enum.each(processes, fn {stream_ref, _entry} -> - send(response_pid(state, stream_ref), {:connection_down, :closed}) - end) + defp via(channel) do + {:via, Registry, {GRPC.Client.Registry, {__MODULE__, owner_key(channel)}}} + end - Telemetry.execute( - :stopped, - %{streams_terminated: map_size(processes)}, - Map.put(metadata(state), :reason, reason) - ) + # Gun sends each DATA frame to `reply_to`, and stops reopening the stream's window + # once `flow` frames are unread. `StreamResponseProcess` returns the frames it hands out. + defp req_opts(%{flow: :infinity}, response_pid), do: %{reply_to: response_pid} + defp req_opts(%{flow: flow}, response_pid), do: %{reply_to: response_pid, flow: flow} - :ok - end + defp window_to_flow(:infinity), do: :infinity - defp open({:local, socket_path}, _port, open_opts), do: :gun.open_unix(socket_path, open_opts) - defp open(host, port, open_opts), do: :gun.open(parse_address(host), port, open_opts) + defp window_to_flow(bytes) when is_integer(bytes), + do: max(div(bytes + @frame_size - 1, @frame_size), 1) - defp parse_address(host) do - host = String.to_charlist(host) + defp start_response_process do + StreamResponseProcess.start_link() + end - case :inet.parse_address(host) do - {:ok, address} -> address - {:error, _} -> host + defp put_response_pid( + %{response_processes: processes} = state, + stream_ref, + response_pid, + caller_pid + ) do + response_monitor = Process.monitor(response_pid) + caller_monitor = if is_pid(caller_pid), do: Process.monitor(caller_pid), else: nil + + entry = %{ + response_pid: response_pid, + response_monitor: response_monitor, + caller_pid: caller_pid, + caller_monitor: caller_monitor + } + + new_state = %{state | response_processes: Map.put(processes, stream_ref, entry)} + emit_streams(new_state, map_size(new_state.response_processes)) + new_state end - end - defp via(channel) do - {:via, Registry, {GRPC.Client.Registry, {__MODULE__, owner_key(channel)}}} - end + defp drop_response_pid(%{response_processes: processes} = state, stream_ref) do + case Map.pop(processes, stream_ref) do + {%{response_monitor: r_mon, caller_monitor: c_mon}, remaining} -> + if r_mon, do: Process.demonitor(r_mon, [:flush]) + if c_mon, do: Process.demonitor(c_mon, [:flush]) + new_state = %{state | response_processes: remaining} + emit_streams(new_state, map_size(remaining)) + new_state + + {{_response_pid, monitor_ref}, remaining} -> + Process.demonitor(monitor_ref, [:flush]) + new_state = %{state | response_processes: remaining} + emit_streams(new_state, map_size(remaining)) + new_state + + {nil, _remaining} -> + state + end + end - # Gun sends each DATA frame to `reply_to`, and stops reopening the stream's window - # once `flow` frames are unread. `StreamResponseProcess` returns the frames it hands out. - defp req_opts(%{flow: :infinity}, response_pid), do: %{reply_to: response_pid} - defp req_opts(%{flow: flow}, response_pid), do: %{reply_to: response_pid, flow: flow} + defp find_stream_by_monitor(%{response_processes: processes}, monitor_ref) do + Enum.find(processes, fn {_stream_ref, entry} -> + case entry do + %{response_monitor: r_mon, caller_monitor: c_mon} -> + r_mon == monitor_ref or c_mon == monitor_ref - defp window_to_flow(:infinity), do: :infinity + {_pid, r_mon} -> + r_mon == monitor_ref - defp window_to_flow(bytes) when is_integer(bytes), - do: max(div(bytes + @frame_size - 1, @frame_size), 1) + _ -> + false + end + end) + end - defp start_response_process do - StreamResponseProcess.start_link() - end + defp response_pid(%{response_processes: processes}, stream_ref) do + case Map.get(processes, stream_ref) do + %{response_pid: response_pid} -> response_pid + {response_pid, _monitor_ref} -> response_pid + nil -> nil + end + end - defp put_response_pid( - %{response_processes: processes} = state, - stream_ref, - response_pid, - caller_pid - ) do - response_monitor = Process.monitor(response_pid) - caller_monitor = if is_pid(caller_pid), do: Process.monitor(caller_pid), else: nil - - entry = %{ - response_pid: response_pid, - response_monitor: response_monitor, - caller_pid: caller_pid, - caller_monitor: caller_monitor - } - - new_state = %{state | response_processes: Map.put(processes, stream_ref, entry)} - emit_streams(new_state, map_size(new_state.response_processes)) - new_state - end + defp cancel_stream(state, stream_ref, expected_pid, stop?) do + response_pid = response_pid(state, stream_ref) - defp drop_response_pid(%{response_processes: processes} = state, stream_ref) do - case Map.pop(processes, stream_ref) do - {%{response_monitor: r_mon, caller_monitor: c_mon}, remaining} -> - if r_mon, do: Process.demonitor(r_mon, [:flush]) - if c_mon, do: Process.demonitor(c_mon, [:flush]) - new_state = %{state | response_processes: remaining} - emit_streams(new_state, map_size(remaining)) - new_state - - {{_response_pid, monitor_ref}, remaining} -> - Process.demonitor(monitor_ref, [:flush]) - new_state = %{state | response_processes: remaining} - emit_streams(new_state, map_size(remaining)) - new_state - - {nil, _remaining} -> + if response_pid && (is_nil(expected_pid) or response_pid == expected_pid) do + :ok = :gun.cancel(state.gun_pid, stream_ref) + if stop?, do: stop_response_process(response_pid) + drop_response_pid(state, stream_ref) + else state + end end - end - defp find_stream_by_monitor(%{response_processes: processes}, monitor_ref) do - Enum.find(processes, fn {_stream_ref, entry} -> - case entry do - %{response_monitor: r_mon, caller_monitor: c_mon} -> - r_mon == monitor_ref or c_mon == monitor_ref + defp stop_response_process(response_pid) do + GenServer.stop(response_pid, :normal) + catch + :exit, _reason -> :ok + end - {_pid, r_mon} -> - r_mon == monitor_ref + defp emit_streams(state, active_streams) do + Telemetry.execute(:streams, %{active: active_streams}, metadata(state)) + end - _ -> - false - end - end) - end + defp normalize_max_streams(:infinity), do: :infinity + defp normalize_max_streams(value) when is_integer(value) and value > 0, do: value + defp normalize_max_streams(_value), do: :unknown - defp response_pid(%{response_processes: processes}, stream_ref) do - case Map.get(processes, stream_ref) do - %{response_pid: response_pid} -> response_pid - {response_pid, _monitor_ref} -> response_pid - nil -> nil + # Stops with `:normal` so `GRPC.Client.Supervisor` doesn't log every failed + # connect; the reason reaches callers through the waiter replies. + defp fail_connect(state, reason) do + reply_waiters(state, {:error, reason}) + {:stop, :normal, %{state | status: :failed, waiters: []}} end - end - - defp cancel_stream(state, stream_ref, expected_pid, stop?) do - response_pid = response_pid(state, stream_ref) - if response_pid && (is_nil(expected_pid) or response_pid == expected_pid) do - :ok = :gun.cancel(state.gun_pid, stream_ref) - if stop?, do: stop_response_process(response_pid) - drop_response_pid(state, stream_ref) - else - state + defp reply_waiters(%{waiters: waiters}, reply) do + Enum.each(waiters, &GenServer.reply(&1, reply)) end - end - defp stop_response_process(response_pid) do - GenServer.stop(response_pid, :normal) - catch - :exit, _reason -> :ok - end + defp connect_failed(metadata, reason) do + maybe_connect_error(metadata, reason) + Telemetry.execute(:stopped, %{streams_terminated: 0}, Map.put(metadata, :reason, reason)) + end - defp emit_streams(state, active_streams) do - Telemetry.execute(:streams, %{active: active_streams}, metadata(state)) - end + defp maybe_connect_error(metadata, reason) do + if stage = connect_stage(reason) do + Telemetry.execute( + :connect_error, + %{}, + Map.merge(metadata, %{stage: stage, reason: reason}) + ) + end + end - defp normalize_max_streams(:infinity), do: :infinity - defp normalize_max_streams(value) when is_integer(value) and value > 0, do: value - defp normalize_max_streams(_value), do: :unknown + defp connect_stage(reason) when reason in [:nxdomain, :host_not_found], do: :resolve - # Stops with `:normal` so `GRPC.Client.Supervisor` doesn't log every failed - # connect; the reason reaches callers through the waiter replies. - defp fail_connect(state, reason) do - reply_waiters(state, {:error, reason}) - {:stop, :normal, %{state | status: :failed, waiters: []}} - end + defp connect_stage(reason) when reason in [:econnrefused, :enetunreach, :ehostunreach], + do: :tcp - defp reply_waiters(%{waiters: waiters}, reply) do - Enum.each(waiters, &GenServer.reply(&1, reply)) - end + defp connect_stage({:tls_alert, _detail}), do: :tls + defp connect_stage({:down, reason}), do: connect_stage(reason) + defp connect_stage({_tag, reason}), do: connect_stage(reason) + defp connect_stage(_reason), do: nil - defp connect_failed(metadata, reason) do - maybe_connect_error(metadata, reason) - Telemetry.execute(:stopped, %{streams_terminated: 0}, Map.put(metadata, :reason, reason)) - end + defp metadata(%{channel: channel, logical_connection_ref: logical_ref}), + do: metadata(channel, logical_ref) - defp maybe_connect_error(metadata, reason) do - if stage = connect_stage(reason) do - Telemetry.execute(:connect_error, %{}, Map.merge(metadata, %{stage: stage, reason: reason})) + defp metadata(channel, logical_ref) do + %{ + logical_connection_ref: logical_ref, + transport_ref: self(), + target: {channel.host, channel.port}, + adapter: GRPC.Client.Adapters.Gun + } end - end - defp connect_stage(reason) when reason in [:nxdomain, :host_not_found], do: :resolve - defp connect_stage(reason) when reason in [:econnrefused, :enetunreach, :ehostunreach], do: :tcp - defp connect_stage({:tls_alert, _detail}), do: :tls - defp connect_stage({:down, reason}), do: connect_stage(reason) - defp connect_stage({_tag, reason}), do: connect_stage(reason) - defp connect_stage(_reason), do: nil - - defp metadata(%{channel: channel, logical_connection_ref: logical_ref}), - do: metadata(channel, logical_ref) - - defp metadata(channel, logical_ref) do - %{ - logical_connection_ref: logical_ref, - transport_ref: self(), - target: {channel.host, channel.port}, - adapter: GRPC.Client.Adapters.Gun - } + defp owner_key(%{ref: ref, host: host, port: port}), do: {ref, host, port} end - - defp owner_key(%{ref: ref, host: host, port: port}), do: {ref, host, port} end diff --git a/grpc/lib/grpc/client/adapters/gun/stream_response_process.ex b/grpc/lib/grpc/client/adapters/gun/stream_response_process.ex index 98c8a655..e7393a7c 100644 --- a/grpc/lib/grpc/client/adapters/gun/stream_response_process.ex +++ b/grpc/lib/grpc/client/adapters/gun/stream_response_process.ex @@ -1,197 +1,199 @@ -defmodule GRPC.Client.Adapters.Gun.StreamResponseProcess do - @moduledoc """ - Owns response state for a single Gun request stream. - - Gun can deliver response messages for many concurrent streams over the same - connection, so request-specific response handling needs to stay isolated per - stream. - - This process buffers the messages for one stream, serves them back to the Gun - adapter in arrival order, and terminates once the stream has reached a - terminal state and all buffered messages have been consumed. - - Streams are opened with a finite Gun `flow`, a count of DATA frames. Gun keeps - sending `:gun_data` after the count reaches zero, but stops reopening the - stream's window until `:gun.update_flow/3` credits frames back. This process - credits one frame each time a data message leaves the queue. When the caller - reads slowly, the queue holds the credited frames plus what is left of the - HTTP/2 stream window. See the `:response_window` option of - `GRPC.Client.Adapters.Gun` for the bound. - """ - - use GenServer - require Logger - - @terminated_stream_error {:error, {:connection_error, :closed}} - - def start_link do - GenServer.start_link(__MODULE__, []) - end - - def track(pid, connection_pid, stream_ref, deadline) do - GenServer.call(pid, {:track, connection_pid, stream_ref, deadline}) - catch - :exit, _reason -> - :ok - end - - def await(pid, deadline) do - GenServer.call(pid, {:await, deadline}, :infinity) - catch - :exit, _reason -> - @terminated_stream_error - end - - @impl GenServer - def init([]) do - {:ok, - %{ - messages: :queue.new(), - waiter: nil, - done: false, - deadline: :infinity, - deadline_timer: nil, - cleanup_target: nil, - flow_target: nil - }} - end - - @impl GenServer - def handle_call({:track, connection_pid, stream_ref, deadline}, _from, state) do - state = - state - |> Map.put(:cleanup_target, {connection_pid, stream_ref}) - |> put_earlier_deadline(deadline) +if Code.ensure_loaded?(:gun) do + defmodule GRPC.Client.Adapters.Gun.StreamResponseProcess do + @moduledoc """ + Owns response state for a single Gun request stream. + + Gun can deliver response messages for many concurrent streams over the same + connection, so request-specific response handling needs to stay isolated per + stream. + + This process buffers the messages for one stream, serves them back to the Gun + adapter in arrival order, and terminates once the stream has reached a + terminal state and all buffered messages have been consumed. + + Streams are opened with a finite Gun `flow`, a count of DATA frames. Gun keeps + sending `:gun_data` after the count reaches zero, but stops reopening the + stream's window until `:gun.update_flow/3` credits frames back. This process + credits one frame each time a data message leaves the queue. When the caller + reads slowly, the queue holds the credited frames plus what is left of the + HTTP/2 stream window. See the `:response_window` option of + `GRPC.Client.Adapters.Gun` for the bound. + """ + + use GenServer + require Logger + + @terminated_stream_error {:error, {:connection_error, :closed}} + + def start_link do + GenServer.start_link(__MODULE__, []) + end - {:reply, :ok, state} - end + def track(pid, connection_pid, stream_ref, deadline) do + GenServer.call(pid, {:track, connection_pid, stream_ref, deadline}) + catch + :exit, _reason -> + :ok + end - def handle_call({:await, deadline}, from, state) do - state = put_earlier_deadline(state, deadline) - %{messages: messages, done: done?} = state + def await(pid, deadline) do + GenServer.call(pid, {:await, deadline}, :infinity) + catch + :exit, _reason -> + @terminated_stream_error + end - case :queue.out(messages) do - {{:value, message}, remaining} -> - credit_flow(state, message) - new_state = %{state | messages: remaining} + @impl GenServer + def init([]) do + {:ok, + %{ + messages: :queue.new(), + waiter: nil, + done: false, + deadline: :infinity, + deadline_timer: nil, + cleanup_target: nil, + flow_target: nil + }} + end - if done? and :queue.is_empty(remaining) do - {:stop, :normal, message, new_state} - else - {:reply, message, new_state} - end + @impl GenServer + def handle_call({:track, connection_pid, stream_ref, deadline}, _from, state) do + state = + state + |> Map.put(:cleanup_target, {connection_pid, stream_ref}) + |> put_earlier_deadline(deadline) - {:empty, _} -> - if done? do - {:stop, :normal, @terminated_stream_error, state} - else - {:noreply, %{state | waiter: from}} - end + {:reply, :ok, state} end - end - @impl GenServer - def handle_info({:deadline_expired, timer_ref}, %{deadline_timer: timer_ref} = state) do - if state.waiter, do: GenServer.reply(state.waiter, {:error, :timeout}) + def handle_call({:await, deadline}, from, state) do + state = put_earlier_deadline(state, deadline) + %{messages: messages, done: done?} = state + + case :queue.out(messages) do + {{:value, message}, remaining} -> + credit_flow(state, message) + new_state = %{state | messages: remaining} + + if done? and :queue.is_empty(remaining) do + {:stop, :normal, message, new_state} + else + {:reply, message, new_state} + end + + {:empty, _} -> + if done? do + {:stop, :normal, @terminated_stream_error, state} + else + {:noreply, %{state | waiter: from}} + end + end + end - case state.cleanup_target do - {connection_pid, stream_ref} -> - send(connection_pid, {:stream_expired, stream_ref, self()}) + @impl GenServer + def handle_info({:deadline_expired, timer_ref}, %{deadline_timer: timer_ref} = state) do + if state.waiter, do: GenServer.reply(state.waiter, {:error, :timeout}) - nil -> - :ok - end + case state.cleanup_target do + {connection_pid, stream_ref} -> + send(connection_pid, {:stream_expired, stream_ref, self()}) - {:stop, :normal, %{state | waiter: nil, done: true, deadline_timer: nil}} - end + nil -> + :ok + end - def handle_info({:deadline_expired, _timer_ref}, state), do: {:noreply, state} + {:stop, :normal, %{state | waiter: nil, done: true, deadline_timer: nil}} + end - def handle_info({:gun_response, _conn_pid, _stream_ref, fin, status, headers}, state) do - state - |> push_message({:response, fin, status, headers}, terminal?(fin)) - end + def handle_info({:deadline_expired, _timer_ref}, state), do: {:noreply, state} - def handle_info({:gun_data, gun_pid, stream_ref, fin, data}, state) do - %{state | flow_target: {gun_pid, stream_ref}} - |> push_message({:data, fin, data}, terminal?(fin)) - end + def handle_info({:gun_response, _conn_pid, _stream_ref, fin, status, headers}, state) do + state + |> push_message({:response, fin, status, headers}, terminal?(fin)) + end - def handle_info({:gun_trailers, _conn_pid, _stream_ref, trailers}, state) do - state - |> push_message({:trailers, trailers}, true) - end + def handle_info({:gun_data, gun_pid, stream_ref, fin, data}, state) do + %{state | flow_target: {gun_pid, stream_ref}} + |> push_message({:data, fin, data}, terminal?(fin)) + end - def handle_info({:gun_error, _conn_pid, _stream_ref, reason}, state) do - state - |> push_message({:error, {:stream_error, reason}}, true) - end + def handle_info({:gun_trailers, _conn_pid, _stream_ref, trailers}, state) do + state + |> push_message({:trailers, trailers}, true) + end - def handle_info({:gun_error, _conn_pid, reason}, state) do - state - |> push_message({:error, {:connection_error, reason}}, true) - end + def handle_info({:gun_error, _conn_pid, _stream_ref, reason}, state) do + state + |> push_message({:error, {:stream_error, reason}}, true) + end - def handle_info({:connection_down, reason}, state) do - push_message(state, {:error, {:connection_error, reason}}, true) - end + def handle_info({:gun_error, _conn_pid, reason}, state) do + state + |> push_message({:error, {:connection_error, reason}}, true) + end - def handle_info(msg, state) do - Logger.warning("#{inspect(__MODULE__)} received unexpected message: #{inspect(msg)}") - push_message(state, {:error, {:unexpected_message, inspect(msg)}}, true) - end + def handle_info({:connection_down, reason}, state) do + push_message(state, {:error, {:connection_error, reason}}, true) + end - defp push_message(%{done: true} = state, _message, _terminal?) do - {:noreply, state} - end + def handle_info(msg, state) do + Logger.warning("#{inspect(__MODULE__)} received unexpected message: #{inspect(msg)}") + push_message(state, {:error, {:unexpected_message, inspect(msg)}}, true) + end - defp push_message(%{waiter: from} = state, message, terminal?) when not is_nil(from) do - state = if terminal?, do: cancel_deadline(state), else: state - GenServer.reply(from, message) - credit_flow(state, message) - new_state = %{state | waiter: nil, done: terminal?} + defp push_message(%{done: true} = state, _message, _terminal?) do + {:noreply, state} + end - if terminal? do - {:stop, :normal, new_state} - else - {:noreply, new_state} + defp push_message(%{waiter: from} = state, message, terminal?) when not is_nil(from) do + state = if terminal?, do: cancel_deadline(state), else: state + GenServer.reply(from, message) + credit_flow(state, message) + new_state = %{state | waiter: nil, done: terminal?} + + if terminal? do + {:stop, :normal, new_state} + else + {:noreply, new_state} + end end - end - defp push_message(%{messages: messages} = state, message, terminal?) do - state = if terminal?, do: cancel_deadline(state), else: state - {:noreply, %{state | messages: :queue.in(message, messages), done: terminal?}} - end + defp push_message(%{messages: messages} = state, message, terminal?) do + state = if terminal?, do: cancel_deadline(state), else: state + {:noreply, %{state | messages: :queue.in(message, messages), done: terminal?}} + end - # Returns the frame to Gun's `flow`, which reopens the stream's window once it is - # positive again. After the last frame there is nothing left to reopen. - defp credit_flow(%{done: false, flow_target: {gun_pid, stream_ref}}, {:data, :nofin, _data}) do - :gun.update_flow(gun_pid, stream_ref, 1) - end + # Returns the frame to Gun's `flow`, which reopens the stream's window once it is + # positive again. After the last frame there is nothing left to reopen. + defp credit_flow(%{done: false, flow_target: {gun_pid, stream_ref}}, {:data, :nofin, _data}) do + :gun.update_flow(gun_pid, stream_ref, 1) + end - defp credit_flow(_state, _message), do: :ok + defp credit_flow(_state, _message), do: :ok - defp terminal?(:fin), do: true - defp terminal?(:nofin), do: false + defp terminal?(:fin), do: true + defp terminal?(:nofin), do: false - defp put_earlier_deadline(%{done: true} = state, _deadline), do: state - defp put_earlier_deadline(state, :infinity), do: state + defp put_earlier_deadline(%{done: true} = state, _deadline), do: state + defp put_earlier_deadline(state, :infinity), do: state - defp put_earlier_deadline(%{deadline: current} = state, deadline) - when is_integer(deadline) and (current == :infinity or deadline < current) do - state = cancel_deadline(state) - timer_ref = make_ref() - timeout = max(deadline - System.monotonic_time(:millisecond), 0) - Process.send_after(self(), {:deadline_expired, timer_ref}, timeout) - %{state | deadline: deadline, deadline_timer: timer_ref} - end + defp put_earlier_deadline(%{deadline: current} = state, deadline) + when is_integer(deadline) and (current == :infinity or deadline < current) do + state = cancel_deadline(state) + timer_ref = make_ref() + timeout = max(deadline - System.monotonic_time(:millisecond), 0) + Process.send_after(self(), {:deadline_expired, timer_ref}, timeout) + %{state | deadline: deadline, deadline_timer: timer_ref} + end - defp put_earlier_deadline(state, _deadline), do: state + defp put_earlier_deadline(state, _deadline), do: state - defp cancel_deadline(%{deadline_timer: nil} = state), do: state + defp cancel_deadline(%{deadline_timer: nil} = state), do: state - defp cancel_deadline(%{deadline_timer: timer_ref} = state) do - Process.cancel_timer(timer_ref) - %{state | deadline_timer: nil} + defp cancel_deadline(%{deadline_timer: timer_ref} = state) do + Process.cancel_timer(timer_ref) + %{state | deadline_timer: nil} + end end end