1.8 KiB · text History 573fef1
defmodule VigilWeb.Api.V0.MonitorController do
  @moduledoc """
  `GET /api/0/organizations/{org}/monitors/`: the cron monitors of the
  projects the token can see, in Sentry's shape (sentry-cli's `monitors
  list` reads `id`, `slug`, `name` and `status`). One page: there is no
  Link header, which sentry-cli reads as the end.
  """
  use VigilWeb, :controller

  alias Vigil.{Monitors, Projects}
  alias Vigil.Monitors.Schedule
  alias VigilWeb.Api.Auth

  def index(conn, %{"org" => slug}) do
    with {:ok, conn} <- Auth.put_org(conn, slug),
         {:ok, conn} <- Auth.require_scope(conn, "project:read") do
      project_ids = conn.assigns.current_scope |> Projects.list_visible() |> Enum.map(& &1.id)
      json(conn, project_ids |> Monitors.list_for_projects() |> Enum.map(&monitor_json/1))
    else
      {:error, conn} -> conn
    end
  end

  defp monitor_json(m) do
    %{
      id: m.id,
      slug: m.slug,
      name: m.name,
      status: if(m.enabled, do: "active", else: "disabled"),
      isMuted: false,
      dateCreated: m.inserted_at,
      project: %{id: to_string(m.project.dsn_id), slug: m.project.slug, name: m.project.name},
      config: %{
        schedule_type: to_string(m.schedule_type),
        schedule:
          if(m.schedule_type == :crontab,
            do: m.schedule,
            else: [m.interval_value, m.interval_unit]
          ),
        checkin_margin: m.checkin_margin,
        max_runtime: m.max_runtime,
        timezone: m.timezone,
        failure_issue_threshold: m.failure_threshold,
        recovery_threshold: m.recovery_threshold
      },
      # Vigil's own: the monitor's health and when it's next due.
      health: to_string(m.health),
      schedule: Schedule.describe(m),
      nextCheckIn: m.next_expected_at,
      lastCheckIn: m.last_checkin_at
    }
  end
end