aprs.me/lib/aprsme/cluster/packet_distributor.ex
Graham McIntire 7db78675a2
refactor: collapse nested if/case into pattern-matched helpers
- SharedPacketHandler.handle_packet_update: dispatch on filter-result,
  and use maybe_enrich/2 dispatched on the enrich? boolean instead of
  an inner `if`. lookup_device_info/1 is now a trio of function heads.
- Cluster.Topology.child_spec: build_spec/3 dispatches on
  (cluster_enabled?, topologies) tuples — no more nested `if`.
- Cluster.PacketDistributor.distribute_packet: maybe_broadcast/2
  dispatches on the leader-and-enabled check; the non-leader / disabled
  paths return :ok explicitly instead of relying on an `if` expression's
  implicit nil.

Adds tests for SharedPacketHandler (filter/enrich/match paths,
callsign_filter + callsign_and_weather_filter factories) and extends
Cluster.Topology tests to cover the nil-topology and opts-merge cases.
Coverage 66.41 → 66.81%.
2026-04-23 13:55:11 -05:00

58 lines
1.6 KiB
Elixir

defmodule Aprsme.Cluster.PacketDistributor do
@moduledoc """
Distributes APRS packets from the leader node to all cluster members.
This ensures all nodes can serve real-time updates via LiveView while
only the leader maintains the APRS-IS connection.
"""
use GenServer
alias Aprsme.Cluster.LeaderElection
@pubsub_topic "cluster:packets"
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
def distribute_packet(packet) do
cluster_enabled = Application.get_env(:aprsme, :cluster_enabled, false)
maybe_broadcast(cluster_enabled and LeaderElection.leader_cached?(), packet)
end
# Only the leader broadcasts; non-leader clustered nodes and non-clustered
# nodes silently drop the packet.
defp maybe_broadcast(true, packet) do
Phoenix.PubSub.broadcast(Aprsme.PubSub, @pubsub_topic, {:distributed_packet, packet})
end
defp maybe_broadcast(false, _packet), do: :ok
def subscribe do
Phoenix.PubSub.subscribe(Aprsme.PubSub, @pubsub_topic)
end
def handle_distributed_packet({:distributed_packet, packet}) do
Aprsme.StreamingPacketsPubSub.broadcast_packet(packet)
Aprsme.SpatialPubSub.broadcast_packet(packet)
:ok
end
@impl true
def handle_info({:distributed_packet, _packet} = msg, state) do
handle_distributed_packet(msg)
{:noreply, state}
end
@impl true
def init(_opts) do
:ok = Phoenix.PubSub.subscribe(Aprsme.PubSub, @pubsub_topic)
{:ok, %{}}
end
@impl true
def terminate(_reason, _state) do
_ = Phoenix.PubSub.unsubscribe(Aprsme.PubSub, @pubsub_topic)
:ok
end
end