1.5 KiB · text History 2977adf
defmodule VigilWeb.Api.V0.UptimeController do
  @moduledoc """
  `GET /api/0/organizations/{org}/uptime/` (`project:read` and up): the
  uptime monitors of the projects the token can see, read-only, for
  `vgl uptime list`. Vigil's own endpoint: Sentry has no uptime API, and
  GlitchTip's `/monitors/` path is the cron monitors' here. The heartbeat
  token, a secret, is left out.
  """
  use VigilWeb, :controller

  alias Vigil.Uptime
  alias VigilWeb.Api.Auth
  alias VigilWeb.Api.V0.ReleaseController

  def index(conn, %{"org" => org}) do
    with {:ok, conn} <- Auth.put_org(conn, org),
         {:ok, conn} <-
           Auth.require_any_scope(conn, ~w(project:read project:write project:admin)) do
      monitors = Uptime.list_monitors(conn.assigns.current_scope)
      json(conn, Enum.map(monitors, &monitor_json/1))
    end
    |> ReleaseController.done()
  end

  defp monitor_json(m) do
    %{
      id: m.id,
      name: m.name,
      type: to_string(m.type),
      target: Uptime.target(m),
      enabled: m.enabled,
      status: status(m),
      reason: m.reason,
      interval: m.interval_seconds,
      responseMs: m.response_ms,
      lastCheck: m.last_check_at,
      lastChange: m.last_change_at,
      sslExpires: m.ssl_expires_at,
      project: %{id: to_string(m.project.dsn_id), slug: m.project.slug, name: m.project.name}
    }
  end

  defp status(%{enabled: false}), do: "paused"
  defp status(%{is_up: nil}), do: "pending"
  defp status(%{is_up: true}), do: "up"
  defp status(%{is_up: false}), do: "down"
end