7.5 KiB · text History 573fef1
defmodule VigilWeb.StatusPageLive.Show do
  @moduledoc """
  A status page (`/status/:org/:slug`): for anyone when public, for the
  organization's members otherwise (`Vigil.Uptime.get_status_page/3`). An
  overall banner, then each chosen monitor's state, its uptime over 24
  hours and 30 days, and a strip of its last 30 days. Live over PubSub,
  at most once a second.

  Deliberately thin: names and states only, never a monitor's target or
  why a check failed. A page that doesn't exist and one the caller may
  not see answer the same "not found".
  """
  use VigilWeb, :live_view

  import VigilWeb.UptimeComponents, only: [day_strip: 1, percent: 1, state: 1]

  alias Vigil.Uptime

  @refresh_ms 1000
  @days 30

  @impl true
  def mount(%{"org" => org_slug, "slug" => slug}, _session, socket) do
    scope = socket.assigns.current_scope
    user = scope && scope.user

    case Uptime.get_status_page(org_slug, slug, user) do
      nil ->
        {:ok, socket |> assign(:page, nil) |> assign(:page_title, "Not found")}

      page ->
        if connected?(socket),
          do: Phoenix.PubSub.subscribe(Vigil.PubSub, "uptime:org:#{page.organization_id}")

        {:ok,
         socket
         |> assign(:page_title, page.name)
         |> assign(:slugs, {org_slug, slug})
         |> assign(:refresh_scheduled?, false)
         |> load(page)}
    end
  end

  defp load(socket, page) do
    now = DateTime.utc_now()

    rows =
      Enum.map(page.monitors, fn m ->
        %{
          id: m.id,
          name: m.name,
          state: state(m),
          enabled: m.enabled,
          day: Uptime.uptime_ratio(m, 24, now),
          month: Uptime.uptime_ratio(m, 24 * @days, now),
          days: Uptime.daily_uptime(m, @days, now)
        }
      end)

    socket
    |> assign(:page, page)
    |> assign(:rows, rows)
    |> assign(:down, Enum.count(rows, &(&1.state == :down and &1.enabled)))
    |> assign(:updated_at, now)
  end

  defp reload(socket) do
    {org_slug, slug} = socket.assigns.slugs
    scope = socket.assigns.current_scope

    case Uptime.get_status_page(org_slug, slug, scope && scope.user) do
      nil -> assign(socket, :page, nil)
      page -> load(socket, page)
    end
  end

  @impl true
  def handle_info({:uptime_updated, id}, socket) do
    if socket.assigns.page && Enum.any?(socket.assigns.rows, &(&1.id == id)),
      do: {:noreply, schedule_refresh(socket)},
      else: {:noreply, socket}
  end

  def handle_info(:refresh, socket),
    do: {:noreply, socket |> assign(:refresh_scheduled?, false) |> reload()}

  defp schedule_refresh(%{assigns: %{refresh_scheduled?: true}} = socket), do: socket

  defp schedule_refresh(socket) do
    Process.send_after(self(), :refresh, @refresh_ms)
    assign(socket, :refresh_scheduled?, true)
  end

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope}>
      <%= if @page do %>
        <div class="mx-auto max-w-3xl space-y-8">
          <header class="space-y-1 text-center">
            <p class="inline-flex items-center gap-1 text-xs uppercase tracking-wide text-base-content/50">
              <%= if @page.is_public do %>
                <.icon name="hero-signal-micro" class="size-3.5" /> Status
              <% else %>
                <.icon name="hero-lock-closed-micro" class="size-3.5" /> Status · members only
              <% end %>
            </p>
            <h1 id="status-name" class="text-2xl font-bold tracking-tight sm:text-3xl">
              {@page.name}
            </h1>
          </header>

          <div
            id="status-banner"
            role="status"
            class={[
              "flex items-center gap-3 rounded-box px-5 py-4 font-semibold shadow-sm",
              cond do
                @rows == [] -> "bg-base-200 text-base-content/70"
                @down > 0 -> "bg-error text-error-content status-banner-down"
                true -> "bg-success text-success-content status-banner-up"
              end
            ]}
          >
            <%= cond do %>
              <% @rows == [] -> %>
                <.icon name="hero-information-circle" class="size-6 shrink-0" />
                Nothing to show here yet.
              <% @down > 0 -> %>
                <.icon name="hero-exclamation-triangle" class="size-6 shrink-0" />
                {@down} {if @down == 1, do: "system", else: "systems"} down
              <% true -> %>
                <.icon name="hero-check-circle" class="size-6 shrink-0" /> All systems operational
            <% end %>
          </div>

          <ul :if={@rows != []} id="status-monitors" class="space-y-3">
            <li
              :for={row <- @rows}
              id={"status-monitor-#{row.id}"}
              data-state={row.state}
              class="space-y-3 rounded-box border border-base-300 bg-base-100 p-4 transition hover:border-base-content/20"
            >
              <div class="flex flex-wrap items-center justify-between gap-2">
                <h2 class="font-semibold">{row.name}</h2>
                <.public_state state={row.state} id={"status-state-#{row.id}"} />
              </div>
              <.day_strip id={"status-days-#{row.id}"} days={row.days} />
              <div class="flex flex-wrap justify-between gap-2 text-xs text-base-content/60">
                <span>30 days ago</span>
                <span>
                  <span id={"status-24h-#{row.id}"} class="font-medium text-base-content">
                    {percent(row.day)}
                  </span>
                  last 24 hours ·
                  <span id={"status-30d-#{row.id}"} class="font-medium text-base-content">
                    {percent(row.month)}
                  </span>
                  last 30 days
                </span>
                <span>Today</span>
              </div>
            </li>
          </ul>

          <p class="text-center text-xs text-base-content/50">
            Updates live ·
            <time datetime={DateTime.to_iso8601(@updated_at)}>
              as of {Calendar.strftime(@updated_at, "%Y-%m-%d %H:%M UTC")}
            </time>
          </p>
        </div>
      <% else %>
        <div
          id="status-not-found"
          class="mx-auto max-w-md rounded-box border border-dashed border-base-300 p-10 text-center"
        >
          <.icon name="hero-eye-slash" class="mx-auto size-8 text-base-content/40" />
          <h1 class="mt-3 font-semibold">Status page not found</h1>
          <p class="mt-1 text-sm text-base-content/60">
            There's no status page here, or it isn't public.
            <span :if={is_nil(@current_scope)}>
              If you're a member of its organization, <.link
                navigate={~p"/users/log-in"}
                class="link"
              >log in</.link>.
            </span>
          </p>
        </div>
      <% end %>
    </Layouts.app>
    """
  end

  attr :state, :atom, required: true
  attr :id, :string, required: true

  defp public_state(assigns) do
    ~H"""
    <span id={@id}>
      <%= case @state do %>
        <% :down -> %>
          <span class="badge badge-error gap-1 status-down">
            <.icon name="hero-arrow-down-circle-micro" class="size-3.5" /> Down
          </span>
        <% :up -> %>
          <span class="badge badge-success badge-soft gap-1 status-up">
            <.icon name="hero-check-circle-micro" class="size-3.5" /> Operational
          </span>
        <% :pending -> %>
          <span class="badge badge-ghost gap-1 status-pending">
            <.icon name="hero-clock-micro" class="size-3.5" /> Pending
          </span>
      <% end %>
    </span>
    """
  end
end