5.6 KiB · text History 3208487
defmodule VigilWeb.SentryCliDebugFilesTest do
  @moduledoc """
  Slice 12: the real sentry-cli (on PATH, or `SENTRY_CLI`) uploads a debug
  information file with `debug-files upload --wait` (chunk upload, difs
  assemble, `ok` with the stored file), and a native crash in it then
  reads as functions, files and lines. Skipped when there is no binary.

  The fixture is test/support/fixtures/native/crash, built from crash.c
  next to it (the command is in its header).
  """
  use VigilWeb.ConnCase, async: false

  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.{ApiTokens, DebugFiles, Ingest, Issues, Repo}
  alias Vigil.DebugFiles.DebugFile
  alias Vigil.Ingest.{Drain, Envelope}

  @cli System.get_env("SENTRY_CLI") || System.find_executable("sentry-cli")
  @fixture "test/support/fixtures/native/crash"
  @debug_id "17a26fb0-52e9-5d5a-f357-3b8717704094"

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

    {: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 "debug-files upload --wait, then a symbolicated native crash", ctx do
    if @cli do
      %{env: env, project: project, org: org} = ctx
      File.cp!(@fixture, Path.join(ctx.tmp_dir, "crash"))

      stop = run_jobs_meanwhile()
      out = ok!(env, ["debug-files", "upload", "--wait", ctx.tmp_dir])
      stop.()

      assert out =~ "File processing complete"
      assert out =~ @debug_id

      assert [%DebugFile{debug_id: @debug_id, cpu_name: "x86_64", file_format: "elf"} = file] =
               Repo.all(DebugFile)

      assert "debug" in file.features and "symtab" in file.features

      # Again: the server has it, nothing is uploaded.
      out = ok!(env, ["debug-files", "upload", "--wait", ctx.tmp_dir])
      assert out =~ "Nothing to upload" or out =~ "OK"

      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!(Vigil.NativeFixtures.crash_event())
      }

      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"]
      functions = Enum.map(exception["stacktrace"]["frames"], & &1["function"])

      # Oldest first: main, run, compute, and `scale` inlined into compute.
      assert functions == ["main", "run", "compute", "scale"]
      assert exception["raw_stacktrace"]["frames"] |> length() == 3
      assert issue.culprit =~ "scale"
    else
      IO.puts("skipping sentry-cli debug-files: no sentry-cli on PATH")
    end
  end

  @tag :sdk
  @tag :tmp_dir
  test "upload-proguard, legacy zip upload and chunked", ctx do
    if @cli do
      %{env: env, project: project} = ctx
      mapping = Path.join(ctx.tmp_dir, "mapping.txt")
      File.cp!("test/support/fixtures/proguard/mapping.txt", mapping)
      {:ok, %{uuid: uuid}} = Vigil.Symbolic.proguard_info(File.read!(mapping))

      # The default: a zip to files/dsyms/.
      out = ok!(env, ["upload-proguard", mapping])
      assert out =~ uuid
      assert %DebugFile{file_format: "proguard"} = DebugFiles.proguard_mapping(project.id, uuid)

      # Chunked, through difs/assemble, under a forced UUID. Another build's
      # mapping (a different checksum: the same file would already be there).
      forced = "0b0b0b0b-1111-4222-8333-444455556666"
      File.write!(mapping, "# build 2\n", [:append])
      stop = run_jobs_meanwhile()

      out =
        ok!([{"SENTRY_EXPERIMENTAL_PROGUARD_CHUNK_UPLOAD", "1"} | env], [
          "upload-proguard",
          "--uuid",
          forced,
          mapping
        ])

      stop.()
      assert out =~ "OK" or out =~ forced
      assert %DebugFile{file_format: "proguard"} = DebugFiles.proguard_mapping(project.id, forced)
    else
      IO.puts("skipping sentry-cli upload-proguard: no sentry-cli on PATH")
    end
  end
end