Skip to content

Commit

Permalink
Fix ChainSync reconnection
Browse files Browse the repository at this point in the history
  • Loading branch information
caike committed Jul 1, 2024
1 parent d8f4e61 commit edbb710
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
19 changes: 13 additions & 6 deletions lib/xogmios/chain_sync.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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),
Expand Down
14 changes: 10 additions & 4 deletions lib/xogmios/chain_sync/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit edbb710

Please sign in to comment.