19.6 KiB · text History 573fef1
defmodule VigilWeb.ReleaseLive.Show do
  @moduledoc """
  One release of a project: a summary (made, finalized, commits, deploys),
  the issues first seen in it, those resolved in it, earlier issues seen
  again in it (carried over or regressed), its deploys, the artifact
  bundles uploaded for it, and the commits `sentry-cli releases
  set-commits` sent. Someone who may change releases can finalize,
  archive and restore it here.
  """
  use VigilWeb, :live_view

  import VigilWeb.IssueListComponents,
    only: [relative_time: 1, plural: 2, level_marker: 1, status_badge: 1, compact: 1]

  alias Vigil.Releases

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

    case Releases.get_release(scope, version, project: project) do
      nil ->
        {:ok,
         socket
         |> put_flash(:error, "That release isn't one of this project's.")
         |> push_navigate(to: releases_path(scope, project))}

      release ->
        {:ok,
         socket
         |> assign(:page_title, "#{Releases.short_version(release.version)} · #{project.name}")
         |> assign(:can_write?, Releases.can_write?(scope))
         |> stream_configure(:commits, dom_id: &"commit-#{&1["id"]}")
         |> load(release)}
    end
  end

  defp load(socket, release) do
    %{current_scope: scope, project: project} = socket.assigns
    stats = Releases.release_stats([release])[release.id]
    issues = Releases.release_issues(release, project)
    deploys = Releases.list_deploys(scope, release)
    bundles = Releases.list_artifact_bundles(release, project)
    commits = Releases.list_commits(release)

    socket
    |> assign(:release, release)
    |> assign(:stats, stats)
    |> assign(:health, Vigil.ReleaseHealth.summary(project.id, release.version))
    |> assign(:sessions_hourly, Vigil.ReleaseHealth.hourly(project.id, release.version))
    |> assign(:counts, %{
      new: length(issues.new),
      resolved: length(issues.resolved),
      seen_again: length(issues.seen_again),
      deploys: length(deploys),
      bundles: length(bundles)
    })
    |> stream(:new_issues, issues.new, reset: true)
    |> stream(:resolved_issues, issues.resolved, reset: true)
    |> stream(:seen_again_issues, issues.seen_again, reset: true)
    |> stream(:deploys, deploys, reset: true)
    |> stream(:bundles, bundles, reset: true)
    |> stream(:commits, commits, reset: true)
  end

  @impl true
  def handle_event("finalize", _params, socket),
    do: change(socket, %{"date_released" => DateTime.utc_now(:second)}, "Release finalized.")

  def handle_event("archive", _params, socket),
    do: change(socket, %{"status" => "archived"}, "Release archived.")

  def handle_event("restore", _params, socket),
    do: change(socket, %{"status" => "open"}, "Release restored.")

  defp change(socket, attrs, message) do
    case Releases.update_release(socket.assigns.current_scope, socket.assigns.release, attrs) do
      {:ok, release} -> {:noreply, socket |> load(release) |> put_flash(:info, message)}
      {:error, _} -> {:noreply, put_flash(socket, :error, "You can't change this release.")}
    end
  end

  @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="release-version" class="font-mono">{Releases.short_version(@release.version)}</span>
            <span
              :if={@release.date_released}
              id="release-released"
              class="badge badge-success badge-soft badge-sm"
            >
              released
            </span>
            <span
              :if={!@release.date_released}
              id="release-unreleased"
              class="badge badge-ghost badge-sm"
            >
              unreleased
            </span>
            <span
              :if={@release.status == :archived}
              id="release-archived"
              class="badge badge-warning badge-soft badge-sm"
            >
              archived
            </span>
          </span>
          <:subtitle>
            <span class="font-mono break-all">{@release.version}</span>
            <span :if={@release.ref}> · ref <span class="font-mono">{@release.ref}</span></span>
            <span :if={@release.url}>
              ·
              <a href={@release.url} target="_blank" rel="noopener noreferrer" class="link link-hover">
                {@release.url}
              </a>
            </span>
          </:subtitle>
          <:actions>
            <div class="flex flex-wrap items-center gap-1">
              <.link
                navigate={releases_path(@current_scope, @project)}
                class="btn btn-ghost btn-sm"
                id="release-back"
              >
                <.icon name="hero-arrow-left-micro" class="size-4" /> Releases
              </.link>
              <%= if @can_write? do %>
                <button
                  :if={!@release.date_released}
                  type="button"
                  id="release-finalize"
                  class="btn btn-primary btn-sm"
                  phx-click="finalize"
                >
                  <.icon name="hero-check-badge-micro" class="size-4" /> Finalize
                </button>
                <button
                  :if={@release.status == :open}
                  type="button"
                  id="release-archive"
                  class="btn btn-ghost btn-sm"
                  phx-click="archive"
                >
                  <.icon name="hero-archive-box-micro" class="size-4" /> Archive
                </button>
                <button
                  :if={@release.status == :archived}
                  type="button"
                  id="release-restore"
                  class="btn btn-ghost btn-sm"
                  phx-click="restore"
                >
                  <.icon name="hero-arrow-uturn-left-micro" class="size-4" /> Restore
                </button>
              <% end %>
            </div>
          </:actions>
        </.header>

        <dl id="release-summary" class="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
          <.stat label="Created"><.relative_time at={@release.inserted_at} /></.stat>
          <.stat label="Released">
            <%= if @release.date_released do %>
              <.relative_time at={@release.date_released} />
            <% else %>
              <span class="text-base-content/50">not yet</span>
            <% end %>
          </.stat>
          <.stat label="New issues">
            <span id="stat-new-issues" class={[@stats.new_groups > 0 && "text-error"]}>
              {@stats.new_groups}
            </span>
          </.stat>
          <.stat label="Last event"><.relative_time at={@stats.last_event} /></.stat>
          <.stat label="Commits"><span id="stat-commits">{@release.commit_count}</span></.stat>
          <.stat label="Deploys">
            <span id="stat-deploys">{@release.deploy_count}</span>
            <span :if={@stats.last_deploy} class="ml-1 text-xs font-normal text-base-content/60">
              last to {@stats.last_deploy.environment}
            </span>
          </.stat>
        </dl>

        <section
          :if={@health.sessions > 0}
          id="release-health"
          class="rounded-box border border-base-300 bg-base-100 p-5"
          aria-labelledby="release-health-title"
        >
          <h2 id="release-health-title" class="text-sm font-semibold">Health</h2>
          <dl class="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-4">
            <.stat label="Crash-free sessions">
              <span id="health-crash-free-sessions" class={health_class(@health.crash_free_sessions)}>
                {percent(@health.crash_free_sessions)}
              </span>
            </.stat>
            <.stat label="Crash-free users">
              <span id="health-crash-free-users" class={health_class(@health.crash_free_users)}>
                {percent(@health.crash_free_users)}
              </span>
            </.stat>
            <.stat label="Adoption (24h)">
              <span id="health-adoption">{percent(@health.adoption)}</span>
            </.stat>
            <.stat label="Sessions">
              <span id="health-sessions">{@health.sessions}</span>
              <span class="ml-1 text-xs font-normal text-base-content/60">
                {@health.crashed} crashed · {@health.users} users
              </span>
            </.stat>
          </dl>
          <div class="mt-4">
            <p class="text-xs text-base-content/60">Sessions per hour, last 24 hours</p>
            <VigilWeb.ChartComponents.bars
              id="sessions-chart"
              label="Sessions per hour over the last 24 hours"
              key_header="Hour (UTC)"
              value_header="Sessions"
              points={session_points(@sessions_hourly)}
            />
          </div>
        </section>

        <div class="grid gap-6 lg:grid-cols-2">
          <.issue_section
            id="new-issues"
            title="New in this release"
            hint="First seen in this version."
            count={@counts.new}
            empty="No new issues. Nice."
            issues={@streams.new_issues}
            scope={@current_scope}
            project={@project}
          />
          <.issue_section
            id="resolved-issues"
            title="Resolved in this release"
            hint="Marked fixed as of this version."
            count={@counts.resolved}
            empty="Nothing was resolved in this release."
            issues={@streams.resolved_issues}
            scope={@current_scope}
            project={@project}
          />
        </div>

        <.issue_section
          id="seen-again-issues"
          title="Earlier issues seen in this release"
          hint="First seen in an earlier release (or none) and still happening here: carried over, or regressed."
          count={@counts.seen_again}
          empty="No older issues have shown up in this release."
          issues={@streams.seen_again_issues}
          scope={@current_scope}
          project={@project}
        />

        <section class="space-y-2">
          <h2 class="flex items-baseline gap-2 font-semibold">
            Deploys <span class="text-sm font-normal text-base-content/60">{@counts.deploys}</span>
          </h2>
          <div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
            <table class="table table-sm">
              <thead>
                <tr>
                  <th>Environment</th>
                  <th>Name</th>
                  <th>Started</th>
                  <th>Finished</th>
                </tr>
              </thead>
              <tbody id="deploys" phx-update="stream">
                <tr id="deploys-empty" class="hidden only:table-row">
                  <td colspan="4" class="py-6 text-center text-base-content/60">
                    No deploys.
                    <code class="font-mono">sentry-cli deploys new -r VERSION -e production</code>
                  </td>
                </tr>
                <tr :for={{dom_id, d} <- @streams.deploys} id={dom_id} class="hover:bg-base-200/50">
                  <td><span class="badge badge-outline badge-sm">{d.environment}</span></td>
                  <td>
                    <%= if d.url do %>
                      <a
                        href={d.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        class="link link-hover"
                      >
                        {d.name || "unnamed"}
                      </a>
                    <% else %>
                      {d.name || "unnamed"}
                    <% end %>
                  </td>
                  <td class="text-base-content/70">
                    <%= if d.date_started do %>
                      <.relative_time at={d.date_started} />
                    <% else %>
                      —
                    <% end %>
                  </td>
                  <td class="text-base-content/70"><.relative_time at={d.date_finished} /></td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>

        <section class="space-y-2">
          <h2 class="flex items-baseline gap-2 font-semibold">
            Artifact bundles
            <span class="text-sm font-normal text-base-content/60">{@counts.bundles}</span>
          </h2>
          <div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
            <table class="table table-sm">
              <thead>
                <tr>
                  <th>Bundle</th>
                  <th>Dist</th>
                  <th class="text-right">Files</th>
                  <th class="text-right">Size</th>
                  <th class="text-right">Uploaded</th>
                </tr>
              </thead>
              <tbody id="bundles" phx-update="stream">
                <tr id="bundles-empty" class="hidden only:table-row">
                  <td colspan="5" class="py-6 text-center text-base-content/60">
                    No source maps for this release.
                    <code class="font-mono">sentry-cli sourcemaps upload --release VERSION</code>
                  </td>
                </tr>
                <tr :for={{dom_id, b} <- @streams.bundles} id={dom_id} class="hover:bg-base-200/50">
                  <td class="font-mono text-xs" title={b.checksum}>
                    {b.bundle_id || String.slice(b.checksum, 0, 12)}
                  </td>
                  <td class="font-mono text-xs">{b.dist || "—"}</td>
                  <td class="text-right tabular-nums">{b.artifact_count}</td>
                  <td class="text-right tabular-nums">{format_bytes(b.size)}</td>
                  <td class="text-right text-base-content/70">
                    <.relative_time at={b.inserted_at} />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>

        <section class="space-y-2">
          <h2 class="flex items-baseline gap-2 font-semibold">
            Commits
            <span class="text-sm font-normal text-base-content/60">{@release.commit_count}</span>
          </h2>
          <ul
            id="commits"
            phx-update="stream"
            class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
          >
            <li
              id="commits-empty"
              class="hidden p-6 text-center text-sm text-base-content/60 only:block"
            >
              No commits.
              <code class="font-mono">sentry-cli releases set-commits VERSION --auto</code>
            </li>
            <li
              :for={{dom_id, c} <- @streams.commits}
              id={dom_id}
              class="flex items-start gap-3 px-4 py-2.5"
            >
              <span class="mt-0.5 rounded bg-base-200 px-1.5 py-0.5 font-mono text-xs" title={c["id"]}>
                {String.slice(c["id"], 0, 7)}
              </span>
              <div class="min-w-0 flex-1">
                <p class="truncate text-sm">{first_line(c["message"])}</p>
                <p class="truncate text-xs text-base-content/60">
                  {c["author_name"] || c["author_email"] || "unknown author"}
                  <span :if={c["repository"]}> · {c["repository"]}</span>
                  <span :if={c["patch_set"] != []}>
                    · {length(c["patch_set"])} {plural(length(c["patch_set"]), "file")}
                  </span>
                </p>
              </div>
              <time
                :if={c["timestamp"]}
                class="shrink-0 text-xs text-base-content/60"
                datetime={c["timestamp"]}
              >
                {commit_date(c["timestamp"])}
              </time>
            </li>
          </ul>
        </section>
      </div>
    </Layouts.app>
    """
  end

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

  defp stat(assigns) do
    ~H"""
    <div 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 :id, :string, required: true
  attr :title, :string, required: true
  attr :hint, :string, required: true
  attr :count, :integer, required: true
  attr :empty, :string, required: true
  attr :issues, :any, required: true
  attr :scope, :any, required: true
  attr :project, :any, required: true

  defp issue_section(assigns) do
    ~H"""
    <section class="space-y-2">
      <div>
        <h2 class="flex items-baseline gap-2 font-semibold">
          {@title} <span class="text-sm font-normal text-base-content/60">{@count}</span>
        </h2>
        <p class="text-xs text-base-content/60">{@hint}</p>
      </div>
      <ul
        id={@id}
        phx-update="stream"
        class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
      >
        <li id={"#{@id}-empty"} class="hidden p-6 text-center text-sm text-base-content/60 only:block">
          {@empty}
        </li>
        <li :for={{dom_id, issue} <- @issues} id={dom_id}>
          <.link
            navigate={
              ~p"/orgs/#{@scope.organization.slug}/projects/#{@project.slug}/issues/#{issue.short_id}"
            }
            class="group flex items-center gap-3 px-4 py-2.5 transition hover:bg-base-200/60"
          >
            <.level_marker level={issue.level} />
            <div class="min-w-0 flex-1">
              <p class="truncate text-sm font-medium group-hover:text-primary">{issue.title}</p>
              <p class="truncate text-xs text-base-content/60">
                <span class="font-mono">{String.upcase(@project.slug)}-{issue.short_id}</span>
                <span :if={issue.culprit}> · {issue.culprit}</span>
              </p>
            </div>
            <.status_badge status={issue.status} />
            <div class="shrink-0 text-right text-xs text-base-content/60">
              <p class="tabular-nums">{compact(issue.count)} {plural(issue.count, "event")}</p>
              <.relative_time at={issue.last_seen} />
            </div>
          </.link>
        </li>
      </ul>
    </section>
    """
  end

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

  defp first_line(nil), do: "(no message)"
  defp first_line(message), do: message |> String.split("\n", parts: 2) |> hd()

  defp commit_date(ts) do
    case DateTime.from_iso8601(ts) do
      {:ok, dt, _} -> Calendar.strftime(dt, "%b %-d, %Y")
      _ -> ts
    end
  end

  defp format_bytes(n) when n < 1024, do: "#{n} B"
  defp format_bytes(n) when n < 1024 * 1024, do: "#{Float.round(n / 1024, 1)} KB"
  defp format_bytes(n), do: "#{Float.round(n / (1024 * 1024), 1)} MB"

  # Crashes, when there are any, show in the error color on that hour's bar.
  defp session_points(hourly) do
    for %{hour: h, sessions: n, crashed: c} <- hourly do
      %{
        value: n,
        tip:
          "at #{Calendar.strftime(h, "%H:00")} UTC" <> if(c > 0, do: ", #{c} crashed", else: ""),
        axis: Calendar.strftime(h, "%H:00"),
        row: Calendar.strftime(h, "%Y-%m-%d %H:00"),
        tone: if(c > 0, do: :error)
      }
    end
  end

  defp percent(nil), do: "—"

  defp percent(r),
    do: "#{:erlang.float_to_binary(r * 100, decimals: if(r >= 0.999 and r < 1, do: 2, else: 1))}%"

  defp health_class(nil), do: nil
  defp health_class(r) when r < 0.95, do: "text-error"
  defp health_class(r) when r < 0.99, do: "text-warning"
  defp health_class(_), do: "text-success"
end