Skip to content

Commit cf34012

Browse files
authored
Handle disconnect when channel is not initialized (#23)
fixes #22 Signed-off-by: Yordis Prieto <yordis.prieto@gmail.com>
1 parent c88d6fc commit cf34012

2 files changed

Lines changed: 46 additions & 7 deletions

File tree

lib/conn_grpc/channel.ex

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -253,14 +253,17 @@ defmodule ConnGRPC.Channel do
253253
defp handle_disconnect(state) do
254254
now = System.monotonic_time()
255255
debug(state, "Connection down")
256-
state.on_disconnect.()
257-
state.channel.adapter.disconnect(state.channel)
258256

259-
:telemetry.execute(
260-
[:conn_grpc, :channel, :disconnected],
261-
%{duration: now - state.connection_start},
262-
telemetry_metadata(state)
263-
)
257+
if state.channel do
258+
state.on_disconnect.()
259+
state.channel.adapter.disconnect(state.channel)
260+
261+
:telemetry.execute(
262+
[:conn_grpc, :channel, :disconnected],
263+
%{duration: now - state.connection_start},
264+
telemetry_metadata(state)
265+
)
266+
end
264267

265268
state = %{state | channel: nil}
266269
schedule_retry(state)

test/conn_grpc/channel_test.exs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,24 @@ defmodule ConnGRPC.ChannelTest do
176176
_metadata = %{channel_name: :test_channel}
177177
}
178178
end
179+
180+
test "handles disconnect when channel is not yet connected" do
181+
{:ok, channel_pid} =
182+
Channel.start_link(
183+
address: "address",
184+
opts: [adapter: GRPC.Client.TestAdapters.Error],
185+
on_disconnect: fn -> send(:channel_test, :disconnect_called) end,
186+
backoff_module: ConnGRPC.Backoff.NoRetry
187+
)
188+
189+
# Verify channel is not connected before sending disconnect
190+
assert {:error, :not_connected} = Channel.get(channel_pid)
191+
192+
send(channel_pid, {:gun_down, fake_pid(), :http2, :normal, []})
193+
194+
refute_receive :disconnect_called
195+
assert Process.alive?(channel_pid)
196+
end
179197
end
180198

181199
describe "Mint disconnect handling" do
@@ -223,6 +241,24 @@ defmodule ConnGRPC.ChannelTest do
223241
_metadata = %{channel_name: :test_channel}
224242
}
225243
end
244+
245+
test "handles disconnect when channel is not yet connected" do
246+
{:ok, channel_pid} =
247+
Channel.start_link(
248+
address: "address",
249+
opts: [adapter: GRPC.Client.TestAdapters.Error],
250+
on_disconnect: fn -> send(:channel_test, :disconnect_called) end,
251+
backoff_module: ConnGRPC.Backoff.NoRetry
252+
)
253+
254+
# Verify channel is not connected before sending disconnect
255+
assert {:error, :not_connected} = Channel.get(channel_pid)
256+
257+
send(channel_pid, {:elixir_grpc, :connection_down, fake_pid()})
258+
259+
refute_receive :disconnect_called
260+
assert Process.alive?(channel_pid)
261+
end
226262
end
227263

228264
describe "Retry and backoff" do

0 commit comments

Comments
 (0)