10.5 KiB · text History b431af3
defmodule VigilWeb.MonitorComponents do
  @moduledoc """
  Pieces the cron monitor pages share: a monitor's health badge, its status
  timeline (one tick per check-in, colored and sized by status, with a
  hover tooltip and a summary for screen readers), relative times in both
  directions, spans of time, and the create/edit form's fields.
  """
  use Phoenix.Component

  import VigilWeb.CoreComponents, only: [icon: 1, input: 1]

  alias Vigil.Monitors.{Monitor, Schedule}

  @statuses [:ok, :error, :missed, :timeout, :in_progress]

  @doc "The check-in statuses, in legend order."
  def statuses, do: @statuses

  @doc "A check-in status for people."
  def status_label(:ok), do: "OK"
  def status_label(:error), do: "Error"
  def status_label(:missed), do: "Missed"
  def status_label(:timeout), do: "Timed out"
  def status_label(:in_progress), do: "In progress"

  def status_label(s) when is_binary(s),
    do: Enum.find_value(@statuses, s, &(to_string(&1) == s && status_label(&1)))

  def status_label(other), do: to_string(other)

  @doc "The tick color of a check-in status."
  def status_color(:ok), do: "bg-success"
  def status_color(:error), do: "bg-error"
  def status_color(:missed), do: "bg-warning"
  def status_color(:timeout), do: "bg-orange-500"
  def status_color(:in_progress), do: "bg-info"
  def status_color(_), do: "bg-base-300"

  @doc "A small badge for a check-in status: dot plus word."
  attr :status, :atom, required: true

  def status_badge(assigns) do
    ~H"""
    <span class="inline-flex items-center gap-1.5 text-sm">
      <span class={["size-2 shrink-0 rounded-full", status_color(@status)]} aria-hidden="true" />
      <span class={[@status in [:error, :missed, :timeout] && "font-medium"]}>
        {status_label(@status)}
      </span>
    </span>
    """
  end

  @doc "A monitor's health (and paused state), as an icon and a word, never color alone."
  attr :monitor, Monitor, required: true
  attr :id, :string, default: nil

  def health_badge(assigns) do
    ~H"""
    <span id={@id} class="inline-flex flex-wrap items-center gap-1">
      <%= case @monitor.health do %>
        <% :error -> %>
          <span class="badge badge-error badge-sm gap-1 monitor-health-error">
            <.icon name="hero-exclamation-triangle-micro" class="size-3.5" /> Failing
          </span>
        <% :ok -> %>
          <span class="badge badge-success badge-soft badge-sm gap-1 monitor-health-ok">
            <.icon name="hero-check-circle-micro" class="size-3.5" /> OK
          </span>
        <% _ -> %>
          <span class="badge badge-ghost badge-sm gap-1 monitor-health-new">
            <.icon name="hero-sparkles-micro" class="size-3.5" /> New
          </span>
      <% end %>
      <span
        :if={!@monitor.enabled}
        class="badge badge-outline badge-sm gap-1 monitor-disabled"
      >
        <.icon name="hero-pause-micro" class="size-3.5" /> Disabled
      </span>
    </span>
    """
  end

  @doc """
  A monitor's latest check-ins (oldest first) as a row of ticks, left-padded
  to `slots` so rows line up. Failures stand full height, successes a little
  shorter, runs in progress shorter still: the shape tells them apart as
  well as the color. Each tick has a tooltip (status, time, duration); the
  row has a summary as its accessible label.
  """
  attr :id, :string, required: true
  attr :check_ins, :list, required: true
  attr :slots, :integer, default: 30
  attr :class, :string, default: "h-6"

  def timeline(assigns) do
    check_ins = Enum.take(assigns.check_ins, -assigns.slots)

    assigns =
      assign(assigns,
        check_ins: check_ins,
        pad: max(assigns.slots - length(check_ins), 0),
        summary: summary(check_ins)
      )

    ~H"""
    <div
      id={@id}
      class={["flex items-end gap-[2px]", @class]}
      role="img"
      aria-label={@summary}
    >
      <span
        :for={_ <- List.duplicate(nil, @pad)}
        class="h-1/3 flex-1 rounded-[2px] bg-base-300/50"
        aria-hidden="true"
      />
      <span
        :for={c <- @check_ins}
        id={"#{@id}-tick-#{c.id}"}
        data-status={c.status}
        class="monitor-tick group relative flex h-full flex-1 items-end"
      >
        <span class={[
          "w-full rounded-[2px] transition-opacity group-hover:opacity-75",
          status_color(c.status),
          tick_height(c.status),
          c.status == :in_progress && "animate-pulse"
        ]} />
        <span class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden -translate-x-1/2 whitespace-nowrap rounded-box border border-base-300 bg-base-100 px-2 py-1 text-xs shadow-md group-hover:block">
          <span class="font-semibold">{status_label(c.status)}</span>
          · {format_time(check_in_time(c))}
          <span :if={c.duration_ms}>· {VigilWeb.PerformanceComponents.duration(c.duration_ms)}</span>
        </span>
      </span>
    </div>
    """
  end

  defp tick_height(status) when status in [:error, :missed, :timeout], do: "h-full"
  defp tick_height(:in_progress), do: "h-1/2"
  defp tick_height(_), do: "h-3/4"

  defp summary([]), do: "No check-ins yet"

  defp summary(check_ins) do
    counts =
      check_ins
      |> Enum.frequencies_by(& &1.status)
      |> then(fn f -> for s <- @statuses, n = f[s], do: "#{n} #{String.downcase(status_label(s))}" end)
      |> Enum.join(", ")

    "Last #{length(check_ins)} check-ins: #{counts}"
  end

  @doc "A legend for the timeline's colors."
  def legend(assigns) do
    assigns = assign(assigns, :statuses, @statuses)

    ~H"""
    <ul class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-base-content/60" aria-hidden="true">
      <li :for={s <- @statuses} class="flex items-center gap-1.5">
        <span class={["size-2.5 rounded-[2px]", status_color(s)]} />{status_label(s)}
      </li>
    </ul>
    """
  end

  @doc "When a check-in happened: when it started, finished or was due."
  def check_in_time(c), do: c.started_at || c.finished_at || c.expected_at

  @doc "A time in full, UTC; nil is a dash."
  def format_time(nil), do: "—"
  def format_time(dt), do: Calendar.strftime(dt, "%Y-%m-%d %H:%M:%S UTC")

  @doc "A time briefly: `Dec 1 14:05`."
  def short_time(nil), do: "—"
  def short_time(dt), do: Calendar.strftime(dt, "%b %-d %H:%M")

  @doc "A `<time>` relative to now in either direction (`5m ago`, `in 2h`), in full on hover."
  attr :at, :any, required: true
  attr :id, :string, default: nil
  attr :class, :any, default: nil
  attr :empty, :string, default: "—"

  def rel_time(assigns) do
    ~H"""
    <time
      id={@id}
      datetime={@at && DateTime.to_iso8601(@at)}
      title={@at && format_time(@at)}
      class={@class}
    >
      {if @at, do: relative(@at), else: @empty}
    </time>
    """
  end

  @doc "How far `at` is from `now`: `just now`, `12m ago`, `in 3h`, `in 2d`."
  def relative(at, now \\ DateTime.utc_now()) do
    diff = DateTime.diff(at, now)

    cond do
      abs(diff) < 45 -> if diff >= 0, do: "in under a minute", else: "just now"
      diff > 0 -> "in #{span(diff)}"
      true -> "#{span(-diff)} ago"
    end
  end

  @doc "A span of seconds, briefly: `45s`, `12m`, `2h 5m`, `3d 4h`."
  def span(s) when s < 60, do: "#{s}s"
  def span(s) when s < 3600, do: "#{div(s, 60)}m"

  def span(s) when s < 86_400 do
    m = rem(div(s, 60), 60)
    if m == 0, do: "#{div(s, 3600)}h", else: "#{div(s, 3600)}h #{m}m"
  end

  def span(s) do
    h = rem(div(s, 3600), 24)
    if h == 0, do: "#{div(s, 86_400)}d", else: "#{div(s, 86_400)}d #{h}h"
  end

  @doc "Minutes for people: `1 minute`, `30 minutes`, `2h`."
  def minutes(1), do: "1 minute"
  def minutes(m) when is_integer(m) and m < 120, do: "#{m} minutes"
  def minutes(m) when is_integer(m), do: span(m * 60)
  def minutes(_), do: "—"

  @doc "The create/edit form's fields (`slug?`: only when creating)."
  attr :form, Phoenix.HTML.Form, required: true
  attr :slug?, :boolean, default: false

  def monitor_fields(assigns) do
    assigns =
      assign(assigns,
        type: to_string(assigns.form[:schedule_type].value),
        units: Enum.map(Monitor.units(), &{"#{&1}s", &1}),
        tz_database?: Schedule.tz_database?()
      )

    ~H"""
    <div class="grid gap-x-3 sm:grid-cols-2">
      <.input
        :if={@slug?}
        field={@form[:slug]}
        label="Slug"
        placeholder="nightly-backup"
        autocomplete="off"
        required
      />
      <.input field={@form[:name]} label="Name" placeholder="Nightly backup (defaults to the slug)" />
    </div>
    <p :if={@slug?} class="-mt-1 mb-2 text-xs text-base-content/60">
      SDKs check in by slug: use the same one in <code class="font-mono">monitor_slug</code>.
    </p>

    <div class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
      <.input
        field={@form[:schedule_type]}
        type="select"
        label="Schedule"
        options={[{"Crontab", "crontab"}, {"Interval", "interval"}]}
      />
      <%= if @type == "interval" do %>
        <div class="grid grid-cols-2 gap-x-3">
          <.input
            field={@form[:interval_value]}
            type="number"
            label="Every"
            min="1"
            id="monitor-interval-value"
          />
          <.input
            field={@form[:interval_unit]}
            type="select"
            label="Unit"
            options={@units}
            prompt="Pick a unit"
            id="monitor-interval-unit"
          />
        </div>
      <% else %>
        <.input
          field={@form[:schedule]}
          label="Crontab expression"
          placeholder="0 3 * * *"
          class="input w-full font-mono"
          id="monitor-crontab"
        />
      <% end %>
    </div>

    <.input field={@form[:timezone]} label="Time zone" placeholder="Etc/UTC" id="monitor-timezone" />
    <p :if={!@tz_database?} id="monitor-tz-hint" class="-mt-1 mb-2 text-xs text-base-content/60">
      <.icon name="hero-information-circle-micro" class="size-3.5 align-text-bottom" />
      This server has no time zone database: schedules are evaluated in UTC.
    </p>

    <div class="grid gap-x-3 sm:grid-cols-2">
      <.input
        field={@form[:checkin_margin]}
        type="number"
        label="Check-in margin (minutes late before missed)"
        min="1"
      />
      <.input
        field={@form[:max_runtime]}
        type="number"
        label="Max runtime (minutes before timed out)"
        min="1"
      />
      <.input
        field={@form[:failure_threshold]}
        type="number"
        label="Failures in a row to open an incident"
        min="1"
      />
      <.input
        field={@form[:recovery_threshold]}
        type="number"
        label="Successes in a row to resolve it"
        min="1"
      />
    </div>
    """
  end
end