17.3 KiB · text History 573fef1
defmodule VigilWeb.MonitorLive.Show do
  @moduledoc """
  One cron monitor: its settings, health and next expected run, a timeline
  of its last 60 check-ins, the latest 100 check-ins and 20 incidents.
  Check-ins refresh it live (PubSub), at most once a second. Someone with
  `project:write` can edit, enable and disable it; `project:admin` can
  delete it.
  """
  use VigilWeb, :live_view

  import VigilWeb.MonitorComponents
  import VigilWeb.PerformanceComponents, only: [duration: 1]

  alias Vigil.Accounts.Scope
  alias Vigil.Monitors
  alias Vigil.Monitors.Schedule

  @refresh_ms 1000
  @slots 60

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

    case Monitors.get_monitor(project, slug) do
      nil ->
        {:ok,
         socket
         |> put_flash(:error, "That monitor isn't one of this project's.")
         |> push_navigate(to: list_path(scope, project))}

      monitor ->
        if connected?(socket),
          do: Phoenix.PubSub.subscribe(Vigil.PubSub, "project:#{project.id}:monitors")

        {:ok,
         socket
         |> assign(:page_title, "#{monitor.name} · #{project.name}")
         |> assign(:can_write?, Scope.can?(scope, "project:write"))
         |> assign(:can_admin?, Scope.can?(scope, "project:admin"))
         |> assign(:editing?, false)
         |> assign(:form, nil)
         |> assign(:slots, @slots)
         |> assign(:refresh_scheduled?, false)
         |> stream_configure(:check_ins, dom_id: &"checkin-#{&1.id}")
         |> stream_configure(:incidents, dom_id: &"incident-#{&1.id}")
         |> load(monitor)}
    end
  end

  defp load(socket, monitor) do
    check_ins = Monitors.list_check_ins(monitor, 100)
    incidents = Monitors.list_incidents(monitor)

    socket
    |> assign(:monitor, monitor)
    |> assign(:timeline, check_ins |> Enum.take(@slots) |> Enum.reverse())
    |> assign(:check_in_count, length(check_ins))
    |> assign(:incident_count, length(incidents))
    |> stream(:check_ins, check_ins, reset: true)
    |> stream(:incidents, incidents, reset: true)
  end

  defp reload(socket) do
    %{current_scope: scope, project: project, monitor: monitor} = socket.assigns

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

      monitor ->
        load(socket, monitor)
    end
  end

  @impl true
  def handle_event("edit", _params, socket) do
    form = socket.assigns.monitor |> Monitors.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
      |> Monitors.change_monitor(Map.delete(params, "slug"))
      |> 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 Monitors.update_monitor(scope, monitor, Map.delete(params, "slug")) do
      {:ok, monitor} ->
        {:noreply,
         socket
         |> assign(editing?: false, form: nil)
         |> load(monitor)
         |> 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 Monitors.update_monitor(scope, monitor, %{enabled: !monitor.enabled}) do
      {:ok, monitor} ->
        {:noreply,
         socket
         |> load(monitor)
         |> put_flash(
           :info,
           if(monitor.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, project: project, monitor: monitor} = socket.assigns

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

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

  @impl true
  def handle_info({:monitor_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, project),
    do: ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}/monitors"

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
      <div class="mx-auto max-w-5xl space-y-8">
        <.header>
          <span class="flex flex-wrap items-center gap-2">
            <span id="monitor-name">{@monitor.name}</span>
            <.health_badge monitor={@monitor} id="monitor-health" />
          </span>
          <:subtitle>
            <span class="font-mono">{@monitor.slug}</span>
            · <span class="font-mono" id="monitor-schedule">{Schedule.describe(@monitor)}</span>
          </:subtitle>
          <:actions>
            <div class="flex flex-wrap items-center gap-1">
              <.link
                navigate={list_path(@current_scope, @project)}
                class="btn btn-ghost btn-sm"
                id="monitor-back"
              >
                <.icon name="hero-arrow-left-micro" class="size-4" /> Monitors
              </.link>
              <%= if @can_write? do %>
                <button
                  :if={!@editing?}
                  type="button"
                  id="edit-monitor"
                  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-enabled"
                  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-monitor"
                class="btn btn-ghost btn-sm text-error"
                phx-click="delete"
                data-confirm={"Delete the monitor #{@monitor.name} and all its check-ins?"}
              >
                <.icon name="hero-trash-micro" class="size-4" /> Delete
              </button>
            </div>
          </:actions>
        </.header>

        <p
          :if={!@monitor.enabled}
          id="monitor-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: its check-ins are dropped and missed runs aren't counted.
        </p>

        <.form
          :if={@editing? and @form}
          for={@form}
          id="monitor-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>
          <.monitor_fields form={@form} />
          <div class="flex gap-2 pt-1">
            <.button class="btn btn-primary btn-sm" phx-disable-with="Saving…" id="save-monitor">
              Save
            </.button>
            <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel" id="cancel-edit">
              Cancel
            </button>
          </div>
        </.form>

        <dl id="monitor-stats" class="grid grid-cols-2 gap-3 sm:grid-cols-4">
          <.tile id="stat-last" label="Last check-in">
            <.rel_time at={@monitor.last_checkin_at} empty="never" />
            <span :if={@monitor.last_status} class="block text-xs font-normal text-base-content/60">
              {status_label(@monitor.last_status)}
            </span>
          </.tile>
          <.tile id="stat-next" label="Next expected">
            <%= if @monitor.enabled do %>
              <.rel_time at={@monitor.next_expected_at} />
              <span
                :if={@monitor.next_expected_at}
                class="block text-xs font-normal text-base-content/60"
              >
                {short_time(@monitor.next_expected_at)} UTC
              </span>
            <% else %>
              <span class="text-base-content/50">paused</span>
            <% end %>
          </.tile>
          <.tile id="stat-failures" label="Failures in a row">
            <span class={[@monitor.consecutive_failures > 0 && "text-error"]}>
              {@monitor.consecutive_failures}
            </span>
          </.tile>
          <.tile id="stat-incidents" label="Incidents">
            {@incident_count}{if @incident_count >= 20, do: "+"}
          </.tile>
        </dl>

        <section
          id="monitor-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="Schedule">
              <span class="font-mono" id="setting-schedule">{schedule_text(@monitor)}</span>
            </.setting>
            <.setting label="Time zone">
              <span id="setting-timezone">{@monitor.timezone}</span>
              <span :if={!Schedule.tz_database?()} class="text-xs text-base-content/60">
                (evaluated in UTC: no time zone database)
              </span>
            </.setting>
            <.setting label="Check-in margin">
              <span id="setting-margin">{minutes(@monitor.checkin_margin)}</span>
            </.setting>
            <.setting label="Max runtime">
              <span id="setting-runtime">{minutes(@monitor.max_runtime)}</span>
            </.setting>
            <.setting label="Opens an incident after">
              <span id="setting-failure-threshold">
                {@monitor.failure_threshold} {if @monitor.failure_threshold == 1,
                  do: "failure",
                  else: "failures in a row"}
              </span>
            </.setting>
            <.setting label="Resolves after">
              <span id="setting-recovery-threshold">
                {@monitor.recovery_threshold} {if @monitor.recovery_threshold == 1,
                  do: "success",
                  else: "successes in a row"}
              </span>
            </.setting>
          </dl>
        </section>

        <section class="space-y-3">
          <div class="flex flex-wrap items-center justify-between gap-2">
            <h2 class="font-semibold">Last {@slots} check-ins</h2>
            <.legend />
          </div>
          <div class="rounded-box border border-base-300 bg-base-100 px-4 pb-3 pt-8">
            <.timeline
              id={"monitor-timeline-#{@monitor.id}"}
              check_ins={@timeline}
              slots={@slots}
              class="h-12"
            />
          </div>
        </section>

        <section class="space-y-2">
          <h2 class="font-semibold">Incidents</h2>
          <ul
            id="incidents"
            phx-update="stream"
            class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
          >
            <li
              id="incidents-empty"
              class="hidden p-4 text-center text-sm text-base-content/60 only:block"
            >
              No incidents: it hasn't crossed its failure threshold.
            </li>
            <li
              :for={{dom_id, i} <- @streams.incidents}
              id={dom_id}
              class="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-2 text-sm"
            >
              <%= if i.resolved_at do %>
                <span class="badge badge-ghost badge-sm gap-1">
                  <.icon name="hero-check-micro" class="size-3.5" /> Resolved
                </span>
              <% else %>
                <span class="badge badge-error badge-sm gap-1">
                  <.icon name="hero-exclamation-triangle-micro" class="size-3.5" /> Open
                </span>
              <% end %>
              <span class="incident-reason">{reason_text(i.reason)}</span>
              <span class="text-base-content/60">
                <time datetime={DateTime.to_iso8601(i.started_at)} title={format_time(i.started_at)}>
                  {short_time(i.started_at)}
                </time>
                <%= if i.resolved_at do %>
                  →
                  <time
                    datetime={DateTime.to_iso8601(i.resolved_at)}
                    title={format_time(i.resolved_at)}
                  >
                    {short_time(i.resolved_at)}
                  </time>
                <% end %>
              </span>
              <span class="ml-auto tabular-nums text-base-content/70 incident-duration">
                {incident_span(i)}
              </span>
            </li>
          </ul>
        </section>

        <section class="space-y-2">
          <h2 class="font-semibold">
            Check-ins
            <span :if={@check_in_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>Status</th>
                  <th>Expected</th>
                  <th>Started</th>
                  <th class="text-right">Duration</th>
                  <th>Environment</th>
                  <th>Release</th>
                </tr>
              </thead>
              <tbody id="checkins" phx-update="stream">
                <tr id="checkins-empty" class="hidden only:table-row">
                  <td colspan="6" class="py-6 text-center text-base-content/60">
                    No check-ins yet.
                  </td>
                </tr>
                <tr :for={{dom_id, c} <- @streams.check_ins} id={dom_id} data-status={c.status}>
                  <td><.status_badge status={c.status} /></td>
                  <td class="whitespace-nowrap tabular-nums" title={format_time(c.expected_at)}>
                    {short_time(c.expected_at)}
                  </td>
                  <td class="whitespace-nowrap tabular-nums" title={format_time(c.started_at)}>
                    {short_time(c.started_at)}
                  </td>
                  <td class="text-right tabular-nums">{duration(c.duration_ms)}</td>
                  <td class="text-base-content/70">{c.environment || "—"}</td>
                  <td class="max-w-48 truncate font-mono text-xs" title={c.release}>
                    {c.release || "—"}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </Layouts.app>
    """
  end

  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

  defp schedule_text(%{schedule_type: :crontab, schedule: s}), do: "crontab #{s}"
  defp schedule_text(monitor), do: Schedule.describe(monitor)

  defp reason_text("missed"), do: "Missed check-in"
  defp reason_text("timeout"), do: "Ran past max runtime"
  defp reason_text("error"), do: "Reported an error"
  defp reason_text(other), do: other

  defp incident_span(%{started_at: s, resolved_at: nil}),
    do: "ongoing, #{span(DateTime.diff(DateTime.utc_now(), s))}"

  defp incident_span(%{started_at: s, resolved_at: r}), do: span(DateTime.diff(r, s))
end