Skip to content

Commit

Permalink
Add connection callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
caike committed Jan 29, 2024
1 parent 7e37262 commit 268d625
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
6 changes: 6 additions & 0 deletions lib/xogmios/chain_sync.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ defmodule Xogmios.ChainSync do
@callback handle_block(map(), any()) ::
{:ok, :next_block, map()} | {:ok, map()} | {:ok, :close, map()}

@callback handle_connect(map()) :: {:ok, map()}
@callback handle_disconnect(String.t(), map()) :: :ok

# The keepalive option is used to maintain the connection active.
# This is important because proxies might close idle connections after a few seconds.
@keepalive_in_ms 5_000
Expand All @@ -29,6 +32,9 @@ defmodule Xogmios.ChainSync do

require Logger

def handle_connect(state), do: {:ok, state}
def handle_disconnect(_reason, _state), do: :ok

def handle_message(%{"id" => "start"} = message, state) do
%{
"method" => "nextBlock",
Expand Down
19 changes: 16 additions & 3 deletions lib/xogmios/chain_sync/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,27 @@ defmodule Xogmios.ChainSync.Connection do
def onconnect(_arg, state) do
start_message = Messages.next_block_start()
:websocket_client.cast(self(), {:text, start_message})
Logger.debug("onconnect")
{:ok, state}

case state.handler.handle_connect(state) do
{:ok, new_state} ->
{:ok, new_state}

_ ->
{:ok, state}
end
end

@impl true
def ondisconnect(reason, state) do
Logger.debug("ondisconnect #{inspect(reason)}")
{:reconnect, 5_000, state}

case state.handler.handle_disconnect(reason, state) do
:ok ->
{:reconnect, 5_000, state}

_ ->
{:reconnect, 5_000, state}
end
end

@impl true
Expand Down

0 comments on commit 268d625

Please sign in to comment.