defmodule CodeNameRaven.MonitorComponents do @moduledoc """ The standard component library for monitor panels. Monitor authors may use these components to build custom renders that fit naturally into the Raven dashboard, or ignore them entirely and write whatever HEEx they want. The `default_render/1` function is the render implementation used by any monitor that does not override `render/1`. ## Platform features available in renders The following are supported platform features that integrations can opt into displaying. All data is available in the assigns passed to `render/1`. ### Silence (`@config.silenced_until`) When a monitor is silenced, `@config.silenced_until` holds a `DateTime` in the future. The platform automatically suppresses warning logs and shows a "SILENCED" badge on the card, but your render can also surface this state. Use `silence_badge/1` to show a compact inline indicator: <.silence_badge silenced_until={@config.silenced_until} /> Silence is managed from the card flip side — no integration code required. """ use Phoenix.Component @doc """ The default panel render used when a monitor does not provide its own. Shows status, last check time, last error, and the collect result as a key-value table when one is available. """ def default_render(assigns) do ~H"""
Not yet checked
""" end def check_time(assigns) do ~H"""Last checked: {Calendar.strftime(@checked_at, "%Y-%m-%d %H:%M:%S UTC")}
""" end attr :message, :string, default: nil @doc """ Displays the monitor's last error message in a red monospace font, if present. Shows nothing when `nil`. Hover for full message text on truncation. """ def error_message(%{message: nil} = assigns), do: ~H"" def error_message(assigns) do ~H"""{@message}
""" end attr :status, :atom, values: [:up, :degraded, :down, :unknown], required: true @doc """ A compact status chip with a coloured dot and label. Suitable for panel headers and inline status indicators. Uses badge styling matched to the status severity. """ def status_chip(assigns) do {label, cls} = case assigns.status do :up -> {"Up", "badge-success"} :degraded -> {"Degraded", "badge-warning"} :down -> {"Down", "badge-error"} _ -> {"Unknown", "badge-neutral"} end assigns = assign(assigns, label: label, cls: cls) ~H""" {@label} """ end attr :label, :string, required: true attr :value, :string, required: true @doc """ A single metric stat block — label above, value below in monospace. Use within a flex row to display a small set of key measurements side by side (e.g. status code and latency). """ def stat(assigns) do ~H"""{@label}
{@value}
| {k} | {inspect(v)} |
Chart appears after the second check…
""" else computed_max = all_values |> Enum.max() |> max(0) |> mc_nice_ceil() # `assigns.y_max || computed_max` would treat an explicitly-pinned # `0.0` ceiling as "unset" (0 is truthy in Elixir) and fall through to # computed_max instead — an is_nil check is the only way to actually # distinguish "not provided" from "provided as zero". y_max = if is_nil(assigns.y_max), do: computed_max, else: assigns.y_max y_min = assigns.y_min t_unix = Enum.map(assigns.samples, &DateTime.to_unix(&1.collected_at)) t_min = Enum.min(t_unix) t_max = Enum.max(t_unix) t_span = max(t_max - t_min, 1) geo = %{t_min: t_min, t_span: t_span, pw: pw, pl: pl, ph: ph, bottom: bottom, y_max: y_max, y_min: y_min} svg_traces = build_svg_traces(by_instance, assigns.local_id, metric_name, geo) y_ticks = [y_min, y_min + (y_max - y_min) * 0.25, y_min + (y_max - y_min) * 0.5, y_min + (y_max - y_min) * 0.75, y_max] |> Enum.map(fn val -> y = bottom - round(safe_ratio(val - y_min, y_max - y_min) * ph) {y, mc_fmt_y(val)} end) |> Enum.uniq_by(&elem(&1, 0)) t_mid = t_min + div(t_span, 2) x_ticks = [{pl, t_min}, {pl + div(pw, 2), t_mid}, {pl + pw, t_max}] |> Enum.map(fn {x, t} -> {x, Calendar.strftime(DateTime.from_unix!(t), "%I:%M %p")} end) assigns = assign(assigns, svg_traces: svg_traces, y_ticks: y_ticks, x_ticks: x_ticks, bottom: bottom, multi: map_size(by_instance) > 1, pl: pl, pw: pw, pt: pt ) ~H""" """ end end defp build_svg_traces(by_instance, local_id, metric_name, geo) do by_instance |> Enum.map(fn {instance_id, inst_samples} -> {instance_id == local_id, build_dots(inst_samples, metric_name, geo)} end) # An instance whose samples all lack this particular metric (e.g. a # ratio metric that's only emitted once traffic starts flowing) now # produces no dots at all — nothing to draw a trace from, and hd/1 and # List.last/1 below would raise on an empty list. |> Enum.reject(fn {_is_local, dots} -> dots == [] end) |> Enum.map(fn {is_local, dots} -> {x0, _, _} = hd(dots) {xn, _, _} = List.last(dots) inner = Enum.map_join(dots, " L ", &dot_xy/1) %{ is_local: is_local, line_pts: Enum.map_join(dots, " ", &dot_xy/1), dots: dots, area_d: "M #{x0},#{geo.bottom} L #{inner} L #{xn},#{geo.bottom} Z", label: if(is_local, do: "Local", else: "Sibling") } end) end defp build_dots(inst_samples, metric_name, geo) do inst_samples |> Enum.sort_by(&DateTime.to_unix(&1.collected_at)) |> Enum.map(&build_dot(&1, metric_name, geo)) |> Enum.reject(&is_nil/1) end # A sample with no value for this metric (never checked yet, or a ratio # metric that's only meaningful once some activity has occurred) is a gap # in the data, not a real zero — plotting it as 0 would draw a false dip # to the bottom of the chart that reads as an incident. defp build_dot(s, metric_name, geo) do case mc_value(s, metric_name) do nil -> nil raw_val -> t = DateTime.to_unix(s.collected_at) x = geo.pl + round((t - geo.t_min) / geo.t_span * geo.pw) val = raw_val |> max(geo.y_min) |> min(geo.y_max) y = geo.bottom - round(safe_ratio(val - geo.y_min, geo.y_max - geo.y_min) * geo.ph) {x, y, mc_dot_fill(s.status)} end end # An explicitly-pinned range of zero width (y_max == y_min, e.g. both left # at their 0.0 defaults) is now honored rather than silently swapped for a # computed ceiling (see metric_chart/1) — which means it's real and # reachable, not just a theoretical gap in the public contract. A # zero-width range has no proportional space to plot against, so every # value collapses to the baseline instead of dividing by zero. defp safe_ratio(_numerator, denominator) when denominator == 0, do: 0.0 defp safe_ratio(numerator, denominator), do: numerator / denominator defp dot_xy({x, y, _}), do: "#{x},#{y}" # Reads a metric value from a sample. For "latency_ms" falls back to the # dedicated column so HTTP samples (which don't populate metrics JSONB) # continue to chart correctly via line_chart. defp mc_value(%{metrics: m} = s, "latency_ms") when is_map(m) do Map.get(m, "latency_ms") || s.latency_ms end defp mc_value(s, "latency_ms"), do: s.latency_ms defp mc_value(%{metrics: m}, name) when is_map(m), do: Map.get(m, name) defp mc_value(_s, _name), do: nil defp mc_nice_ceil(n) when n <= 0, do: 1.0 defp mc_nice_ceil(n) when n <= 1.0, do: 1.0 defp mc_nice_ceil(n) when n <= 10, do: 10 defp mc_nice_ceil(n) when n <= 50, do: 50 defp mc_nice_ceil(n) when n <= 100, do: 100 defp mc_nice_ceil(n) when n <= 250, do: 250 defp mc_nice_ceil(n) when n <= 500, do: 500 defp mc_nice_ceil(n) when n <= 1_000, do: 1_000 defp mc_nice_ceil(n) when n <= 2_500, do: 2_500 defp mc_nice_ceil(n) when n <= 5_000, do: 5_000 defp mc_nice_ceil(n) when n <= 10_000, do: 10_000 defp mc_nice_ceil(n) when n <= 100_000, do: 100_000 defp mc_nice_ceil(n) when n <= 1_000_000, do: 1_000_000 defp mc_nice_ceil(n), do: ceil(n / 1_000_000) * 1_000_000 # Its only call site (the y-axis tick labels in metric_chart/1) always # passes a number, so a catch-all clause here is unreachable dead code — # confirmed by the compiler's own "this clause is never used" warning. defp mc_fmt_y(val) when val == 0, do: "0" defp mc_fmt_y(val) when is_number(val) do v = val * 1.0 cond do v >= 1.0e9 -> "#{Float.round(v / 1.0e9, 1)}G" v >= 1.0e6 -> "#{Float.round(v / 1.0e6, 1)}M" v >= 1.0e3 -> "#{Float.round(v / 1.0e3, 1)}k" v < 10.0 -> :erlang.float_to_binary(Float.round(v, 2), decimals: 2) true -> "#{round(v)}" end end defp mc_dot_fill("up"), do: "var(--color-success)" defp mc_dot_fill("degraded"), do: "var(--color-warning)" defp mc_dot_fill("down"), do: "var(--color-error)" defp mc_dot_fill(_), do: "#94a3b8" end