Uptime UI: org monitor list and detail, status page management, public status pages

2bb12dd · gmorell · 2026-12-02 03:16

23 files +2452 -30
Message
{commit_body(@commit)}

Files changed

modified lib/vigil/uptime.ex
+98 −21
@@ -296,7 +296,8 @@ defmodule Vigil.Uptime do
296 296
297 297 @doc """
298 298 The share of the last `hours` (24) a monitor was up, from its changes:
299 − a float 0..1, or nil before its first check.
299 + a float 0..1, or nil before its first check. Time before its first
300 + check isn't counted: a monitor made an hour ago and up since is at 100%.
300 301 """
301 302 def uptime_ratio(%Monitor{} = monitor, hours \\ 24, now \\ DateTime.utc_now()) do
302 303 from = DateTime.add(now, -hours * 3600, :second)
@@ -304,33 +305,99 @@ defmodule Vigil.Uptime do
304 305 if is_nil(monitor.is_up) do
305 306 nil
306 307 else
307 − changes =
308 − Repo.all(
309 − from c in Check,
310 − where: c.monitor_id == ^monitor.id and c.is_change and c.checked_at >= ^from,
311 − order_by: [asc: c.id],
312 − select: {c.checked_at, c.is_up}
313 − )
308 + {up, known} =
309 + monitor
310 + |> up_segments(from, now)
311 + |> Enum.reduce({0, 0}, fn {s_from, s_to, up?}, {up, known} ->
312 + d = max(DateTime.diff(s_to, s_from, :microsecond), 0)
313 + {if(up?, do: up + d, else: up), known + d}
314 + end)
314 315
315 − # The state at the window's start: the opposite of the first change
316 − # in it, or the current state when nothing changed.
317 − start_up =
318 − case changes do
319 − [{_, up} | _] -> not up
320 − [] -> monitor.is_up
321 − end
316 + cond do
317 + known > 0 -> up / known
318 + monitor.is_up -> 1.0
319 + true -> 0.0
320 + end
321 + end
322 + end
322 323
323 − {up_seconds, last_at, last_up} =
324 − Enum.reduce(changes, {0, from, start_up}, fn {at, up}, {acc, since, was_up} ->
325 − {acc + if(was_up, do: max(DateTime.diff(at, since), 0), else: 0), at, up}
324 + @doc """
325 + A monitor's up share per UTC day for the last `days` days (today
326 + included, so far), oldest first: `%{date: Date, ratio: float 0..1 | nil}`.
327 + Built from its changes like `uptime_ratio/3`; `ratio` is nil for days
328 + before its first check (or all of them before any check), and a day it
329 + was checked for only part of counts only that part.
330 + """
331 + def daily_uptime(%Monitor{} = monitor, days \\ 30, now \\ DateTime.utc_now()) do
332 + today = DateTime.to_date(now)
333 + first_day = Date.add(today, -(days - 1))
334 + from = DateTime.new!(first_day, ~T[00:00:00], "Etc/UTC")
335 +
336 + segments = up_segments(monitor, from, now)
337 +
338 + for date <- Date.range(first_day, today) do
339 + day_start = DateTime.new!(date, ~T[00:00:00], "Etc/UTC")
340 + day_end = Enum.min([DateTime.add(day_start, 1, :day), now], DateTime)
341 +
342 + {up, known} =
343 + Enum.reduce(segments, {0, 0}, fn {s_from, s_to, up?}, {up, known} ->
344 + overlap =
345 + max(
346 + DateTime.diff(
347 + Enum.min([s_to, day_end], DateTime),
348 + Enum.max([s_from, day_start], DateTime),
349 + :microsecond
350 + ),
351 + 0
352 + )
353 +
354 + {if(up?, do: up + overlap, else: up), known + overlap}
326 355 end)
327 356
328 − total = DateTime.diff(now, from)
329 − up_seconds = up_seconds + if(last_up, do: max(DateTime.diff(now, last_at), 0), else: 0)
330 − up_seconds / total
357 + %{date: date, ratio: if(known > 0, do: up / known)}
331 358 end
332 359 end
333 360
361 + # `{from, to, up?}` spans covering what's known of [from, now]: from the
362 + # state before the window (the last change before it), or else from the
363 + # first change in it.
364 + defp up_segments(%Monitor{id: id} = monitor, from, now) do
365 + before =
366 + Repo.one(
367 + from c in Check,
368 + where: c.monitor_id == ^id and c.is_change and c.checked_at < ^from,
369 + order_by: [desc: c.checked_at],
370 + limit: 1,
371 + select: c.is_up
372 + )
373 +
374 + changes =
375 + Repo.all(
376 + from c in Check,
377 + where:
378 + c.monitor_id == ^id and c.is_change and c.checked_at >= ^from and
379 + c.checked_at <= ^now,
380 + order_by: [asc: c.checked_at],
381 + select: {c.checked_at, c.is_up}
382 + )
383 +
384 + points =
385 + cond do
386 + not is_nil(before) -> [{from, before} | changes]
387 + changes != [] -> changes
388 + # Checked, but the changes are gone (pruned): its current state.
389 + not is_nil(monitor.is_up) and not is_nil(monitor.last_check_at) -> [{from, monitor.is_up}]
390 + true -> []
391 + end
392 +
393 + points
394 + |> Enum.chunk_every(2, 1)
395 + |> Enum.map(fn
396 + [{at, up}, {next, _}] -> {at, next, up}
397 + [{at, up}] -> {at, now, up}
398 + end)
399 + end
400 +
334 401 ## Status pages
335 402
336 403 @doc "An organization's status pages, by name."
@@ -338,6 +405,16 @@ defmodule Vigil.Uptime do
338 405 Repo.all(from p in StatusPage, where: p.organization_id == ^org_id, order_by: p.name)
339 406 end
340 407
408 + @doc "An organization's status pages, by name, with their monitors (by name)."
409 + def list_status_pages_with_monitors(org_id) do
410 + Repo.all(
411 + from p in StatusPage,
412 + where: p.organization_id == ^org_id,
413 + order_by: p.name,
414 + preload: [monitors: ^from(m in Monitor, order_by: m.name)]
415 + )
416 + end
417 +
341 418 def change_status_page(%StatusPage{} = p, attrs \\ %{}), do: StatusPage.changeset(p, attrs)
342 419
343 420 @doc "Makes a status page (`org:write`); `monitor_ids` must be the organization's."
modified lib/vigil_web/components/chart_components.ex
+15 −8
@@ -14,7 +14,9 @@ defmodule VigilWeb.ChartComponents do
14 14 @doc """
15 15 Bars for `points`, each `%{value:, tip:, axis:, row:}`: `tip` is the
16 16 tooltip's text after the value, `axis` the short label used for the
17 − three axis marks, `row` the table's first column. DOM ids hang off `id`:
17 + three axis marks, `row` the table's first column. An optional
18 + `tone: :error` draws that bar in the error color (full height when its
19 + value is 0), for a point that failed. DOM ids hang off `id`:
18 20 `<id>-bars`, `<id>-bar-<i>`, `<id>-table`.
19 21 """
20 22 attr :id, :string, required: true
@@ -51,14 +53,16 @@ defmodule VigilWeb.ChartComponents do
51 53 class="group relative flex h-full flex-1 items-end"
52 54 >
53 55 <div
56 + data-tone={p[:tone]}
54 57 class={[
55 58 "w-full rounded-t-[4px] transition-colors",
56 − if(p.value > 0,
57 − do: "bg-primary group-hover:bg-primary/80",
58 − else: "bg-base-300/60"
59 − )
59 + cond do
60 + p[:tone] == :error -> "bg-error group-hover:bg-error/80"
61 + p.value > 0 -> "bg-primary group-hover:bg-primary/80"
62 + true -> "bg-base-300/60"
63 + end
60 64 ]}
61 − style={"height: #{bar_height(p.value, @max)}"}
65 + style={"height: #{bar_height(p, @max)}"}
62 66 />
63 67 <div 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">
64 68 <span class="font-semibold tabular-nums">{@format.(p.value)}</span> {p.tip}
@@ -101,8 +105,11 @@ defmodule VigilWeb.ChartComponents do
101 105 end
102 106 end
103 107
104 − defp bar_height(n, _max) when n <= 0, do: "2px"
105 − defp bar_height(n, max), do: "max(3px, #{Float.round(n / max * 100, 2)}%)"
108 + # A flagged bar with no value (a failed check with no timing) stands
109 + # full height, so it can't be missed.
110 + defp bar_height(%{tone: :error, value: n}, _max) when n <= 0, do: "100%"
111 + defp bar_height(%{value: n}, _max) when n <= 0, do: "2px"
112 + defp bar_height(%{value: n}, max), do: "max(3px, #{Float.round(n / max * 100, 2)}%)"
106 113
107 114 defp axis_marks([]), do: []
108 115
modified lib/vigil_web/components/layouts.ex
+11 −1
@@ -22,7 +22,7 @@ defmodule VigilWeb.Layouts do
22 22
23 23 attr :active, :atom,
24 24 default: nil,
25 − values: [nil, :home, :invites, :settings, :orgs, :projects, :org_settings, :tokens],
25 + values: [nil, :home, :invites, :settings, :orgs, :projects, :uptime, :org_settings, :tokens],
26 26 doc: "the nav section this page belongs to"
27 27
28 28 attr :wide, :boolean,
@@ -60,6 +60,16 @@ defmodule VigilWeb.Layouts do
60 60 Projects
61 61 </.nav_link>
62 62 </li>
63 + <li>
64 + <.nav_link
65 + id="org-uptime"
66 + navigate={~p"/orgs/#{@current_scope.organization.slug}/uptime"}
67 + icon="hero-signal-micro"
68 + active={@active == :uptime}
69 + >
70 + Uptime
71 + </.nav_link>
72 + </li>
63 73 <li>
64 74 <%!-- Which organization this is: its settings, and the way to the others. --%>
65 75 <details class="dropdown dropdown-end" id="nav-org">
added lib/vigil_web/components/uptime_components.ex
+325 −0
@@ -0,0 +1,325 @@
1 +defmodule VigilWeb.UptimeComponents do
2 + @moduledoc """
3 + Pieces the uptime pages share: a monitor's state badge (icon and word,
4 + never color alone), its type badge, the strip of its recent checks (one
5 + tick per check, with a hover tooltip and a summary for screen readers),
6 + the per-day uptime strip of a status page, percentages and response
7 + times for people, and the create/edit form's type-dependent fields.
8 + Relative times come from `VigilWeb.MonitorComponents`.
9 + """
10 + use Phoenix.Component
11 +
12 + import VigilWeb.CoreComponents, only: [icon: 1, input: 1]
13 + import VigilWeb.MonitorComponents, only: [format_time: 1]
14 +
15 + alias Vigil.Uptime
16 + alias Vigil.Uptime.Monitor
17 +
18 + @doc "A monitor type for people."
19 + def type_label(:ping), do: "HTTP ping"
20 + def type_label(:get), do: "HTTP GET"
21 + def type_label(:post), do: "HTTP POST"
22 + def type_label(:tcp), do: "TCP port"
23 + def type_label(:ssl), do: "TLS certificate"
24 + def type_label(:heartbeat), do: "Heartbeat"
25 + def type_label(other), do: to_string(other)
26 +
27 + @doc "The type select's options."
28 + def type_options, do: Enum.map(Monitor.types(), &{type_label(&1), to_string(&1)})
29 +
30 + @doc "A small badge naming a monitor's type."
31 + attr :type, :atom, required: true
32 + attr :id, :string, default: nil
33 +
34 + def type_badge(assigns) do
35 + ~H"""
36 + <span id={@id} class="badge badge-outline badge-sm gap-1 whitespace-nowrap text-base-content/70">
37 + <.icon name={type_icon(@type)} class="size-3.5" />{type_label(@type)}
38 + </span>
39 + """
40 + end
41 +
42 + defp type_icon(:heartbeat), do: "hero-heart-micro"
43 + defp type_icon(:tcp), do: "hero-server-micro"
44 + defp type_icon(:ssl), do: "hero-lock-closed-micro"
45 + defp type_icon(_), do: "hero-globe-alt-micro"
46 +
47 + @doc "Up, down or pending (not checked yet): `:up`, `:down`, `:pending`."
48 + def state(%{is_up: true}), do: :up
49 + def state(%{is_up: false}), do: :down
50 + def state(_), do: :pending
51 +
52 + @doc "A monitor's state (and paused state) as an icon and a word."
53 + attr :monitor, :map, required: true
54 + attr :id, :string, default: nil
55 + attr :size, :string, default: "badge-sm"
56 +
57 + def state_badge(assigns) do
58 + assigns = assign(assigns, :state, state(assigns.monitor))
59 +
60 + ~H"""
61 + <span id={@id} class="inline-flex flex-wrap items-center gap-1">
62 + <%= case @state do %>
63 + <% :down -> %>
64 + <span class={["badge badge-error gap-1 uptime-state-down", @size]}>
65 + <.icon name="hero-arrow-down-circle-micro" class="size-3.5" /> Down
66 + </span>
67 + <% :up -> %>
68 + <span class={["badge badge-success badge-soft gap-1 uptime-state-up", @size]}>
69 + <.icon name="hero-arrow-up-circle-micro" class="size-3.5" /> Up
70 + </span>
71 + <% :pending -> %>
72 + <span class={["badge badge-ghost gap-1 uptime-state-pending", @size]}>
73 + <.icon name="hero-clock-micro" class="size-3.5" /> Pending
74 + </span>
75 + <% end %>
76 + <span
77 + :if={Map.get(@monitor, :enabled) == false}
78 + class={["badge badge-outline gap-1 uptime-disabled", @size]}
79 + >
80 + <.icon name="hero-pause-micro" class="size-3.5" /> Disabled
81 + </span>
82 + </span>
83 + """
84 + end
85 +
86 + @doc """
87 + A monitor's latest checks (oldest first) as a row of ticks, left-padded
88 + to `slots`. Down checks stand full height in the error color, up ones a
89 + little shorter in the success color: shape and color both tell them
90 + apart. Each tick has a tooltip; the row has a summary as its accessible
91 + label.
92 + """
93 + attr :id, :string, required: true
94 + attr :checks, :list, required: true
95 + attr :slots, :integer, default: 30
96 + attr :class, :string, default: "h-6"
97 +
98 + def check_strip(assigns) do
99 + checks = Enum.take(assigns.checks, -assigns.slots)
100 +
101 + assigns =
102 + assign(assigns,
103 + checks: checks,
104 + pad: max(assigns.slots - length(checks), 0),
105 + summary: strip_summary(checks)
106 + )
107 +
108 + ~H"""
109 + <div id={@id} class={["flex items-end gap-[2px]", @class]} role="img" aria-label={@summary}>
110 + <span
111 + :for={_ <- List.duplicate(nil, @pad)}
112 + class="h-1/3 flex-1 rounded-[2px] bg-base-300/50"
113 + aria-hidden="true"
114 + />
115 + <span
116 + :for={c <- @checks}
117 + id={"#{@id}-tick-#{c.id}"}
118 + data-up={to_string(c.is_up)}
119 + class="uptime-tick group relative flex h-full flex-1 items-end"
120 + >
121 + <span class={[
122 + "w-full rounded-[2px] transition-opacity group-hover:opacity-75",
123 + if(c.is_up, do: "h-3/4 bg-success", else: "h-full bg-error")
124 + ]} />
125 + <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">
126 + <span class="font-semibold">{if c.is_up, do: "Up", else: "Down"}</span>
127 + · {format_time(c.checked_at)}
128 + <span :if={c.response_ms}>· {ms(c.response_ms)}</span>
129 + <span :if={!c.is_up}>· {Uptime.describe_reason(c.reason)}</span>
130 + </span>
131 + </span>
132 + </div>
133 + """
134 + end
135 +
136 + defp strip_summary([]), do: "No checks yet"
137 +
138 + defp strip_summary(checks) do
139 + down = Enum.count(checks, &(!&1.is_up))
140 + "Last #{length(checks)} checks: #{length(checks) - down} up, #{down} down"
141 + end
142 +
143 + @doc "A legend for the check strip's colors."
144 + def legend(assigns) do
145 + ~H"""
146 + <ul class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-base-content/60" aria-hidden="true">
147 + <li class="flex items-center gap-1.5"><span class="size-2.5 rounded-[2px] bg-success" />Up</li>
148 + <li class="flex items-center gap-1.5"><span class="size-2.5 rounded-[2px] bg-error" />Down</li>
149 + </ul>
150 + """
151 + end
152 +
153 + @doc """
154 + Per-day uptime (`Vigil.Uptime.daily_uptime/3`) as a strip of day bars:
155 + green when fully up, amber for a partial outage, red for a mostly-down
156 + day, grey before monitoring began. Each has a tooltip; the strip a
157 + summary.
158 + """
159 + attr :id, :string, required: true
160 + attr :days, :list, required: true
161 +
162 + def day_strip(assigns) do
163 + known = Enum.reject(assigns.days, &is_nil(&1.ratio))
164 + bad = Enum.count(known, &(&1.ratio < 1.0))
165 +
166 + summary =
167 + case known do
168 + [] -> "No data for the last #{length(assigns.days)} days yet"
169 + _ -> "Last #{length(assigns.days)} days: #{bad} with downtime"
170 + end
171 +
172 + assigns = assign(assigns, :summary, summary)
173 +
174 + ~H"""
175 + <div id={@id} class="flex h-8 items-stretch gap-[2px]" role="img" aria-label={@summary}>
176 + <span
177 + :for={d <- @days}
178 + data-date={Date.to_iso8601(d.date)}
179 + class={["status-day group relative flex-1 rounded-[2px]", day_color(d.ratio)]}
180 + >
181 + <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 text-base-content shadow-md group-hover:block">
182 + <span class="font-semibold">{Calendar.strftime(d.date, "%b %-d")}</span>
183 + · {if d.ratio, do: "#{percent(d.ratio)} up", else: "no data"}
184 + </span>
185 + </span>
186 + </div>
187 + """
188 + end
189 +
190 + defp day_color(nil), do: "bg-base-300/60"
191 + defp day_color(r) when r >= 1.0, do: "bg-success hover:bg-success/80"
192 + defp day_color(r) when r >= 0.95, do: "bg-warning hover:bg-warning/80"
193 + defp day_color(_), do: "bg-error hover:bg-error/80"
194 +
195 + @doc "An uptime share for people: `100%`, `99.95%`; nil is a dash."
196 + def percent(nil), do: "—"
197 + def percent(r) when r >= 1.0, do: "100%"
198 +
199 + def percent(r) do
200 + p = Float.floor(r * 100, 2)
201 + :erlang.float_to_binary(p, decimals: if(p == Float.round(p), do: 0, else: 2)) <> "%"
202 + end
203 +
204 + @doc "A response time in ms; nil is a dash."
205 + def ms(nil), do: "—"
206 + def ms(n), do: "#{n} ms"
207 +
208 + @doc "Where a heartbeat monitor's pings go."
209 + def heartbeat_url(org_slug, %Monitor{heartbeat_token: token}),
210 + do: "#{VigilWeb.base_url()}/api/0/organizations/#{org_slug}/heartbeat_check/#{token}/"
211 +
212 + @doc """
213 + The create/edit form's fields; `projects` (`{name, id}` options) adds a
214 + project select, for creating. Which fields show depends on the type.
215 + """
216 + attr :form, Phoenix.HTML.Form, required: true
217 + attr :projects, :list, default: nil
218 +
219 + def uptime_fields(assigns) do
220 + assigns = assign(assigns, :type, to_string(assigns.form[:type].value || "get"))
221 +
222 + ~H"""
223 + <div class="grid gap-x-3 sm:grid-cols-2">
224 + <.input field={@form[:name]} label="Name" placeholder="Website" autocomplete="off" required />
225 + <.input
226 + :if={@projects}
227 + field={@form[:project_id]}
228 + type="select"
229 + label="Project (its alert rules are used)"
230 + options={@projects}
231 + prompt="Pick a project"
232 + id="uptime-field-project"
233 + />
234 + </div>
235 +
236 + <div class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
237 + <.input
238 + field={@form[:type]}
239 + type="select"
240 + label="Type"
241 + options={type_options()}
242 + id="uptime-field-type"
243 + />
244 + <div :if={@type != "heartbeat"}>
245 + <.input
246 + field={@form[:url]}
247 + label={url_label(@type)}
248 + placeholder={url_placeholder(@type)}
249 + class="input w-full font-mono"
250 + autocomplete="off"
251 + id="uptime-field-url"
252 + />
253 + </div>
254 + </div>
255 + <p id="uptime-field-type-hint" class="-mt-1 mb-2 text-xs text-base-content/60">
256 + <.icon name="hero-information-circle-micro" class="size-3.5 align-text-bottom" />
257 + {type_hint(@type)}
258 + </p>
259 +
260 + <div :if={@type in ["get", "post"]} class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
261 + <.input
262 + field={@form[:expected_status]}
263 + type="number"
264 + label="Expected status"
265 + placeholder="any 2xx"
266 + min="100"
267 + max="599"
268 + id="uptime-field-expected-status"
269 + />
270 + <.input
271 + field={@form[:expected_body]}
272 + label="Expected text in the response (optional)"
273 + id="uptime-field-expected-body"
274 + />
275 + </div>
276 +
277 + <div class="grid gap-x-3 sm:grid-cols-3">
278 + <.input
279 + field={@form[:interval_seconds]}
280 + type="number"
281 + label={if @type == "heartbeat", do: "Expect a beat every (s)", else: "Check every (s)"}
282 + min="10"
283 + id="uptime-field-interval"
284 + />
285 + <.input
286 + field={@form[:timeout_seconds]}
287 + type="number"
288 + label={if @type == "heartbeat", do: "Grace (s)", else: "Timeout (s)"}
289 + min="1"
290 + max="60"
291 + id="uptime-field-timeout"
292 + />
293 + <.input
294 + :if={@type == "ssl"}
295 + field={@form[:ssl_warn_days]}
296 + type="number"
297 + label="Down when expiring within (days)"
298 + min="0"
299 + id="uptime-field-ssl-warn"
300 + />
301 + </div>
302 + """
303 + end
304 +
305 + defp url_label("tcp"), do: "Host and port"
306 + defp url_label("ssl"), do: "Host or https:// URL"
307 + defp url_label(_), do: "URL"
308 +
309 + defp url_placeholder("tcp"), do: "db.example.com:5432"
310 + defp url_placeholder("ssl"), do: "example.com"
311 + defp url_placeholder(_), do: "https://example.com/health"
312 +
313 + defp type_hint("ping"), do: "An HTTP HEAD request: any answer at all counts as up."
314 + defp type_hint("get"), do: "Up when the GET answers the expected status (any 2xx by default)."
315 + defp type_hint("post"), do: "Up when the POST answers the expected status (any 2xx by default)."
316 + defp type_hint("tcp"), do: "Up when a TCP connection to host:port opens."
317 +
318 + defp type_hint("ssl"),
319 + do: "Up while the TLS handshake succeeds and the certificate isn't about to expire."
320 +
321 + defp type_hint("heartbeat"),
322 + do: "Your job calls this monitor's URL; no call within the interval (plus grace) is down."
323 +
324 + defp type_hint(_), do: ""
325 +end
added lib/vigil_web/live/status_page_live/index.ex
+336 −0
@@ -0,0 +1,336 @@
1 +defmodule VigilWeb.StatusPageLive.Index do
2 + @moduledoc """
3 + An organization's status pages (`Vigil.Uptime`): each one's name, where
4 + it lives (`/status/:org/:slug`), whether anyone may see it or only
5 + members, and which monitors it shows. Someone with `org:write` (managers
6 + and owners) can make, edit, publish and delete them; everyone else sees
7 + the list and the links.
8 + """
9 + use VigilWeb, :live_view
10 +
11 + alias Vigil.Accounts.Scope
12 + alias Vigil.Uptime
13 + alias Vigil.Uptime.StatusPage
14 +
15 + @impl true
16 + def mount(_params, _session, socket) do
17 + scope = socket.assigns.current_scope
18 +
19 + {:ok,
20 + socket
21 + |> assign(:page_title, "#{scope.organization.name} · Status pages")
22 + |> assign(:can_manage?, Scope.can?(scope, "org:write"))
23 + |> assign(:monitors, Uptime.list_monitors(scope))
24 + |> assign(:editing, nil)
25 + |> assign(:form, nil)
26 + |> assign(:selected, MapSet.new())
27 + |> stream_configure(:pages, dom_id: &"status-page-#{&1.id}")
28 + |> load()}
29 + end
30 +
31 + defp load(socket) do
32 + pages = Uptime.list_status_pages_with_monitors(socket.assigns.current_scope.organization.id)
33 +
34 + socket
35 + |> assign(:count, length(pages))
36 + |> stream(:pages, pages, reset: true)
37 + end
38 +
39 + defp form_for(page, params, action \\ nil),
40 + do: page |> Uptime.change_status_page(params) |> to_form(action: action)
41 +
42 + defp monitor_ids(params),
43 + do: params |> Map.get("monitor_ids", []) |> List.wrap() |> Enum.reject(&(&1 == ""))
44 +
45 + defp base(%StatusPage{} = page), do: page
46 + defp base(_), do: %StatusPage{}
47 +
48 + defp forbidden(socket),
49 + do: put_flash(socket, :error, "Only managers and owners can change status pages.")
50 +
51 + @impl true
52 + def handle_event("new", _params, socket) do
53 + {:noreply,
54 + assign(socket,
55 + editing: :new,
56 + form: form_for(%StatusPage{}, %{}),
57 + selected: MapSet.new()
58 + )}
59 + end
60 +
61 + def handle_event("edit", %{"id" => id}, socket) do
62 + case Uptime.get_org_status_page(socket.assigns.current_scope.organization.id, id) do
63 + nil ->
64 + {:noreply, put_flash(socket, :error, "That status page is gone.")}
65 +
66 + page ->
67 + {:noreply,
68 + assign(socket,
69 + editing: page,
70 + form: form_for(page, %{}),
71 + selected: MapSet.new(page.monitors, & &1.id)
72 + )}
73 + end
74 + end
75 +
76 + def handle_event("cancel", _params, socket),
77 + do: {:noreply, assign(socket, editing: nil, form: nil)}
78 +
79 + def handle_event("validate", %{"status_page" => attrs} = params, socket) do
80 + {:noreply,
81 + assign(socket,
82 + form: form_for(base(socket.assigns.editing), attrs, :validate),
83 + selected: MapSet.new(monitor_ids(params))
84 + )}
85 + end
86 +
87 + def handle_event("save", %{"status_page" => attrs} = params, socket) do
88 + scope = socket.assigns.current_scope
89 + ids = monitor_ids(params)
90 +
91 + result =
92 + case socket.assigns.editing do
93 + %StatusPage{} = page -> Uptime.update_status_page(scope, page, attrs, ids)
94 + _ -> Uptime.create_status_page(scope, attrs, ids)
95 + end
96 +
97 + case result do
98 + {:ok, page} ->
99 + {:noreply,
100 + socket
101 + |> assign(editing: nil, form: nil)
102 + |> put_flash(:info, "Status page #{page.name} saved.")
103 + |> load()}
104 +
105 + {:error, %Ecto.Changeset{} = cs} ->
106 + {:noreply, assign(socket, form: to_form(cs, action: :insert), selected: MapSet.new(ids))}
107 +
108 + {:error, _} ->
109 + {:noreply, forbidden(socket)}
110 + end
111 + end
112 +
113 + def handle_event("toggle_public", %{"id" => id}, socket) do
114 + scope = socket.assigns.current_scope
115 +
116 + with %StatusPage{} = page <- Uptime.get_org_status_page(scope.organization.id, id),
117 + {:ok, page} <-
118 + Uptime.update_status_page(
119 + scope,
120 + page,
121 + %{is_public: !page.is_public},
122 + Enum.map(page.monitors, & &1.id)
123 + ) do
124 + {:noreply,
125 + socket
126 + |> put_flash(
127 + :info,
128 + if(page.is_public,
129 + do: "#{page.name} is public now.",
130 + else: "#{page.name} is for members only now."
131 + )
132 + )
133 + |> load()}
134 + else
135 + nil -> {:noreply, put_flash(socket, :error, "That status page is gone.")}
136 + {:error, _} -> {:noreply, forbidden(socket)}
137 + end
138 + end
139 +
140 + def handle_event("delete", %{"id" => id}, socket) do
141 + scope = socket.assigns.current_scope
142 +
143 + with %StatusPage{} = page <- Uptime.get_org_status_page(scope.organization.id, id),
144 + {:ok, page} <- Uptime.delete_status_page(scope, page) do
145 + {:noreply,
146 + socket
147 + |> put_flash(:info, "Status page #{page.name} deleted.")
148 + |> stream_delete(:pages, page)
149 + |> assign(:count, socket.assigns.count - 1)}
150 + else
151 + nil -> {:noreply, put_flash(socket, :error, "That status page is gone.")}
152 + {:error, _} -> {:noreply, forbidden(socket)}
153 + end
154 + end
155 +
156 + @impl true
157 + def render(assigns) do
158 + ~H"""
159 + <Layouts.app flash={@flash} current_scope={@current_scope} active={:uptime}>
160 + <div class="mx-auto max-w-5xl space-y-6">
161 + <.header>
162 + Status pages
163 + <:subtitle>
164 + Show chosen monitors' state to your users, or to your members only.
165 + </:subtitle>
166 + <:actions>
167 + <div class="flex flex-wrap items-center gap-1">
168 + <.link
169 + navigate={~p"/orgs/#{@current_scope.organization.slug}/uptime"}
170 + class="btn btn-ghost btn-sm"
171 + id="status-pages-back"
172 + >
173 + <.icon name="hero-arrow-left-micro" class="size-4" /> Uptime
174 + </.link>
175 + <button
176 + :if={@can_manage? and is_nil(@editing)}
177 + type="button"
178 + id="new-status-page"
179 + class="btn btn-primary btn-sm"
180 + phx-click="new"
181 + >
182 + <.icon name="hero-plus-micro" class="size-4" /> New status page
183 + </button>
184 + </div>
185 + </:actions>
186 + </.header>
187 +
188 + <.form
189 + :if={@can_manage? and @form}
190 + for={@form}
191 + id="status-page-form"
192 + phx-change="validate"
193 + phx-submit="save"
194 + class="space-y-1 rounded-box border border-base-300 bg-base-200/60 p-4"
195 + >
196 + <h2 class="mb-2 text-sm font-semibold">
197 + {if @editing == :new, do: "New status page", else: "Edit #{@editing.name}"}
198 + </h2>
199 + <div class="grid gap-x-3 sm:grid-cols-2">
200 + <.input field={@form[:name]} label="Name" placeholder="Acme status" required />
201 + <.input
202 + field={@form[:slug]}
203 + label="Slug (in its address)"
204 + placeholder="made from the name"
205 + autocomplete="off"
206 + />
207 + </div>
208 + <.input
209 + field={@form[:is_public]}
210 + type="checkbox"
211 + label="Public: anyone with the link can see it (otherwise members only)"
212 + />
213 +
214 + <fieldset class="mt-2" id="status-page-monitors">
215 + <legend class="mb-1 text-sm font-medium">Monitors to show</legend>
216 + <input type="hidden" name="monitor_ids[]" value="" />
217 + <p :if={@monitors == []} class="text-sm text-base-content/60">
218 + No uptime monitors yet: make some first.
219 + </p>
220 + <div class="grid gap-1 sm:grid-cols-2">
221 + <label
222 + :for={m <- @monitors}
223 + class="flex cursor-pointer items-center gap-2 rounded-box px-2 py-1.5 text-sm transition hover:bg-base-300/50"
224 + >
225 + <input
226 + type="checkbox"
227 + name="monitor_ids[]"
228 + value={m.id}
229 + id={"status-page-monitor-#{m.id}"}
230 + checked={MapSet.member?(@selected, m.id)}
231 + class="checkbox checkbox-sm"
232 + />
233 + <span class="truncate">{m.name}</span>
234 + <span class="ml-auto truncate text-xs text-base-content/50">{m.project.name}</span>
235 + </label>
236 + </div>
237 + </fieldset>
238 +
239 + <div class="flex gap-2 pt-3">
240 + <.button class="btn btn-primary btn-sm" phx-disable-with="Saving…" id="save-status-page">
241 + Save
242 + </.button>
243 + <button
244 + type="button"
245 + class="btn btn-ghost btn-sm"
246 + phx-click="cancel"
247 + id="cancel-status-page"
248 + >
249 + Cancel
250 + </button>
251 + </div>
252 + </.form>
253 +
254 + <ul id="status-pages" phx-update="stream" class="space-y-2">
255 + <li
256 + id="status-pages-empty"
257 + class="hidden rounded-box border border-dashed border-base-300 bg-base-100 p-8 text-center text-sm text-base-content/60 only:block"
258 + >
259 + <.icon name="hero-signal" class="mx-auto mb-2 block size-8 text-primary/50" />
260 + No status pages yet.
261 + <span :if={@can_manage?}>
262 + Make one with <em>New status page</em>, pick its monitors, and share its link.
263 + </span>
264 + </li>
265 + <li
266 + :for={{dom_id, page} <- @streams.pages}
267 + id={dom_id}
268 + class="flex flex-wrap items-center gap-x-4 gap-y-2 rounded-box border border-base-300 bg-base-100 px-4 py-3 transition hover:border-base-content/20"
269 + >
270 + <div class="min-w-0 flex-1">
271 + <p class="flex flex-wrap items-center gap-2">
272 + <span class="font-semibold">{page.name}</span>
273 + <%= if page.is_public do %>
274 + <span class="badge badge-info badge-soft badge-sm gap-1 status-page-public">
275 + <.icon name="hero-globe-alt-micro" class="size-3.5" /> Public
276 + </span>
277 + <% else %>
278 + <span class="badge badge-ghost badge-sm gap-1 status-page-private">
279 + <.icon name="hero-lock-closed-micro" class="size-3.5" /> Members only
280 + </span>
281 + <% end %>
282 + </p>
283 + <p class="mt-0.5 truncate text-xs text-base-content/60">
284 + <.link
285 + navigate={~p"/status/#{@current_scope.organization.slug}/#{page.slug}"}
286 + class="link link-hover font-mono"
287 + id={"status-page-link-#{page.id}"}
288 + >
289 + /status/{@current_scope.organization.slug}/{page.slug}
290 + </.link>
291 + · {length(page.monitors)} {if length(page.monitors) == 1,
292 + do: "monitor",
293 + else: "monitors"}
294 + </p>
295 + </div>
296 + <div :if={@can_manage?} class="flex flex-wrap items-center gap-1">
297 + <button
298 + type="button"
299 + id={"edit-status-page-#{page.id}"}
300 + class="btn btn-ghost btn-sm"
301 + phx-click="edit"
302 + phx-value-id={page.id}
303 + >
304 + <.icon name="hero-pencil-square-micro" class="size-4" /> Edit
305 + </button>
306 + <button
307 + type="button"
308 + id={"toggle-status-page-#{page.id}"}
309 + class="btn btn-ghost btn-sm"
310 + phx-click="toggle_public"
311 + phx-value-id={page.id}
312 + >
313 + <%= if page.is_public do %>
314 + <.icon name="hero-lock-closed-micro" class="size-4" /> Make private
315 + <% else %>
316 + <.icon name="hero-globe-alt-micro" class="size-4" /> Make public
317 + <% end %>
318 + </button>
319 + <button
320 + type="button"
321 + id={"delete-status-page-#{page.id}"}
322 + class="btn btn-ghost btn-sm text-error"
323 + phx-click="delete"
324 + phx-value-id={page.id}
325 + data-confirm={"Delete the status page #{page.name}?"}
326 + >
327 + <.icon name="hero-trash-micro" class="size-4" /> Delete
328 + </button>
329 + </div>
330 + </li>
331 + </ul>
332 + </div>
333 + </Layouts.app>
334 + """
335 + end
336 +end
added lib/vigil_web/live/status_page_live/show.ex
+218 −0

Click to load diff…

added lib/vigil_web/live/uptime_live/index.ex
+332 −0

Click to load diff…

added lib/vigil_web/live/uptime_live/show.ex
+584 −0

Click to load diff…

modified lib/vigil_web/router.ex
+9 −0

Click to load diff…

modified test/vigil/uptime_test.exs
+65 −0

Click to load diff…

added test/vigil_web/live/status_page_live_test.exs
+176 −0

Click to load diff…

added test/vigil_web/live/uptime_live_test.exs
+283 −0

Click to load diff…

Parents: e47e04f