Merge origin/main into main

This commit is contained in:
tyuXX 2026-11-19 13:15:34 +00:00
commit 161bf5e8cb
20 changed files with 1592 additions and 116 deletions

260
internal/server/charts.go Normal file
View file

@ -0,0 +1,260 @@
package server
import (
"fmt"
"html/template"
"strconv"
"strings"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/history"
)
// safeColor strips a color string down to characters safe to embed in an SVG
// presentation attribute.
func safeColor(c string) string {
var b strings.Builder
for _, r := range c {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9',
r == '#', r == '(', r == ')', r == ',', r == '.', r == '%', r == ' ', r == '-':
b.WriteRune(r)
}
}
return b.String()
}
func f2(v float64) string {
return strconv.FormatFloat(v, 'f', -1, 64)
}
// uptimeColorFor picks a state color for a bucket based on its uptime percent.
func uptimeColorFor(uptime float64, up, degraded, down string) string {
switch {
case uptime >= 99.5:
return up
case uptime >= 90:
return degraded
default:
return down
}
}
// uptimeBarChart renders one vertical bar per bucket (daily or hourly) whose
// height is the bucket's uptime percentage, colored by uptime thresholds.
type barBucket struct {
Label string
UptimePct float64
Checks int
Up int
Degraded int
Down int
AvgLatency float64
}
func uptimeBarChart(buckets []barBucket, w, h int, upColor, degColor, downColor string) template.HTML {
if len(buckets) == 0 || w <= 0 || h <= 0 {
return ""
}
padL, padR, padT, padB := 34.0, 8.0, 10.0, 18.0
plotW := float64(w) - padL - padR
plotH := float64(h) - padT - padB
if plotW <= 0 || plotH <= 0 {
return ""
}
slot := plotW / float64(len(buckets))
barW := slot * 0.72
if barW < 1 {
barW = 1
}
var b strings.Builder
b.WriteString(`<svg viewBox="0 0 ` + strconv.Itoa(w) + ` ` + strconv.Itoa(h) + `" style="width:100%;height:auto;display:block" role="img">`)
// horizontal gridlines at 0/50/100%
for _, pct := range []float64{0, 50, 100} {
y := padT + plotH*(1-pct/100)
b.WriteString(fmt.Sprintf(`<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="var(--border,#333)" stroke-width="0.5"/>`, padL, y, float64(w)-padR, y))
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="end">%d%%</text>`, padL-4, y+3, int(pct)))
}
for i, bk := range buckets {
x := padL + float64(i)*slot + (slot-barW)/2
bh := plotH * bk.UptimePct / 100
if bh < 0.5 {
bh = 0.5
}
y := padT + plotH - bh
color := uptimeColorFor(bk.UptimePct, safeColor(upColor), safeColor(degColor), safeColor(downColor))
tip := fmt.Sprintf("%s — uptime %.2f%% | checks %d (up %d, degraded %d, down %d)",
bk.Label, bk.UptimePct, bk.Checks, bk.Up, bk.Degraded, bk.Down)
if bk.AvgLatency > 0 {
tip += fmt.Sprintf(" | avg %.1fms", bk.AvgLatency)
}
b.WriteString(fmt.Sprintf(`<rect x="%.1f" y="%.1f" width="%.1f" height="%.1f" fill="%s" rx="1"><title>%s</title></rect>`,
x, y, barW, bh, color, template.HTMLEscapeString(tip)))
}
// x labels: first, middle, last
labelIdx := []int{0, len(buckets) / 2, len(buckets) - 1}
seen := map[int]bool{}
for _, i := range labelIdx {
if i < 0 || i >= len(buckets) || seen[i] {
continue
}
seen[i] = true
x := padL + float64(i)*slot + slot/2
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="middle">%s</text>`,
x, float64(h)-5, template.HTMLEscapeString(buckets[i].Label)))
}
b.WriteString(`</svg>`)
return template.HTML(b.String())
}
// dailyBarBuckets converts DailyStat rows into chart buckets.
func dailyBarBuckets(stats []history.DailyStat) []barBucket {
out := make([]barBucket, 0, len(stats))
for _, d := range stats {
label := d.Date
if t, err := time.Parse("2006-01-02", d.Date); err == nil {
label = t.Format("02-01")
}
out = append(out, barBucket{
Label: label,
UptimePct: d.UptimePct,
Checks: d.Checks,
Up: d.Up,
Degraded: d.Degraded,
Down: d.Down,
AvgLatency: d.AvgLatencyMs,
})
}
return out
}
// hourlyBarBuckets converts HourlyStat rows into chart buckets.
func hourlyBarBuckets(stats []history.HourlyStat) []barBucket {
out := make([]barBucket, 0, len(stats))
for _, s := range stats {
uptime := 0.0
if s.Checks > 0 {
uptime = float64(s.Up+s.Degraded) / float64(s.Checks) * 100
}
out = append(out, barBucket{
Label: s.Hour.UTC().Format("15:04"),
UptimePct: uptime,
Checks: s.Checks,
Up: s.Up,
Degraded: s.Degraded,
Down: s.Down,
AvgLatency: s.AvgLatencyMs,
})
}
return out
}
// latencyLineChart renders avg-latency values as an SVG area/line chart.
func latencyLineChart(values []float64, labels []string, w, h int, lineColor string) template.HTML {
n := len(values)
if n == 0 || w <= 0 || h <= 0 {
return ""
}
padL, padR, padT, padB := 44.0, 10.0, 10.0, 18.0
plotW := float64(w) - padL - padR
plotH := float64(h) - padT - padB
if plotW <= 0 || plotH <= 0 {
return ""
}
minV, maxV := values[0], values[0]
for _, v := range values {
if v < minV {
minV = v
}
if v > maxV {
maxV = v
}
}
if maxV == minV {
maxV = minV + 1
}
pad := (maxV - minV) * 0.08
minV -= pad
maxV += pad
x := func(i int) float64 {
if n == 1 {
return padL + plotW/2
}
return padL + plotW*float64(i)/float64(n-1)
}
y := func(v float64) float64 {
return padT + plotH*(1-(v-minV)/(maxV-minV))
}
var b strings.Builder
b.WriteString(`<svg viewBox="0 0 ` + strconv.Itoa(w) + ` ` + strconv.Itoa(h) + `" style="width:100%;height:auto;display:block" role="img">`)
// gridlines + y labels (4 ticks)
for i := 0; i <= 3; i++ {
v := minV + (maxV-minV)*float64(i)/3
yy := y(v)
b.WriteString(fmt.Sprintf(`<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="var(--border,#333)" stroke-width="0.5"/>`, padL, yy, float64(w)-padR, yy))
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="end">%.0fms</text>`, padL-4, yy+3, v))
}
color := safeColor(lineColor)
// area fill
b.WriteString(`<path d="`)
b.WriteString(fmt.Sprintf(`M %.1f %.1f `, x(0), padT+plotH))
for i, v := range values {
b.WriteString(fmt.Sprintf(`L %.1f %.1f `, x(i), y(v)))
}
b.WriteString(fmt.Sprintf(`L %.1f %.1f Z" fill="%s" fill-opacity="0.15" stroke="none"/>`, x(n-1), padT+plotH, color))
// line
b.WriteString(`<polyline fill="none" stroke="` + color + `" stroke-width="1.5" points="`)
for i, v := range values {
b.WriteString(fmt.Sprintf(`%.1f,%.1f `, x(i), y(v)))
}
b.WriteString(`"/>`)
// dots with tooltips
for i, v := range values {
label := ""
if i < len(labels) {
label = labels[i]
}
tip := fmt.Sprintf("%s — %.1fms", label, v)
b.WriteString(fmt.Sprintf(`<circle cx="%.1f" cy="%.1f" r="2.5" fill="%s"><title>%s</title></circle>`, x(i), y(v), color, template.HTMLEscapeString(tip)))
}
// x labels: first, middle, last
idxs := []int{0, n / 2, n - 1}
seen := map[int]bool{}
for _, i := range idxs {
if i < 0 || i >= n || seen[i] {
continue
}
seen[i] = true
lbl := ""
if i < len(labels) {
lbl = labels[i]
}
b.WriteString(fmt.Sprintf(`<text x="%.1f" y="%.1f" font-size="9" fill="var(--muted,#888)" text-anchor="middle">%s</text>`, x(i), float64(h)-5, template.HTMLEscapeString(lbl)))
}
b.WriteString(`</svg>`)
return template.HTML(b.String())
}
// dailyLatencyChart builds a latency line chart from daily stats.
func dailyLatencyChart(stats []history.DailyStat, w, h int, color string) template.HTML {
values := make([]float64, 0, len(stats))
labels := make([]string, 0, len(stats))
for _, d := range stats {
if d.Checks == 0 {
continue
}
values = append(values, d.AvgLatencyMs)
labels = append(labels, d.Date)
}
return latencyLineChart(values, labels, w, h, color)
}

View file

@ -0,0 +1,23 @@
package server
import "net/http"
const faviconSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="5" fill="#111111"/>
<text x="32" y="35" text-anchor="middle" font-family="ui-monospace, Menlo, Consolas, monospace" font-size="19" font-weight="700" fill="#2ecc71">Rud?</text>
<rect x="10" y="40" width="45" height="5" rx="1.5" fill="#2ecc71"/>
</svg>`
func (s *Server) serveFavicon(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8")
w.Header().Set("Cache-Control", "public, max-age=86400")
if r.Method == http.MethodHead {
return
}
_, _ = w.Write([]byte(faviconSVG))
}

169
internal/server/monitor.go Normal file
View file

@ -0,0 +1,169 @@
package server
import (
"bytes"
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
type monitorPageData struct {
Title string
Theme config.ThemeConfig
CustomCSS template.CSS
BackLink string
Index bool
Monitor *store.MonitorState
MonitorID string
Monitors []store.MonitorState
Days int
HourlyLabel string
HasStats bool
RangeChecks int
RangeUptime float64
RangeAvgLat float64
RangeUp int
RangeDegraded int
RangeDown int
UptimeChart template.HTML
LatencyChart template.HTML
HourlyChart template.HTML
}
func (s *Server) serveMonitor(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
snap := s.store.Snapshot()
backLink := s.cfg.Server.Endpoint
if backLink == "" {
backLink = "/"
}
// Monitor ID comes from /monitor/<id> path or ?id= query param.
id := strings.Trim(strings.TrimPrefix(r.URL.Path, "/monitor"), "/")
if id == "" {
id = r.URL.Query().Get("id")
}
data := monitorPageData{
Title: "Monitors — " + s.pageTitle(),
Theme: s.cfg.Page.Theme,
CustomCSS: template.CSS(s.cfg.Page.Theme.CustomCSS),
BackLink: backLink,
MonitorID: id,
Days: s.statsDays(r),
}
if id == "" {
data.Index = true
data.Monitors = snap.Monitors
} else if m, ok := snap.MonitorsByID[id]; ok {
mc := m
data.Monitor = &mc
data.Title = mc.Name + " — " + s.pageTitle()
s.fillStats(&data, id)
} else {
// Unknown to the store; still try stats in case it existed before.
s.fillStats(&data, id)
}
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
var buf bytes.Buffer
if err := templates.ExecuteTemplate(&buf, "monitor", data); err != nil {
http.Error(w, "template error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
if r.Method == http.MethodHead {
return
}
_, _ = w.Write(buf.Bytes())
}
func (s *Server) pageTitle() string {
if s.cfg.Page.Title != "" {
return s.cfg.Page.Title
}
return "R u ded?"
}
// statsDays resolves the requested history window, capped at the configured
// stats retention period.
func (s *Server) statsDays(r *http.Request) int {
retention := s.cfg.Storage.StatsRetentionDays
if retention <= 0 {
retention = 90
}
days := retention
if v := r.URL.Query().Get("days"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
days = n
}
}
if days > retention {
days = retention
}
return days
}
// fillStats queries the stats DB and renders the SVG charts for a monitor.
func (s *Server) fillStats(data *monitorPageData, monitorID string) {
if s.stats == nil {
return
}
daily, err := s.stats.DailyStats(monitorID, data.Days)
if err != nil {
return
}
hours := data.Days * 24
if hours > 168 {
hours = 168
}
hourly, err := s.stats.HourlyStats(monitorID, hours)
if err != nil {
hourly = nil
}
if len(daily) == 0 && len(hourly) == 0 {
return
}
data.HasStats = true
data.HourlyLabel = fmt.Sprintf("last %d hours", hours)
var checks, up, degraded, down int
var uptimeSum, latSum float64
for _, d := range daily {
checks += d.Checks
up += d.Up
degraded += d.Degraded
down += d.Down
uptimeSum += d.UptimePct * float64(d.Checks)
latSum += d.AvgLatencyMs * float64(d.Checks)
}
data.RangeChecks = checks
data.RangeUp = up
data.RangeDegraded = degraded
data.RangeDown = down
if checks > 0 {
data.RangeUptime = uptimeSum / float64(checks)
data.RangeAvgLat = latSum / float64(checks)
}
th := s.cfg.Page.Theme
data.UptimeChart = uptimeBarChart(dailyBarBuckets(daily), 720, 140, th.UpColor, th.DegradedColor, th.DownColor)
data.LatencyChart = dailyLatencyChart(daily, 720, 120, th.AccentColor)
data.HourlyChart = uptimeBarChart(hourlyBarBuckets(hourly), 720, 120, th.UpColor, th.DegradedColor, th.DownColor)
}

View file

@ -10,13 +10,24 @@ import (
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
"git.gsdistance.org/tyuXX/RUD/internal/history"
"git.gsdistance.org/tyuXX/RUD/internal/store"
)
// Server serves the single configured HTTP status and health check endpoint.
const Version = "v1.1"
// StatsQuerier is the read interface for long-term aggregated check statistics.
type StatsQuerier interface {
DailyStats(monitorID string, days int) ([]history.DailyStat, error)
HourlyStats(monitorID string, hours int) ([]history.HourlyStat, error)
}
// Server serves the single configured HTTP status and health check endpoint,
// plus the per-monitor historical stats page at /monitor.
type Server struct {
cfg *config.Config
store *store.Store
stats StatsQuerier
}
// New creates a new single-endpoint HTTP server.
@ -27,8 +38,22 @@ func New(cfg *config.Config, st *store.Store) *Server {
}
}
// SetStats attaches a long-term stats store used by the /monitor page.
func (s *Server) SetStats(q StatsQuerier) {
s.stats = q
}
// ServeHTTP handles incoming HTTP requests strictly on the configured single endpoint.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/favicon.svg" {
s.serveFavicon(w, r)
return
}
if r.URL.Path == "/monitor" || strings.HasPrefix(r.URL.Path, "/monitor/") {
s.serveMonitor(w, r)
return
}
endpoint := s.cfg.Server.Endpoint
if endpoint == "" {
endpoint = "/"
@ -276,7 +301,7 @@ func (s *Server) renderHTML(snap store.Snapshot) ([]byte, error) {
}
var buf bytes.Buffer
if err := pageTemplate.Execute(&buf, vd); err != nil {
if err := templates.ExecuteTemplate(&buf, "page", vd); err != nil {
return nil, err
}
return buf.Bytes(), nil
@ -429,22 +454,19 @@ func safeCSSValue(v string) template.CSS {
return template.CSS(cssSanitizer.Replace(strings.TrimSpace(v)))
}
var pageTemplate = template.Must(template.New("status").Funcs(template.FuncMap{
var templates = template.Must(template.New("status").Funcs(template.FuncMap{
"upper": strings.ToUpper,
"safeCSS": safeCSSValue,
"Version": func() string {
return Version
},
"fmtTime": func(t time.Time) string {
if t.IsZero() {
return "-"
}
return t.UTC().Format("2006-01-02 15:04:05 UTC")
},
}).Parse(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
<style>
}).Parse(`{{define "pagecss"}}<style>
:root {
--bg: {{safeCSS .Theme.BgColor}};
--card: {{safeCSS .Theme.CardBgColor}};
@ -612,7 +634,14 @@ a:hover { color: var(--accent); }
color: var(--muted);
}
{{.CustomCSS}}
</style>
</style>{{end}}{{define "page"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<title>{{.Title}}</title>
{{template "pagecss" .}}
</head>
<body>
<div class="container">
@ -667,11 +696,8 @@ a:hover { color: var(--accent); }
<div class="mon" data-monitor-id="{{.Monitor.ID}}">
<div class="mon-top">
<div class="mon-left">
{{- if .Monitor.Link}}
<a class="mon-name" href="{{.Monitor.Link}}" target="_blank" rel="noopener">{{.Monitor.Name}}</a>
{{- else}}
<span class="mon-name">{{.Monitor.Name}}</span>
{{- end}}
<a class="mon-name" href="/monitor?id={{.Monitor.ID}}">{{.Monitor.Name}}</a>
{{- if .Monitor.Link}}<a class="mon-ext" href="{{.Monitor.Link}}" target="_blank" rel="noopener" title="External link">&#8599;</a>{{end}}
{{- if $disp.ShowMethod}}<span class="mon-method">{{upper .Monitor.Method}}</span>{{end}}
{{- if and $disp.ShowTarget .Monitor.Target}}<span class="mon-target">{{.Monitor.Target}}</span>{{end}}
</div>
@ -714,7 +740,7 @@ a:hover { color: var(--accent); }
{{- end}}
<footer class="footer">
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a>
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a> {{Version}}
</footer>
</div>
{{- if gt .RefreshMs 0}}
@ -813,5 +839,97 @@ a:hover { color: var(--accent); }
</script>
{{- end}}
</body>
</html>
</html>{{end}}
{{define "monitor"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<title>{{.Title}}</title>
{{template "pagecss" .}}
</head>
<body>
<div class="container">
<header class="header header-left">
<div>
{{- if .Monitor}}<h1>{{.Monitor.Name}}</h1>
<div class="subtitle">{{upper .Monitor.Method}}{{if .Monitor.Target}} — {{.Monitor.Target}}{{end}}</div>
{{- else if .Index}}<h1>Monitors</h1>
<div class="subtitle">Select a monitor to view its history</div>
{{- else}}<h1>{{.MonitorID}}</h1>
<div class="subtitle">Monitor not found</div>{{end}}
</div>
<div class="header-meta"><a href="{{.BackLink}}">&larr; status page</a></div>
</header>
{{- if .Index}}
<section class="group">
<div class="monitors-list">
{{- range .Monitors}}
<div class="mon">
<div class="mon-top">
<div class="mon-left">
<a class="mon-name" href="/monitor?id={{.ID}}">{{.Name}}</a>
<span class="mon-method">{{upper .Method}}</span>
{{- if .Target}}<span class="mon-target">{{.Target}}</span>{{end}}
</div>
<div class="mon-right">
<span class="badge" data-state="{{.State}}">{{.State}}</span>
</div>
</div>
</div>
{{- end}}
</div>
</section>
{{- else if .Monitor}}
<section class="banner" data-state="{{.Monitor.State}}">
<div class="banner-title">{{upper .Monitor.State}}</div>
<div class="banner-meta">
<span>last checked {{fmtTime .Monitor.LastCheckedAt}}</span>
<span>{{printf "%.1fms" .Monitor.LatencyMs}} latency</span>
<span>{{printf "%.2f%%" .Monitor.UptimePct}} uptime</span>
{{- if .Monitor.LastMessage}}<span>{{.Monitor.LastMessage}}</span>{{end}}
</div>
</section>
<section>
<div class="cards">
<div class="card"><div class="card-label">CHECKS ({{.Days}}D)</div><div class="card-val">{{.RangeChecks}}</div></div>
<div class="card"><div class="card-label">UPTIME ({{.Days}}D)</div><div class="card-val">{{printf "%.2f%%" .RangeUptime}}</div></div>
<div class="card"><div class="card-label">AVG LATENCY</div><div class="card-val">{{printf "%.1fms" .RangeAvgLat}}</div></div>
<div class="card"><div class="card-label">FAILURES ({{.Days}}D)</div><div class="card-val" style="color:var(--down)">{{.RangeDown}}</div></div>
</div>
</section>
{{- if .HasStats}}
<section class="group">
<div class="group-hdr"><div class="group-title">Daily uptime — last {{.Days}} days</div></div>
{{.UptimeChart}}
</section>
<section class="group">
<div class="group-hdr"><div class="group-title">Avg response time — last {{.Days}} days</div></div>
{{.LatencyChart}}
</section>
<section class="group">
<div class="group-hdr"><div class="group-title">Hourly uptime — {{.HourlyLabel}}</div></div>
{{.HourlyChart}}
</section>
{{- else}}
<section class="custom-block" data-style="info"><div>No historical stats recorded yet for this monitor.</div></section>
{{- end}}
{{- if .Monitor.Description}}<section class="custom-block" data-style="neutral"><div>{{.Monitor.Description}}</div></section>{{end}}
{{- else}}
<section class="custom-block" data-style="warning"><div>Unknown monitor <code>{{.MonitorID}}</code>.</div></section>
{{- end}}
<footer class="footer">
Powered by <a href="https://git.gsdistance.org/tyuXX/RUD" target="_blank" rel="noopener">R u ded?</a> {{Version}}
</footer>
</div>
</body>
</html>{{end}}
`))