Cron monitors UI: list with status timelines, detail, create/edit, toggle, delete

b431af3 · gmorell · 2026-12-02 03:01

15 files +1425 -0

Files changed

added lib/vigil_web/components/monitor_components.ex
+328 −0
@@ -0,0 +1,328 @@
1 +defmodule VigilWeb.MonitorComponents do
2 + @moduledoc """
3 + Pieces the cron monitor pages share: a monitor's health badge, its status
4 + timeline (one tick per check-in, colored and sized by status, with a
5 + hover tooltip and a summary for screen readers), relative times in both
6 + directions, spans of time, and the create/edit form's fields.
7 + """
8 + use Phoenix.Component
9 +
10 + import VigilWeb.CoreComponents, only: [icon: 1, input: 1]
11 +
12 + alias Vigil.Monitors.{Monitor, Schedule}
13 +
14 + @statuses [:ok, :error, :missed, :timeout, :in_progress]
15 +
16 + @doc "The check-in statuses, in legend order."
17 + def statuses, do: @statuses
18 +
19 + @doc "A check-in status for people."
20 + def status_label(:ok), do: "OK"
21 + def status_label(:error), do: "Error"
22 + def status_label(:missed), do: "Missed"
23 + def status_label(:timeout), do: "Timed out"
24 + def status_label(:in_progress), do: "In progress"
25 +
26 + def status_label(s) when is_binary(s),
27 + do: Enum.find_value(@statuses, s, &(to_string(&1) == s && status_label(&1)))
28 +
29 + def status_label(other), do: to_string(other)
30 +
31 + @doc "The tick color of a check-in status."
32 + def status_color(:ok), do: "bg-success"
33 + def status_color(:error), do: "bg-error"
34 + def status_color(:missed), do: "bg-warning"
35 + def status_color(:timeout), do: "bg-orange-500"
36 + def status_color(:in_progress), do: "bg-info"
37 + def status_color(_), do: "bg-base-300"
38 +
39 + @doc "A small badge for a check-in status: dot plus word."
40 + attr :status, :atom, required: true
41 +
42 + def status_badge(assigns) do
43 + ~H"""
44 + <span class="inline-flex items-center gap-1.5 text-sm">
45 + <span class={["size-2 shrink-0 rounded-full", status_color(@status)]} aria-hidden="true" />
46 + <span class={[@status in [:error, :missed, :timeout] && "font-medium"]}>
47 + {status_label(@status)}
48 + </span>
49 + </span>
50 + """
51 + end
52 +
53 + @doc "A monitor's health (and paused state), as an icon and a word, never color alone."
54 + attr :monitor, Monitor, required: true
55 + attr :id, :string, default: nil
56 +
57 + def health_badge(assigns) do
58 + ~H"""
59 + <span id={@id} class="inline-flex flex-wrap items-center gap-1">
60 + <%= case @monitor.health do %>
61 + <% :error -> %>
62 + <span class="badge badge-error badge-sm gap-1 monitor-health-error">
63 + <.icon name="hero-exclamation-triangle-micro" class="size-3.5" /> Failing
64 + </span>
65 + <% :ok -> %>
66 + <span class="badge badge-success badge-soft badge-sm gap-1 monitor-health-ok">
67 + <.icon name="hero-check-circle-micro" class="size-3.5" /> OK
68 + </span>
69 + <% _ -> %>
70 + <span class="badge badge-ghost badge-sm gap-1 monitor-health-new">
71 + <.icon name="hero-sparkles-micro" class="size-3.5" /> New
72 + </span>
73 + <% end %>
74 + <span
75 + :if={!@monitor.enabled}
76 + class="badge badge-outline badge-sm gap-1 monitor-disabled"
77 + >
78 + <.icon name="hero-pause-micro" class="size-3.5" /> Disabled
79 + </span>
80 + </span>
81 + """
82 + end
83 +
84 + @doc """
85 + A monitor's latest check-ins (oldest first) as a row of ticks, left-padded
86 + to `slots` so rows line up. Failures stand full height, successes a little
87 + shorter, runs in progress shorter still: the shape tells them apart as
88 + well as the color. Each tick has a tooltip (status, time, duration); the
89 + row has a summary as its accessible label.
90 + """
91 + attr :id, :string, required: true
92 + attr :check_ins, :list, required: true
93 + attr :slots, :integer, default: 30
94 + attr :class, :string, default: "h-6"
95 +
96 + def timeline(assigns) do
97 + check_ins = Enum.take(assigns.check_ins, -assigns.slots)
98 +
99 + assigns =
100 + assign(assigns,
101 + check_ins: check_ins,
102 + pad: max(assigns.slots - length(check_ins), 0),
103 + summary: summary(check_ins)
104 + )
105 +
106 + ~H"""
107 + <div
108 + id={@id}
109 + class={["flex items-end gap-[2px]", @class]}
110 + role="img"
111 + aria-label={@summary}
112 + >
113 + <span
114 + :for={_ <- List.duplicate(nil, @pad)}
115 + class="h-1/3 flex-1 rounded-[2px] bg-base-300/50"
116 + aria-hidden="true"
117 + />
118 + <span
119 + :for={c <- @check_ins}
120 + id={"#{@id}-tick-#{c.id}"}
121 + data-status={c.status}
122 + class="monitor-tick group relative flex h-full flex-1 items-end"
123 + >
124 + <span class={[
125 + "w-full rounded-[2px] transition-opacity group-hover:opacity-75",
126 + status_color(c.status),
127 + tick_height(c.status),
128 + c.status == :in_progress && "animate-pulse"
129 + ]} />
130 + <span class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden -translate-x-1/2 whitespace-nowrap rounded-box border border-base-300 bg-base-100 px-2 py-1 text-xs shadow-md group-hover:block">
131 + <span class="font-semibold">{status_label(c.status)}</span>
132 + · {format_time(check_in_time(c))}
133 + <span :if={c.duration_ms}>· {VigilWeb.PerformanceComponents.duration(c.duration_ms)}</span>
134 + </span>
135 + </span>
136 + </div>
137 + """
138 + end
139 +
140 + defp tick_height(status) when status in [:error, :missed, :timeout], do: "h-full"
141 + defp tick_height(:in_progress), do: "h-1/2"
142 + defp tick_height(_), do: "h-3/4"
143 +
144 + defp summary([]), do: "No check-ins yet"
145 +
146 + defp summary(check_ins) do
147 + counts =
148 + check_ins
149 + |> Enum.frequencies_by(& &1.status)
150 + |> then(fn f -> for s <- @statuses, n = f[s], do: "#{n} #{String.downcase(status_label(s))}" end)
151 + |> Enum.join(", ")
152 +
153 + "Last #{length(check_ins)} check-ins: #{counts}"
154 + end
155 +
156 + @doc "A legend for the timeline's colors."
157 + def legend(assigns) do
158 + assigns = assign(assigns, :statuses, @statuses)
159 +
160 + ~H"""
161 + <ul class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-base-content/60" aria-hidden="true">
162 + <li :for={s <- @statuses} class="flex items-center gap-1.5">
163 + <span class={["size-2.5 rounded-[2px]", status_color(s)]} />{status_label(s)}
164 + </li>
165 + </ul>
166 + """
167 + end
168 +
169 + @doc "When a check-in happened: when it started, finished or was due."
170 + def check_in_time(c), do: c.started_at || c.finished_at || c.expected_at
171 +
172 + @doc "A time in full, UTC; nil is a dash."
173 + def format_time(nil), do: "—"
174 + def format_time(dt), do: Calendar.strftime(dt, "%Y-%m-%d %H:%M:%S UTC")
175 +
176 + @doc "A time briefly: `Dec 1 14:05`."
177 + def short_time(nil), do: "—"
178 + def short_time(dt), do: Calendar.strftime(dt, "%b %-d %H:%M")
179 +
180 + @doc "A `<time>` relative to now in either direction (`5m ago`, `in 2h`), in full on hover."
181 + attr :at, :any, required: true
182 + attr :id, :string, default: nil
183 + attr :class, :any, default: nil
184 + attr :empty, :string, default: "—"
185 +
186 + def rel_time(assigns) do
187 + ~H"""
188 + <time
189 + id={@id}
190 + datetime={@at && DateTime.to_iso8601(@at)}
191 + title={@at && format_time(@at)}
192 + class={@class}
193 + >
194 + {if @at, do: relative(@at), else: @empty}
195 + </time>
196 + """
197 + end
198 +
199 + @doc "How far `at` is from `now`: `just now`, `12m ago`, `in 3h`, `in 2d`."
200 + def relative(at, now \\ DateTime.utc_now()) do
201 + diff = DateTime.diff(at, now)
202 +
203 + cond do
204 + abs(diff) < 45 -> if diff >= 0, do: "in under a minute", else: "just now"
205 + diff > 0 -> "in #{span(diff)}"
206 + true -> "#{span(-diff)} ago"
207 + end
208 + end
209 +
210 + @doc "A span of seconds, briefly: `45s`, `12m`, `2h 5m`, `3d 4h`."
211 + def span(s) when s < 60, do: "#{s}s"
212 + def span(s) when s < 3600, do: "#{div(s, 60)}m"
213 +
214 + def span(s) when s < 86_400 do
215 + m = rem(div(s, 60), 60)
216 + if m == 0, do: "#{div(s, 3600)}h", else: "#{div(s, 3600)}h #{m}m"
217 + end
218 +
219 + def span(s) do
220 + h = rem(div(s, 3600), 24)
221 + if h == 0, do: "#{div(s, 86_400)}d", else: "#{div(s, 86_400)}d #{h}h"
222 + end
223 +
224 + @doc "Minutes for people: `1 minute`, `30 minutes`, `2h`."
225 + def minutes(1), do: "1 minute"
226 + def minutes(m) when is_integer(m) and m < 120, do: "#{m} minutes"
227 + def minutes(m) when is_integer(m), do: span(m * 60)
228 + def minutes(_), do: "—"
229 +
230 + @doc "The create/edit form's fields (`slug?`: only when creating)."
231 + attr :form, Phoenix.HTML.Form, required: true
232 + attr :slug?, :boolean, default: false
233 +
234 + def monitor_fields(assigns) do
235 + assigns =
236 + assign(assigns,
237 + type: to_string(assigns.form[:schedule_type].value),
238 + units: Enum.map(Monitor.units(), &{"#{&1}s", &1}),
239 + tz_database?: Schedule.tz_database?()
240 + )
241 +
242 + ~H"""
243 + <div class="grid gap-x-3 sm:grid-cols-2">
244 + <.input
245 + :if={@slug?}
246 + field={@form[:slug]}
247 + label="Slug"
248 + placeholder="nightly-backup"
249 + autocomplete="off"
250 + required
251 + />
252 + <.input field={@form[:name]} label="Name" placeholder="Nightly backup (defaults to the slug)" />
253 + </div>
254 + <p :if={@slug?} class="-mt-1 mb-2 text-xs text-base-content/60">
255 + SDKs check in by slug: use the same one in <code class="font-mono">monitor_slug</code>.
256 + </p>
257 +
258 + <div class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
259 + <.input
260 + field={@form[:schedule_type]}
261 + type="select"
262 + label="Schedule"
263 + options={[{"Crontab", "crontab"}, {"Interval", "interval"}]}
264 + />
265 + <%= if @type == "interval" do %>
266 + <div class="grid grid-cols-2 gap-x-3">
267 + <.input
268 + field={@form[:interval_value]}
269 + type="number"
270 + label="Every"
271 + min="1"
272 + id="monitor-interval-value"
273 + />
274 + <.input
275 + field={@form[:interval_unit]}
276 + type="select"
277 + label="Unit"
278 + options={@units}
279 + prompt="Pick a unit"
280 + id="monitor-interval-unit"
281 + />
282 + </div>
283 + <% else %>
284 + <.input
285 + field={@form[:schedule]}
286 + label="Crontab expression"
287 + placeholder="0 3 * * *"
288 + class="input w-full font-mono"
289 + id="monitor-crontab"
290 + />
291 + <% end %>
292 + </div>
293 +
294 + <.input field={@form[:timezone]} label="Time zone" placeholder="Etc/UTC" id="monitor-timezone" />
295 + <p :if={!@tz_database?} id="monitor-tz-hint" class="-mt-1 mb-2 text-xs text-base-content/60">
296 + <.icon name="hero-information-circle-micro" class="size-3.5 align-text-bottom" />
297 + This server has no time zone database: schedules are evaluated in UTC.
298 + </p>
299 +
300 + <div class="grid gap-x-3 sm:grid-cols-2">
301 + <.input
302 + field={@form[:checkin_margin]}
303 + type="number"
304 + label="Check-in margin (minutes late before missed)"
305 + min="1"
306 + />
307 + <.input
308 + field={@form[:max_runtime]}
309 + type="number"
310 + label="Max runtime (minutes before timed out)"
311 + min="1"
312 + />
313 + <.input
314 + field={@form[:failure_threshold]}
315 + type="number"
316 + label="Failures in a row to open an incident"
317 + min="1"
318 + />
319 + <.input
320 + field={@form[:recovery_threshold]}
321 + type="number"
322 + label="Successes in a row to resolve it"
323 + min="1"
324 + />
325 + </div>
326 + """
327 + end
328 +end
modified lib/vigil_web/live/issue_live/index.ex
+9 −0
@@ -242,6 +242,15 @@ defmodule VigilWeb.IssueLive.Index do
242 242 >
243 243 <.icon name="hero-bolt-micro" class="size-4" /> Performance
244 244 </.link>
245 + <.link
246 + navigate={
247 + ~p"/orgs/#{@current_scope.organization.slug}/projects/#{@project.slug}/monitors"
248 + }
249 + class="btn btn-ghost btn-sm"
250 + id="project-monitors"
251 + >
252 + <.icon name="hero-clock-micro" class="size-4" /> Crons
253 + </.link>
245 254 <.link
246 255 :if={Scope.can?(@current_scope, "project:write")}
247 256 navigate={
added lib/vigil_web/live/monitor_live/index.ex
+316 −0
@@ -0,0 +1,316 @@
1 +defmodule VigilWeb.MonitorLive.Index do
2 + @moduledoc """
3 + A project's cron monitors (`Vigil.Monitors`): each one's schedule,
4 + health, a timeline of its last 30 check-ins, when it last checked in and
5 + when it's next due. Check-ins refresh the list live (PubSub), at most
6 + once a second, and relative times refresh every minute. A project with
7 + none explains how check-ins arrive from the SDKs and sentry-cli. Someone
8 + with `project:write` can make a monitor here.
9 + """
10 + use VigilWeb, :live_view
11 +
12 + import VigilWeb.MonitorComponents
13 +
14 + alias Vigil.Accounts.Scope
15 + alias Vigil.Monitors
16 + alias Vigil.Monitors.{Monitor, Schedule}
17 +
18 + @refresh_ms 1000
19 + @clock_ms 60_000
20 + @slots 30
21 +
22 + @impl true
23 + def mount(_params, _session, socket) do
24 + %{current_scope: scope, project: project} = socket.assigns
25 +
26 + if connected?(socket) do
27 + Phoenix.PubSub.subscribe(Vigil.PubSub, "project:#{project.id}:monitors")
28 + :timer.send_interval(@clock_ms, :clock)
29 + end
30 +
31 + {:ok,
32 + socket
33 + |> assign(:page_title, "#{project.name} · Cron monitors")
34 + |> assign(:can_write?, Scope.can?(scope, "project:write"))
35 + |> assign(:creating?, false)
36 + |> assign(:slots, @slots)
37 + |> assign(:form, new_form())
38 + |> assign(:refresh_scheduled?, false)
39 + |> stream_configure(:monitors, dom_id: &"monitor-#{&1.id}")
40 + |> load()}
41 + end
42 +
43 + defp load(socket) do
44 + monitors = Monitors.list_monitors(socket.assigns.project)
45 + recent = Monitors.recent_check_ins(Enum.map(monitors, & &1.id), @slots)
46 + rows = Enum.map(monitors, &%{id: &1.id, monitor: &1, check_ins: Map.get(recent, &1.id, [])})
47 +
48 + socket
49 + |> assign(:count, length(monitors))
50 + |> assign(:failing, Enum.count(monitors, &(&1.health == :error)))
51 + |> stream(:monitors, rows, reset: true)
52 + end
53 +
54 + defp new_form(params \\ %{}, action \\ nil) do
55 + %Monitor{schedule_type: :crontab}
56 + |> Monitors.change_monitor(params)
57 + |> to_form(action: action)
58 + end
59 +
60 + @impl true
61 + def handle_event("new", _params, socket),
62 + do: {:noreply, assign(socket, creating?: true, form: new_form())}
63 +
64 + def handle_event("cancel", _params, socket), do: {:noreply, assign(socket, :creating?, false)}
65 +
66 + def handle_event("validate", %{"monitor" => params}, socket),
67 + do: {:noreply, assign(socket, :form, new_form(params, :validate))}
68 +
69 + def handle_event("create", %{"monitor" => params}, socket) do
70 + %{current_scope: scope, project: project} = socket.assigns
71 +
72 + case Monitors.create_monitor(scope, project, params) do
73 + {:ok, monitor} ->
74 + {:noreply,
75 + socket
76 + |> put_flash(:info, "Monitor created.")
77 + |> push_navigate(to: monitor_path(scope, project, monitor))}
78 +
79 + {:error, %Ecto.Changeset{} = cs} ->
80 + {:noreply, assign(socket, :form, to_form(cs, action: :insert))}
81 +
82 + {:error, _} ->
83 + {:noreply, put_flash(socket, :error, "You can't change this project's monitors.")}
84 + end
85 + end
86 +
87 + @impl true
88 + def handle_info({:monitor_updated, _id}, socket), do: {:noreply, schedule_refresh(socket)}
89 +
90 + def handle_info(:refresh, socket),
91 + do: {:noreply, socket |> assign(:refresh_scheduled?, false) |> load()}
92 +
93 + def handle_info(:clock, socket), do: {:noreply, schedule_refresh(socket)}
94 +
95 + defp schedule_refresh(%{assigns: %{refresh_scheduled?: true}} = socket), do: socket
96 +
97 + defp schedule_refresh(socket) do
98 + Process.send_after(self(), :refresh, @refresh_ms)
99 + assign(socket, :refresh_scheduled?, true)
100 + end
101 +
102 + defp monitor_path(scope, project, monitor),
103 + do: ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}/monitors/#{monitor.slug}"
104 +
105 + @impl true
106 + def render(assigns) do
107 + ~H"""
108 + <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
109 + <div class="mx-auto max-w-6xl space-y-6">
110 + <.header>
111 + {@project.name} cron monitors
112 + <:subtitle>
113 + Scheduled jobs checking in: whether each ran on time, and how it went.
114 + </:subtitle>
115 + <:actions>
116 + <div class="flex flex-wrap items-center gap-1">
117 + <.link
118 + navigate={~p"/orgs/#{@current_scope.organization.slug}/projects/#{@project.slug}"}
119 + class="btn btn-ghost btn-sm"
120 + id="monitors-back"
121 + >
122 + <.icon name="hero-arrow-left-micro" class="size-4" /> Issues
123 + </.link>
124 + <button
125 + :if={@can_write? and not @creating?}
126 + type="button"
127 + id="new-monitor"
128 + class="btn btn-primary btn-sm"
129 + phx-click="new"
130 + >
131 + <.icon name="hero-plus-micro" class="size-4" /> New monitor
132 + </button>
133 + </div>
134 + </:actions>
135 + </.header>
136 +
137 + <.form
138 + :if={@can_write? and @creating?}
139 + for={@form}
140 + id="monitor-form"
141 + phx-change="validate"
142 + phx-submit="create"
143 + class="space-y-1 rounded-box border border-base-300 bg-base-200/60 p-4"
144 + >
145 + <h2 class="mb-2 text-sm font-semibold">New monitor</h2>
146 + <.monitor_fields form={@form} slug?={true} />
147 + <div class="flex gap-2 pt-1">
148 + <.button class="btn btn-primary btn-sm" phx-disable-with="Creating…" id="create-monitor">
149 + Create monitor
150 + </.button>
151 + <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel" id="cancel-monitor">
152 + Cancel
153 + </button>
154 + </div>
155 + </.form>
156 +
157 + <%= if @count > 0 do %>
158 + <div class="flex flex-wrap items-center justify-between gap-2">
159 + <p id="monitors-summary" class="text-sm text-base-content/70">
160 + {@count} {if @count == 1, do: "monitor", else: "monitors"}<span :if={@failing > 0}>
161 + ·
162 + <span class="font-semibold text-error">
163 + <.icon name="hero-exclamation-triangle-micro" class="size-4 align-text-bottom" />
164 + {@failing} failing
165 + </span></span>
166 + </p>
167 + <.legend />
168 + </div>
169 +
170 + <div class="rounded-box border border-base-300 bg-base-100">
171 + <div class="hidden rounded-t-box grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_6.5rem_6.5rem] gap-4 border-b border-base-300 bg-base-200/50 px-4 py-2 text-xs font-medium uppercase tracking-wide text-base-content/60 md:grid">
172 + <span>Monitor</span>
173 + <span>Last {@slots} check-ins</span>
174 + <span class="text-right">Last check-in</span>
175 + <span class="text-right">Next expected</span>
176 + </div>
177 + <ul id="monitors" phx-update="stream" class="divide-y divide-base-300">
178 + <li :for={{dom_id, row} <- @streams.monitors} id={dom_id}>
179 + <.link
180 + navigate={monitor_path(@current_scope, @project, row.monitor)}
181 + class={[
182 + "group grid grid-cols-2 gap-x-4 gap-y-2 px-4 py-3 transition hover:bg-base-200/60 md:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_6.5rem_6.5rem] md:items-center",
183 + !row.monitor.enabled && "opacity-70"
184 + ]}
185 + >
186 + <div class="col-span-2 min-w-0 md:col-span-1">
187 + <p class="flex min-w-0 flex-wrap items-center gap-2">
188 + <span class="truncate font-semibold group-hover:text-primary">
189 + {row.monitor.name}
190 + </span>
191 + <.health_badge monitor={row.monitor} id={"monitor-health-#{row.id}"} />
192 + </p>
193 + <p class="mt-0.5 flex min-w-0 flex-wrap items-center gap-x-2 text-xs text-base-content/60">
194 + <span class="font-mono">{row.monitor.slug}</span>
195 + <span aria-hidden="true">·</span>
196 + <span class="font-mono" id={"monitor-schedule-#{row.id}"}>
197 + {Schedule.describe(row.monitor)}
198 + </span>
199 + </p>
200 + </div>
201 + <div class="col-span-2 md:col-span-1">
202 + <.timeline
203 + id={"monitor-timeline-#{row.id}"}
204 + check_ins={row.check_ins}
205 + slots={@slots}
206 + />
207 + </div>
208 + <span class="text-sm tabular-nums md:text-right">
209 + <span class="block text-xs text-base-content/50 md:hidden">Last check-in</span>
210 + <.rel_time
211 + at={row.monitor.last_checkin_at}
212 + id={"monitor-last-#{row.id}"}
213 + empty="never"
214 + />
215 + </span>
216 + <span class="text-sm tabular-nums md:text-right">
217 + <span class="block text-xs text-base-content/50 md:hidden">Next expected</span>
218 + <%= if row.monitor.enabled do %>
219 + <.rel_time at={row.monitor.next_expected_at} id={"monitor-next-#{row.id}"} />
220 + <% else %>
221 + <span id={"monitor-next-#{row.id}"} class="text-base-content/50">paused</span>
222 + <% end %>
223 + </span>
224 + </.link>
225 + </li>
226 + </ul>
227 + </div>
228 + <% else %>
229 + <.setup_crons
230 + can_write?={@can_write?}
231 + alerts_path={
232 + ~p"/orgs/#{@current_scope.organization.slug}/projects/#{@project.slug}/alerts"
233 + }
234 + />
235 + <% end %>
236 + </div>
237 + </Layouts.app>
238 + """
239 + end
240 +
241 + attr :can_write?, :boolean, required: true
242 + attr :alerts_path, :string, required: true
243 +
244 + defp setup_crons(assigns) do
245 + ~H"""
246 + <section id="monitors-empty" class="rounded-box border border-dashed border-base-300 bg-base-100 p-8">
247 + <div class="mx-auto max-w-2xl space-y-5">
248 + <div class="text-center">
249 + <.icon name="hero-clock" class="mx-auto mb-2 block size-10 text-primary/60" />
250 + <h2 class="text-lg font-semibold">No cron monitors yet</h2>
251 + <p class="mt-1 text-sm text-base-content/70">
252 + Have your scheduled jobs check in when they start and finish. A check-in that
253 + carries its schedule makes its monitor here on the spot; then a run that's late,
254 + fails or runs too long shows up, and can alert you.
255 + <span :if={@can_write?}>You can also make one by hand with <em>New monitor</em>.</span>
256 + </p>
257 + </div>
258 +
259 + <div class="space-y-2">
260 + <h3 class="text-sm font-semibold">sentry-elixir</h3>
261 + <p class="text-sm text-base-content/70">
262 + Turn on the Oban or Quantum cron integration, or check in yourself with
263 + <code class="font-mono">Sentry.capture_check_in/1</code>:
264 + </p>
265 + <pre
266 + id="setup-crons-elixir"
267 + class="overflow-x-auto rounded-box bg-base-200 p-3 text-xs"
268 + phx-no-curly-interpolation
269 + ><code># config/config.exs
270 + config :sentry,
271 + integrations: [
272 + oban: [cron: [enabled: true]],
273 + quantum: [cron: [enabled: true]]
274 + ]
275 +
276 + # or by hand
277 + {:ok, id} = Sentry.capture_check_in(status: :in_progress, monitor_slug: "nightly-backup")
278 + # … the job …
279 + Sentry.capture_check_in(check_in_id: id, status: :ok, monitor_slug: "nightly-backup")</code></pre>
280 + </div>
281 +
282 + <div class="space-y-2">
283 + <h3 class="text-sm font-semibold">sentry-python</h3>
284 + <pre
285 + id="setup-crons-python"
286 + class="overflow-x-auto rounded-box bg-base-200 p-3 text-xs"
287 + phx-no-curly-interpolation
288 + ><code>from sentry_sdk.crons import monitor
289 +
290 + @monitor(monitor_slug="nightly-backup")
291 + def nightly_backup():
292 + ...
293 +
294 + # or: sentry_sdk.crons.capture_checkin(monitor_slug="nightly-backup", status="ok")</code></pre>
295 + </div>
296 +
297 + <div class="space-y-2">
298 + <h3 class="text-sm font-semibold">sentry-cli</h3>
299 + <pre
300 + id="setup-crons-cli"
301 + class="overflow-x-auto rounded-box bg-base-200 p-3 text-xs"
302 + phx-no-curly-interpolation
303 + ><code>sentry-cli monitors run nightly-backup -- ./backup.sh</code></pre>
304 + </div>
305 +
306 + <p class="text-xs text-base-content/60">
307 + <.icon name="hero-bell-micro" class="size-3.5 align-text-bottom" />
308 + To be told when a job fails or recovers, add an alert rule
309 + <em>“A cron monitor fails or recovers”</em> on the project's
310 + <.link navigate={@alerts_path} class="link link-hover" id="monitors-alerts-link">Alerts page</.link>.
311 + </p>
312 + </div>
313 + </section>
314 + """
315 + end
316 +end
added lib/vigil_web/live/monitor_live/show.ex
+474 −0
@@ -0,0 +1,474 @@
1 +defmodule VigilWeb.MonitorLive.Show do
2 + @moduledoc """
3 + One cron monitor: its settings, health and next expected run, a timeline
4 + of its last 60 check-ins, the latest 100 check-ins and 20 incidents.
5 + Check-ins refresh it live (PubSub), at most once a second. Someone with
6 + `project:write` can edit, enable and disable it; `project:admin` can
7 + delete it.
8 + """
9 + use VigilWeb, :live_view
10 +
11 + import VigilWeb.MonitorComponents
12 + import VigilWeb.PerformanceComponents, only: [duration: 1]
13 +
14 + alias Vigil.Accounts.Scope
15 + alias Vigil.Monitors
16 + alias Vigil.Monitors.Schedule
17 +
18 + @refresh_ms 1000
19 + @slots 60
20 +
21 + @impl true
22 + def mount(%{"slug" => slug}, _session, socket) do
23 + %{current_scope: scope, project: project} = socket.assigns
24 +
25 + case Monitors.get_monitor(project, slug) do
26 + nil ->
27 + {:ok,
28 + socket
29 + |> put_flash(:error, "That monitor isn't one of this project's.")
30 + |> push_navigate(to: list_path(scope, project))}
31 +
32 + monitor ->
33 + if connected?(socket),
34 + do: Phoenix.PubSub.subscribe(Vigil.PubSub, "project:#{project.id}:monitors")
35 +
36 + {:ok,
37 + socket
38 + |> assign(:page_title, "#{monitor.name} · #{project.name}")
39 + |> assign(:can_write?, Scope.can?(scope, "project:write"))
40 + |> assign(:can_admin?, Scope.can?(scope, "project:admin"))
41 + |> assign(:editing?, false)
42 + |> assign(:form, nil)
43 + |> assign(:slots, @slots)
44 + |> assign(:refresh_scheduled?, false)
45 + |> stream_configure(:check_ins, dom_id: &"checkin-#{&1.id}")
46 + |> stream_configure(:incidents, dom_id: &"incident-#{&1.id}")
47 + |> load(monitor)}
48 + end
49 + end
50 +
51 + defp load(socket, monitor) do
52 + check_ins = Monitors.list_check_ins(monitor, 100)
53 + incidents = Monitors.list_incidents(monitor)
54 +
55 + socket
56 + |> assign(:monitor, monitor)
57 + |> assign(:timeline, check_ins |> Enum.take(@slots) |> Enum.reverse())
58 + |> assign(:check_in_count, length(check_ins))
59 + |> assign(:incident_count, length(incidents))
60 + |> stream(:check_ins, check_ins, reset: true)
61 + |> stream(:incidents, incidents, reset: true)
62 + end
63 +
64 + defp reload(socket) do
65 + %{current_scope: scope, project: project, monitor: monitor} = socket.assigns
66 +
67 + case Monitors.get_monitor(project, monitor.slug) do
68 + nil ->
69 + socket
70 + |> put_flash(:info, "That monitor was deleted.")
71 + |> push_navigate(to: list_path(scope, project))
72 +
73 + monitor ->
74 + load(socket, monitor)
75 + end
76 + end
77 +
78 + @impl true
79 + def handle_event("edit", _params, socket) do
80 + form = socket.assigns.monitor |> Monitors.change_monitor() |> to_form()
81 + {:noreply, assign(socket, editing?: true, form: form)}
82 + end
83 +
84 + def handle_event("cancel", _params, socket),
85 + do: {:noreply, assign(socket, editing?: false, form: nil)}
86 +
87 + def handle_event("validate", %{"monitor" => params}, socket) do
88 + form =
89 + socket.assigns.monitor
90 + |> Monitors.change_monitor(Map.delete(params, "slug"))
91 + |> to_form(action: :validate)
92 +
93 + {:noreply, assign(socket, :form, form)}
94 + end
95 +
96 + def handle_event("save", %{"monitor" => params}, socket) do
97 + %{current_scope: scope, monitor: monitor} = socket.assigns
98 +
99 + case Monitors.update_monitor(scope, monitor, Map.delete(params, "slug")) do
100 + {:ok, monitor} ->
101 + {:noreply,
102 + socket
103 + |> assign(editing?: false, form: nil)
104 + |> load(monitor)
105 + |> put_flash(:info, "Monitor saved.")}
106 +
107 + {:error, %Ecto.Changeset{} = cs} ->
108 + {:noreply, assign(socket, :form, to_form(cs, action: :update))}
109 +
110 + {:error, _} ->
111 + {:noreply, put_flash(socket, :error, "You can't change this monitor.")}
112 + end
113 + end
114 +
115 + def handle_event("toggle_enabled", _params, socket) do
116 + %{current_scope: scope, monitor: monitor} = socket.assigns
117 +
118 + case Monitors.update_monitor(scope, monitor, %{enabled: !monitor.enabled}) do
119 + {:ok, monitor} ->
120 + {:noreply,
121 + socket
122 + |> load(monitor)
123 + |> put_flash(:info, if(monitor.enabled, do: "Monitor enabled.", else: "Monitor disabled."))}
124 +
125 + {:error, _} ->
126 + {:noreply, put_flash(socket, :error, "You can't change this monitor.")}
127 + end
128 + end
129 +
130 + def handle_event("delete", _params, socket) do
131 + %{current_scope: scope, project: project, monitor: monitor} = socket.assigns
132 +
133 + case Monitors.delete_monitor(scope, monitor) do
134 + {:ok, _} ->
135 + {:noreply,
136 + socket
137 + |> put_flash(:info, "Monitor #{monitor.name} deleted.")
138 + |> push_navigate(to: list_path(scope, project))}
139 +
140 + {:error, _} ->
141 + {:noreply, put_flash(socket, :error, "You can't delete this monitor.")}
142 + end
143 + end
144 +
145 + @impl true
146 + def handle_info({:monitor_updated, id}, socket) do
147 + if id == socket.assigns.monitor.id,
148 + do: {:noreply, schedule_refresh(socket)},
149 + else: {:noreply, socket}
150 + end
151 +
152 + def handle_info(:refresh, socket),
153 + do: {:noreply, socket |> assign(:refresh_scheduled?, false) |> reload()}
154 +
155 + defp schedule_refresh(%{assigns: %{refresh_scheduled?: true}} = socket), do: socket
156 +
157 + defp schedule_refresh(socket) do
158 + Process.send_after(self(), :refresh, @refresh_ms)
159 + assign(socket, :refresh_scheduled?, true)
160 + end
161 +
162 + defp list_path(scope, project),
163 + do: ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}/monitors"
164 +
165 + @impl true
166 + def render(assigns) do
167 + ~H"""
168 + <Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
169 + <div class="mx-auto max-w-5xl space-y-8">
170 + <.header>
171 + <span class="flex flex-wrap items-center gap-2">
172 + <span id="monitor-name">{@monitor.name}</span>
173 + <.health_badge monitor={@monitor} id="monitor-health" />
174 + </span>
175 + <:subtitle>
176 + <span class="font-mono">{@monitor.slug}</span>
177 + · <span class="font-mono" id="monitor-schedule">{Schedule.describe(@monitor)}</span>
178 + </:subtitle>
179 + <:actions>
180 + <div class="flex flex-wrap items-center gap-1">
181 + <.link
182 + navigate={list_path(@current_scope, @project)}
183 + class="btn btn-ghost btn-sm"
184 + id="monitor-back"
185 + >
186 + <.icon name="hero-arrow-left-micro" class="size-4" /> Monitors
187 + </.link>
188 + <%= if @can_write? do %>
189 + <button
190 + :if={!@editing?}
191 + type="button"
192 + id="edit-monitor"
193 + class="btn btn-ghost btn-sm"
194 + phx-click="edit"
195 + >
196 + <.icon name="hero-pencil-square-micro" class="size-4" /> Edit
197 + </button>
198 + <button
199 + type="button"
200 + id="toggle-enabled"
201 + class="btn btn-ghost btn-sm"
202 + phx-click="toggle_enabled"
203 + >
204 + <%= if @monitor.enabled do %>
205 + <.icon name="hero-pause-micro" class="size-4" /> Disable
206 + <% else %>
207 + <.icon name="hero-play-micro" class="size-4" /> Enable
208 + <% end %>
209 + </button>
210 + <% end %>
211 + <button
212 + :if={@can_admin?}
213 + type="button"
214 + id="delete-monitor"
215 + class="btn btn-ghost btn-sm text-error"
216 + phx-click="delete"
217 + data-confirm={"Delete the monitor #{@monitor.name} and all its check-ins?"}
218 + >
219 + <.icon name="hero-trash-micro" class="size-4" /> Delete
220 + </button>
221 + </div>
222 + </:actions>
223 + </.header>
224 +
225 + <p
226 + :if={!@monitor.enabled}
227 + id="monitor-disabled-note"
228 + class="flex items-center gap-2 rounded-box border border-dashed border-base-300 bg-base-200/40 px-4 py-3 text-sm text-base-content/70"
229 + >
230 + <.icon name="hero-pause-circle" class="size-5 shrink-0" />
231 + This monitor is disabled: its check-ins are dropped and missed runs aren't counted.
232 + </p>
233 +
234 + <.form
235 + :if={@editing? and @form}
236 + for={@form}
237 + id="monitor-form"
238 + phx-change="validate"
239 + phx-submit="save"
240 + class="space-y-1 rounded-box border border-base-300 bg-base-200/60 p-4"
241 + >
242 + <h2 class="mb-2 text-sm font-semibold">Edit monitor</h2>
243 + <.monitor_fields form={@form} />
244 + <div class="flex gap-2 pt-1">
245 + <.button class="btn btn-primary btn-sm" phx-disable-with="Saving…" id="save-monitor">
246 + Save
247 + </.button>
248 + <button type="button" class="btn btn-ghost btn-sm" phx-click="cancel" id="cancel-edit">
249 + Cancel
250 + </button>
251 + </div>
252 + </.form>
253 +
254 + <dl id="monitor-stats" class="grid grid-cols-2 gap-3 sm:grid-cols-4">
255 + <.tile id="stat-last" label="Last check-in">
256 + <.rel_time at={@monitor.last_checkin_at} empty="never" />
257 + <span :if={@monitor.last_status} class="block text-xs font-normal text-base-content/60">
258 + {status_label(@monitor.last_status)}
259 + </span>
260 + </.tile>
261 + <.tile id="stat-next" label="Next expected">
262 + <%= if @monitor.enabled do %>
263 + <.rel_time at={@monitor.next_expected_at} />
264 + <span
265 + :if={@monitor.next_expected_at}
266 + class="block text-xs font-normal text-base-content/60"
267 + >
268 + {short_time(@monitor.next_expected_at)} UTC
269 + </span>
270 + <% else %>
271 + <span class="text-base-content/50">paused</span>
272 + <% end %>
273 + </.tile>
274 + <.tile id="stat-failures" label="Failures in a row">
275 + <span class={[@monitor.consecutive_failures > 0 && "text-error"]}>
276 + {@monitor.consecutive_failures}
277 + </span>
278 + </.tile>
279 + <.tile id="stat-incidents" label="Incidents">
280 + {@incident_count}{if @incident_count >= 20, do: "+"}
281 + </.tile>
282 + </dl>
283 +
284 + <section
285 + id="monitor-settings"
286 + class="rounded-box border border-base-300 bg-base-100 p-4"
287 + >
288 + <h2 class="mb-3 font-semibold">Settings</h2>
289 + <dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-2">
290 + <.setting label="Schedule">
291 + <span class="font-mono" id="setting-schedule">{schedule_text(@monitor)}</span>
292 + </.setting>
293 + <.setting label="Time zone">
294 + <span id="setting-timezone">{@monitor.timezone}</span>
295 + <span :if={!Schedule.tz_database?()} class="text-xs text-base-content/60">
296 + (evaluated in UTC: no time zone database)
297 + </span>
298 + </.setting>
299 + <.setting label="Check-in margin">
300 + <span id="setting-margin">{minutes(@monitor.checkin_margin)}</span>
301 + </.setting>
302 + <.setting label="Max runtime">
303 + <span id="setting-runtime">{minutes(@monitor.max_runtime)}</span>
304 + </.setting>
305 + <.setting label="Opens an incident after">
306 + <span id="setting-failure-threshold">
307 + {@monitor.failure_threshold} {if @monitor.failure_threshold == 1,
308 + do: "failure",
309 + else: "failures in a row"}
310 + </span>
311 + </.setting>
312 + <.setting label="Resolves after">
313 + <span id="setting-recovery-threshold">
314 + {@monitor.recovery_threshold} {if @monitor.recovery_threshold == 1,
315 + do: "success",
316 + else: "successes in a row"}
317 + </span>
318 + </.setting>
319 + </dl>
320 + </section>
321 +
322 + <section class="space-y-3">
323 + <div class="flex flex-wrap items-center justify-between gap-2">
324 + <h2 class="font-semibold">Last {@slots} check-ins</h2>
325 + <.legend />
326 + </div>
327 + <div class="rounded-box border border-base-300 bg-base-100 px-4 pb-3 pt-8">
328 + <.timeline
329 + id={"monitor-timeline-#{@monitor.id}"}
330 + check_ins={@timeline}
331 + slots={@slots}
332 + class="h-12"
333 + />
334 + </div>
335 + </section>
336 +
337 + <section class="space-y-2">
338 + <h2 class="font-semibold">Incidents</h2>
339 + <ul
340 + id="incidents"
341 + phx-update="stream"
342 + class="divide-y divide-base-300 rounded-box border border-base-300 bg-base-100"
343 + >
344 + <li
345 + id="incidents-empty"
346 + class="hidden p-4 text-center text-sm text-base-content/60 only:block"
347 + >
348 + No incidents: it hasn't crossed its failure threshold.
349 + </li>
350 + <li
351 + :for={{dom_id, i} <- @streams.incidents}
352 + id={dom_id}
353 + class="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-2 text-sm"
354 + >
355 + <%= if i.resolved_at do %>
356 + <span class="badge badge-ghost badge-sm gap-1">
357 + <.icon name="hero-check-micro" class="size-3.5" /> Resolved
358 + </span>
359 + <% else %>
360 + <span class="badge badge-error badge-sm gap-1">
361 + <.icon name="hero-exclamation-triangle-micro" class="size-3.5" /> Open
362 + </span>
363 + <% end %>
364 + <span class="incident-reason">{reason_text(i.reason)}</span>
365 + <span class="text-base-content/60">
366 + <time datetime={DateTime.to_iso8601(i.started_at)} title={format_time(i.started_at)}>
367 + {short_time(i.started_at)}
368 + </time>
369 + <%= if i.resolved_at do %>
370 + →
371 + <time
372 + datetime={DateTime.to_iso8601(i.resolved_at)}
373 + title={format_time(i.resolved_at)}
374 + >
375 + {short_time(i.resolved_at)}
376 + </time>
377 + <% end %>
378 + </span>
379 + <span class="ml-auto tabular-nums text-base-content/70 incident-duration">
380 + {incident_span(i)}
381 + </span>
382 + </li>
383 + </ul>
384 + </section>
385 +
386 + <section class="space-y-2">
387 + <h2 class="font-semibold">
388 + Check-ins
389 + <span :if={@check_in_count >= 100} class="text-sm font-normal text-base-content/60">
390 + (latest 100)
391 + </span>
392 + </h2>
393 + <div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
394 + <table class="table table-sm">
395 + <thead>
396 + <tr>
397 + <th>Status</th>
398 + <th>Expected</th>
399 + <th>Started</th>
400 + <th class="text-right">Duration</th>
401 + <th>Environment</th>
402 + <th>Release</th>
403 + </tr>
404 + </thead>
405 + <tbody id="checkins" phx-update="stream">
406 + <tr id="checkins-empty" class="hidden only:table-row">
407 + <td colspan="6" class="py-6 text-center text-base-content/60">
408 + No check-ins yet.
409 + </td>
410 + </tr>
411 + <tr :for={{dom_id, c} <- @streams.check_ins} id={dom_id} data-status={c.status}>
412 + <td><.status_badge status={c.status} /></td>
413 + <td class="whitespace-nowrap tabular-nums" title={format_time(c.expected_at)}>
414 + {short_time(c.expected_at)}
415 + </td>
416 + <td class="whitespace-nowrap tabular-nums" title={format_time(c.started_at)}>
417 + {short_time(c.started_at)}
418 + </td>
419 + <td class="text-right tabular-nums">{duration(c.duration_ms)}</td>
420 + <td class="text-base-content/70">{c.environment || "—"}</td>
421 + <td class="max-w-48 truncate font-mono text-xs" title={c.release}>
422 + {c.release || "—"}
423 + </td>
424 + </tr>
425 + </tbody>
426 + </table>
427 + </div>
428 + </section>
429 + </div>
430 + </Layouts.app>
431 + """
432 + end
433 +
434 + attr :id, :string, required: true
435 + attr :label, :string, required: true
436 + slot :inner_block, required: true
437 +
438 + defp tile(assigns) do
439 + ~H"""
440 + <div
441 + id={@id}
442 + class="rounded-box border border-base-300 bg-base-100 px-4 py-3 transition hover:border-base-content/20"
443 + >
444 + <dt class="text-xs font-medium uppercase tracking-wide text-base-content/60">{@label}</dt>
445 + <dd class="mt-1 text-lg font-semibold tabular-nums">{render_slot(@inner_block)}</dd>
446 + </div>
447 + """
448 + end
449 +
450 + attr :label, :string, required: true
451 + slot :inner_block, required: true
452 +
453 + defp setting(assigns) do
454 + ~H"""
455 + <div class="flex flex-wrap items-baseline justify-between gap-2 border-b border-base-200 pb-2 sm:block sm:border-0 sm:pb-0">
456 + <dt class="text-base-content/60">{@label}</dt>
457 + <dd class="font-medium">{render_slot(@inner_block)}</dd>
458 + </div>
459 + """
460 + end
461 +
462 + defp schedule_text(%{schedule_type: :crontab, schedule: s}), do: "crontab #{s}"
463 + defp schedule_text(monitor), do: Schedule.describe(monitor)
464 +
465 + defp reason_text("missed"), do: "Missed check-in"
466 + defp reason_text("timeout"), do: "Ran past max runtime"
467 + defp reason_text("error"), do: "Reported an error"
468 + defp reason_text(other), do: other
469 +
470 + defp incident_span(%{started_at: s, resolved_at: nil}),
471 + do: "ongoing, #{span(DateTime.diff(DateTime.utc_now(), s))}"
472 +
473 + defp incident_span(%{started_at: s, resolved_at: r}), do: span(DateTime.diff(r, s))
474 +end
modified lib/vigil_web/router.ex
+2 −0
@@ -133,6 +133,8 @@ defmodule VigilWeb.Router do
133 133 live "/orgs/:org/projects/:project/releases/:version", ReleaseLive.Show, :show
134 134 live "/orgs/:org/projects/:project/performance", PerformanceLive.Index, :index
135 135 live "/orgs/:org/projects/:project/performance/:group_id", PerformanceLive.Show, :show
136 + live "/orgs/:org/projects/:project/monitors", MonitorLive.Index, :index
137 + live "/orgs/:org/projects/:project/monitors/:slug", MonitorLive.Show, :show
136 138 live "/orgs/:org/projects/:project/issues/:short_id", IssueLive.Show, :show
137 139
138 140 live "/orgs/:org/projects/:project/issues/:short_id/events/:event_id",
added test/vigil_web/live/monitor_live_test.exs
+296 −0
@@ -0,0 +1,296 @@
1 +defmodule VigilWeb.MonitorLiveTest do
2 + use VigilWeb.ConnCase, async: true
3 +
4 + import Phoenix.LiveViewTest
5 + import Vigil.OrganizationsFixtures
6 +
7 + alias Vigil.Monitors
8 +
9 + setup :register_and_log_in_user
10 +
11 + setup %{user: user} do
12 + org = organization_fixture(user)
13 + project = project_fixture(org_scope(user, org), %{"name" => "web"})
14 + base = ~p"/orgs/#{org.slug}/projects/web/monitors"
15 + %{org: org, project: project, base: base}
16 + end
17 +
18 + @config %{
19 + "schedule" => %{"type" => "interval", "value" => 1, "unit" => "hour"},
20 + "checkin_margin" => 5,
21 + "max_runtime" => 10
22 + }
23 +
24 + defp check_in(project, slug, status, at \\ DateTime.utc_now(), extra \\ %{}) do
25 + payload =
26 + Map.merge(
27 + %{"monitor_slug" => slug, "status" => status, "monitor_config" => @config},
28 + extra
29 + )
30 +
31 + {:ok, c} = Monitors.check_in(project, payload, at)
32 + c
33 + end
34 +
35 + defp ago(minutes), do: DateTime.add(DateTime.utc_now(), -minutes, :minute)
36 +
37 + describe "list" do
38 + test "is linked from the project's issues page", %{conn: conn, org: org} do
39 + {:ok, view, _} = live(conn, ~p"/orgs/#{org.slug}/projects/web")
40 + assert has_element?(view, "#project-monitors[href$='/projects/web/monitors']")
41 + end
42 +
43 + test "explains how check-ins arrive when there are none", %{conn: conn, base: base} do
44 + {:ok, view, _} = live(conn, base)
45 + assert has_element?(view, "#monitors-empty")
46 + assert has_element?(view, "#setup-crons-elixir", "capture_check_in")
47 + assert has_element?(view, "#setup-crons-python", "monitor_slug")
48 + assert has_element?(view, "#setup-crons-cli", "sentry-cli monitors run")
49 + assert has_element?(view, "#monitors-alerts-link[href$='/alerts']")
50 + refute has_element?(view, "#monitors")
51 + end
52 +
53 + test "shows monitors with health, schedule and a timeline", %{
54 + conn: conn,
55 + base: base,
56 + project: project
57 + } do
58 + check_in(project, "backup", "ok", ago(120), %{"duration" => 2.5})
59 + check_in(project, "backup", "ok", ago(60))
60 + check_in(project, "sync", "error", ago(5))
61 + backup = Monitors.get_monitor(project, "backup")
62 + sync = Monitors.get_monitor(project, "sync")
63 +
64 + {:ok, view, _} = live(conn, base)
65 + refute has_element?(view, "#monitors-empty")
66 + assert has_element?(view, "#monitor-#{backup.id}", "backup")
67 + assert has_element?(view, "#monitor-#{backup.id} a[href$='/monitors/backup']")
68 + assert has_element?(view, "#monitor-schedule-#{backup.id}", "every hour")
69 + assert has_element?(view, "#monitor-health-#{backup.id} .monitor-health-ok")
70 + assert has_element?(view, "#monitor-health-#{sync.id} .monitor-health-error", "Failing")
71 + assert has_element?(view, "#monitors-summary", "1 failing")
72 +
73 + assert has_element?(
74 + view,
75 + "#monitor-timeline-#{backup.id} .monitor-tick[data-status='ok']"
76 + )
77 +
78 + assert has_element?(
79 + view,
80 + "#monitor-timeline-#{backup.id}[aria-label='Last 2 check-ins: 2 ok']"
81 + )
82 +
83 + assert has_element?(view, "#monitor-timeline-#{sync.id} .monitor-tick[data-status='error']")
84 + assert has_element?(view, "#monitor-last-#{sync.id}", "5m ago")
85 + assert has_element?(view, "#monitor-next-#{backup.id}[datetime]")
86 + end
87 +
88 + test "refreshes when a monitor checks in", %{conn: conn, base: base, project: project} do
89 + check_in(project, "backup", "ok", ago(60))
90 + m = Monitors.get_monitor(project, "backup")
91 +
92 + {:ok, view, _} = live(conn, base)
93 + refute has_element?(view, "#monitor-timeline-#{m.id} .monitor-tick[data-status='error']")
94 +
95 + Phoenix.PubSub.subscribe(Vigil.PubSub, "project:#{project.id}:monitors")
96 + check_in(project, "backup", "error")
97 + assert_receive {:monitor_updated, _}
98 + check_in(project, "fresh", "ok")
99 + fresh = Monitors.get_monitor(project, "fresh")
100 +
101 + send(view.pid, :refresh)
102 + assert has_element?(view, "#monitor-timeline-#{m.id} .monitor-tick[data-status='error']")
103 + assert has_element?(view, "#monitor-health-#{m.id} .monitor-health-error")
104 + assert has_element?(view, "#monitor-#{fresh.id}")
105 + end
106 + end
107 +
108 + describe "create" do
109 + test "shows validation errors, then makes the monitor", %{
110 + conn: conn,
111 + base: base,
112 + project: project,
113 + org: org
114 + } do
115 + {:ok, view, _} = live(conn, base)
116 + refute has_element?(view, "#monitor-form")
117 + view |> element("#new-monitor") |> render_click()
118 + assert has_element?(view, "#monitor-form")
119 +
120 + view
121 + |> form("#monitor-form",
122 + monitor: %{slug: "Bad Slug!", schedule_type: "crontab", schedule: "nope"}
123 + )
124 + |> render_submit()
125 +
126 + assert has_element?(view, "#monitor-form", "lowercase letters")
127 + assert has_element?(view, "#monitor-form", "is not a valid crontab")
128 + assert Monitors.list_monitors(project) == []
129 +
130 + # Switching to an interval shows its inputs.
131 + view
132 + |> form("#monitor-form", monitor: %{schedule_type: "interval"})
133 + |> render_change()
134 +
135 + assert has_element?(view, "#monitor-interval-value")
136 + refute has_element?(view, "#monitor-crontab")
137 +
138 + {:ok, show, _} =
139 + view
140 + |> form("#monitor-form",
141 + monitor: %{
142 + slug: "reports",
143 + name: "Weekly reports",
144 + schedule_type: "interval",
145 + interval_value: "2",
146 + interval_unit: "hour",
147 + timezone: "Etc/UTC",
148 + checkin_margin: "3",
149 + max_runtime: "15",
150 + failure_threshold: "2",
151 + recovery_threshold: "1"
152 + }
153 + )
154 + |> render_submit()
155 + |> follow_redirect(conn, ~p"/orgs/#{org.slug}/projects/web/monitors/reports")
156 +
157 + assert has_element?(show, "#monitor-name", "Weekly reports")
158 + assert has_element?(show, "#monitor-health .monitor-health-new")
159 +
160 + assert %{interval_value: 2, interval_unit: "hour", failure_threshold: 2} =
161 + Monitors.get_monitor(project, "reports")
162 + end
163 + end
164 +
165 + describe "detail" do
166 + setup %{project: project, org: org} do
167 + t0 = DateTime.add(DateTime.utc_now(:second), -3, :hour)
168 + check_in(project, "backup", "ok", t0, %{"environment" => "prod", "release" => "1.2.3"})
169 + # Nothing for over an hour: the next slot is missed, opening an incident.
170 + Monitors.tick(DateTime.add(t0, 70, :minute))
171 + check_in(project, "backup", "ok", DateTime.add(t0, 80, :minute), %{"duration" => 42})
172 + m = Monitors.get_monitor(project, "backup")
173 + %{monitor: m, path: ~p"/orgs/#{org.slug}/projects/web/monitors/backup"}
174 + end
175 +
176 + test "shows settings, timeline, check-ins and incidents", %{
177 + conn: conn,
178 + path: path,
179 + monitor: m
180 + } do
181 + {:ok, view, _} = live(conn, path)
182 + assert has_element?(view, "#monitor-name", "backup")
183 + assert has_element?(view, "#setting-schedule", "every hour")
184 + assert has_element?(view, "#setting-margin", "5 minutes")
185 + assert has_element?(view, "#setting-runtime", "10 minutes")
186 + assert has_element?(view, "#monitor-timeline-#{m.id} .monitor-tick[data-status='missed']")
187 + assert has_element?(view, "#stat-next time[datetime]")
188 +
189 + assert has_element?(view, "#checkins tr[data-status='ok']", "prod")
190 + assert has_element?(view, "#checkins tr[data-status='ok']", "1.2.3")
191 + assert has_element?(view, "#checkins tr[data-status='ok']", "42.0s")
192 + assert has_element?(view, "#checkins tr[data-status='missed']")
193 +
194 + assert [incident] = Monitors.list_incidents(m)
195 + assert has_element?(view, "#incident-#{incident.id} .incident-reason", "Missed check-in")
196 + assert has_element?(view, "#incident-#{incident.id}", "Resolved")
197 + assert has_element?(view, "#incident-#{incident.id} .incident-duration", "10m")
198 + end
199 +
200 + test "an unknown slug goes back to the list", %{conn: conn, org: org} do
201 + assert {:error, {:live_redirect, %{to: to}}} =
202 + live(conn, ~p"/orgs/#{org.slug}/projects/web/monitors/nope")
203 +
204 + assert to == ~p"/orgs/#{org.slug}/projects/web/monitors"
205 + end
206 +
207 + test "edits the schedule", %{conn: conn, path: path, project: project} do
208 + {:ok, view, _} = live(conn, path)
209 + refute has_element?(view, "#monitor-form")
210 + view |> element("#edit-monitor") |> render_click()
211 +
212 + view
213 + |> form("#monitor-form", monitor: %{schedule_type: "crontab"})
214 + |> render_change()
215 +
216 + view
217 + |> form("#monitor-form", monitor: %{schedule_type: "crontab", schedule: "bad"})
218 + |> render_submit()
219 +
220 + assert has_element?(view, "#monitor-form", "is not a valid crontab")
221 +
222 + view
223 + |> form("#monitor-form", monitor: %{schedule_type: "crontab", schedule: "*/5 * * * *"})
224 + |> render_submit()
225 +
226 + refute has_element?(view, "#monitor-form")
227 + assert has_element?(view, "#setting-schedule", "*/5 * * * *")
228 +
229 + assert %{schedule_type: :crontab, schedule: "*/5 * * * *"} =
230 + Monitors.get_monitor(project, "backup")
231 + end
232 +
233 + test "disables and enables", %{conn: conn, path: path, project: project} do
234 + {:ok, view, _} = live(conn, path)
235 + view |> element("#toggle-enabled") |> render_click()
236 + refute Monitors.get_monitor(project, "backup").enabled
237 + assert has_element?(view, "#monitor-disabled-note")
238 + assert has_element?(view, "#monitor-health .monitor-disabled")
239 +
240 + view |> element("#toggle-enabled") |> render_click()
241 + assert Monitors.get_monitor(project, "backup").enabled
242 + refute has_element?(view, "#monitor-disabled-note")
243 + end
244 +
245 + test "an admin deletes it", %{conn: conn, path: path, project: project, org: org} do
246 + {:ok, view, _} = live(conn, path)
247 +
248 + {:ok, list, _} =
249 + view
250 + |> element("#delete-monitor")
251 + |> render_click()
252 + |> follow_redirect(conn, ~p"/orgs/#{org.slug}/projects/web/monitors")
253 +
254 + assert Monitors.get_monitor(project, "backup") == nil
255 + assert has_element?(list, "#monitors-empty")
256 + end
257 +
258 + test "refreshes when it checks in", %{conn: conn, path: path, project: project} do
259 + {:ok, view, _} = live(conn, path)
260 + refute has_element?(view, "#checkins tr[data-status='error']")
261 + check_in(project, "backup", "error")
262 + send(view.pid, :refresh)
263 + assert has_element?(view, "#checkins tr[data-status='error']")
264 + assert has_element?(view, "#monitor-health .monitor-health-error")
265 + end
266 + end
267 +
268 + test "members without project:write see monitors but can't change them", %{
269 + conn: conn,
270 + user: user
271 + } do
272 + owner = Vigil.AccountsFixtures.user_fixture()
273 + other = organization_fixture(owner)
274 + p = project_fixture(org_scope(owner, other), %{"name" => "api"})
275 + member_fixture(other, user, :member)
276 +
277 + {:ok, _} =
278 + Vigil.Organizations.update_organization(org_scope(owner, other), other, %{
279 + open_membership: true
280 + })
281 +
282 + check_in(p, "backup", "ok")
283 + m = Monitors.get_monitor(p, "backup")
284 +
285 + {:ok, list, _} = live(conn, ~p"/orgs/#{other.slug}/projects/api/monitors")
286 + assert has_element?(list, "#monitor-#{m.id}")
287 + refute has_element?(list, "#new-monitor")
288 +
289 + {:ok, view, _} = live(conn, ~p"/orgs/#{other.slug}/projects/api/monitors/backup")
290 + assert has_element?(view, "#monitor-name")
291 + refute has_element?(view, "#edit-monitor")
292 + refute has_element?(view, "#toggle-enabled")
293 + refute has_element?(view, "#delete-monitor")
294 + refute has_element?(view, "#monitor-form")
295 + end
296 +end

Parents: 28e6625