dotfiles/app/lib/prymn_web/live/server_live/index.ex
Nikos Papadakis 26ba60b95d
app: refactor the Connection to make it asynchronous when connecting
Some work has been done on making the Connection feel nicer, but also
more work is needed to not have the channel be exposed to the upper
layers of the application. We should wrap all the GRPC calls in the
GenServer (which may also allow caching on certain calls such as
get_sys_info)
2023-08-28 23:32:42 +03:00

87 lines
2.2 KiB
Elixir

defmodule PrymnWeb.ServerLive.Index do
require Logger
alias Prymn.{Servers, Agents}
use PrymnWeb, :live_view
@impl true
def mount(_params, _session, socket) do
servers = Servers.list_servers()
healths =
if connected?(socket) do
for %Servers.Server{status: :registered, public_ip: ip} <- servers, into: %{} do
Agents.subscribe_to_health(ip)
Agents.start_connection(ip)
{ip, Agents.get_health(ip)}
end
else
%{}
end
{:ok,
socket
|> assign(:servers, servers)
|> assign(:healths, healths)}
end
@impl true
def handle_params(_params, _url, socket) do
socket =
case socket.assigns.live_action do
:new -> assign(socket, :page_title, gettext("Connect a Server"))
:index -> assign(socket, :page_title, gettext("Listing Servers"))
end
{:noreply, socket}
end
@impl true
def handle_info({:connect, %Servers.Server{} = server}, socket) do
{:noreply,
socket
|> update(:servers, fn servers -> [server | servers] end)}
end
def handle_info(%Agents.Health{} = health, socket) do
healths = Map.put(socket.assigns.healths, health.host, health)
{:noreply, assign(socket, :healths, healths)}
end
def handle_info(msg, state) do
Logger.debug("received unexpected message #{inspect(msg)}")
{:noreply, state}
end
defp server_status(assigns) do
case {assigns.status, assigns.health} do
{:unregistered, _} ->
~H"""
<span class="text-gray-500">Needs registration</span>
"""
{:registered, nil} ->
~H"""
<span class="text-yellow-600">Connecting...</span>
"""
{:registered, %Agents.Health{message: "Connected"}} ->
~H"""
<span class="text-green-600">Connected</span>
"""
{:registered, %Agents.Health{message: "Disconnected"}} ->
~H"""
<span class="text-red-600">Disconnected</span>
"""
{:registered, %Agents.Health{message: message}} ->
assigns = assign(assigns, :message, message)
~H"""
<span class="text-yellow-900"><%= @message %></span>
"""
end
end
end