21.0 KiB · text History 2bb12dd
defmodule VigilWeb.UptimeLive.Show do
  @moduledoc """
  One uptime monitor: its state and settings, a heartbeat monitor's URL
  (with a curl example), response times of its last 60 checks (failed
  ones in red), its uptime over 24 hours, 7 and 30 days, its ups and
  downs, and its latest 100 checks. Results refresh it live (PubSub), at
  most once a second. Someone with `project:write` can edit, enable and
  disable it; `project:admin` can delete it. This is the page uptime
  alerts link to (`/orgs/:org/uptime/:id`).
  """
  use VigilWeb, :live_view

  import VigilWeb.MonitorComponents, only: [rel_time: 1, format_time: 1, short_time: 1, span: 1]
  import VigilWeb.UptimeComponents
  import VigilWeb.ChartComponents, only: [bars: 1]

  alias Vigil.Accounts.Scope
  alias Vigil.Uptime

  @refresh_ms 1000
  @chart_slots 60

  @impl true
  def mount(%{"id" => id}, _session, socket) do
    scope = socket.assigns.current_scope

    case Uptime.get_monitor(scope, id) do
      nil ->
        {:ok,
         socket
         |> put_flash(:error, "That monitor doesn't exist, or you can't see it.")
         |> push_navigate(to: list_path(scope))}

      monitor ->
        if connected?(socket),
          do: Phoenix.PubSub.subscribe(Vigil.PubSub, "uptime:org:#{scope.organization.id}")

        {:ok,
         socket
         |> assign(:page_title, "#{monitor.name} · Uptime")
         |> assign(:can_write?, Scope.can?(scope, "project:write"))
         |> assign(:can_admin?, Scope.can?(scope, "project:admin"))
         |> assign(:editing?, false)
         |> assign(:form, nil)
         |> assign(:refresh_scheduled?, false)
         |> stream_configure(:checks, dom_id: &"check-#{&1.id}")
         |> stream_configure(:changes, dom_id: &"change-#{&1.id}")
         |> load(monitor)}
    end
  end

  defp load(socket, monitor) do
    now = DateTime.utc_now()
    checks = Uptime.list_checks(monitor, 100)
    changes = Uptime.list_changes(monitor, 50)

    socket
    |> assign(:monitor, monitor)
    |> assign(:points, chart_points(checks))
    |> assign(:check_count, length(checks))
    |> assign(:uptime, %{
      day: Uptime.uptime_ratio(monitor, 24, now),
      week: Uptime.uptime_ratio(monitor, 24 * 7, now),
      month: Uptime.uptime_ratio(monitor, 24 * 30, now)
    })
    |> stream(:checks, checks, reset: true)
    |> stream(:changes, change_rows(changes, now), reset: true)
  end

  defp reload(socket) do
    scope = socket.assigns.current_scope

    case Uptime.get_monitor(scope, socket.assigns.monitor.id) do
      nil ->
        socket
        |> put_flash(:info, "That monitor was deleted.")
        |> push_navigate(to: list_path(scope))

      monitor ->
        load(socket, monitor)
    end
  end

  # Newest first: each change lasted until the next (newer) one, or now.
  defp change_rows(changes, now) do
    ends = [nil | Enum.map(changes, & &1.checked_at)]

    Enum.zip_with(changes, ends, fn c, until ->
      %{
        id: c.id,
        is_up: c.is_up,
        reason: c.reason,
        at: c.checked_at,
        ongoing?: is_nil(until),
        seconds: DateTime.diff(until || now, c.checked_at)
      }
    end)
  end

  defp chart_points(checks) do
    checks
    |> Enum.take(@chart_slots)
    |> Enum.reverse()
    |> Enum.map(fn c ->
      %{
        value: c.response_ms || 0,
        tone: if(c.is_up, do: nil, else: :error),
        tip:
          if(c.is_up,
            do: "at #{format_time(c.checked_at)}",
            else: "down (#{Uptime.describe_reason(c.reason)}) at #{format_time(c.checked_at)}"
          ),
        axis: Calendar.strftime(c.checked_at, "%H:%M"),
        row: format_time(c.checked_at) <> if(c.is_up, do: "", else: " (down)")
      }
    end)
  end

  @impl true
  def handle_event("edit", _params, socket) do
    form = socket.assigns.monitor |> Uptime.change_monitor() |> to_form()
    {:noreply, assign(socket, editing?: true, form: form)}
  end

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

  def handle_event("validate", %{"monitor" => params}, socket) do
    form =
      socket.assigns.monitor
      |> Uptime.change_monitor(params)
      |> to_form(action: :validate)

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

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

    case Uptime.update_monitor(scope, monitor, params) do
      {:ok, monitor} ->
        {:noreply,
         socket
         |> assign(editing?: false, form: nil)
         |> load(%{monitor | project: socket.assigns.monitor.project})
         |> put_flash(:info, "Monitor saved.")}

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

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "You can't change this monitor.")}
    end
  end

  def handle_event("toggle_enabled", _params, socket) do
    %{current_scope: scope, monitor: monitor} = socket.assigns

    case Uptime.update_monitor(scope, monitor, %{enabled: !monitor.enabled}) do
      {:ok, updated} ->
        {:noreply,
         socket
         |> load(%{updated | project: monitor.project})
         |> put_flash(
           :info,
           if(updated.enabled, do: "Monitor enabled.", else: "Monitor disabled.")
         )}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "You can't change this monitor.")}
    end
  end

  def handle_event("delete", _params, socket) do
    %{current_scope: scope, monitor: monitor} = socket.assigns

    case Uptime.delete_monitor(scope, monitor) do
      {:ok, _} ->
        {:noreply,
         socket
         |> put_flash(:info, "Monitor #{monitor.name} deleted.")
         |> push_navigate(to: list_path(scope))}

      {:error, _} ->
        {:noreply, put_flash(socket, :error, "You can't delete this monitor.")}
    end
  end

  @impl true
  def handle_info({:uptime_updated, id}, socket) do
    if id == socket.assigns.monitor.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

  defp list_path(scope), do: ~p"/orgs/#{scope.organization.slug}/uptime"

  @impl true
  def render(assigns) do
    assigns =
      assign(
        assigns,
        :heartbeat_url,
        assigns.monitor.type == :heartbeat &&
          heartbeat_url(assigns.current_scope.organization.slug, assigns.monitor)
      )

    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:uptime}>
      <div class="mx-auto max-w-5xl space-y-8">
        <.header>
          <span class="flex flex-wrap items-center gap-2">
            <span id="uptime-name">{@monitor.name}</span>
            <.state_badge monitor={@monitor} id="uptime-state" />
          </span>
          <:subtitle>
            <span class="inline-flex flex-wrap items-center gap-2">
              <.type_badge type={@monitor.type} id="uptime-type" />
              <span class="break-all font-mono" id="uptime-target">{Uptime.target(@monitor)}</span>
              <span aria-hidden="true">·</span>
              <.link
                navigate={
                  ~p"/orgs/#{@current_scope.organization.slug}/projects/#{@monitor.project.slug}"
                }
                class="link link-hover"
                id="uptime-project"
              >
                {@monitor.project.name}
              </.link>
            </span>
          </:subtitle>
          <:actions>
            <div class="flex flex-wrap items-center gap-1">
              <.link
                navigate={list_path(@current_scope)}
                class="btn btn-ghost btn-sm"
                id="uptime-back"
              >
                <.icon name="hero-arrow-left-micro" class="size-4" /> Uptime
              </.link>
              <%= if @can_write? do %>
                <button
                  :if={!@editing?}
                  type="button"
                  id="edit-uptime"
                  class="btn btn-ghost btn-sm"
                  phx-click="edit"
                >
                  <.icon name="hero-pencil-square-micro" class="size-4" /> Edit
                </button>
                <button
                  type="button"
                  id="toggle-uptime"
                  class="btn btn-ghost btn-sm"
                  phx-click="toggle_enabled"
                >
                  <%= if @monitor.enabled do %>
                    <.icon name="hero-pause-micro" class="size-4" /> Disable
                  <% else %>
                    <.icon name="hero-play-micro" class="size-4" /> Enable
                  <% end %>
                </button>
              <% end %>
              <button
                :if={@can_admin?}
                type="button"
                id="delete-uptime"
                class="btn btn-ghost btn-sm text-error"
                phx-click="delete"
                data-confirm={"Delete the monitor #{@monitor.name} and all its checks?"}
              >
                <.icon name="hero-trash-micro" class="size-4" /> Delete
              </button>
            </div>
          </:actions>
        </.header>

        <p
          :if={!@monitor.enabled}
          id="uptime-disabled-note"
          class="flex items-center gap-2 rounded-box border border-dashed border-base-300 bg-base-200/40 px-4 py-3 text-sm text-base-content/70"
        >
          <.icon name="hero-pause-circle" class="size-5 shrink-0" />
          This monitor is disabled: it isn't checked and doesn't alert.
        </p>

        <p
          :if={@monitor.is_up == false}
          id="uptime-down-note"
          class="flex items-center gap-2 rounded-box border border-error/40 bg-error/10 px-4 py-3 text-sm"
        >
          <.icon name="hero-exclamation-triangle" class="size-5 shrink-0 text-error" />
          <span>
            Down <span :if={@monitor.last_change_at}>
              since <.rel_time at={@monitor.last_change_at} />
            </span>: {Uptime.describe_reason(
              @monitor.reason
            )}.
          </span>
        </p>

        <.form
          :if={@editing? and @form}
          for={@form}
          id="uptime-form"
          phx-change="validate"
          phx-submit="save"
          class="space-y-1 rounded-box border border-base-300 bg-base-200/60 p-4"
        >
          <h2 class="mb-2 text-sm font-semibold">Edit monitor</h2>
          <.uptime_fields form={@form} />
          <div class="flex gap-2 pt-1">
            <.button class="btn btn-primary btn-sm" phx-disable-with="Saving…" id="save-uptime">
              Save
            </.button>
            <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel" id="cancel-edit">
              Cancel
            </button>
          </div>
        </.form>

        <section
          :if={@heartbeat_url}
          id="heartbeat"
          class="space-y-3 rounded-box border border-base-300 bg-base-100 p-4"
        >
          <div>
            <h2 class="font-semibold">Heartbeat URL</h2>
            <p class="text-sm text-base-content/70">
              Have your job call this at least every {span(@monitor.interval_seconds)} (plus {span(
                @monitor.timeout_seconds
              )} grace). GET or POST, no token needed:
              the URL is the secret.
            </p>
          </div>
          <div class="join w-full">
            <input
              id="heartbeat-url"
              type="text"
              readonly
              value={@heartbeat_url}
              class="input input-sm join-item min-w-0 flex-1 font-mono text-xs"
              aria-label="Heartbeat URL"
            />
            <button
              id="copy-heartbeat-url"
              type="button"
              class="btn btn-sm btn-primary join-item"
              phx-click={JS.dispatch("phx:copy", to: "#heartbeat-url")}
            >
              <.icon name="hero-clipboard-document-micro" class="size-4" /> Copy
            </button>
          </div>
          <pre
            id="heartbeat-curl"
            class="overflow-x-auto rounded-box bg-base-200 p-3 font-mono text-xs"
          ><code>curl -fsS -X POST {@heartbeat_url}</code></pre>
          <p :if={@monitor.last_heartbeat_at} class="text-xs text-base-content/60">
            Last heartbeat <.rel_time at={@monitor.last_heartbeat_at} id="heartbeat-last" />
          </p>
        </section>

        <dl id="uptime-stats" class="grid grid-cols-2 gap-3 sm:grid-cols-4">
          <.tile id="stat-last" label="Last check">
            <.rel_time at={@monitor.last_check_at} empty="never" />
            <span :if={@monitor.response_ms} class="block text-xs font-normal text-base-content/60">
              {ms(@monitor.response_ms)}
            </span>
          </.tile>
          <.tile id="stat-24h" label="Uptime 24h">{percent(@uptime.day)}</.tile>
          <.tile id="stat-7d" label="Uptime 7 days">{percent(@uptime.week)}</.tile>
          <.tile id="stat-30d" label="Uptime 30 days">{percent(@uptime.month)}</.tile>
        </dl>

        <section id="uptime-settings" class="rounded-box border border-base-300 bg-base-100 p-4">
          <h2 class="mb-3 font-semibold">Settings</h2>
          <dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-2">
            <.setting label="Type">{type_label(@monitor.type)}</.setting>
            <.setting :if={@monitor.type != :heartbeat} label="Target">
              <span class="break-all font-mono" id="setting-url">{@monitor.url}</span>
            </.setting>
            <.setting label={
              if @monitor.type == :heartbeat, do: "Expected every", else: "Checked every"
            }>
              <span id="setting-interval">{span(@monitor.interval_seconds)}</span>
            </.setting>
            <.setting label={if @monitor.type == :heartbeat, do: "Grace", else: "Timeout"}>
              <span id="setting-timeout">{span(@monitor.timeout_seconds)}</span>
            </.setting>
            <%= if @monitor.type in [:get, :post] do %>
              <.setting label="Expected status">
                <span id="setting-status">{@monitor.expected_status || "any 2xx"}</span>
              </.setting>
              <.setting label="Expected text">
                <span id="setting-body" class="break-all font-mono">
                  {@monitor.expected_body || "—"}
                </span>
              </.setting>
            <% end %>
            <%= if @monitor.type == :ssl do %>
              <.setting label="Down when expiring within">
                <span id="setting-ssl-warn">{@monitor.ssl_warn_days} days</span>
              </.setting>
              <.setting label="Certificate expires">
                <span id="setting-ssl-expires">
                  {if @monitor.ssl_expires_at, do: short_time(@monitor.ssl_expires_at), else: "—"}
                </span>
              </.setting>
            <% end %>
          </dl>
        </section>

        <section
          id="response-chart"
          class="rounded-box border border-base-300 bg-base-100 p-5"
          aria-labelledby="response-chart-title"
        >
          <div class="flex flex-wrap items-baseline justify-between gap-2">
            <h2 id="response-chart-title" class="text-sm font-semibold">
              Response time, last {length(@points)} checks
            </h2>
            <ul class="flex gap-4 text-xs text-base-content/60" aria-hidden="true">
              <li class="flex items-center gap-1.5">
                <span class="size-2.5 rounded-[2px] bg-primary" />Up
              </li>
              <li class="flex items-center gap-1.5">
                <span class="size-2.5 rounded-[2px] bg-error" />Down
              </li>
            </ul>
          </div>
          <%= if @points == [] do %>
            <p id="response-chart-empty" class="mt-4 text-sm text-base-content/60">
              No checks yet.
            </p>
          <% else %>
            <.bars
              id="response"
              points={@points}
              label="Response time of recent checks, failed ones in red"
              key_header="Checked (UTC)"
              value_header="Response"
              format={&ms_value/1}
            />
          <% end %>
        </section>

        <section class="space-y-2">
          <h2 class="font-semibold">Ups and downs</h2>
          <ul
            id="uptime-changes"
            phx-update="stream"
            class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
          >
            <li
              id="changes-empty"
              class="hidden p-4 text-center text-sm text-base-content/60 only:block"
            >
              Not checked yet.
            </li>
            <li
              :for={{dom_id, c} <- @streams.changes}
              id={dom_id}
              class="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-2 text-sm"
            >
              <%= if c.is_up do %>
                <span class="badge badge-success badge-soft badge-sm gap-1">
                  <.icon name="hero-arrow-up-circle-micro" class="size-3.5" /> Went up
                </span>
              <% else %>
                <span class="badge badge-error badge-sm gap-1">
                  <.icon name="hero-arrow-down-circle-micro" class="size-3.5" /> Went down
                </span>
                <span class="change-reason">{Uptime.describe_reason(c.reason)}</span>
              <% end %>
              <time
                datetime={DateTime.to_iso8601(c.at)}
                title={format_time(c.at)}
                class="text-base-content/60"
              >
                {short_time(c.at)}
              </time>
              <span class="ml-auto tabular-nums text-base-content/70 change-duration">
                {if c.ongoing?, do: "ongoing, #{span(c.seconds)}", else: "lasted #{span(c.seconds)}"}
              </span>
            </li>
          </ul>
        </section>

        <section class="space-y-2">
          <h2 class="font-semibold">
            Checks
            <span :if={@check_count >= 100} class="text-sm font-normal text-base-content/60">
              (latest 100)
            </span>
          </h2>
          <div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
            <table class="table table-sm">
              <thead>
                <tr>
                  <th>Time</th>
                  <th>State</th>
                  <th>Reason</th>
                  <th class="text-right">Status</th>
                  <th class="text-right">Response</th>
                </tr>
              </thead>
              <tbody id="uptime-checks" phx-update="stream">
                <tr id="checks-empty" class="hidden only:table-row">
                  <td colspan="5" class="py-6 text-center text-base-content/60">No checks yet.</td>
                </tr>
                <tr :for={{dom_id, c} <- @streams.checks} id={dom_id} data-up={to_string(c.is_up)}>
                  <td class="whitespace-nowrap tabular-nums" title={format_time(c.checked_at)}>
                    {short_time(c.checked_at)}
                  </td>
                  <td>
                    <span class="inline-flex items-center gap-1.5">
                      <span
                        class={[
                          "size-2 shrink-0 rounded-full",
                          if(c.is_up, do: "bg-success", else: "bg-error")
                        ]}
                        aria-hidden="true"
                      />
                      <span class={[!c.is_up && "font-medium"]}>
                        {if c.is_up, do: "Up", else: "Down"}
                      </span>
                    </span>
                  </td>
                  <td class="text-base-content/70">
                    {if c.is_up, do: "—", else: Uptime.describe_reason(c.reason)}
                  </td>
                  <td class="text-right tabular-nums">{c.status_code || "—"}</td>
                  <td class="text-right tabular-nums">{ms(c.response_ms)}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </Layouts.app>
    """
  end

  defp ms_value(0), do: "—"
  defp ms_value(n), do: "#{n} ms"

  attr :id, :string, required: true
  attr :label, :string, required: true
  slot :inner_block, required: true

  defp tile(assigns) do
    ~H"""
    <div
      id={@id}
      class="rounded-box border border-base-300 bg-base-100 px-4 py-3 transition hover:border-base-content/20"
    >
      <dt class="text-xs font-medium uppercase tracking-wide text-base-content/60">{@label}</dt>
      <dd class="mt-1 text-lg font-semibold tabular-nums">{render_slot(@inner_block)}</dd>
    </div>
    """
  end

  attr :label, :string, required: true
  slot :inner_block, required: true

  defp setting(assigns) do
    ~H"""
    <div class="flex flex-wrap items-baseline justify-between gap-2 border-b border-base-200 pb-2 sm:block sm:border-0 sm:pb-0">
      <dt class="text-base-content/60">{@label}</dt>
      <dd class="font-medium">{render_slot(@inner_block)}</dd>
    </div>
    """
  end
end