diff --git a/lib/xogmios/chain_sync.ex b/lib/xogmios/chain_sync.ex index e0d7413..77d96a4 100644 --- a/lib/xogmios/chain_sync.ex +++ b/lib/xogmios/chain_sync.ex @@ -56,14 +56,20 @@ defmodule Xogmios.ChainSync do @doc """ Invoked upon disconnecting from the server. This callback is optional. - Returning `{:ok, new_state}` will allow the connection to close. + Returning `{:reconnect, interval_in_ms, new_state}` will attempt a reconnection + after `interval_in_ms`. - Returning `{:reconnect, interval_in_ms}` will attempt a reconnection after `interval_in_ms` + Returning `{:close, reason, new_state}` will allow the connection to close and + shut the process down cleanly. + + Returning `{:ok, new_state}` will allow the connection to close but keeps + process alive. """ - @callback handle_disconnect(reason :: String.t(), state) :: - {:ok, new_state} - | {:reconnect, interval_in_ms :: non_neg_integer(), new_state} - when state: term(), new_state: term() + @callback handle_disconnect(reason, state) :: + {:reconnect, interval_in_ms :: non_neg_integer(), new_state} + | {:close, reason, new_state} + | {:ok, new_state} + when reason: String.t(), state: term(), new_state: term() # The keepalive option is used to maintain the connection active. # This is important because proxies might close idle connections after a few seconds. @@ -81,6 +87,7 @@ defmodule Xogmios.ChainSync do def start_link(client, opts) do {url, opts} = Keyword.pop(opts, :url) {name, opts} = Keyword.pop(opts, :name, client) + initial_state = Keyword.merge(opts, handler: client, notify_on_connect: self()) with {:ok, process_name} <- build_process_name(name), diff --git a/lib/xogmios/chain_sync/connection.ex b/lib/xogmios/chain_sync/connection.ex index 18e99f3..6eaa9c7 100644 --- a/lib/xogmios/chain_sync/connection.ex +++ b/lib/xogmios/chain_sync/connection.ex @@ -20,7 +20,7 @@ defmodule Xogmios.ChainSync.Connection do id: Keyword.get(opts, :id, __MODULE__), start: {__MODULE__, :start_link, [opts]}, shutdown: 5_000, - restart: Keyword.get(opts, :restart, :transient), + restart: Keyword.get(opts, :restart, :temporary), type: :worker } end @@ -55,11 +55,17 @@ defmodule Xogmios.ChainSync.Connection do @impl true def ondisconnect(reason, state) do case state.handler.handle_disconnect(reason, state) do - {:ok, state} -> - {:ok, state} - + # Attempt to reconnect after interval in ms {:reconnect, reconnect_interval_in_ms, new_state} -> {:reconnect, reconnect_interval_in_ms, new_state} + + # Shut the process down cleanly + {:close, reason, state} -> + {:close, reason, state} + + # Disconnect but keeps process alive + {:ok, state} -> + {:ok, state} end end