Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions grpc/lib/grpc/client/adapters/mint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,21 +42,18 @@ if Code.ensure_loaded?(Mint.HTTP) do

@behaviour GRPC.Client.Adapter

@default_connect_opts [
protocols: [:http2]
]
@default_client_settings [
initial_window_size: 8_000_000,
max_frame_size: 8_000_000
]
@default_transport_opts [timeout: :infinity, nodelay: true]
@default_transport_opts [timeout: 20_000, nodelay: true]
@cleanup_timeout 1_000
@unavailable GRPC.Status.unavailable()

@doc """
Connects using Mint based on the provided configs. Options
* `:transport_opts`: Defaults to `[timeout: :infinity, nodelay: true]`, given the nature of H2 connections (with support to
long-lived streams) `timeout: :infinity` is set to avoid timeouts while waiting for server streams to complete.
* `:transport_opts`: Defaults to `[timeout: 20_000, nodelay: true]`. `timeout` bounds the whole connect, including
the wait for the server's first SETTINGS frame, but not streams.
`nodelay: true` sets `TCP_NODELAY`, so small writes go out at once instead of waiting on Nagle's algorithm and
delayed ACKs, which adds tens of milliseconds to sequential calls. Pass `nodelay: false` to turn it off. The other
options may vary based on the transport used for this connection (tcp or ssl). Check [Mint.HTTP.connect/4](https://hexdocs.pm/mint/Mint.HTTP.html#connect/4)
Expand Down Expand Up @@ -254,11 +251,6 @@ if Code.ensure_loaded?(Mint.HTTP) do
]
end

defp merge_opts(opts, module_opts) do
opts = Keyword.merge(opts, module_opts)
Keyword.merge(@default_connect_opts, opts)
end

defp mint_scheme(%Channel{scheme: "https"} = _channel), do: :https
defp mint_scheme(_channel), do: :http

Expand All @@ -279,7 +271,7 @@ if Code.ensure_loaded?(Mint.HTTP) do
opts =
channel
|> connect_opts(opts)
|> merge_opts(module_opts)
|> Keyword.merge(module_opts)
|> Keyword.put(:retry, retry)
|> Keyword.put(:notify_drain, notify_drain)
|> Keyword.put(:grpc_transport_metadata, transport_metadata)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ if Code.ensure_loaded?(Mint.HTTP) do
@reconnect_stop_event [:grpc, :client, :mint, :reconnect, :stop]
@reconnect_error_event [:grpc, :client, :mint, :reconnect, :error]
@reconnect_exhausted_event [:grpc, :client, :mint, :reconnect, :exhausted]
@mint_default_connect_timeout 30_000

@doc """
Starts and link connection process
Expand Down Expand Up @@ -97,7 +98,7 @@ if Code.ensure_loaded?(Mint.HTTP) do
Telemetry.execute(:started, %{generation: 0, active_streams: 0}, metadata)
{keepalive_opts, opts} = Keyword.split(opts, [:keepalive, :keepalive_tolerance])

case Mint.HTTP.connect(scheme, host, port, opts) do
case connect(scheme, host, port, opts) do
{:ok, conn} ->
state_opts = [
parent: opts[:parent],
Expand All @@ -111,7 +112,12 @@ if Code.ensure_loaded?(Mint.HTTP) do
]

Telemetry.execute(:connected, %{generation: 1}, Map.put(metadata, :reconnect, false))
{:ok, conn |> State.new(state_opts ++ keepalive_opts) |> schedule_keepalive()}

{:ok,
conn
|> State.new(state_opts ++ keepalive_opts)
|> observe_settings()
|> schedule_keepalive()}

{:error, reason} ->
Logger.error(
Expand Down Expand Up @@ -688,7 +694,7 @@ if Code.ensure_loaded?(Mint.HTTP) do

start = System.monotonic_time()

case Mint.HTTP.connect(state.scheme, state.host, state.port, state.connect_opts) do
case connect(state.scheme, state.host, state.port, state.connect_opts) do
{:ok, conn} ->
Logger.info("Reconnected successfully to #{state.scheme}://#{state.host}:#{state.port}")

Expand Down Expand Up @@ -716,7 +722,7 @@ if Code.ensure_loaded?(Mint.HTTP) do
pings_unacked: 0
}

{:noreply, new_state}
{:noreply, observe_settings(new_state)}

