7.8 KiB · text History 1a4b866
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 --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` or `both` (default)
    * `--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] [--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: []

    items =
      for event <- errors ++ messages do
        payload = Jason.encode!(event)

        %Envelope.Item{
          type: "event",
          headers: %{"type" => "event", "event_id" => event["event_id"]},
          payload: payload
        }
      end

    %{headers: %{"event_id" => hd(errors ++ messages)["event_id"]}, items: items}
  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} event(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