5.0 KiB · text History 3208487
defmodule VigilWeb.SentryCliSourcemapsTest do
  @moduledoc """
  Slice 5's exit: the real sentry-cli (on PATH, or `SENTRY_CLI`) creates
  and finalizes a release, uploads source maps with `--wait` (chunk
  upload, assemble, `ok`), and a minified-JS error then reads as the
  TypeScript it came from. Skipped when there is no binary.
  """
  use VigilWeb.ConnCase, async: false

  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.{ApiTokens, Ingest, Issues, Repo}
  alias Vigil.Artifacts.ArtifactBundle
  alias Vigil.Ingest.{Drain, Envelope}

  @cli System.get_env("SENTRY_CLI") || System.find_executable("sentry-cli")
  @abs_path "https://example.com/static/js/app.min.js"
  @release "web@2.0.0"

  setup do
    owner = user_fixture()
    org = organization_fixture(owner)
    scope = org_scope(owner, org)
    project = project_fixture(scope, %{"name" => "web"})

    {:ok, token} =
      ApiTokens.create_token(owner, %{
        label: "cli",
        scopes: ["project:releases", "project:read", "org:read"]
      })

    server = start_supervised!({Bandit, plug: VigilWeb.Endpoint, port: 0, ip: :loopback})
    {:ok, {_ip, port}} = ThousandIsland.listener_info(server)

    env = [
      {"SENTRY_URL", "http://127.0.0.1:#{port}"},
      {"SENTRY_AUTH_TOKEN", token.token},
      {"SENTRY_ORG", org.slug},
      {"SENTRY_PROJECT", project.slug},
      {"SENTRY_LOG_LEVEL", "warn"},
      {"SENTRY_DISABLE_UPDATE_CHECK", "true"},
      {"SENTRY_LOAD_DOTENV", "0"}
    ]

    %{env: env, org: org, project: project}
  end

  defp ok!(env, args) do
    {out, status} =
      System.cmd(@cli, args, env: env, stderr_to_stdout: true, cd: System.tmp_dir!())

    assert status == 0, "sentry-cli #{Enum.join(args, " ")} failed:\n#{out}"
    out
  end

  # Oban runs jobs only when asked in tests: run the assemble jobs while
  # sentry-cli polls for them.
  defp run_jobs_meanwhile do
    parent = self()

    task =
      Task.async(fn ->
        Ecto.Adapters.SQL.Sandbox.allow(Repo, parent, self())

        Stream.repeatedly(fn -> Oban.drain_queue(queue: :processing) end)
        |> Enum.reduce_while(nil, fn _, _ ->
          receive do
            :stop -> {:halt, :ok}
          after
            100 -> {:cont, nil}
          end
        end)
      end)

    fn ->
      send(task.pid, :stop)
      Task.await(task)
    end
  end

  @tag :sdk
  @tag :tmp_dir
  test "release, sourcemaps upload --wait, and a readable stacktrace", ctx do
    if @cli do
      %{env: env, project: project, org: org} = ctx

      dir = Path.join(ctx.tmp_dir, "static/js")
      File.mkdir_p!(dir)
      File.cp_r!("test/support/fixtures/sourcemaps/injected", dir)

      ok!(env, ["releases", "new", @release])

      stop = run_jobs_meanwhile()

      out =
        ok!(env, [
          "sourcemaps",
          "upload",
          "--release",
          @release,
          "--url-prefix",
          "~/static/js",
          "--wait",
          dir
        ])

      stop.()
      assert out =~ "File processing complete"

      assert [%ArtifactBundle{release: @release, artifact_count: 2}] =
               Vigil.Releases.list_artifact_bundles(
                 Vigil.Releases.ensure_release(org.id, project.id, @release),
                 project
               )

      ok!(env, ["releases", "finalize", @release])

      target = %Ingest.Target{
        project_id: project.id,
        dsn_id: project.dsn_id,
        organization_id: org.id,
        key_id: Ecto.UUID.generate()
      }

      item = %Envelope.Item{
        type: "event",
        headers: %{"type" => "event"},
        payload: Jason.encode!(minified_error())
      }

      Ingest.accept(target, %{headers: %{}, items: [item]}, %{client_ip: nil, user_agent: nil})
      Drain.drain(project.id)

      [issue] = Repo.all(Vigil.Issues.Issue)
      event = Issues.latest_event(issue)
      [exception] = event.data["exception"]["values"]
      frames = exception["stacktrace"]["frames"]

      assert Enum.any?(frames, &(&1["filename"] =~ "app.ts" and &1["function"] == "startApp"))
      assert Enum.all?(frames, &get_in(&1, ["data", "symbolicated"]))
      assert exception["raw_stacktrace"]["frames"] |> hd() |> Map.get("lineno") == 3
    else
      IO.puts("skipping sentry-cli sourcemaps: no sentry-cli on PATH")
    end
  end

  # What @sentry/browser sends for startApp("{}") on the injected bundle,
  # matched by url (and release), as no debug_meta is sent.
  defp minified_error do
    frames =
      for {function, col} <- [{"o", 217}, {"n", 182}, {"t", 77}] do
        %{
          "function" => function,
          "abs_path" => @abs_path,
          "filename" => @abs_path,
          "lineno" => 3,
          "colno" => col,
          "in_app" => true
        }
      end

    %{
      "event_id" => Vigil.Schema.uuid7() |> String.replace("-", ""),
      "platform" => "javascript",
      "release" => @release,
      "exception" => %{
        "values" => [
          %{
            "type" => "Error",
            "value" => "retries must be a number",
            "stacktrace" => %{"frames" => frames}
          }
        ]
      }
    }
  end
end