{:error, reason} ->
Logger.warning(
Expand Down Expand Up @@ -809,6 +815,45 @@ if Code.ensure_loaded?(Mint.HTTP) do
defp normalize_max_streams(value) when is_integer(value) and value > 0, do: value
defp normalize_max_streams(_value), do: :unknown

defp connect(scheme, host, port, opts) do
timeout = get_in(opts, [:transport_opts, :timeout]) || @mint_default_connect_timeout
deadline = connect_deadline(timeout)

with {:ok, conn} <-
Mint.HTTP.connect(
scheme,
host,
port,
Keyword.merge(opts, mode: :passive, protocols: [:http2])
),
{:ok, conn} <- await_server_preface(conn, deadline) do
Mint.HTTP.set_mode(conn, :active)
end
end

defp await_server_preface(%Mint.HTTP2{state: :handshaking} = conn, deadline) do
case Mint.HTTP.recv(conn, 0, remaining_time(deadline)) do
{:ok, conn, []} ->
await_server_preface(conn, deadline)

{:error, _conn, reason, _responses} ->
{:ok, _conn} = Mint.HTTP.close(conn)
{:error, reason}
end
end

defp await_server_preface(conn, _deadline) do
if Mint.HTTP.open?(conn),
do: {:ok, conn},
else: {:error, %Mint.TransportError{reason: :closed}}
end

defp connect_deadline(:infinity), do: :infinity
defp connect_deadline(timeout), do: System.monotonic_time(:millisecond) + timeout

defp remaining_time(:infinity), do: :infinity
defp remaining_time(deadline), do: max(deadline - System.monotonic_time(:millisecond), 0)

defp connect_failed(metadata, reason) do
maybe_connect_error(metadata, reason)
Telemetry.execute(:stopped, %{streams_terminated: 0}, Map.put(metadata, :reason, reason))
Expand Down
3 changes: 3 additions & 0 deletions grpc/lib/grpc/client/telemetry.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ defmodule GRPC.Client.Telemetry do
| `:settings` | none | common metadata plus `max_concurrent_streams` |
| `:streams` | `active` | common metadata |

With the Mint adapter, `:connected` is emitted once the server's first HTTP/2
SETTINGS frame has arrived.

Generations start at one on the first successful establishment and increment
after recovery. Stream occupancy is an authoritative snapshot after each
stream-table mutation.
Expand Down
15 changes: 15 additions & 0 deletions grpc/test/grpc/adapters/mint_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ defmodule GRPC.Client.Adapters.MintTest do
Mint.connect(channel, config_options: [transport_opts: [ip: "256.0.0.0"]])
end

test "fails if the server closes before sending its SETTINGS frame" do
{:ok, listen_socket} = :gen_tcp.listen(0, [:binary, active: false, reuseaddr: true])
{:ok, port} = :inet.port(listen_socket)
on_exit(fn -> :gen_tcp.close(listen_socket) end)

spawn_link(fn ->
{:ok, socket} = :gen_tcp.accept(listen_socket)
{:ok, _preface} = :gen_tcp.recv(socket, 0, 1_000)
:gen_tcp.close(socket)
end)

channel = build(:channel, adapter: Mint, port: port, host: "localhost")
assert {:error, %TransportError{reason: :closed}} = Mint.connect(channel, [])
end

test "defaults client settings when none is passed", %{port: port} do
channel = build(:channel, adapter: Mint, port: port, host: "localhost")

Expand Down
19 changes: 19 additions & 0 deletions grpc/test/grpc/adapters/mtls_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,25 @@ defmodule GRPC.Client.Adapters.MTLSTest do
end
end

describe "mint adapter, client side of a rejected certificate" do
setup do
Process.flag(:trap_exit, true)
:ok
end

test "a missing certificate fails the connect", %{port: port, certs: certs} do
assert {:error,
%Elixir.Mint.TransportError{reason: {:tls_alert, {:certificate_required, _}}}} =
GRPC.Client.Adapters.Mint.ConnectionProcess.start_link(:https, "localhost", port,
transport_opts: [
timeout: 5_000,
cacertfile: certs.server_ca,
verify: :verify_peer
]
)
end
end

# Builds a CA and a leaf for the server, and another pair for the client, and
# writes them as PEM files like the ones a real deployment has.
defp write_certs(dir) do
Expand Down
Loading