3.3 KiB · text History 3208487
defmodule VigilWeb.HealthPlug do
  @moduledoc """
  Operational endpoints, answered in the Endpoint ahead of sessions and
  parsers:

    * `GET /_health/`: liveness. 200 `ok` while the VM serves requests;
      touches nothing else, so a slow database doesn't get the pod killed.
    * `GET /api/0/internal/health/`: readiness, in Sentry's shape
      (`{"problems": [...], "healthy": {...}}`): the database answers,
      Oban is running, and the ingest buffer isn't badly backed up. 503
      with the problems otherwise.
    * `GET /metrics`: Prometheus text (`VigilWeb.Telemetry.prometheus_metrics/0`).
      Served only when configured: with `METRICS_TOKEN` set it needs
      `Authorization: Bearer <token>`; with `METRICS_PUBLIC=true` it is
      open (for a scrape over a private network); otherwise 404.
  """
  @behaviour Plug

  import Plug.Conn

  @backlog_warn 50_000

  @impl Plug
  def init(opts), do: opts

  @impl Plug
  def call(%{method: "GET", path_info: ["_health"]} = conn, _opts) do
    conn |> put_resp_content_type("text/plain") |> send_resp(200, "ok") |> halt()
  end

  def call(%{method: "GET", path_info: ["api", "0", "internal", "health"]} = conn, _opts) do
    checks = %{
      "database" => check(&database/0),
      "oban" => check(&oban/0),
      "ingest_backlog" => check(&backlog/0)
    }

    problems =
      for {name, {:error, why}} <- checks, do: %{id: name, message: why, severity: "critical"}

    healthy = Map.new(checks, fn {name, result} -> {name, result == :ok} end)

    conn
    |> put_resp_content_type("application/json")
    |> send_resp(
      if(problems == [], do: 200, else: 503),
      Jason.encode!(%{problems: problems, healthy: healthy})
    )
    |> halt()
  end

  def call(%{method: "GET", path_info: ["metrics"]} = conn, _opts) do
    case metrics_access(conn) do
      :ok ->
        conn
        |> put_resp_content_type("text/plain; version=0.0.4")
        |> send_resp(200, TelemetryMetricsPrometheus.Core.scrape(:vigil_prometheus))
        |> halt()

      :unauthorized ->
        conn |> send_resp(401, "unauthorized") |> halt()

      :off ->
        conn |> send_resp(404, "not found") |> halt()
    end
  end

  def call(conn, _opts), do: conn

  defp check(fun) do
    fun.()
  rescue
    e -> {:error, Exception.message(e)}
  end

  defp database do
    Vigil.Repo.query!("SELECT 1", [], timeout: 2_000)
    :ok
  end

  defp oban do
    case Oban.Registry.whereis(Oban) do
      pid when is_pid(pid) -> :ok
      _ -> {:error, "Oban isn't running"}
    end
  end

  defp backlog do
    import Ecto.Query

    pending =
      Vigil.Repo.aggregate(
        from(i in Vigil.Ingest.BufferedItem, where: i.state == :pending),
        :count,
        timeout: 2_000
      )

    if pending < @backlog_warn,
      do: :ok,
      else: {:error, "#{pending} ingest items waiting"}
  end

  defp metrics_access(conn) do
    token = Application.get_env(:vigil, :metrics_token)

    cond do
      is_binary(token) and token != "" ->
        case get_req_header(conn, "authorization") do
          ["Bearer " <> given] ->
            if Plug.Crypto.secure_compare(String.trim(given), token), do: :ok, else: :unauthorized

          _ ->
            :unauthorized
        end

      Application.get_env(:vigil, :metrics_public, false) ->
        :ok

      true ->
        :off
    end
  end
end