diff --git a/lib/aprsme/cluster/connection_manager.ex b/lib/aprsme/cluster/connection_manager.ex index 14ec32e..04103d5 100644 --- a/lib/aprsme/cluster/connection_manager.ex +++ b/lib/aprsme/cluster/connection_manager.ex @@ -40,25 +40,28 @@ defmodule Aprsme.Cluster.ConnectionManager do @impl true def handle_info({:leadership_change, node, became_leader}, state) do - cond do - became_leader and node == node() and not state.connection_started -> - Logger.info("This node became the leader, starting APRS-IS connection") - start_aprs_connection() - {:noreply, %{state | connection_started: true}} - - not became_leader and node == node() and state.connection_started -> - Logger.info("This node lost leadership, stopping APRS-IS connection") - stop_aprs_connection() - {:noreply, %{state | connection_started: false}} - - true -> - {:noreply, state} - end + handle_leadership_change(became_leader, node == node(), state) end - @impl true def handle_info(_msg, state), do: {:noreply, state} + # Became the cluster leader and we weren't already running — start APRS-IS. + defp handle_leadership_change(true, true, %{connection_started: false} = state) do + Logger.info("This node became the leader, starting APRS-IS connection") + start_aprs_connection() + {:noreply, %{state | connection_started: true}} + end + + # Lost leadership while we were running — stop APRS-IS. + defp handle_leadership_change(false, true, %{connection_started: true} = state) do + Logger.info("This node lost leadership, stopping APRS-IS connection") + stop_aprs_connection() + {:noreply, %{state | connection_started: false}} + end + + # Any other combination (different node, already in the right state) is a no-op. + defp handle_leadership_change(_became_leader, _us?, state), do: {:noreply, state} + @impl true def terminate(_reason, _state) do Phoenix.PubSub.unsubscribe(Aprsme.PubSub, "cluster:leadership")