11.0 KiB · text History 573fef1
defmodule VigilWeb.PerformanceLive.Show do
  @moduledoc """
  One transaction group: its lifetime count, throughput, average and
  p50/p95/p99 durations and error rate; transactions per hour over the
  last day and the duration histogram, both as bar charts; and sample
  transactions, the most recent or the slowest (`samples` in the URL),
  each linking to its trace. Follows new transactions live, at most once
  a second.
  """
  use VigilWeb, :live_view

  import VigilWeb.ChartComponents, only: [bars: 1, hourly_points: 1]
  import VigilWeb.PerformanceComponents
  import VigilWeb.IssueListComponents, only: [relative_time: 1]

  alias Vigil.Performance

  @refresh_ms 1000

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

    case Performance.get_group(project.id, id) do
      nil ->
        {:ok,
         socket
         |> assign(:group, nil)
         |> put_flash(:error, "That transaction doesn't exist in this project.")
         |> push_navigate(to: list_path(scope, project))}

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

        {:ok,
         socket
         |> assign(:page_title, "#{group.name} · Performance")
         |> assign(:order, "recent")
         |> assign(:refresh_scheduled?, false)
         |> stream_configure(:samples, dom_id: &"sample-#{&1.id}")
         |> load(group)}
    end
  end

  @impl true
  def handle_params(_params, _uri, %{assigns: %{group: nil}} = socket), do: {:noreply, socket}

  def handle_params(params, _uri, socket) do
    order = if params["samples"] == "slowest", do: "slowest", else: "recent"
    {:noreply, socket |> assign(:order, order) |> load_samples()}
  end

  defp load(socket, group) do
    hourly = Performance.group_hourly(group.id)

    socket
    |> assign(:group, group)
    |> assign(:hourly, Enum.map(hourly, &{&1.hour, &1.count}))
    |> assign(:total_24h, hourly |> Enum.map(& &1.count) |> Enum.sum())
    |> assign(:buckets, histogram_points(Performance.histogram_buckets(group)))
  end

  defp load_samples(socket) do
    order = if socket.assigns.order == "slowest", do: :slowest, else: :recent
    samples = Performance.samples(socket.assigns.group.id, order: order, limit: 20)

    socket
    |> assign(:sample_count, length(samples))
    |> stream(:samples, samples, reset: true)
  end

  # The histogram's buckets that matter: from the first one with a count to
  # the last, padded by one empty bucket on each side.
  defp histogram_points(buckets) do
    counted = buckets |> Enum.with_index() |> Enum.filter(fn {b, _} -> b.count > 0 end)

    case counted do
      [] ->
        []

      _ ->
        first = max(elem(hd(counted), 1) - 1, 0)
        last = min(elem(List.last(counted), 1) + 1, length(buckets) - 1)

        for b <- Enum.slice(buckets, first..last) do
          range = "#{duration(b.from_ms)}–#{duration(b.to_ms)}"
          %{value: b.count, tip: "took #{range}", axis: duration(b.from_ms), row: range}
        end
    end
  end

  @impl true
  def handle_info({:transactions, _}, socket), do: {:noreply, schedule_refresh(socket)}

  def handle_info(:refresh, socket) do
    socket = assign(socket, :refresh_scheduled?, false)

    case Performance.get_group(socket.assigns.project.id, socket.assigns.group.id) do
      nil -> {:noreply, socket}
      group -> {:noreply, socket |> load(group) |> load_samples()}
    end
  end

  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}/performance"

  defp samples_path(scope, project, group, order) do
    params = if order == "slowest", do: %{"samples" => "slowest"}, else: %{}

    ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}/performance/#{group.id}?#{params}"
  end

  @impl true
  def render(%{group: nil} = assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
      <p id="txn-missing" class="text-base-content/60">No such transaction.</p>
    </Layouts.app>
    """
  end

  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">
        <.link
          navigate={list_path(@current_scope, @project)}
          id="back-to-performance"
          class="group inline-flex items-center gap-1 text-sm text-base-content/60 transition hover:text-base-content"
        >
          <.icon
            name="hero-arrow-left-micro"
            class="size-4 transition-transform group-hover:-translate-x-0.5"
          />
          {@project.name} performance
        </.link>

        <header id="txn-header" class="space-y-1">
          <div class="flex flex-wrap items-center gap-2">
            <h1 id="txn-name" class="break-all font-mono text-xl font-semibold sm:text-2xl">
              {@group.name}
            </h1>
            <.txn_badges group={@group} />
          </div>
          <p class="text-sm text-base-content/60">
            First seen <.relative_time at={@group.first_seen} /> · last seen
            <.relative_time at={@group.last_seen} />
          </p>
        </header>

        <dl id="txn-stats" class="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-7">
          <.stat id="stat-count" label="Count">{@group.stats.count}</.stat>
          <.stat id="stat-tpm" label="TPM" hint="Transactions a minute since first seen">
            {tpm(@group.stats.tpm)}
          </.stat>
          <.stat id="stat-avg" label="Average">{duration(@group.stats.avg_ms)}</.stat>
          <.stat id="stat-p50" label="p50">{duration(@group.stats.p50)}</.stat>
          <.stat id="stat-p95" label="p95">{duration(@group.stats.p95)}</.stat>
          <.stat id="stat-p99" label="p99">{duration(@group.stats.p99)}</.stat>
          <.stat
            id="stat-error-rate"
            label="Error rate"
            tone={if(@group.stats.error_count > 0, do: :error)}
          >
            {rate(@group.stats.error_rate)}
          </.stat>
        </dl>

        <div class="grid gap-6 lg:grid-cols-2">
          <section
            id="throughput-chart"
            class="rounded-box border border-base-300 bg-base-100 p-5"
            aria-labelledby="throughput-chart-title"
          >
            <div class="flex items-baseline justify-between gap-3">
              <h2 id="throughput-chart-title" class="text-sm font-semibold">
                Transactions per hour, last 24 hours
              </h2>
              <p class="text-sm text-base-content/70">
                <span id="throughput-total" class="text-2xl font-bold tabular-nums text-base-content">
                  {@total_24h}
                </span>
                total
              </p>
            </div>
            <.bars
              id="throughput"
              points={hourly_points(@hourly)}
              label="Transactions per hour over the last 24 hours"
              key_header="Hour (UTC)"
              value_header="Transactions"
            />
          </section>

          <section
            id="duration-chart"
            class="rounded-box border border-base-300 bg-base-100 p-5"
            aria-labelledby="duration-chart-title"
          >
            <h2 id="duration-chart-title" class="text-sm font-semibold">
              Transactions by duration
            </h2>
            <%= if @buckets == [] do %>
              <p id="duration-empty" class="mt-6 text-center text-sm text-base-content/60">
                No durations recorded yet.
              </p>
            <% else %>
              <.bars
                id="duration"
                points={@buckets}
                label="Transactions by how long they took"
                key_header="Duration"
                value_header="Transactions"
              />
            <% end %>
          </section>
        </div>

        <section id="txn-samples" class="space-y-3">
          <div class="flex flex-wrap items-center justify-between gap-3">
            <h2 class="text-sm font-semibold">Sample transactions</h2>
            <div role="tablist" class="tabs tabs-box tabs-sm">
              <.link
                patch={samples_path(@current_scope, @project, @group, "recent")}
                id="samples-recent"
                role="tab"
                class={["tab", @order == "recent" && "tab-active"]}
              >
                Recent
              </.link>
              <.link
                patch={samples_path(@current_scope, @project, @group, "slowest")}
                id="samples-slowest"
                role="tab"
                class={["tab", @order == "slowest" && "tab-active"]}
              >
                Slowest
              </.link>
            </div>
          </div>
          <ul
            id="samples"
            phx-update="stream"
            class="divide-y divide-base-300 overflow-hidden rounded-box border border-base-300 bg-base-100"
          >
            <li
              id="samples-empty"
              class="hidden px-4 py-8 text-center text-sm text-base-content/60 only:block"
            >
              No samples kept: older transactions age out of retention.
            </li>
            <li :for={{dom_id, s} <- @streams.samples} id={dom_id}>
              <.link
                navigate={~p"/orgs/#{@current_scope.organization.slug}/traces/#{s.trace_id}"}
                class="group flex items-center gap-4 px-4 py-3 transition hover:bg-base-200/60"
              >
                <span
                  class={[
                    "h-8 w-1 shrink-0 rounded-full",
                    if(failed?(s.status), do: "bg-error", else: "bg-primary/60")
                  ]}
                  aria-hidden="true"
                />
                <div class="min-w-0 flex-1">
                  <p class="truncate font-mono text-sm group-hover:text-primary">
                    {s.trace_id}
                  </p>
                  <p class="flex flex-wrap gap-x-3 text-xs text-base-content/60">
                    <span><.relative_time at={s.start_at} /></span>
                    <span :if={s.environment}>{s.environment}</span>
                    <span :if={s.release} class="font-mono">{s.release}</span>
                    <span :if={failed?(s.status)} class="text-error">
                      <.icon name="hero-exclamation-triangle-micro" class="size-3" /> {s.status}
                    </span>
                  </p>
                </div>
                <span class="sample-duration shrink-0 text-sm font-semibold tabular-nums">
                  {duration(s.duration_ms)}
                </span>
                <.icon
                  name="hero-chevron-right-micro"
                  class="size-4 shrink-0 opacity-40 transition-transform group-hover:translate-x-0.5"
                />
              </.link>
            </li>
          </ul>
        </section>
      </div>
    </Layouts.app>
    """
  end
end