12.5 KiB · text History 573fef1
defmodule VigilWeb.MonitorLive.Index do
  @moduledoc """
  A project's cron monitors (`Vigil.Monitors`): each one's schedule,
  health, a timeline of its last 30 check-ins, when it last checked in and
  when it's next due. Check-ins refresh the list live (PubSub), at most
  once a second, and relative times refresh every minute. A project with
  none explains how check-ins arrive from the SDKs and sentry-cli. Someone
  with `project:write` can make a monitor here.
  """
  use VigilWeb, :live_view

  import VigilWeb.MonitorComponents

  alias Vigil.Accounts.Scope
  alias Vigil.Monitors
  alias Vigil.Monitors.{Monitor, Schedule}

  @refresh_ms 1000
  @clock_ms 60_000
  @slots 30

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

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

    {:ok,
     socket
     |> assign(:page_title, "#{project.name} · Cron monitors")
     |> assign(:can_write?, Scope.can?(scope, "project:write"))
     |> assign(:creating?, false)
     |> assign(:slots, @slots)
     |> assign(:form, new_form())
     |> assign(:refresh_scheduled?, false)
     |> stream_configure(:monitors, dom_id: &"monitor-#{&1.id}")
     |> load()}
  end

  defp load(socket) do
    monitors = Monitors.list_monitors(socket.assigns.project)
    recent = Monitors.recent_check_ins(Enum.map(monitors, & &1.id), @slots)
    rows = Enum.map(monitors, &%{id: &1.id, monitor: &1, check_ins: Map.get(recent, &1.id, [])})

    socket
    |> assign(:count, length(monitors))
    |> assign(:failing, Enum.count(monitors, &(&1.health == :error)))
    |> stream(:monitors, rows, reset: true)
  end

  defp new_form(params \\ %{}, action \\ nil) do
    %Monitor{schedule_type: :crontab}
    |> Monitors.change_monitor(params)
    |> to_form(action: action)
  end

  @impl true
  def handle_event("new", _params, socket),
    do: {:noreply, assign(socket, creating?: true, form: new_form())}

  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
    %{current_scope: scope, project: project} = socket.assigns

    case Monitors.create_monitor(scope, project, params) do
      {:ok, monitor} ->
        {:noreply,
         socket
         |> put_flash(:info, "Monitor created.")
         |> push_navigate(to: monitor_path(scope, project, monitor))}

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

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

  @impl true
  def handle_info({:monitor_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

  defp monitor_path(scope, project, monitor),
    do: ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}/monitors/#{monitor.slug}"

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
      <div class="mx-auto max-w-6xl space-y-6">
        <.header>
          {@project.name} cron monitors
          <:subtitle>
            Scheduled jobs checking in: whether each ran on time, and how it went.
          </:subtitle>
          <:actions>
            <div class="flex flex-wrap items-center gap-1">
              <.link
                navigate={~p"/orgs/#{@current_scope.organization.slug}/projects/#{@project.slug}"}
                class="btn btn-ghost btn-sm"
                id="monitors-back"
              >
                <.icon name="hero-arrow-left-micro" class="size-4" /> Issues
              </.link>
              <button
                :if={@can_write? and not @creating?}
                type="button"
                id="new-monitor"
                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="monitor-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>
          <.monitor_fields form={@form} slug?={true} />
          <div class="flex gap-2 pt-1">
            <.button class="btn btn-primary btn-sm" phx-disable-with="Creating…" id="create-monitor">
              Create monitor
            </.button>
            <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel" id="cancel-monitor">
              Cancel
            </button>
          </div>
        </.form>

        <%= if @count > 0 do %>
          <div class="flex flex-wrap items-center justify-between gap-2">
            <p id="monitors-summary" class="text-sm text-base-content/70">
              {@count} {if @count == 1, do: "monitor", else: "monitors"}
              <span :if={@failing > 0}>
                ·
                <span class="font-semibold text-error">
                  <.icon name="hero-exclamation-triangle-micro" class="size-4 align-text-bottom" />
                  {@failing} failing
                </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.3fr)_minmax(0,1fr)_6.5rem_6.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} check-ins</span>
              <span class="text-right">Last check-in</span>
              <span class="text-right">Next expected</span>
            </div>
            <ul id="monitors" phx-update="stream" class="divide-y divide-base-300">
              <li :for={{dom_id, row} <- @streams.monitors} id={dom_id}>
                <.link
                  navigate={monitor_path(@current_scope, @project, row.monitor)}
                  class={[
                    "group grid grid-cols-2 gap-x-4 gap-y-2 px-4 py-3 transition hover:bg-base-200/60 md:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_6.5rem_6.5rem] md:items-center",
                    !row.monitor.enabled && "opacity-70"
                  ]}
                >
                  <div class="col-span-2 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>
                      <.health_badge monitor={row.monitor} id={"monitor-health-#{row.id}"} />
                    </p>
                    <p class="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 text-xs text-base-content/60">
                      <span class="font-mono">{row.monitor.slug}</span>
                      <span aria-hidden="true">·</span>
                      <span class="font-mono" id={"monitor-schedule-#{row.id}"}>
                        {Schedule.describe(row.monitor)}
                      </span>
                    </p>
                  </div>
                  <div class="col-span-2 md:col-span-1">
                    <.timeline
                      id={"monitor-timeline-#{row.id}"}
                      check_ins={row.check_ins}
                      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-in</span>
                    <.rel_time
                      at={row.monitor.last_checkin_at}
                      id={"monitor-last-#{row.id}"}
                      empty="never"
                    />
                  </span>
                  <span class="text-sm tabular-nums md:text-right">
                    <span class="block text-xs text-base-content/50 md:hidden">Next expected</span>
                    <%= if row.monitor.enabled do %>
                      <.rel_time at={row.monitor.next_expected_at} id={"monitor-next-#{row.id}"} />
                    <% else %>
                      <span id={"monitor-next-#{row.id}"} class="text-base-content/50">paused</span>
                    <% end %>
                  </span>
                </.link>
              </li>
            </ul>
          </div>
        <% else %>
          <.setup_crons
            can_write?={@can_write?}
            alerts_path={
              ~p"/orgs/#{@current_scope.organization.slug}/projects/#{@project.slug}/alerts"
            }
          />
        <% end %>
      </div>
    </Layouts.app>
    """
  end

  attr :can_write?, :boolean, required: true
  attr :alerts_path, :string, required: true

  defp setup_crons(assigns) do
    ~H"""
    <section
      id="monitors-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-clock" class="mx-auto mb-2 block size-10 text-primary/60" />
          <h2 class="text-lg font-semibold">No cron monitors yet</h2>
          <p class="mt-1 text-sm text-base-content/70">
            Have your scheduled jobs check in when they start and finish. A check-in that
            carries its schedule makes its monitor here on the spot; then a run that's late,
            fails or runs too long shows up, and can alert you.
            <span :if={@can_write?}>You can also make one by hand with <em>New monitor</em>.</span>
          </p>
        </div>

        <div class="space-y-2">
          <h3 class="text-sm font-semibold">sentry-elixir</h3>
          <p class="text-sm text-base-content/70">
            Turn on the Oban or Quantum cron integration, or check in yourself with <code class="font-mono">Sentry.capture_check_in/1</code>:
          </p>
          <pre
            id="setup-crons-elixir"
            class="overflow-x-auto rounded-box bg-base-200 p-3 text-xs"
            phx-no-curly-interpolation
          ><code># config/config.exs
    config :sentry,
      integrations: [
        oban: [cron: [enabled: true]],
        quantum: [cron: [enabled: true]]
      ]

    # or by hand
    {:ok, id} = Sentry.capture_check_in(status: :in_progress, monitor_slug: "nightly-backup")
    # … the job …
    Sentry.capture_check_in(check_in_id: id, status: :ok, monitor_slug: "nightly-backup")</code></pre>
        </div>

        <div class="space-y-2">
          <h3 class="text-sm font-semibold">sentry-python</h3>
          <pre
            id="setup-crons-python"
            class="overflow-x-auto rounded-box bg-base-200 p-3 text-xs"
            phx-no-curly-interpolation
          ><code>from sentry_sdk.crons import monitor

    @monitor(monitor_slug="nightly-backup")
    def nightly_backup():
        ...

    # or: sentry_sdk.crons.capture_checkin(monitor_slug="nightly-backup", status="ok")</code></pre>
        </div>

        <div class="space-y-2">
          <h3 class="text-sm font-semibold">sentry-cli</h3>
          <pre
            id="setup-crons-cli"
            class="overflow-x-auto rounded-box bg-base-200 p-3 text-xs"
            phx-no-curly-interpolation
          ><code>sentry-cli monitors run nightly-backup -- ./backup.sh</code></pre>
        </div>

        <p class="text-xs text-base-content/60">
          <.icon name="hero-bell-micro" class="size-3.5 align-text-bottom" />
          To be told when a job fails or recovers, add an alert rule
          <em>“A cron monitor fails or recovers”</em>
          on the project's <.link
            navigate={@alerts_path}
            class="link link-hover"
            id="monitors-alerts-link"
          >Alerts page</.link>.
        </p>
      </div>
    </section>
    """
  end
end