4.7 KiB · text History 3208487
defmodule VigilWeb.SdkTracingConformanceTest do
  @moduledoc """
  Slice 6's exit, with the real SDKs against a running server:
  sentry-elixir with OpenTelemetry (a `transaction` with nested spans,
  `test/support/sdk/sentry_elixir_trace.exs`) and sentry-python 3 (span
  streaming, `span` v2 items). Each becomes transaction groups and a
  trace, and an error raised inside the trace links to it. Skipped when a
  checkout is missing (see `VigilWeb.SdkConformanceTest`).
  """
  use VigilWeb.ConnCase, async: false

  import Ecto.Query
  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.{Performance, Projects, Repo}
  alias Vigil.Issues.IssueEvent
  alias Vigil.Performance.Span

  @elixir_sdk System.get_env(
                "SENTRY_ELIXIR_PATH",
                Path.expand("~/Development/local/sentry_oss_2019/sentry-elixir")
              )

  @python_sdk System.get_env(
                "SENTRY_PYTHON_PATH",
                Path.expand("~/Development/local/sentry_oss_2019/sentry-python")
              )

  setup do
    owner = user_fixture()
    org = organization_fixture(owner)
    project = project_fixture(org_scope(owner, org))
    [key] = Projects.list_keys(project)

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

    hex = String.replace(key.public_key, "-", "")
    %{project: project, dsn: "http://#{hex}@127.0.0.1:#{port}/#{project.dsn_id}"}
  end

  @tag :sdk
  @tag timeout: 300_000
  test "sentry-elixir with OpenTelemetry: a transaction, its spans, and the error in it", ctx do
    if File.exists?(Path.join(@elixir_sdk, "mix.exs")) do
      script = Path.expand("../support/sdk/sentry_elixir_trace.exs", __DIR__)

      {out, status} =
        System.cmd("elixir", [script],
          env: [
            {"SENTRY_DSN", ctx.dsn},
            {"SENTRY_ELIXIR_PATH", @elixir_sdk},
            {"MIX_ENV", "prod"}
          ],
          stderr_to_stdout: true
        )

      assert status == 0, out
      assert out =~ "done", out

      Vigil.Ingest.Drain.drain(ctx.project.id)

      assert [group] = Performance.list_groups(ctx.project.id), out
      assert group.name =~ "/orders"
      assert group.stats.count == 1

      [segment] = Repo.all(from s in Span, where: s.is_segment)
      children = Repo.all(from s in Span, where: not s.is_segment)
      assert Enum.any?(children, &(&1.parent_span_id == segment.span_id)), inspect(children)

      trace = Performance.get_trace([ctx.project.id], segment.trace_id)
      assert length(trace.spans) >= 2
      assert [%IssueEvent{}] = trace.errors, "the error should carry the trace id\n#{out}"
    else
      IO.puts("skipping sentry-elixir tracing: no checkout at #{@elixir_sdk}")
    end
  end

  @tag :sdk
  test "sentry-python 3 span streaming: segments, children, and the error in the trace", ctx do
    if File.dir?(Path.join(@python_sdk, "sentry_sdk")) and System.find_executable("python3") do
      script = """
      import time
      import sentry_sdk
      sentry_sdk.init(dsn=#{inspect(ctx.dsn)}, release="py@1.0", environment="test",
                      traces_sample_rate=1.0)
      with sentry_sdk.start_span(name="/api/checkout",
                                 attributes={"sentry.op": "http.server",
                                             "http.request.method": "POST"}):
          with sentry_sdk.start_span(name="SELECT * FROM carts WHERE id = %s",
                                     attributes={"sentry.op": "db"}):
              time.sleep(0.01)
          try:
              1 / 0
          except ZeroDivisionError:
              sentry_sdk.capture_exception()
      sentry_sdk.flush(timeout=10)
      """

      {out, status} =
        System.cmd("python3", ["-c", script],
          env: [{"PYTHONPATH", @python_sdk}],
          stderr_to_stdout: true
        )

      assert status == 0, out
      Vigil.Ingest.Drain.drain(ctx.project.id)

      assert [%{name: "/api/checkout", op: "http.server", method: "POST"} = group] =
               Performance.list_groups(ctx.project.id),
             out

      assert group.stats.count == 1

      [segment] = Repo.all(from s in Span, where: s.is_segment)
      assert segment.environment == "test" and segment.release == "py@1.0"

      # (sentry-python also traces its own envelope POSTs, as http.client.)
      children = Repo.all(from s in Span, where: not s.is_segment)
      assert %{parent_span_id: parent} = Enum.find(children, &(&1.op == "db")), inspect(children)
      assert parent == segment.span_id

      trace = Performance.get_trace([ctx.project.id], segment.trace_id)
      assert [%IssueEvent{}] = trace.errors, out
    else
      IO.puts("skipping sentry-python tracing: no checkout at #{@python_sdk}")
    end
  end
end