refactor: leadership_change handler pattern-matches instead of cond

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.
This commit is contained in:
Graham McIntire 2026-04-23 14:27:43 -05:00
parent c1c7e10d26
commit a85f74ec3f
No known key found for this signature in database
GPG key ID: F4ABF488E6029E59

View file

@ -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")