10.7 KiB · text History ea450b1
defmodule Mix.Tasks.Vigil.Test do
  @shortdoc "Send a test error and message to a project"
  @moduledoc """
  Sends test events to a project, to see it receive them:

      mix vigil.test ORG PROJECT
      mix vigil.test ORG PROJECT --kind error --count 5
      mix vigil.test ORG PROJECT --kind transaction --count 50
      mix vigil.test ORG PROJECT --unique
      mix vigil.test ORG PROJECT --http
      mix vigil.test ORG PROJECT --http https://vigil.example.com

  `ORG` and `PROJECT` are slugs. By default an error (`Vigil.TestError`,
  with a stack trace) and a message are sent, through the same pipeline
  SDKs' envelopes take (`Vigil.Ingest.accept/3`), and processed right away,
  so the issues are there when the task ends. Repeated runs land in the
  same issues (their counts go up) unless `--unique` gives each run its own.

    * `--kind`    `error`, `message`, `both` (default), or `transaction`:
                  traced requests to three endpoints, each with database
                  spans and varied durations (a few fail), as sentry-elixir
                  sends them, for the performance pages
    * `--count`   how many of each (default 1)
    * `--unique`  a fingerprint per run, so each run makes new issues
    * `--http`    POST the envelope to a running server instead, with the
                  project's DSN, through the whole ingest edge (default URL:
                  the endpoint's configured one); the server processes it
                  in the background
  """

  use Mix.Task

  import Ecto.Query

  alias Vigil.Ingest.{Drain, Envelope, Keys}
  alias Vigil.{Organizations, Projects, Repo}
  alias Vigil.Projects.Project

  @requirements ["app.start"]

  @impl Mix.Task
  def run(args) do
    {opts, rest, _} =
      OptionParser.parse(args,
        strict: [kind: :string, count: :integer, unique: :boolean, http: :boolean, url: :string],
        aliases: [k: :kind, n: :count]
      )

    {http?, url, rest} = http_option(opts, rest)

    with [org_slug, project_slug] <- rest,
         {:ok, org, project, key} <- find(org_slug, project_slug) do
      envelope = envelope(opts)

      if http?,
        do: send_http(envelope, project, key, url),
        else: send_local(envelope, org, project, key)
    else
      {:error, message} ->
        Mix.raise(message)

      _ ->
        Mix.raise(
          "Usage: mix vigil.test ORG PROJECT [--kind error|message|both|transaction] [--count N] [--unique] [--http [URL]]"
        )
    end
  end

  # `--http` alone, or `--http URL` (OptionParser reads booleans strictly,
  # so a URL after it lands in the positional arguments).
  defp http_option(opts, rest) do
    case {opts[:http], rest} do
      {true, [a, b, url]} -> {true, url, [a, b]}
      {true, _} -> {true, opts[:url] || VigilWeb.base_url(), rest}
      _ -> {false, nil, rest}
    end
  end

  defp find(org_slug, project_slug) do
    with %{} = org <-
           Organizations.get_organization_by_slug(org_slug) ||
             {:error, "No organization #{org_slug}"},
         %Project{} = project <-
           Repo.one(
             from p in Project,
               where:
                 p.organization_id == ^org.id and p.slug == ^project_slug and is_nil(p.deleted_at)
           ) || {:error, "No project #{project_slug} in #{org_slug}"},
         %{} = key <-
           Enum.find(Projects.list_keys(project), & &1.active) ||
             {:error, "#{org_slug}/#{project_slug} has no active key"} do
      {:ok, org, project, key}
    end
  end

  ## The events

  defp envelope(opts) do
    count = max(opts[:count] || 1, 1)
    kind = opts[:kind] || "both"
    run = if opts[:unique], do: System.unique_integer([:positive])

    errors =
      if kind in ["error", "both"], do: for(i <- 1..count, do: error_event(i, run)), else: []

    messages =
      if kind in ["message", "both"], do: for(i <- 1..count, do: message_event(i, run)), else: []

    transactions =
      if kind == "transaction", do: for(i <- 1..count, do: transaction_event(i)), else: []

    items =
      for event <- errors ++ messages ++ transactions do
        type = event["type"] || "event"

        %Envelope.Item{
          type: type,
          headers: %{"type" => type, "event_id" => event["event_id"]},
          payload: Jason.encode!(event)
        }
      end

    case items do
      [] -> Mix.raise("Unknown --kind #{kind}")
      [first | _] -> %{headers: %{"event_id" => first.headers["event_id"]}, items: items}
    end
  end

  @routes [
    {"GET", "/users/:id", "SELECT * FROM users WHERE id = $1", 40},
    {"POST", "/orders", "INSERT INTO orders (user_id, total) VALUES ($1, $2)", 180},
    {"GET", "/reports/:id", "SELECT * FROM report_rows WHERE report_id = $1", 900}
  ]

  # A request as sentry-elixir's OpenTelemetry integration sends it: the
  # transaction is the server span, with a controller span and db spans.
  defp transaction_event(i) do
    {method, route, sql, typical} = Enum.at(@routes, rem(i - 1, length(@routes)))
    total = round(typical * (0.5 + :rand.uniform() * if(rem(i, 17) == 0, do: 6, else: 1.2)))
    start = DateTime.add(DateTime.utc_now(), -total - :rand.uniform(5_000), :millisecond)

    at = fn ms ->
      start |> DateTime.add(round(ms * 1000), :microsecond) |> DateTime.to_iso8601()
    end

    hex = fn n -> :crypto.strong_rand_bytes(n) |> Base.encode16(case: :lower) end
    trace_id = hex.(16)
    root = hex.(8)
    controller = hex.(8)
    queries = 1 + rem(i, 3)
    query_ms = total * 0.6 / queries

    db_spans =
      for q <- 0..(queries - 1) do
        from = total * 0.2 + q * query_ms

        %{
          "span_id" => hex.(8),
          "parent_span_id" => controller,
          "trace_id" => trace_id,
          "op" => "db",
          "description" => sql,
          "start_timestamp" => at.(from),
          "timestamp" => at.(from + query_ms * 0.9),
          "data" => %{"db.system" => "postgresql"}
        }
      end

    %{
      "type" => "transaction",
      "event_id" => hex.(16),
      "transaction" => "#{method} #{route}",
      "start_timestamp" => at.(0),
      "timestamp" => at.(total),
      "platform" => "elixir",
      "environment" => "test",
      "release" => "vigil-test@1.0.0",
      "request" => %{"method" => method, "url" => "http://localhost" <> route},
      "contexts" => %{
        "trace" => %{
          "trace_id" => trace_id,
          "span_id" => root,
          "op" => "http.server",
          "status" => if(rem(i, 11) == 0, do: "internal_error", else: "ok")
        }
      },
      "spans" => [
        %{
          "span_id" => controller,
          "parent_span_id" => root,
          "trace_id" => trace_id,
          "op" => "phoenix.controller",
          "description" => "#{route} controller",
          "start_timestamp" => at.(total * 0.1),
          "timestamp" => at.(total * 0.95)
        }
        | db_spans
      ]
    }
  end

  defp base_event(level, run) do
    %{
      "event_id" => Vigil.Schema.uuid7() |> String.replace("-", ""),
      "timestamp" => DateTime.utc_now() |> DateTime.to_iso8601(),
      "platform" => "elixir",
      "level" => level,
      "environment" => "test",
      "release" => "vigil-test@1.0.0",
      "server_name" => node() |> to_string(),
      "logger" => "mix vigil.test",
      "sdk" => %{"name" => "vigil.test", "version" => to_string(Application.spec(:vigil, :vsn))},
      "tags" => %{"source" => "mix vigil.test"}
    }
    |> then(&if(run, do: Map.put(&1, "fingerprint", ["{{ default }}", "run-#{run}"]), else: &1))
  end

  defp error_event(i, run) do
    base_event("error", run)
    |> Map.merge(%{
      "exception" => %{
        "values" => [
          %{
            "type" => "Vigil.TestError",
            "value" => "This is a test error from mix vigil.test",
            "module" => "Vigil",
            "mechanism" => %{"type" => "generic", "handled" => true},
            "stacktrace" => %{
              "frames" => [
                frame("Mix.Task", "run/2", "lib/mix/task.ex", 501, false),
                frame("Mix.Tasks.Vigil.Test", "run/1", "lib/mix/tasks/vigil.test.ex", 52, true),
                frame(
                  "Mix.Tasks.Vigil.Test",
                  "error_event/2",
                  "lib/mix/tasks/vigil.test.ex",
                  120,
                  true
                )
              ]
            }
          }
        ]
      },
      "extra" => %{"sequence" => i}
    })
  end

  defp message_event(i, run) do
    base_event("info", run)
    |> Map.merge(%{
      "message" => %{"formatted" => "This is a test message from mix vigil.test"},
      "extra" => %{"sequence" => i}
    })
  end

  defp frame(module, function, file, line, in_app) do
    %{
      "module" => module,
      "function" => "#{module}.#{function}",
      "filename" => file,
      "lineno" => line,
      "in_app" => in_app
    }
  end

  ## Sending

  defp send_local(envelope, org, project, key) do
    case Keys.lookup(project.dsn_id, key.public_key) do
      {:ok, target} ->
        kept =
          Vigil.Ingest.accept(target, envelope, %{
            client_ip: "127.0.0.1",
            user_agent: "mix vigil.test"
          })

        drain_all(project.id)

        Mix.shell().info(
          "Sent #{kept} item(s) to #{org.slug}/#{project.slug}, and processed them."
        )

        Mix.shell().info(VigilWeb.base_url() <> "/orgs/#{org.slug}/projects/#{project.slug}")

      {:error, :not_accepting} ->
        Mix.raise("#{org.slug} isn't accepting events (organization settings)")

      {:error, _} ->
        Mix.raise("The project's key was refused")
    end
  end

  # Until nothing pending is left (a full batch leaves more).
  defp drain_all(project_id) do
    if Drain.drain(project_id) >= 100, do: drain_all(project_id)
  end

  defp send_http(envelope, project, key, url) do
    body =
      Enum.join(
        [Jason.encode!(envelope.headers)] ++
          Enum.flat_map(envelope.items, fn i ->
            [Jason.encode!(Map.put(i.headers, "length", byte_size(i.payload))), i.payload]
          end),
        "\n"
      ) <> "\n"

    hex = String.replace(key.public_key, "-", "")
    endpoint = String.trim_trailing(url, "/") <> "/api/#{project.dsn_id}/envelope/"

    case Req.post(endpoint,
           body: body,
           headers: [
             {"content-type", "application/x-sentry-envelope"},
             {"x-sentry-auth",
              "Sentry sentry_key=#{hex}, sentry_version=7, sentry_client=vigil.test/1"}
           ],
           retry: false
         ) do
      {:ok, %{status: 200, body: body}} ->
        Mix.shell().info("#{endpoint} accepted it: #{inspect(body)}")

      {:ok, %{status: status, body: body}} ->
        Mix.raise("#{endpoint} answered #{status}: #{inspect(body)}")

      {:error, error} ->
        Mix.raise(
          "Couldn't reach #{endpoint}: #{Exception.message(error)} (is the server running?)"
        )
    end
  end
end