From a85f74ec3f959b81941eb9f1cc6de04e4ff0e049 Mon Sep 17 00:00:00 2001 From: Graham McIntire Date: Thu, 23 Apr 2026 14:27:43 -0500 Subject: [PATCH] refactor: leadership_change handler pattern-matches instead of cond MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cluster.ConnectionManager.handle_info({:leadership_change, ...}) used a cond on the (became_leader, node, connection_started) triple. Split into handle_leadership_change/3 with three clauses: - became_leader=true, us=true, not already started → start APRS-IS - became_leader=false, us=true, already started → stop APRS-IS - everything else → no-op Makes the three state transitions visible in the function heads and eliminates one more cond from the codebase. --- lib/aprsme/cluster/connection_manager.ex | 33 +++++++++++++----------- 1 file changed, 18 insertions(+), 15 deletions(-) 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")