defmodule VigilWeb.UptimeComponents do
@moduledoc """
Pieces the uptime pages share: a monitor's state badge (icon and word,
never color alone), its type badge, the strip of its recent checks (one
tick per check, with a hover tooltip and a summary for screen readers),
the per-day uptime strip of a status page, percentages and response
times for people, and the create/edit form's type-dependent fields.
Relative times come from `VigilWeb.MonitorComponents`.
"""
use Phoenix.Component
import VigilWeb.CoreComponents, only: [icon: 1, input: 1]
import VigilWeb.MonitorComponents, only: [format_time: 1]
alias Vigil.Uptime
alias Vigil.Uptime.Monitor
@doc "A monitor type for people."
def type_label(:ping), do: "HTTP ping"
def type_label(:get), do: "HTTP GET"
def type_label(:post), do: "HTTP POST"
def type_label(:tcp), do: "TCP port"
def type_label(:ssl), do: "TLS certificate"
def type_label(:heartbeat), do: "Heartbeat"
def type_label(other), do: to_string(other)
@doc "The type select's options."
def type_options, do: Enum.map(Monitor.types(), &{type_label(&1), to_string(&1)})
@doc "A small badge naming a monitor's type."
attr :type, :atom, required: true
attr :id, :string, default: nil
def type_badge(assigns) do
~H"""
<span id={@id} class="badge badge-outline badge-sm gap-1 whitespace-nowrap text-base-content/70">
<.icon name={type_icon(@type)} class="size-3.5" />{type_label(@type)}
</span>
"""
end
defp type_icon(:heartbeat), do: "hero-heart-micro"
defp type_icon(:tcp), do: "hero-server-micro"
defp type_icon(:ssl), do: "hero-lock-closed-micro"
defp type_icon(_), do: "hero-globe-alt-micro"
@doc "Up, down or pending (not checked yet): `:up`, `:down`, `:pending`."
def state(%{is_up: true}), do: :up
def state(%{is_up: false}), do: :down
def state(_), do: :pending
@doc "A monitor's state (and paused state) as an icon and a word."
attr :monitor, :map, required: true
attr :id, :string, default: nil
attr :size, :string, default: "badge-sm"
def state_badge(assigns) do
assigns = assign(assigns, :state, state(assigns.monitor))
~H"""
<span id={@id} class="inline-flex flex-wrap items-center gap-1">
<%= case @state do %>
<% :down -> %>
<span class={["badge badge-error gap-1 uptime-state-down", @size]}>
<.icon name="hero-arrow-down-circle-micro" class="size-3.5" /> Down
</span>
<% :up -> %>
<span class={["badge badge-success badge-soft gap-1 uptime-state-up", @size]}>
<.icon name="hero-arrow-up-circle-micro" class="size-3.5" /> Up
</span>
<% :pending -> %>
<span class={["badge badge-ghost gap-1 uptime-state-pending", @size]}>
<.icon name="hero-clock-micro" class="size-3.5" /> Pending
</span>
<% end %>
<span
:if={Map.get(@monitor, :enabled) == false}
class={["badge badge-outline gap-1 uptime-disabled", @size]}
>
<.icon name="hero-pause-micro" class="size-3.5" /> Disabled
</span>
</span>
"""
end
@doc """
A monitor's latest checks (oldest first) as a row of ticks, left-padded
to `slots`. Down checks stand full height in the error color, up ones a
little shorter in the success color: shape and color both tell them
apart. Each tick has a tooltip; the row has a summary as its accessible
label.
"""
attr :id, :string, required: true
attr :checks, :list, required: true
attr :slots, :integer, default: 30
attr :class, :string, default: "h-6"
def check_strip(assigns) do
checks = Enum.take(assigns.checks, -assigns.slots)
assigns =
assign(assigns,
checks: checks,
pad: max(assigns.slots - length(checks), 0),
summary: strip_summary(checks)
)
~H"""
<div id={@id} class={["flex items-end gap-[2px]", @class]} role="img" aria-label={@summary}>
<span
:for={_ <- List.duplicate(nil, @pad)}
class="h-1/3 flex-1 rounded-[2px] bg-base-300/50"
aria-hidden="true"
/>
<span
:for={c <- @checks}
id={"#{@id}-tick-#{c.id}"}
data-up={to_string(c.is_up)}
class="uptime-tick group relative flex h-full flex-1 items-end"
>
<span class={[
"w-full rounded-[2px] transition-opacity group-hover:opacity-75",
if(c.is_up, do: "h-3/4 bg-success", else: "h-full bg-error")
]} />
<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">
<span class="font-semibold">{if c.is_up, do: "Up", else: "Down"}</span>
· {format_time(c.checked_at)}
<span :if={c.response_ms}>· {ms(c.response_ms)}</span>
<span :if={!c.is_up}>· {Uptime.describe_reason(c.reason)}</span>
</span>
</span>
</div>
"""
end
defp strip_summary([]), do: "No checks yet"
defp strip_summary(checks) do
down = Enum.count(checks, &(!&1.is_up))
"Last #{length(checks)} checks: #{length(checks) - down} up, #{down} down"
end
@doc "A legend for the check strip's colors."
def legend(assigns) do
~H"""
<ul class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-base-content/60" aria-hidden="true">
<li class="flex items-center gap-1.5"><span class="size-2.5 rounded-[2px] bg-success" />Up</li>
<li class="flex items-center gap-1.5"><span class="size-2.5 rounded-[2px] bg-error" />Down</li>
</ul>
"""
end
@doc """
Per-day uptime (`Vigil.Uptime.daily_uptime/3`) as a strip of day bars:
green when fully up, amber for a partial outage, red for a mostly-down
day, grey before monitoring began. Each has a tooltip; the strip a
summary.
"""
attr :id, :string, required: true
attr :days, :list, required: true
def day_strip(assigns) do
known = Enum.reject(assigns.days, &is_nil(&1.ratio))
bad = Enum.count(known, &(&1.ratio < 1.0))
summary =
case known do
[] -> "No data for the last #{length(assigns.days)} days yet"
_ -> "Last #{length(assigns.days)} days: #{bad} with downtime"
end
assigns = assign(assigns, :summary, summary)
~H"""
<div id={@id} class="flex h-8 items-stretch gap-[2px]" role="img" aria-label={@summary}>
<span
:for={d <- @days}
data-date={Date.to_iso8601(d.date)}
class={["status-day group relative flex-1 rounded-[2px]", day_color(d.ratio)]}
>
<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">
<span class="font-semibold">{Calendar.strftime(d.date, "%b %-d")}</span>
· {if d.ratio, do: "#{percent(d.ratio)} up", else: "no data"}
</span>
</span>
</div>
"""
end
defp day_color(nil), do: "bg-base-300/60"
defp day_color(r) when r >= 1.0, do: "bg-success hover:bg-success/80"
defp day_color(r) when r >= 0.95, do: "bg-warning hover:bg-warning/80"
defp day_color(_), do: "bg-error hover:bg-error/80"
@doc "An uptime share for people: `100%`, `99.95%`; nil is a dash."
def percent(nil), do: "—"
def percent(r) when r >= 1.0, do: "100%"
def percent(r) do
p = Float.floor(r * 100, 2)
:erlang.float_to_binary(p, decimals: if(p == Float.round(p), do: 0, else: 2)) <> "%"
end
@doc "A response time in ms; nil is a dash."
def ms(nil), do: "—"
def ms(n), do: "#{n} ms"
@doc "Where a heartbeat monitor's pings go."
def heartbeat_url(org_slug, %Monitor{heartbeat_token: token}),
do: "#{VigilWeb.base_url()}/api/0/organizations/#{org_slug}/heartbeat_check/#{token}/"
@doc """
The create/edit form's fields; `projects` (`{name, id}` options) adds a
project select, for creating. Which fields show depends on the type.
"""
attr :form, Phoenix.HTML.Form, required: true
attr :projects, :list, default: nil
def uptime_fields(assigns) do
assigns = assign(assigns, :type, to_string(assigns.form[:type].value || "get"))
~H"""
<div class="grid gap-x-3 sm:grid-cols-2">
<.input field={@form[:name]} label="Name" placeholder="Website" autocomplete="off" required />
<.input
:if={@projects}
field={@form[:project_id]}
type="select"
label="Project (its alert rules are used)"
options={@projects}
prompt="Pick a project"
id="uptime-field-project"
/>
</div>
<div class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
<.input
field={@form[:type]}
type="select"
label="Type"
options={type_options()}
id="uptime-field-type"
/>
<div :if={@type != "heartbeat"}>
<.input
field={@form[:url]}
label={url_label(@type)}
placeholder={url_placeholder(@type)}
class="input w-full font-mono"
autocomplete="off"
id="uptime-field-url"
/>
</div>
</div>
<p id="uptime-field-type-hint" class="-mt-1 mb-2 text-xs text-base-content/60">
<.icon name="hero-information-circle-micro" class="size-3.5 align-text-bottom" />
{type_hint(@type)}
</p>
<div :if={@type in ["get", "post"]} class="grid gap-x-3 sm:grid-cols-[12rem_1fr]">
<.input
field={@form[:expected_status]}
type="number"
label="Expected status"
placeholder="any 2xx"
min="100"
max="599"
id="uptime-field-expected-status"
/>
<.input
field={@form[:expected_body]}
label="Expected text in the response (optional)"
id="uptime-field-expected-body"
/>
</div>
<div class="grid gap-x-3 sm:grid-cols-3">
<.input
field={@form[:interval_seconds]}
type="number"
label={if @type == "heartbeat", do: "Expect a beat every (s)", else: "Check every (s)"}
min="10"
id="uptime-field-interval"
/>
<.input
field={@form[:timeout_seconds]}
type="number"
label={if @type == "heartbeat", do: "Grace (s)", else: "Timeout (s)"}
min="1"
max="60"
id="uptime-field-timeout"
/>
<.input
:if={@type == "ssl"}
field={@form[:ssl_warn_days]}
type="number"
label="Down when expiring within (days)"
min="0"
id="uptime-field-ssl-warn"
/>
</div>
"""
end
defp url_label("tcp"), do: "Host and port"
defp url_label("ssl"), do: "Host or https:// URL"
defp url_label(_), do: "URL"
defp url_placeholder("tcp"), do: "db.example.com:5432"
defp url_placeholder("ssl"), do: "example.com"
defp url_placeholder(_), do: "https://example.com/health"
defp type_hint("ping"), do: "An HTTP HEAD request: any answer at all counts as up."
defp type_hint("get"), do: "Up when the GET answers the expected status (any 2xx by default)."
defp type_hint("post"), do: "Up when the POST answers the expected status (any 2xx by default)."
defp type_hint("tcp"), do: "Up when a TCP connection to host:port opens."
defp type_hint("ssl"),
do: "Up while the TLS handshake succeeds and the certificate isn't about to expire."
defp type_hint("heartbeat"),
do: "Your job calls this monitor's URL; no call within the interval (plus grace) is down."
defp type_hint(_), do: ""
end
neiam
/vigil
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
11.3 KiB · text
History
2bb12dd