12.6 KiB · text History 573fef1
defmodule VigilWeb.UptimeLive.Index do
  @moduledoc """
  An organization's uptime monitors (`Vigil.Uptime`), across the projects
  the caller may see: each one's state, type and target, its project, when
  it was last checked and how fast it answered, its 24-hour uptime and a
  strip of its last 30 checks. Results refresh the list live (PubSub on
  `"uptime:org:<id>"`), at most once a second, and relative times every
  minute. Someone with `project:write` can make a monitor here.
  """
  use VigilWeb, :live_view

  import VigilWeb.MonitorComponents, only: [rel_time: 1]
  import VigilWeb.UptimeComponents

  alias Vigil.Accounts.Scope
  alias Vigil.{Projects, Uptime}
  alias Vigil.Uptime.Monitor

  @refresh_ms 1000
  @clock_ms 60_000
  @slots 30

  @impl true
  def mount(_params, _session, socket) do
    scope = socket.assigns.current_scope
    projects = Projects.list_visible(scope)

    if connected?(socket) do
      Phoenix.PubSub.subscribe(Vigil.PubSub, "uptime:org:#{scope.organization.id}")
      :timer.send_interval(@clock_ms, :clock)
    end

    {:ok,
     socket
     |> assign(:page_title, "#{scope.organization.name} · Uptime")
     |> assign(:projects, projects)
     |> assign(:can_write?, Scope.can?(scope, "project:write") and projects != [])
     |> assign(:creating?, false)
     |> assign(:slots, @slots)
     |> assign(:form, new_form())
     |> assign(:refresh_scheduled?, false)
     |> stream_configure(:monitors, dom_id: &"uptime-#{&1.id}")
     |> load()}
  end

  defp load(socket) do
    monitors = Uptime.list_monitors(socket.assigns.current_scope)
    now = DateTime.utc_now()

    rows =
      Enum.map(monitors, fn m ->
        %{
          id: m.id,
          monitor: m,
          checks: m |> Uptime.list_checks(@slots) |> Enum.reverse(),
          uptime: Uptime.uptime_ratio(m, 24, now)
        }
      end)

    socket
    |> assign(:count, length(monitors))
    |> assign(:down, Enum.count(monitors, &(&1.is_up == false and &1.enabled)))
    |> stream(:monitors, rows, reset: true)
  end

  defp new_form(params \\ %{}, action \\ nil) do
    params = Map.put_new(params, "type", "get")

    %Monitor{}
    |> Uptime.change_monitor(params)
    |> to_form(action: action)
  end

  @impl true
  def handle_event("new", _params, socket) do
    form =
      case socket.assigns.projects do
        [only] -> new_form(%{"project_id" => only.id})
        _ -> new_form()
      end

    {:noreply, assign(socket, creating?: true, form: form)}
  end

  def handle_event("cancel", _params, socket), do: {:noreply, assign(socket, :creating?, false)}

  def handle_event("validate", %{"monitor" => params}, socket),
    do: {:noreply, assign(socket, :form, new_form(params, :validate))}

  def handle_event("create", %{"monitor" => params}, socket) do
    scope = socket.assigns.current_scope

    case Enum.find(socket.assigns.projects, &(&1.id == params["project_id"])) do
      nil ->
        form =
          %Monitor{}
          |> Uptime.change_monitor(params)
          |> Ecto.Changeset.add_error(:project_id, "pick a project")
          |> to_form(action: :insert)

        {:noreply, assign(socket, :form, form)}

      project ->
        case Uptime.create_monitor(scope, project, params) do
          {:ok, monitor} ->
            {:noreply,
             socket
             |> put_flash(:info, "Monitor created.")
             |> push_navigate(to: ~p"/orgs/#{scope.organization.slug}/uptime/#{monitor.id}")}

          {:error, %Ecto.Changeset{} = cs} ->
            {:noreply, assign(socket, :form, to_form(cs, action: :insert))}

          {:error, _} ->
            {:noreply, put_flash(socket, :error, "You can't add monitors to that project.")}
        end
    end
  end

  @impl true
  def handle_info({:uptime_updated, _id}, socket), do: {:noreply, schedule_refresh(socket)}

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

  def handle_info(:clock, socket), do: {:noreply, schedule_refresh(socket)}

  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} active={:uptime}>
      <div class="mx-auto max-w-6xl space-y-6">
        <.header>
          Uptime
          <:subtitle>
            Websites, ports, certificates and heartbeats, checked around the clock.
          </:subtitle>
          <:actions>
            <div class="flex flex-wrap items-center gap-1">
              <.link
                navigate={~p"/orgs/#{@current_scope.organization.slug}/status-pages"}
                class="btn btn-ghost btn-sm"
                id="status-pages-link"
              >
                <.icon name="hero-signal-micro" class="size-4" /> Status pages
              </.link>
              <button
                :if={@can_write? and not @creating?}
                type="button"
                id="new-uptime"
                class="btn btn-primary btn-sm"
                phx-click="new"
              >
                <.icon name="hero-plus-micro" class="size-4" /> New monitor
              </button>
            </div>
          </:actions>
        </.header>

        <.form
          :if={@can_write? and @creating?}
          for={@form}
          id="uptime-form"
          phx-change="validate"
          phx-submit="create"
          class="space-y-1 rounded-box border border-base-300 bg-base-200/60 p-4"
        >
          <h2 class="mb-2 text-sm font-semibold">New monitor</h2>
          <.uptime_fields form={@form} projects={Enum.map(@projects, &{&1.name, &1.id})} />
          <div class="flex gap-2 pt-1">
            <.button class="btn btn-primary btn-sm" phx-disable-with="Creating…" id="create-uptime">
              Create monitor
            </.button>
            <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel" id="cancel-uptime">
              Cancel
            </button>
          </div>
        </.form>

        <%= if @count > 0 do %>
          <div class="flex flex-wrap items-center justify-between gap-2">
            <p id="uptime-summary" class="text-sm text-base-content/70">
              {@count} {if @count == 1, do: "monitor", else: "monitors"}
              <span :if={@down > 0}>
                ·
                <span class="font-semibold text-error">
                  <.icon name="hero-arrow-down-circle-micro" class="size-4 align-text-bottom" />
                  {@down} down
                </span>
              </span>
            </p>
            <.legend />
          </div>

          <div class="rounded-box border border-base-300 bg-base-100">
            <div class="hidden rounded-t-box grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_6rem_5.5rem_5rem] gap-4 border-b border-base-300 bg-base-200/50 px-4 py-2 text-xs font-medium uppercase tracking-wide text-base-content/60 md:grid">
              <span>Monitor</span>
              <span>Last {@slots} checks</span>
              <span class="text-right">Last check</span>
              <span class="text-right">Response</span>
              <span class="text-right">24h</span>
            </div>
            <ul id="uptime-monitors" phx-update="stream" class="divide-y divide-base-300">
              <li :for={{dom_id, row} <- @streams.monitors} id={dom_id}>
                <.link
                  navigate={~p"/orgs/#{@current_scope.organization.slug}/uptime/#{row.id}"}
                  class={[
                    "group grid grid-cols-3 gap-x-4 gap-y-2 px-4 py-3 transition hover:bg-base-200/60 md:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_6rem_5.5rem_5rem] md:items-center",
                    !row.monitor.enabled && "opacity-70"
                  ]}
                >
                  <div class="col-span-3 min-w-0 md:col-span-1">
                    <p class="flex min-w-0 flex-wrap items-center gap-2">
                      <span class="truncate font-semibold group-hover:text-primary">
                        {row.monitor.name}
                      </span>
                      <.state_badge monitor={row.monitor} id={"uptime-state-#{row.id}"} />
                    </p>
                    <p class="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-base-content/60">
                      <.type_badge type={row.monitor.type} id={"uptime-type-#{row.id}"} />
                      <span class="truncate font-mono" id={"uptime-target-#{row.id}"}>
                        {Uptime.target(row.monitor)}
                      </span>
                      <span aria-hidden="true">·</span>
                      <span id={"uptime-project-#{row.id}"}>{row.monitor.project.name}</span>
                    </p>
                  </div>
                  <div class="col-span-3 md:col-span-1">
                    <.check_strip id={"uptime-strip-#{row.id}"} checks={row.checks} slots={@slots} />
                  </div>
                  <span class="text-sm tabular-nums md:text-right">
                    <span class="block text-xs text-base-content/50 md:hidden">Last check</span>
                    <.rel_time
                      at={row.monitor.last_check_at}
                      id={"uptime-last-#{row.id}"}
                      empty="never"
                    />
                  </span>
                  <span class="text-sm tabular-nums md:text-right" id={"uptime-ms-#{row.id}"}>
                    <span class="block text-xs text-base-content/50 md:hidden">Response</span>
                    {ms(row.monitor.response_ms)}
                  </span>
                  <span
                    class={[
                      "text-sm font-medium tabular-nums md:text-right",
                      row.uptime && row.uptime < 0.99 && "text-error"
                    ]}
                    id={"uptime-ratio-#{row.id}"}
                  >
                    <span class="block text-xs font-normal text-base-content/50 md:hidden">
                      24h uptime
                    </span>
                    {percent(row.uptime)}
                  </span>
                </.link>
              </li>
            </ul>
          </div>
        <% else %>
          <.empty_state
            can_write?={@can_write?}
            org_slug={@current_scope.organization.slug}
            projects={@projects}
          />
        <% end %>
      </div>
    </Layouts.app>
    """
  end

  attr :can_write?, :boolean, required: true
  attr :org_slug, :string, required: true
  attr :projects, :list, required: true

  defp empty_state(assigns) do
    ~H"""
    <section
      id="uptime-empty"
      class="rounded-box border border-dashed border-base-300 bg-base-100 p-8"
    >
      <div class="mx-auto max-w-2xl space-y-5">
        <div class="text-center">
          <.icon name="hero-signal" class="mx-auto mb-2 block size-10 text-primary/60" />
          <h2 class="text-lg font-semibold">No uptime monitors yet</h2>
          <p class="mt-1 text-sm text-base-content/70">
            Vigil checks your services from the outside, every minute or as often as you like,
            and tells you when one goes down and when it comes back.
            <span :if={@can_write?}>Make one with <em>New monitor</em>.</span>
          </p>
        </div>

        <ul id="uptime-types" class="grid gap-3 sm:grid-cols-2">
          <li :for={{type, text} <- type_blurbs()} class="flex gap-3 rounded-box bg-base-200/60 p-3">
            <.type_badge type={type} />
            <span class="text-sm text-base-content/70">{text}</span>
          </li>
        </ul>

        <p class="text-xs text-base-content/60">
          <.icon name="hero-bell-micro" class="size-3.5 align-text-bottom" />
          To be told when one goes down or recovers, add an alert rule
          <em>“An uptime monitor goes down or comes back”</em>
          on its project's Alerts page<span :if={@projects != []}>
            (<.link
              navigate={~p"/orgs/#{@org_slug}/projects/#{hd(@projects).slug}/alerts"}
              class="link link-hover"
              id="uptime-alerts-link"
            >{hd(@projects).name}</.link>, for one)</span>.
        </p>
      </div>
    </section>
    """
  end

  defp type_blurbs do
    [
      {:get, "Requests a URL; up on the expected status and, optionally, text in the body."},
      {:post, "The same, with a POST."},
      {:ping, "A HEAD request: any answer at all is up."},
      {:tcp, "Opens a connection to host:port: databases, mail, anything with a port."},
      {:ssl, "Checks the TLS handshake and warns before the certificate expires."},
      {:heartbeat, "Your cron job or worker calls its URL; silence for too long is down."}
    ]
  end
end