dotfiles/app/lib/prymn_web/live/server_live/index.ex
Nikos Papadakis be7f584010
app: a nice poc background connection with the agent
Dynamically supervise a GRPC connection and keep it alive for a while,
using a timeout to kill the process on inactivity.

The Connection GenServer keeps the connection alive, while listening to
a health stream from the GRPC endpoint, notifying any subscribed
listeners about changes to health.

This health is then propagated to the main servers page.

Also create a looping get_sys_info which retrieves some basic system
information.
2023-08-26 00:51:04 +03:00

77 lines
1.8 KiB
Elixir

defmodule PrymnWeb.ServerLive.Index do
require Logger
alias Prymn.Agents.Health
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.start_connection_or_keep_alive(ip)
{ip, Agents.subscribe_to_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({host, %Prymn.Agents.Health{} = health}, socket) do
healths = Map.put(socket.assigns.healths, 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.server, assigns.health} do
{%{status: :registered}, nil} ->
~H"""
Unknown
"""
{%{status: :registered}, %Health{message: message}} ->
assigns = assign(assigns, :status, message)
~H"""
<%= @status %>
"""
{_, _} ->
~H"""
Not registered
"""
end
end
end